Is there a good string pluralization library for actionscript? - actionscript-3

I haven't found a good library actionscript library for this yet.
I want to do things like:
Inflection.pluralize( "cat" ) == "cats"
Inflection.pluralize( "fish" ) == "fish"
I know ruby on rails has a library like this build in; and javascript has a really nice one as well: http://code.google.com/p/inflection-js/.
Any one know of a similar thing for actionscript?

Google says:
http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/
package
{
public class Inflect
{
private static var plural : Array = [
[/(quiz)$/i, "$1zes"],
[/^(ox)$/i, "$1en"],
[/([m|l])ouse$/i, "$1ice"],
[/(matr|vert|ind)ix|ex$/i, "$1ices"],
[/(x|ch|ss|sh)$/i, "$1es"],
[/([^aeiouy]|qu)y$/i, "$1ies"],
[/(hive)$/i, "$1s"],
[/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
[/(shea|lea|loa|thie)f$/i, "$1ves"],
[/sis$/i, "ses"],
[/([ti])um$/i, "$1a"],
[/(tomat|potat|ech|her|vet)o$/i, "$1oes"],
[/(bu)s$/i, "$1ses"],
[/(alias|status)$/i, "$1es"],
[/(octop)us$/i, "$1i"],
[/(ax|test)is$/i, "$1es"],
[/(us)$/i, "$1es"],
[/s$/i, "s"],
[/$/i, "s"]
];
private static var singular : Array = [
[/(quiz)zes$/i, "$1"],
[/(matr)ices$/i, "$1ix"],
[/(vert|ind)ices$/i, "$1ex"],
[/^(ox)en$/i, "$1"],
[/(alias|status)es$/i, "$1"],
[/(octop|vir)i$/i, "$1us"],
[/(cris|ax|test)es$/i, "$1is"],
[/(shoe)s$/i, "$1"],
[/(o)es$/i, "$1"],
[/(bus)es$/i, "$1"],
[/([m|l])ice$/i, "$1ouse"],
[/(x|ch|ss|sh)es$/i, "$1"],
[/(m)ovies$/i, "$1ovie"],
[/(s)eries$/i, "$1eries"],
[/([^aeiouy]|qu)ies$/i, "$1y"],
[/([lr])ves$/i, "$1f"],
[/(tive)s$/i, "$1"],
[/(hive)s$/i, "$1"],
[/(li|wi|kni)ves$/i, "$1fe"],
[/(shea|loa|lea|thie)ves$/i,"$1f"],
[/(^analy)ses$/i, "$1sis"],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, "$1$2sis"],
[/([ti])a$/i, "$1um"],
[/(n)ews$/i, "$1ews"],
[/(h|bl)ouses$/i, "$1ouse"],
[/(corpse)s$/i, "$1"],
[/(us)es$/i, "$1"],
[/s$/i, ""]
];
private static var irregular : Array = [
['move' , 'moves'],
['foot' , 'feet'],
['goose' , 'geese'],
['sex' , 'sexes'],
['child' , 'children'],
['man' , 'men'],
['tooth' , 'teeth'],
['person' , 'people']
];
private static var uncountable : Array = [
'sheep',
'fish',
'deer',
'series',
'species',
'money',
'rice',
'information',
'equipment'
];
public static function pluralize( string : String ) : String
{
var pattern : RegExp;
var result : String;
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(string.toLowerCase()) != -1)
return string;
// check for irregular singular forms
var item : Array;
for each ( item in irregular )
{
pattern = new RegExp(item[0] + "$", "i");
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
// check for matches using regular expressions
for each ( item in plural)
{
pattern = item[0];
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
return string;
}
public static function singularize( string : String ) : String
{
var pattern : RegExp;
var result : String
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(string.toLowerCase()) != -1)
return string;
// check for irregular singular forms
var item : Array;
for each ( item in irregular )
{
pattern = new RegExp(item[1] + "$", "i");
result = item[0];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
// check for matches using regular expressions
for each ( item in singular)
{
pattern = item[0];
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
return string;
}
public static function pluralizeIf(count : int, string : String) : String
{
if (count == 1)
return "1 " + string;
else
return count.toString() + " " + pluralize(string);
}
}
}

Related

Wrong string format when i use persian and english together in Node Js

I have a node js project with MySql database. I have to use Persian data in my DB like:
UserModel = {id: 1200, firstName: 'صابر', lastName: 'سجادی' , nationalCode:'4640147800', displayName: 'saber-sajadi', status: 1, createDateTime: null };
so for run stored procedure i need to convert object to string with this Code:
let objectToString = (object) => {
let _string = "";
let i = 1;
for (let key in object) {
var val = object[key];
_string += (val == undefined || val == null) ? `null` : `'` + val + `' `;
if (i < Object.keys(object).length) {
_string += " , ";
i++;
}
}
return _string;
}
I expect the output of the function to be as follows:
but it return:
1200,'صابر','سجادی','4640147800','saber-sajadi','1',''
Please help me to solve this problem
we can use this function to solve problem:
function wrap(str){ return '\u202B' + str + '\u202C'; }

Angular - TypeError: Converting circular structure to JSON

I'm getting this error at angular service's map method but my returned datas doesn't seem to contain any circular reference, here is my json object:
[{"id":14,
"sender":
{"id":20,"email":"p.martelliere#gmail.com","username":"test5","roles":
["ROLE_USER"],"status":"active","note":"0","points":0,
"devices":[],"job":"Caisse","showJob":false,"notificationsActivated":true,
"connected":true,"tokenConfirm":"","birthDate":[]
},"receiver":
{"id":12,"email":"test2#yopmail.com","username":"test2","tokenConfirm":"",
"job":"g\u00e9rant","showJob":false,"note":"0","points":0,
"roles":["ROLE_USER"],"status":"active","notificationsActivated":true,
"connected":true,"devices":[]
},
"myNeed":"Te ster",
"whatICanGive":"1",
"messages":[],
"status":"active"
}]
Here's my chatRequest angular Entity:
export class NmChatRequest {
// Raw attributes
id : number;
myNeed : string;
whatICanGive : string;
status : string;
createdAt : Date;
updatedAt : Date;
deletedAt : Date;
// x-to-one
id_receiver: number;
constructor(json? : any) {
if (json != null) {
this.id = json.id;
this.myNeed = json.myNeed;
this.whatICanGive = json.whatICanGive;
this.status = json.status;
this.id_receiver = json.id_receiver;
if (json.createdAt != null) {
this.createdAt = new Date(json.createdAt);
}
if (json.updatedAt != null) {
this.updatedAt = new Date(json.updatedAt);
}
if (json.deletedAt != null) {
this.deletedAt = new Date(json.deletedAt);
}
}
}
}
This entity is used to get the object from json.
Here's my ChatRequestService:
/**
* Create the passed nmChatRequest.
*/
add(nmChatRequest : NmChatRequest, token: string) : Observable<NmChatRequest> {
let body = nmChatRequest;
return this.http.post(this.chatUrl, body, {headers: new HttpHeaders({ 'Content-Type': 'application/json', 'X-Auth-Token': token })})
.pipe(
map(response => new NmChatRequest(response)),
catchError(this.handleError)
);
}
What am I missing ?
Thanks to anyone who will take the time to read/answer this question.
I built a stackblitz from the above provided pieces. It seemed to work fine for me if I changed the json string to an object instead of an array.
So no outside brackets:
{"id":14,
"sender":
{"id":20,"email":"p.martelliere#gmail.com","username":"test5","roles":
["ROLE_USER"],"status":"active","note":"0","points":0,
"devices":[],"job":"Caisse","showJob":false,"notificationsActivated":true,
"connected":true,"tokenConfirm":"","birthDate":[]
},"receiver":
{"id":12,"email":"test2#yopmail.com","username":"test2","tokenConfirm":"",
"job":"g\u00e9rant","showJob":false,"note":"0","points":0,
"roles":["ROLE_USER"],"status":"active","notificationsActivated":true,
"connected":true,"devices":[]
},
"myNeed":"Te ster",
"whatICanGive":"1",
"messages":[],
"status":"active"
}
If you are indeed getting an array and not a single object, you may need to modify your code to pass in the first element of the array. Something like this:
map(response => new NmChatRequest(response[0]))
Here is the stackblitz: https://stackblitz.com/edit/angular-wgunjb?file=src%2Fapp%2Fapp.component.ts

Object name from variable in Actionscript

I am trying to use the string in a variable to create an item in an object.
Example non functioning code:
private var myName:String = 'group1';
private var _ins:Object = {
myName : {
data1: arr[0],
data2: arr[1]
}
}
I can not understand what syntax to use to make myName be 'group1' text. Currently I am using:
private var _ins:Object = {
'group1' : {
data1: arr[0],
data2: arr[1]
}
}
Syntax of generic objects in AS3 allow to omit quotes for the keys, but actually your code is:
private var myName:String = 'group1';
private var _ins:Object = {
"myName" : {
"data1": arr[0],
"data2": arr[1]
}
}
You should use myName as a variable, which contains a key.
private var myName:String = 'group1';
private var _ins:Object = {};
_ins[myName] = {
data1: arr[0],
data2: arr[1]
};

JSON is not working

I have one dropdown in the table.Once I make Onchange event I got all the table value and I want to convert it into json to send it to the servlet.
var item = [];
function dropDownOnChange(e) {
var selectedValue = e.options[e.selectedIndex].value;
alert("selectedValue:" + selectedValue);
var currentRow= $(e).closest("tr");
var AccountNo = $("td:eq(0)",$(currentRow)).text();
alert("accountno"+AccountNo);
var AccountType =$("td:eq(1)",$(currentRow)).text();
alert("acctyp"+AccountType);
var AcctypID = $("td:eq(3)",$(currentRow)).text();
alert("accID"+AcctypID);
Here I tried to convert it to JSON. I want to send this JSON value on my final save.
var objddlvalue = {};
objddlvalue["AccountNo"] = AccountNo;
objddlvalue["AccountType"] = AccountType;
objddlvalue["Account Type_Val"] = AcctypID;
objddlvalue["AccountStatus"] = selectedValue;
item.push(objddlvalue);
console.log(item);
jsonObj1 = JSON.stringify(item);
console.log(jsonObj1);
I am getting my JSON value like:
[{
"AccountNo": "89348734",
"AccountType": "Credit",
"Account Type_Val": "21",
"AccountStatus": "Invalid"
}]
When I check on online JSON checker it says the format is correct. But when I access it form servlet I can not parse it to jarray.
JSONObject jsonObj1 = (JSONObject)JSONValue.parse(request.getParameter("jsondata1"));
System.out.println("Json Object........"+jsonObj1.toJSONString());
JSONArray arr = (JSONArray) jsonObj.get(jsonObj1);
How to loop through my JSON object?
public static void main(String[] args) {
String jsonExternal = "[" +
"{"+
"\"AccountNo\": \"89348734\","+
"\"AccountType\": \"Credit\","+
"\"Account Type_Val\": \"21\","+
"\"AccountStatus\": \"Invalid\""+
"},"+
"{"+
"\"AccountNo\": \"89348734_test\","+
"\"AccountType\": \"Credit_test\","+
"\"Account Type_Val\": \"21_test\","+
"\"AccountStatus\": \"Invalid_test\""+
"}]";
JSONArray arr = (JSONArray)JSONValue.parse(jsonExternal);
for(Object obj : arr) {
JSONObject jsonObj = (JSONObject)obj;
Collection keySet = jsonObj.keySet();
Collection entrySet = jsonObj.entrySet();
Collection values = jsonObj.values();
for(Object o : keySet) {
System.out.println(o.toString());
}
for(Object o : entrySet) {
System.out.println(o.toString());
}
for(Object o : values) {
System.out.println(o.toString());
}
System.out.println(jsonObj.get("AccountNo"));
System.out.println(jsonObj.get("AccountType"));
System.out.println(jsonObj.get("Account Type_Val"));
System.out.println(jsonObj.get("AccountStatus"));
}
}

how can i pass parameter to linq query

i want to pass parameter to linq query...
public IEnumerable GetPhotos()
{
PhotoDBDataContext db = new PhotoDBDataContext();
var query = from p in db.Photos
orderby p.PhotoId descending
select new { p.Album, p.AlbumId, p.Description, p.Photographer,
p.PhotographerId, p.PhotoId, p.Tags, p.Thumbnail,
p.Url };
return query;
}
in above example "orderby p.PhotoId descending" is used, i want to use parameter in place of p.PhotoId
is it possible...
public IQueryable<Photo> GetPhotos(PhotoDBDataContext db, string orderBy)
{
var query = from p in db.Photos select p;
switch (orderBy) {
case "PhotoId":
return query.OrderBy(p => p.PhotoId);
case "AlbumId":
return query.OrderBy(p => p.AlbumId);
default:
// Error handling.
}
}
Note that you should not return objects with an anonymous type.
With Dynamic Linq, you can write .OrderBy("ColumnName").
You could do it like this if you had two order-by criteria
public static IQueryable<Photo> GetPhotos(string OrderBy)
{
return db.Photos.OrderBy(p => ( (OrderBy == "PhotoId") ? (p.PhotoId) : (p.AlbumId) ));
}
You could use an extension. This helped me:
public static class OrderExt
{
public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName, SortDirection descending, bool anotherLevel = false)
{
var param = Expression.Parameter(typeof(T), string.Empty);
var property = Expression.PropertyOrField(param, propertyName);
var sort = Expression.Lambda(property, param);
var call = Expression.Call(
typeof(Queryable),
(!anotherLevel ? "OrderBy" : "ThenBy") +
(descending == SortDirection.Descending ? "Descending" : string.Empty),
new[] { typeof(T), property.Type },
source.Expression,
Expression.Quote(sort));
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
}
For full explanation you could go to: http://how-to-code-net.blogspot.ro/2014/04/how-to-call-for-dynamic-orderby-method.html