How does one format a number with commas? - sencha-touch
In Sencha Touch 2, how does one format a number with commas with either 0 or 2 decimal places? I imagine that there's a built in way to do this?
For example, I have 1234.567 and I need the number as 1,234 and 1,234.57.
You can do it easily with JavaScript only :
Add commas to the number
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Round to the nearest integer
var result = Math.round(original)
Round to two decimals
var result = Math.round(original*100)/100
Hope this helps
Take a look at this function from Ext JS 4's Ext.util.Format, which is not part of the Sencha Touch 2 API. Just implement it in your application and you're set.
http://docs.sencha.com/ext-js/4-1/source/Format.html#Ext-util-Format-method-number
function iFormatValueTwoDecimals(inValue)
{
var leftSide = Math.floor(inValue);
var rightSide = Math.round((inValue - leftSide)*100);
if(rightSide === 0)
{
rightSide = '00';
}
else if(rightSide < 10)
{
rightSide = rightSide + '0';
}
return leftSide+'.'+rightSide;
}
Related
Why doesn't this While loop work as intended?
Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance. fun main () { while(true) { println ("\nWrite a positive number: ") var num = readLine()!!.toInt() var sum = 0 if (num > 9) { while (num > 9) { var digit = num % 10 sum = sum + digit num = num / 10 } println("\nDigit Sum: $sum") } else if (num in 1..9) { println("\nDigit Sum for the number $num is $num") } else { println("\nInvalid input, try again.") } } }
The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following: fun main() { while(true) { println ("\nWrite a positive number: ") val insertedNumber = readLine()!!.toInt() var num = insertedNumber var sum = 0 while (num > 9) { val digit = num % 10 sum = sum + digit num = num / 10 } sum = sum + num println("\nDigit Sum for the number $insertedNumber is $sum") } }
You don't need to redeclare the variables every time var sum = sum + digit var num = num / 10 So simply remove var sum = sum + digit num = num / 10
How to make a report parameter selection change another report parameter selection values while allowing multiselect for both of them?
Lets say I have a table with a list of names, such as "a, b, c" and each name has several other values assigned (some of the other values can be assigned to several/all of names values, example below). Table example: ( names - other ): a - aa a - ab a - ac b - ab b - bb b - cb c - ac c - bc c - cc How do I make in birt so that I could select names in one parameter box and get corresponding other values to select for another parameter? I know it's possible to do that with cascading parameter, but that doesn't allow to have multiselect for the first parameter, which in our example would be names values.
Found a solution partly here: https://forums.opentext.com/forums/developer/discussion/61283/allow-multi-value-for-cascading-parameter and here (thanks google translate ^^): https://www.developpez.net/forums/d1402270/logiciels/solutions-d-entreprise/business-intelligence/birt/birt-4-3-1-multi-value-cascade-parameters/ Steps to do: change"\birt\webcontent\birt\ajax\ui\dialog\BirtParameterDialog.js" file contents (there is a file to download for replacement in one of the links, but in case it goes dead I'm sharing 2 snippets from it where the changes occur: __refresh_cascade_select : function( element ) { var matrix = new Array( ); var m = 0; for( var i = 0; i < this.__cascadingParameter.length; i++ ) { for( var j = 0; j < this.__cascadingParameter[i].length; j++ ) { var paramName = this.__cascadingParameter[i][j].name; if( paramName == this.__isnull ) paramName = this.__cascadingParameter[i][j].value; if( paramName == element.id.substr( 0, element.id.length - 10 ) ) { //CHANGE// //The two way work (String(selectedValue) or Array(SelectedValueArray)) var l = 0; var isFirstElement = true; var selectedValue = ""; var selectedValueArray = new Array(); for(var test = 0; test<element.options.length;test++){ if(element.options[test].selected){ if(isFirstElement){ isFirstElement = false; selectedValue = element.options[test].value; } else{ selectedValue = selectedValue+","+element.options[test].value; } selectedValueArray[l] = element.options[test].value; l++; } } //CHANGE// var tempText = element.options[element.selectedIndex].text; var tempValue = element.options[element.selectedIndex].value; // Null Value Parameter if ( tempValue == Constants.nullValue ) { this.__cascadingParameter[i][j].name = this.__isnull; this.__cascadingParameter[i][j].value = paramName; } else if( tempValue == '' ) { if( tempText == "" ) { var target = element; target = target.parentNode; var oInputs = target.getElementsByTagName( "input" ); if( oInputs.length >0 && oInputs[1].value != Constants.TYPE_STRING ) { // Only String parameter allows blank value alert( birtUtility.formatMessage( Constants.error.parameterNotAllowBlank, paramName ) ); this.__clearSubCascadingParameter( this.__cascadingParameter[i], j ); return; } else { // Blank Value this.__cascadingParameter[i][j].name = paramName; this.__cascadingParameter[i][j].value = tempValue; } } else { // Blank Value this.__cascadingParameter[i][j].name = paramName; this.__cascadingParameter[i][j].value = tempValue; } } else { this.__cascadingParameter[i][j].name = paramName; //CHANGE// //The two way work (String(selectedValue) or Array(SelectedValueArray)) this.__cascadingParameter[i][j].value = selectedValueArray; //CHANGE// } for( var m = 0; m <= j; m++ ) { if( !matrix[m] ) { matrix[m] = {}; } matrix[m].name = this.__cascadingParameter[i][m].name; matrix[m].value = this.__cascadingParameter[i][m].value; } this.__pendingCascadingCalls++; birtEventDispatcher.broadcastEvent( birtEvent.__E_CASCADING_PARAMETER, matrix ); } } } }, and this: // exist select control and input text/password // compare the parent div offsetTop if( oFirstITC.parentNode && oFirstST.parentNode ) { // Bugzilla 265615: need to use cumulative offset for special cases // where one element is inside a group container var offsetITC = Position.cumulativeOffset( oFirstITC ); var offsetST = Position.cumulativeOffset( oFirstST ); // compare y-offset first, then x-offset to determine the visual order if( ( offsetITC[1] > offsetST[1] ) || ( offsetITC[1] == offsetST[1] && offsetITC[0] > offsetST[0] ) ) { oFirstST.focus( ); } else { oFirstITC.focus( ); } } After .js is changed cascading parameters can have multiselect on all levels. Example: 1st DataSet "DS_country" query: select CLASSICMODELS.OFFICES.COUNTRY from CLASSICMODELS.OFFICES 2nd DataSet "DS_office" query: select CLASSICMODELS.OFFICES.OFFICECODE from CLASSICMODELS.OFFICES where CLASSICMODELS.OFFICES.COUNTRY IN ('DS_country') After datasets are created we can make cascading report parameters CRP_country and CRP_office (keep in mind that UI doesn't let you to choose "Allow multiple values" on the upper levels, but we can change that in property editor after the parameters are made by going to advanced tab and changing "Scalar parameter type" property value to "Multi Value") The only thing left is to pick lower level cascading parameters (CRP_office in our example) and go to script tab and add this on "beforeOpen": // Do that if your selections are in String type. var stringArray = params["CRP_country"].value.toString().split(","); var result = ""; for(var i =0 ; i < stringArray.length ; i++){ if(i==0){ result = "'"+stringArray[i]+"'"; } else{ result = result+",'"+stringArray[i]+"'"; } } // For String this.queryText = this.queryText.replace("'DS_country'", result); //For integer (the first part is useless) //this.queryText = this.queryText.replace("'DS_country'", params["CRP_country"].value);
Kotlin decomposing numbers into powers of 2
Hi I am writing an app in kotlin and need to decompose a number into powers of 2. I have already done this in c#, PHP and swift but kotlin works differently somehow. having researched this I believe it is something to do with the numbers in my code going negative somewhere and that the solution lies in declaring one or more of the variable as "Long" to prevent this from happening but i have not been able to figure out how to do this. here is my code: var salads = StringBuilder() var value = 127 var j=0 while (j < 256) { var mask = 1 shl j if(value != 0 && mask != 0) { salads.append(mask) salads.append(",") } j += 1 } // salads = (salads.dropLast()) // removes the final "," println("Salads = $salads") This shoud output the following: 1,2,4,8,16,32,64 What I actually get is: 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648, Any ideas?
This works for the one input that you specified, at the very least: fun powersOfTwo(value :Long): String { val result = ArrayList<String>() var i = 0 var lastMask = 0 while (lastMask < value) { val mask = 1 shl i if (value != 0.toLong() && mask < value) { result.add(mask.toString()) } lastMask = mask i += 1 } return result.joinToString(",") } Ran it in a unit test: #Test fun addition_isCorrect() { val result = powersOfTwo(127) assertEquals("1,2,4,8,16,32,64", result) } Test passed.
You can get a list of all powers of two that fit in Int and test each of them for whether the value contains it with the infix function and: val value = 126 val powersOfTwo = (0 until Int.SIZE_BITS).map { n -> 1 shl n } println(powersOfTwo.filter { p -> value and p != 0}.joinToString(",")) // prints: 2,4,8,16,32,64 See the entire code in Kotlin playground: https://pl.kotl.in/f4CZtmCyI
Hi I finally managed to get this working properly: fun decomposeByTwo(value :Int): String { val result = ArrayList<String>() var value = value var j = 0 while (j < 256) { var mask = 1 shl j if ((value and mask) != 0) { value -= mask result.add(mask.toString()) } j += 1 } return result.toString() } I hope this helps someone trying to get a handle on bitwise options!
Somehow you want to do the "bitwise AND" of "value" and "mask" to determine if the j-th bit of "value" is set. I think you just forgot that test in your kotlin implementation.
Conditional Formatting With Icons Epplus
I need to achieve something like this with Epplus. Can someone guide me with the code I need to use.
Following is the code to do exactly what you want but it is for three icon set you can change it based on your icons. I'm setting red color arrow if value is greater than 4,yellow color arrow if value is between 1 and 4 and, finally, green color if it is less than 1. Just change "AddThreeIconSet" to your icons. You should get the idea with this. for (int j = 2; j <= 9; j++) // Loop through columns { for (int i = 3; i <= 12; i++) // Loop through rows { // gets only the current cell as range ExcelRange rng = worksheet.Cells[i, j, i, j]; ExcelAddress address = new ExcelAddress(rng.Address); // Get the value of the current cell if(Convert.ToDouble(worksheet.Cells[i, j].Value) >= 4.0) { var v = worksheet.ConditionalFormatting.AddThreeIconSet(address, eExcelconditionalFormatting3IconsSetType.Arrows); v.Reverse = true; v.Icon1.Type = eExcelConditionalFormattingValueObjectType.Num; } else if (Convert.ToDouble(workSheet.Cells[i, j].Value) > 1.0 && Convert.ToDouble(workSheet.Cells[i, j].Value) < 4.0) { var v = worksheet.ConditionalFormatting.AddThreeIconSet(address , eExcelconditionalFormatting3IconsSetType.Arrows); v.Icon3.Type = eExcelConditionalFormattingValueObjectType.Num; } else if (Convert.ToDouble(workSheet.Cells[i, j].Value) < 1.0) { var v = worksheet.ConditionalFormatting.AddThreeIconSet(address , eExcelconditionalFormatting3IconsSetType.Arrows); v.Icon2.Type = eExcelConditionalFormattingValueObjectType.Num; } } }
apply bind pose to a kinect skeleton
I want to normalize a skeleton in order to make it invariant to the size of the person in front of the kinect; in the same way as the aveteering example. But I don't want to animate a 3D model using XNA, the only thing I need is to normalize an skeleton. So in order to do this task, I have divided it in two functions: (a) apply a bind pose to an skeleton in order to see how to work this matrix. Obviously this is not what i want to do, but it is a first step in order to know how to work whit matrix, and so on. (b) apply any arbitrary pose to a normalized-size-skeleton First of all, I want to apply a bind pose to an skeleton (a). First, I have to load the matrix that describe the bone length/ offset between bones and store it in List BindPose. Due to I have no idea how to do it, I modified the Aveteering example and write in a file all the Matrix that define the BindPose, InverseBindPose and SkeletonHierarchy of the dude. I only need BindPose to this first task, but I have the code prepared in order to do the second task (b) The file looks like this: 1,331581E-06;-5,551115E-17;1;0;1;-4,16881E-11;-1,331581E-06;0;4,16881E-11;1;8,153579E-23;0;0,03756338;37,46099;2,230549;1 1,110223E-16;-4,435054E-22;1;0;1;1,426127E-06;-2,220446E-16;0;-1,426127E-06;1;-7,654181E-22;0;-0,9558675;-4,079016E-08;-6,266987E-12;1 0,9954988;-0,09477358;1,501821E-06;0;0,09477358;0,9954988;-4,019565E-06;0;-1,114112E-06;4,143805E-06;1;0;3,786007;-0,003599779;5,107028E-06;1 0,9948416;-0,101441;-3,23556E-07;0;0,101441;0,9948416;-2,266755E-08;0;3,241862E-07;-1,027114E-08;1;0;4,543321;-0,00359975;-1,33061E-07;1 0,9950595;0,09927933;2,388133E-07;0;-0,09927933;0,9950595;-2,333792E-08;0;-2,399506E-07;-4,86646E-10;1;0;4,544049;-0,003599948;6,324596E-08;1 0,9992647;0,02747673;0,02674458;0;-0,02928042;0,9971476;0,06956656;0;-0,02475683;-0,07029849;0,9972187;0;4,543965;-0,004398902;2,258555E-07;1 0,9154034;0,4025377;1,107153E-06;0;-0,4025377;0,9154033;-2,437432E-07;0;-1,109319E-06;-2,115673E-07;1;0;5,536249;-0,00288291;1,332601E-07;1 0,9812952;-0,1925096;-4,732622E-07;0;0,1925095;0,9812951;-3,00921E-08;0;4,697166E-07;-5,889972E-08;1;0;3,953898;1,702301E-07;4,88653E-08;1 ....... So each line is a 4X4 matrix defining the BindPose. To generate this file, the code is like this: private void ViewSkinningData(SkinningData data) { string nameFile = "bind_pose_transformations"; bool append = false; // The using statement automatically closes the stream and calls IDisposable.Dispose on the stream object. using (System.IO.StreamWriter file = new System.IO.StreamWriter(#nameFile, append)) { for (int i = 0; i < data.BindPose.Count; i++) { Matrix m = data.BindPose[i]; string matrixString = MatrixToString(m); file.WriteLine(matrixString); } for (int i = 0; i < data.InverseBindPose.Count; i++) { Matrix m = data.InverseBindPose[i]; string matrixString = MatrixToString(m); file.WriteLine(matrixString); } for (int i = 0; i < data.SkeletonHierarchy.Count; i++) { file.Write(data.SkeletonHierarchy[i] + ";"); } } } string MatrixToString(Matrix m) { string result; result = m.M11 + ";" + m.M12 + ";" + m.M13 + ";" + m.M14 + ";" + m.M21 + ";" + m.M22 + ";" + m.M23 + ";" + m.M24 + ";" + m.M31 + ";" + m.M32 + ";" + m.M33 + ";" + m.M34 + ";" + m.M41 + ";" + m.M42 + ";" + m.M43 + ";" + m.M44; return result; } Next step is to load all this Skinning data in my program: private void InitializeSkinningDataFromFile() { string filename = "bind_pose_transformations"; int number_avatar_joints = 58; List<Matrix> binpose = new System.Collections.Generic.List<Matrix>(); List<Matrix> inversebindpose = new System.Collections.Generic.List<Matrix>(); List<int> skeletonhierarchy = new System.Collections.Generic.List<int>(); // The using statement automatically closes the stream and calls IDisposable.Dispose on the stream object. using (System.IO.StreamReader file = new System.IO.StreamReader(filename)) { string s; int count = 0; while (!String.IsNullOrEmpty(s = file.ReadLine())) { string[] values = s.Split(';'); Matrix m = BuildMatrix(values); binpose.Add(m); count++; if (count == number_avatar_joints) { break; } } count = 0; while (!String.IsNullOrEmpty(s = file.ReadLine())) { string[] values = s.Split(';'); Matrix m = BuildMatrix(values); inversebindpose.Add(m); count++; if (count == number_avatar_joints) { break; } } string[] skeletonHierarchy = file.ReadLine().Split(';'); //lee un caracter de separacion al final... //for (int i = 0; i < skeletonHierarchy.Count(); i++) for (int i = 0; i < number_avatar_joints; i++) { skeletonhierarchy.Add(int.Parse(skeletonHierarchy[i])); } } skinningDataValue = new SkinningData(binpose, inversebindpose, skeletonhierarchy); } After, I have to construct boneTransforms structure: // Bone matrices for the "dude" model this.boneTransforms = new Matrix[skinningDataValue.BindPose.Count]; this.skinningDataValue.BindPose.CopyTo(this.boneTransforms, 0); Now boneTransforms have the transformation for my skeleton. So now, i have to apply these trasnformations to an skeleton Skeleton skeleton = new Skeleton(); foreach (Joint joint in skeleton.Joints) { int indexMatrix = AvatarBoneToNuiJointIndex(joint.JointType); Matrix transform; if (indexMatrix >= 0) { transform = this.boneTransforms[indexMatrix]; } else { transform = Matrix.Identity; } Joint aux = ApplyMatrixTransformationToJoint(joint, transform); normalizeSkel.Joints[joint.JointType] = aux; } This is a helper function AvatarBoneToNuiJointIndex: public int AvatarBoneToNuiJointIndex(JointType jointType) { switch (jointType) { case JointType.HipCenter: return 1; case JointType.Spine: return 4; case JointType.ShoulderCenter: return 6; case JointType.Head: return 7; case JointType.ShoulderLeft: return 12; case JointType.ElbowLeft: return 13; case JointType.WristLeft: return 14; case JointType.HandLeft: return 15; case JointType.ShoulderRight: return 31; case JointType.ElbowRight: return 32; case JointType.WristRight: return 33; case JointType.HandRight: return 34; case JointType.KneeLeft: return 50; case JointType.AnkleLeft: return 51; case JointType.FootLeft: return 52; case JointType.KneeRight: return 54; case JointType.AnkleRight: return 55; case JointType.FootRight: return 56; default: return -1; } } This is a helper function ApplyMatrixTransformationToJoint: public Joint ApplyMatrixTransformationToJoint(Joint skeletonJoint, Matrix tranformations) { Vector3 pos = SkeletonPointToVector3(skeletonJoint.Position); Vector3 result = ApplyMatrixTransformationToVector(pos, tranformations); SkeletonPoint newPosition = new SkeletonPoint() { X = result.X, Y = result.Y, Z = result.Z }; skeletonJoint.Position = newPosition; return skeletonJoint; } This is the code for ApplyMatrixTransformationToVector: static Vector3 ApplyMatrixTransformationToVector(Vector3 v, Matrix m) { return Vector3.Transform(v, m); } But the problem is that I can't see anything. I don't know if this approach is correct. Any help would be fantastic. Many thanks!