Other ways of counting number of keywords in a complex string - actionscript-3

I am reading a file which contains approx 1200 words in the following format:
words:a:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin
I need to find how many keywords are there in that text file, by keyword i mean:
zen fix we sin ben six he bin
Right now I am trying to do it with RegExp like this:
var s:String = "words:b:sa:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin";
var pattern:RegExp = /:/+/g;
var results:Array = s.match(pattern);
trace(results.length);
Its producing an error, since I am a beginner I really don't understand how this RegExp work , are there any alternate methods to get the same results?
Thanks

Your var pattern:RegExp = /:/+/g; has a syntax error, you skipped a backslash \ change this to :
var pattern:RegExp = /:\/+/g;
and it should work, Alternatively with this format you can use the String split method to get the total word count. Try this:
var s:String = "words:b:sa:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin";
var wordCount:Number = s.split(":/").length -1;
trace( wordCount );
Hope that works.

package
{
import flash.display.Sprite;
public class CountWordsExample extends Sprite
{
public function CountWordsExample()
{
super();
// 8 7 0
trace(countWords(
"words:b:sa:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin",
":/"),
countWords(
"words:b:sa:/:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin",
":/"),
countWords(
"words:b:sa::zenb::fixx::wew::sina::benb::sixx::hew::bin",
":/"));
}
public static function countWords(words:String, delimiter:String,
countBlanks:Boolean = false):uint
{
var result:uint;
var wordPointer:int = -1;
var delimiterPointer:int;
var delimiterLength:uint = delimiter.length;
if (words.length >= delimiterLength)
{
do
{
delimiterPointer = wordPointer;
wordPointer = words.indexOf(
delimiter, wordPointer + delimiterLength);
if (countBlanks ||
// we moved by more characters, then the length of
// delimiter
wordPointer - delimiterLength > delimiterPointer)
result++;
}
while (wordPointer > -1)
}
return result;
}
}
}
Here's an example of how to count words without ever creating additional arrays or sub-strings of the original string. It also verifies that the words counted have at least one character length.

Related

Script that would find and mark the same words in the paragraph

I'm a fiction writer and I used to do my writing in MS Word. I've written some macros to help me edit the fiction text and one of them check the paragraph and marks (red) the duplicate (or triplicate words, etc). Example:
"I came **home**. And while at **home** I did this and that."
Word "home" is used twice and worth checking if I really can't change the sentence.
Now I mostly use google documents for writing, but I still have to do my editing in MS Word, mostly just because of this macro - I am not able to program it in the google script.
function PobarvajBesede() {
var doc = DocumentApp.getActiveDocument();
var cursor = DocumentApp.getActiveDocument().getCursor();
var surroundingText = cursor.getSurroundingText().getText();
var WordsString = WORDS(surroundingText);
Logger.log(WordsString);
//so far, so good. But this doesn't work:
var SortedWordsString = SORT(WordsString[1],1,False);
// and I'm lost.
}
function WORDS(input) {
var input = input.toString();
var inputSplit = input.split(" ");
// Logger.log(inputSplit);
inputSplit = inputSplit.toString();
var punctuationless = inputSplit.replace(/[.,\/#!$%\?^&\*;:{}=\-_`~()]/g," ");
var finalString = punctuationless.replace(/\s{2,}/g," ");
finalString = finalString.toLowerCase();
return finalString.split(" ") ;
}
If I could only get a list of words (in uppercase, longer than 3 characters), sorted by the number of their appearances in the logger, it would help me a lot:
HOME (2)
AND (1)
...
Thank you.
Flow:
Transform the string to upper case and sanitize the string of all non ascii characters
After splitting the string to word array, reduce the array to a object of word:count
Map the reduced object to a 2D array [[word,count of this word],[..],...] and sort the array by the inner array's count.
Snippet:
function wordCount(str) {
str = str || 'I came **home**. And while at **home** I did this and that.';
var countObj = str
.toUpperCase() //'I CAME **HOME**...'
.replace(/[^A-Z ]/g, '') //'I CAME HOME...'
.split(' ') //['I', 'CAME',..]
.reduce(function(obj, word) {
if (word.length >= 3) {
obj[word] = obj[word] ? ++obj[word] : 1;
}
return obj;
}, {}); //{HOME:2,DID:1}
return Object.keys(countObj)
.map(function(word) {
return [word, countObj[word]];
}) //[['HOME',2],['CAME',1],...]
.sort(function(a, b) {
return b[1] - a[1];
});
}
console.info(wordCount());
To read and practice:
Object
Array methods
This is a combination of TheMaster answer and some of my work. I need to learn more about the way he did it so I spent some learning time today. This function eliminates some problems I was having the carriage returns and it also removes items that only appear once. You should probably pick TheMasters solution as I couldn't have done it without his work.
function getDuplicateWords() {
var str=DocumentApp.getActiveDocument().getBody().getText();
var countObj = str
.toUpperCase()
.replace(/\n/g,' ')
.replace(/[^A-Z ]/g, '')
.split(' ')
.reduce(function(obj, word) {
if (word.length >= 2) {
obj[word] = obj[word] ? ++obj[word] : 1;
}
return obj;
}, {});
var oA=Object.keys(countObj).map(function(word){return [word, countObj[word]];}).filter(function(elem){return elem[1]>1;}).sort(function(a,b){return b[1]-a[1]});
var userInterface=HtmlService.createHtmlOutput(oA.join("<br />"));
DocumentApp.getUi().showSidebar(userInterface);
}
function onOpen() {
DocumentApp.getUi().createMenu('MyMenu')
.addItem('Get Duplicates','getDuplicateWords' )
.addToUi();
}
And yes I was having problems with get the results to change in my last solution.

How can I order my string in as3

A complex question :
I've got this code (not the complete code, but the essentials for the question, I think) :
var $pmm:String;
var $pms:String;
var $bmm:String;
var $bms:String;
function get haute1():String { return $pmm; };
function get haute2():String { return $pms; }
function get basse1():String { return $bmm; };
function get basse2():String { return $bms; };
accueil.todayHaute_txt.htmlText = haute1;
accueil.todayBasse_txt.htmlText = basse1;
accueil.todayHauteSecond_txt.htmlText = haute2;
accueil.todayBasseSecond_txt.htmlText = basse2;
"haute1" is an hour (in 24h format). Something like "13h25".
It changes everyday.
Question : How can put them in ascending order in AS3 ?
Example : If haute1 = 15h20, haute2= 6h00, basse1= 11h and basse2 = 17h, the function would put them in this order :
"haute2", then "basse1", then "haute1" and finally "basse2".
Thx
EDIT
I add this code that I have. is it helping you ?
/ Assigns hours and tidal heights
$pmm = convdateheure($tpbs[1 + $deltapm]);
$pms = convdateheure($tpbs[3 + $deltapm]);
$bmm = convdateheure($tpbs[2 - $deltapm]);
$bms = convdateheure($tpbs[4 - $deltapm]);
function convdateheure($valeur:Number):String
{
var $heure:Number = Math.floor($valeur);
var $minute:Number = Math.floor(Math.floor(($valeur - Math.floor($valeur)) * 100) * 0.6);
var hoursLabel:String = "", minsLabel:String = "";
if ($heure == 24) $heure = 0; // Check if at the 24 hour mark, change to 0
if ($heure < 10) hoursLabel += "0" + $heure.toString(); else hoursLabel = $heure.toString();
if ($minute < 10) minsLabel += "0" + $minute.toString(); else minsLabel = $minute.toString();
return hoursLabel + ":" + minsLabel;
}
If you want to order some dates written in some String format:
One way would be, depending on you date string format, just to push them into array and sort them as strings, then read them all.
Another way would be to first parse those strings into Date instances, and push their Date.time property to array, sort it, then do reverse: parse all time values from sorted array into new Date instances then use Date.toString or similar.
Assuming that $valuer is a numerical value:
var timesArray:Array = new Array();
var convertedTimesArray:Array = new Array();
function sortTimes():void{
timesArray.push($valuer);
timesArray.sort(Array.NUMERIC);
}
function convertTimes():void{
convertedTimesArray = []; // clear the array
for (var i:int = 0; i < timesArray.length; i++){
var s:String = convdateheure(timesArray[i]);
convertedTimesArray.push(s);
}
}
That should give you one array of actual times, sorted in numerical order, and one array sorted in the same numerical order, but converted to String values using your function.

I have a function that changes months into numbers, but I'd like to add 0 before the month's number

I have a date like:
19/août/2016 (août = august)
And I have the following function which changes the month into a number:
function swapMonthForNumber(str:String):String {
//do the same line of code for every item in the array
for(var i:int=0;i<months.length;i++){
//i is the item, which is 0 based, so we have to add 1 to make the right month number
str = str.replace(months[i],String(+i+1));
}
//return the updated string
return str;
}
str = swapMonthForNumber(mySharedObject.data.theDate);
trace("Php will use this date :"+str);
So str will be 19/8/2016, but I want str to be 19/08/2016 (adding a 0 before the 8).
How can I do this?
Check out the reference of the Date class!
If forgot to mention this link : flash.globalization.DateTimeFormatter
DateTimeFormatter(requestedLocaleIDName:String, dateStyle:String = "long", timeStyle:String = "long")
Here is an example.
import flash.globalization.DateTimeFormatter;
var df:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE);
var currentDate:Date = new Date(2016,7,19);
var shortDate:String = df.format(currentDate);
trace (shortDate);
// output : 19/08/2016
DateTimeStyle
LocaleID
Adding leading zeros to a number is commonly called zero padding.
Below is a function to do this, from the answer here.
public function zeroPad(number:int, width:int):String {
var ret:String = ""+number;
while( ret.length < width )
ret="0" + ret;
return ret;
}
In your swapMonthForNumber function, in the for loop, swap the code for this:
var month = zeroPad(i + 1, 2);
str = str.replace(months[i], month);

Javascript: Using reviver function, I seem can't get to alter all the keys, while concating the numbers

I just want to change all the keys in batchesX. But I can't seem to alter all keys, because of concat. This is what I learned from post.
Please advise how I can change all keys with numbers.
var batchesX = '[{"batch":"0010002033"},{"batch":"0010001917"},{"batch":"0000020026"},{"batch":"0000017734"},'+
'{"batch":"0000015376"},{"batch":"0000014442"},{"batch":"0000014434"},{"batch":"0000014426"},'+
'{"batch":"0000013280"},{"batch":"0000012078"},{"batch":"0000012075"},{"batch":"0000012072"},'+
'{"batch":"0000011530"},{"batch":"0000011527"},{"batch":"0000011342"},{"batch":"0000010989"},'+
'{"batch":"0000010477"},{"batch":"0000008097"},{"batch":"0000007474"},{"batch":"0000006989"},'+
'{"batch":"0000004801"},{"batch":"0000003566"},{"batch":"0000003565"},{"batch":"0000001392"},'+
'{"batch":"0000001391"},{"batch":"0000000356"},{"batch":"0000"},{"batch":"000"},{"batch":""},'+
'{"batch":null}]'; // 30 elements
//in JSON text
var batchi = "batch";
var obj_batchesY = JSON.parse(batchesX);
console.debug(obj_batchesY);
var obj_batchesYlength = obj_batchesY.length;
console.debug(obj_batchesYlength);
var obj_batchesX = JSON.parse(batchesX,
function(k,v)
{
for(var i=1; i <= obj_batchesYlength; i++ )
{
if(k=="batch")
{
this.batchi.concat(string(i)) = v;
}
else
return v;
}
}
);
console.debug(obj_batchesX);
Is the code too long winded?
Many thanks in advance.
Clement
The return value of the reviver function only replaces values. If you need to replace keys, then use stringify and replace before the parse call, like this:
JSON.parse(JSON.stringify({"alpha":"zulu"}).replace('"alpha":','"omega":'))
Here is how to replace all numeric keys:
function newkey()
{
return Number(Math.random() * 100).toPrecision(2) + RegExp.$1
}
//Stringify JSON
var foo = JSON.stringify({"123":"ashanga", "12":"bantu"});
//Replace each key with a random number without replacing the ": delimiter
var bar = foo.replace(/\d+("?:)/g, newkey)
//Parse resulting string
var baz = JSON.parse(bar);
Make sure each replaced key is unique, since duplicate keys will be removed by the parse method.

Multipass login to assistly.com with as3crypto

I'm trying to automatically login my users into assistly.com with their multipass login as described here: http://dev.assistly.com/docs/portal/multipass
I have tried to convert their code examples ( https://github.com/assistly/multipass-examples) to Actionscript using as3crypto, obviously without success.
Here's what I have:
package
{
import com.adobe.crypto.SHA1;
import com.adobe.serialization.json.JSON;
import com.hurlant.crypto.*
import com.hurlant.util.Base64;
import flash.utils.ByteArray;
public class AssistlySingleSignOn
{
protected static var API_SITE_KEY:String = "YOUR SITE KEY"
protected static var MULTIPASS_KEY:String = "YOUR MULTIPASS API KEY"
public function AssistlySingleSignOn()
{
}
public static function generateMultipass(uid:String, username:String, email:String):String
{
var o:Object = {};
o.uid = uid;
o.expires = "2012-12-29T10:25:28-08:00";
o.customer_email = email;
o.customer_name = username;
var salted:String = API_SITE_KEY + MULTIPASS_KEY;
var hash:String = SHA1.hash(salted);
var saltedHash:String = hash.substr(0, 16);
var iv:String = "OpenSSL for Ruby";
var ivByteArray:ByteArray = new ByteArray();
ivByteArray.writeUTFBytes(iv);
var key:ByteArray = new ByteArray();
key.writeUTFBytes(saltedHash);
key.position = 0;
var json:String = JSON.encode(o);
var jsonByteArray:ByteArray = new ByteArray();
jsonByteArray.writeUTFBytes(json);
var padding:IPad = new PKCS5(16);
ivByteArray.position = 0;
key.position = 0;
var cyphered:CBCMode = Crypto.getCipher("aes-128-cbc", key, padding) as CBCMode;
jsonByteArray.position = 0;
cyphered.IV = ivByteArray;
cyphered.encrypt(jsonByteArray);
jsonByteArray.position = 0;
var base64:String = Base64.encode(jsonByteArray.readUTFBytes(jsonByteArray.length));
/*Convert to a URL safe string by performing the following
Remove any newlines
Remove trailing equal (=) characters
Change any plus (+) characters to dashes (-)
Change any slashes (/) characters to underscores (_)*/
base64 = base64.replace(/\n/g, "");
base64 = base64.replace(/=/g, "");
base64 = base64.replace(/+/g, "-");
base64 = base64.replace(/\//g, "_");
return base64;
}
}
}
I'm assuming that I'm doing something wrong with the IV stuff or the padding, because I don't quite understand it ;-)
You might want to use a different crypto class, or modify the as3crypto one. I know there are inconsistencies in the SHA1 function vs. the PHP sha1 function. See this:
sha1 hash from as3crypto differs from the one made with PHP
This could be making your values invalid. My recommendation would be to trace out all your data as it's being calculated and run it against the same things in PHP or another of the examples in github. See where the data diverges. I'm betting it's going to be issues relating to AS3Crypto.