I'm attempting to use the build in Functions in OrientDB studio to group Workstations that aren't in use by a Person. The query to get these vertices works fine but I'm trying to avoid Traverse as it is very slow - too slow to be used in production. Instead of iterating through each free station and grouping it together with all it's neighbours, keeping each grouped 'named' with the smallest #rid in the set.
var groups = {}; //The list of groups of workpoints. The key is the lowest RID in the group
var mappedDesks = {}; //Every desk's RID is in this object with it's matching value being the group name they're in
//Get all Workpoints that don't have a Locale CURRENTLY_LOCATED_ON them
var freeDesks = db.query("SELECT FROM Workpoint WHERE #rid NOT IN (SELECT #rid FROM (SELECT EXPAND(OUT('CURRENTLY_LOCATED_ON').OUT('LOCATED_ON')) FROM Person) WHERE #class = 'Workpoint')");
//Iterate through all vacant Workpoints
for (var j=0; j < freeDesks.length; j++){
var baseNodeRid = freeDesks[j].getRecord().getIdentity().toString(); // The RID of the Workpoint
var baseNodeNumber = parseFloat(baseNodeRid.replace("#", "").replace(":",".")); // The RID converted to a number for comparisons. The lower RID takes precedence
var baseSanitized = baseNodeRid.replace(":","-") // Keys cannot contain colon so they are replaced with a dash
if (freeDesks[j].getRecord().field("out_NEIGHBOUR_OF") == null ) {
// Desks without neighbours can be put in a group on their own
groups[baseSanitized] = new Array();
groups[baseSanitized].push(baseNodeRid);
mappedDesks[baseSanitized] = baseSanitized;
} else {
//Iterate over all the desk's neighbours
for (var n = 0; n < freeDesks[j].getRecord().field("out_NEIGHBOUR_OF").length; n++){
//Convert the neighbour's RID to a number too
var nSanitized = n.replace(":","-");
if (parseFloat(n.replace("#", "").replace(":",".")) > baseNodeNumber ){
//The neighbour's node group is larger than the current one. This needs to be merged into the group with the smaller rid
//Move the desks from the neighbour's group into the base's group. If it has none then do nothing
var nGroup = groups[mappedDesks[nSanitized]]
if ( nGroup != null) {
groups[baseSanitized] = groups[baseSanitized].concat(nGroup);
//Change the mapping of each moved desk to the base's
for (var g = 0; g < nGroup.length; g++){
mappedDesks[nGroup[g]] = baseSanitized;
}
}
//Delete the reference to the old group
delete groups[mappedDesks[nSanitized]];
//Update the mappings for the desks dealt with
mappedDesks[nSanitized] = baseSanitized;
mappedDesks[baseSanitized] = baseSanitized;
} else {
// The neighbour is lower than the current desk so the desk should be merged into the neighbour's group
mappedDesks[baseSanitized] = nSanitized;
groups[nSanitized].push(baseNodeRid);
}
}
}
}
return groups;
My problem comes from accessing a vertex's neighbours. It correctly determines whether there are neighbours in the if statement return freeDesks[j].getRecord().field("out_NEIGHBOUR_OF") but I want to be able to get each neighbour's #rid so I can sort the #rids into groups.
freeDesks[j].getRecord().field("out_NEIGHBOUR_OF") returns the edge record but I dont seem to be able to get the "in" or "out" fields using the field() method (not found on this object) or accessing it as an array [].
[
{
"#type": "d",
"#rid": "#34:18176",
"#version": 6,
"#class": "NEIGHBOUR_OF",
"out": "#16:13",
"in": "#16:1408",
"#fieldTypes": "out=x,in=x"
}
]
Can you help be get a list/array of the neighbour #rids so I can iterate over them with the rest of the code?
Cheers!
A simpler example to understand what you can do:
create class Person extends V
create class IsNeighbour extends E
create vertex Person set name = 'P1' // 12:0
create vertex Person set name = 'P2' // 12:1
create vertex Person set name = 'P3' // 12:2
create edge IsNeighbour from #12:0 to #12:1
create edge IsNeighbour from #12:0 to #12:2
Define this Javascript Function:
var gdb = orient.getGraphNoTx();
var v = gdb.command("sql", "select from " + personRID);
var neighbours = v[0].getRecord().field("out_IsNeighbour").iterator();
var result = [];
while(neighbours.hasNext()){
var neighbour = neighbours.next();
result.push(neighbour.field("in"));
}
return result;
like this:
And then you can:
select getNeighbours("#12:0")
Related
I have a multidimensional array created by taking data from a google spreadsheet. I am attempting to seperate out the data based on results in a specific column. For example:
var j = {
["Mine", "House"],
["Your", "House"],
["his", "apt"]
}
Given that we want to seperate by column 2. We should get in theory:
var new = {
[["Mine", "House"] , ["Your", "House"]],
[["his", "apt"]]
}
Two entries being a house, and 1 being an apartment. I am haveing a huge issue with treating each entry as its own obj. Assuming it is even possible. I guess we would access specific parts of each object like so, new[0][1][1]? This obviously shouldnt work like this. Is there another way to seperate the entries in the way I am attempting? As it stands right now, I believe my code is just creating the same number of rows as in the original data.
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.insertSheet("Report");
var data_sheet =spreadsheet.getSheetByName("Data");
var genCounsel_data = data_sheet.getRange(240, 1, 96, 7).getValues(); //get genCounseling data
var report_sheet = spreadsheet.getSheetByName("Report");
//setup key values for columns in report sheet
report_sheet.appendRow(["Student Service", "Unit Student Service Outcome", "Indicators Data Sources", "How indicator was measured", "Benchmark Data", "Assigned to do Assessment", "Email"])
//seperate out by SS outcomes
var genCounselDataByOutcomes = new Array(new Array()); //all responses for each outcome, also parrellel
var outcomes_freq = new Array(); //parrellel arrays
var found = false;
//get services and frequency;
for(var i=0; i<genCounsel_data.length; ++i){
genCounsel_data[i][OUTCOMES_COL].toString().toLowerCase();
for(var j=0; j<genCounselDataByOutcomes.length && !found; ++j){
if(genCounselDataByOutcomes[j][OUTCOMES_COL] == genCounsel_data[i][OUTCOMES_COL]){
genCounselDataByOutcomes[j].push(genCounsel_data[i]); //ADD to row with same outcomes
++outcomes_freq[j]; //update amount of entries in said outcome
found = true;
}
}
if(found == false){
genCounselDataByOutcomes.push(new Array);
genCounselDataByOutcomes[genCounselDataByOutcomes.length-1].push([genCounsel_data[i]]);
outcomes_freq.push(1);
}
else
found = false;
}
for(var i=0; i<outcomes_freq.length;++i)
Logger.log(outcomes_freq[i]);
//for each outcome select a random one and move entire row to sheet;
for(var i=0; i<genCounselDataByOutcomes.length; ++i){
Logger.log(genCounselDataByOutcomes[i]);
}
QUESTION:
How can I seperate my data as multiple objects in a row of an array and be able to access specific components of each entry as shown in my example above? If this is not exactly possible in this way, is there another solution to this issue?
First of all, your j and new (which by the way is not a valid var name) need a key if they are objects or to be used as array, like below:
var j = [
["Mine", "House"],
["Your", "House"],
["his", "apt"]
];
var newVar = [
[["Mine", "House"] , ["Your", "House"]],
[["his", "apt"]]
];
That said and fixed, you can iterate over your array of arrays and use the column you want to use as filter to get the unique values to be used to group the final result.
Here is the final result:
var j = [
["Mine", "House"],
["Your", "House"],
["his", "apt"]
];
var uniqueValues = [];
var indexColumn = 1; //Here you specify the column you want to use to filter/group the elements from j
j.forEach(function(element){
if(!uniqueValues.includes(element[indexColumn])){
uniqueValues.push(element[indexColumn]);
}
});
//Now you use the `uniqueValues` to filter the `j` array and generate the `groupedArrays` array, which is the one you are looking for:
var groupedArrays = [];
uniqueValues.forEach(function(uniqueValue){
groupedArrays.push(j.filter(function(element){
return element[indexColumn] === uniqueValue;
}));
});
console.log(groupedArrays);
I hope this helps you.
Good luck.
My problem is as follows: I am trying to take data as formatted in the 'names' variable in the snippet below, convert the string to array, then reorganize the array so the text is in the correct order. I am able to get the pieces I have put together to properly sort the first or last instance of a first & last name, but am seeking guidance on how to go about processing multiple names. The snippet below will return the last instance of the first & last name in the correct order. At this point, I am only looking to have the data returned as a properly sorted array, e.g.
if the input string is
names = "Bond, James & Banner, Bruce";
once processed should return: ['James', 'Bond,', '&', 'Bruce', 'Banner,']
As always I appreciate all the help I can get, thanks in advance!
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
idx = i;
}
}
namesArr.move(idx, idx+1);
console.log(namesArr);
You were close but this solution should work for you. Basically you need to update in the loop and increment the index i to account for the switch. Otherwise you will end up revisiting the first last name you switch.
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce & Guy, Other";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
namesArr.move(i, i+1);
i++;
}
}
console.log(namesArr);
Another solution could be by using String.prototype.match() and a regular expression \w+ to match the names:
var names = "Bond, James & Banner, Bruce & Licoln, Anna"; // ...
var arr_names = names.match(/\w+/g); // Match names
var res = [];
for (var i = 0; i < arr_names.length; i += 2) { // Step by 2
res.push(arr_names[i + 1]); // Push the name before
res.push(arr_names[i]); // Push the current name
res.push("&"); // Add "&"
}
res.splice((res.length - 1), 1); // Remove last "&"
console.log(res);
I've got this code that is sorting through the various items in after effects and returning all the compositions in the project, then I narrow it down based on the specific composition i'm looking for, in this case one ending with assemble. I get the name and that's great but what I really need is the index number to come along with the name, so that when I search for assemble I get a return of app.project.item(3), its index in the project window. Every time I try to get the number from the array all I seem to get is the total number of items which doesn't help.
Thanks.
function retrieveProjectItems(itemType){
var typeOptions = ["Composition", "Folder", "Footage"];
for(var t = 0; t<3; t++){
if(itemType == typeOptions[t]){
var proj, itemTotal, curItem, itemArray;
itemAry = [];
proj = app.project;
itemTotal = proj.numItems;
for(var i = 1; i <= itemTotal; i++){
curItem = proj.item(i);
//alert(curItem.name);
if(curItem.typeName == itemType){
itemAry[itemAry.length] = curItem.name;
}
}
return itemAry;
}
}
}
retrieveProjectItems("Composition");
//alert(comps); lists all COMPS in the Array
var comps = itemAry;
var compWithAssemble;
for(var i in comps){
if(comps[i].indexOf("assemble") > -1){ ///search for part of the name///////////////////////////////////
compWithAssemble = comps[i];
break;
}
}
// compWithAssemble has the string you are looking for.
alert(compWithAssemble);
//app.project.item(3).selected = true;
compWithAssemble.selected = true; //I'm looking to make this work...
I am assuming you want to programatically find the composition with a layer named "assemble"
This bit of code
if(comps[i].indexOf("assemble") > -1){ ///search for part of the name///////////////////////////////////
compWithAssemble = comps[i];
break;
}
does not give you the results you want because comps[i] is a object of CompItem, not an Array or a collection. You need to first retrieve the Layer Collection for each comp[i]. Then, when you have that LayerCollection, you can find the layer named "assemble" by using the .byName() method. If you don't get a returned layer, you'll receive null, otherwise, you'll receive a Layer Object.
It might look something like:
var comps = itemAry;
var compWithAssemble;
for (var i in comps){
if(comps[i].layers.byName("assemble") != null) {
compWithAssemble = comps[i];
break;
}
}
I'm trying to create a code that will take a sentence as a param, split that sentence into an array of words and then create a loop that checks if any of theses word matches a word in some other arrays.
In the example below, I have a sentence that contains the word "ski". This means that the return value should be categories.type3.
How can I have make the loop check this? Could I have a function switching between different categories ? (ie : if a word is not in action, look in adventure and so on).
var categories = {
type1: "action",
type2: "adventure",
type3: "sport"
}
var Sentence = "This sentence contains the word ski";
var sport = ["soccer", "tennis", "Ski"];
var action = ["weapon", "explosions"];
var adventure = ["puzzle", "exploring"];
var myFreeFunc = function (Sentence) {
for (var i = 0; i < arrayLength; i++) {
if (typeArr[i] == word) {
}
}
}
You appear to want to know which categories match the sentence.
To start with, get rid of the meaningless type1 etc identifiers and re-arrange your fixed data into objects that directly represent the required data, specifically a Map of key/value pairs, where each key is a "category" name, and each value is a Set of keywords associated with that category:
var categories = new Map([
['action', new Set(['weapon', 'explosions'])],
['adventure', new Set(['puzzle', 'exploring'])],
['sport', new Set(['soccer', 'tennis', 'ski'])]
]);
[NB: Set and Map are new ES6 features. Polyfills are available]
You now have the ability to iterate over the categories map to get the list of categories, and over the contents of each category to find the key words:
function getCategories(sentence) {
var result = new Set();
var words = new Set(sentence.toLowerCase().split(/\b/g)); /* "/b" for word boundary */
categories.forEach(function(wordset, category) {
wordset.forEach(function(word) {
if (words.has(word)) {
result.add(category);
}
});
});
return result.values(); // NB: Iterator interface
}
NB: I've avoided for .. of because it's not possible to polyfill that, whereas Set.prototype.forEach and Map.prototype.forEach can be.
I would rewrite the code (you should always combine var statements).
I've added a small fiddle snippet, how i would rewrite the function. Just as an example, how you could iterate your data. Of course you should check out the other posts to optimise this code snipped ( e.g. fix for multiple spaces! ).
// make sure, your dictionary contains lower case words
var categories = {
action: ["soccer", "tennis", "ski"],
adventure: ["weapon", "explosions"],
sport: ["puzzle", "exploring"]
}
var myFreeFunc = function myFreeFunc(Sentence) {
// iterates over all keys on the categories object
for (var key in categories) {
// convert the sentence to lower case and split it on spaces
var words = Sentence.toLowerCase().split(' ');
// iterates the positions of the words-array
for (var wordIdx in words)
{
// output debug infos
console.log('test:', words[wordIdx], categories[key], categories[key].indexOf(words[wordIdx]) != -1, '('+categories[key].indexOf(words[wordIdx])+')');
// lets the array function 'indexOf' check for the word on position wordIdx in the words-array
if (categories[key].indexOf(words[wordIdx]) != -1 ) {
// output the found key
console.log('found', key);
// return the found key and stop searching by leaving the function
return key;
}
}//-for words
}//-for categories
// nothing found while iterating categories with all words
return null;
}
stripped down the function part snippet (no comments, no extra spaces, no console.log):
var myFreeFunc = function myFreeFunc(Sentence) {
for (var key in categories) {
var words = Sentence.toLowerCase().split(' ');
for (var wordIdx in words)
{
if (categories[key].indexOf(words[wordIdx]) != -1 ) {
return key;
}
}
}
return null;
}
Accumulated the topics covered in the comments
check if the Object really owns the property: obj.hasOwnProperty(prop)
split string by word bounds, as mentioned by Alnitak (using RegExp): /\b/g
collecting categories for multiple matching
Snippet:
var myFreeFunc = function myFreeFunc(Sentence) {
var result = []; // collection of results.
for (var key in categories) {
if (categories.hasOwnProperty(key)) { // check if it really is an owned key
var words = Sentence.toLowerCase().split(/\b/g); // splitting on word bounds
for (var wordIdx in words)
{
if (categories[key].indexOf(words[wordIdx]) != -1 ) {
result.push(key);
}
}
}
}
return result;
}
One simple way would be to do like this :
function determineCategory(word){
var dictionnary = {
// I assume here you don't need category1 and such
action: ["weapon", "explosions"],
aventure: ["puzzle", "exploring"],
sport: ["soccer", "tennis", "ski"]
}
var categories = Object.keys(dictionnary);
for(var i = 0; i<categories.length; i++){
for(var j = 0; j<categories[i].length;j++){
var wordCompared = dictionnary[categories[i]][j];
if(wordCompared == word){
return categories[i];
}
}
}
return "not found";
}
var sentence = "This sentence contains the word ski";
var words = sentence.split(" "); // simple separation into words
var result = [];
for(var i=0; i<words.length; i++){
result[i] = determineCategory(words[i]);
}
A few notes on this approach :
it needs you to change your existing structure (I don't know if its possible)
it doesn't do much for your sentence splitting (just using the white space). For more clever approach, see Alnitak's answer, or look for tokenization/lemmatization methods.
it is up to you to determine what to do when a word doesn't belong to a category (right now, it just stores "not found".
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.