Using variable names as property names in lodash _.findIndex - lodash

var ids = ["John", "Mary", "Joe", "Chase", "Sarah"];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var max = 25; // fixed for simplicity
var maxObj = _.findIndex(people['scores'], { id : max });
}
The above does not work as _.findIndex returns -1 for maxObj. However, if i explicitly define the property name as a string (instead of using the id variable), it works.
var maxObj = _.findIndex(people['scores'], { "John" : max });
Is there a way to pass variable values to the property name in lodash or an alternate way to achieve this using lodash?

You could construct an object literal using the dynamic key and then feed that to _.findIndex:
var ids = ["John", "Mary", "Joe", "Chase", "Sarah"];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var max = 25; // fixed for simplicity
var obj = {};
obj[id] = max;
var maxObj = _.findIndex(people['scores'], obj);
}

Related

Loop over path points in Photoshop

I'm trying to iterate over a create path in Photoshop finding out the anchor points position etc
var srcDoc = app.activeDocument;
// create the array of PathPointInfo objects
var lineArray = new Array();
lineArray.push(new PathPointInfo());
lineArray[0].kind = PointKind.CORNERPOINT;
lineArray[0].anchor = new Array(20, 160);
lineArray[0].leftDirection = [35, 200];
lineArray[0].rightDirection = lineArray[0].anchor;
lineArray.push(new PathPointInfo());
lineArray[1].kind = PointKind.CORNERPOINT;
lineArray[1].anchor = new Array(20, 40);
lineArray[1].leftDirection = lineArray[1].anchor;
lineArray[1].rightDirection = [220, 260];
// create a SubPathInfo object, which holds the line array in its entireSubPath property.
var lineSubPathArray = new Array();
lineSubPathArray.push(new SubPathInfo());
lineSubPathArray[0].operation = ShapeOperation.SHAPEXOR;
lineSubPathArray[0].closed = false;
lineSubPathArray[0].entireSubPath = lineArray;
//create the path item, passing subpath to add method
var myPathItem = srcDoc.pathItems.add("A Line", lineSubPathArray);
for (var i = 0; i < lineSubPathArray[0].entireSubPath.length; i++)
{
var b = lineSubPathArray[0].entireSubPath[i].anchor;
alert(b);
}
This works fine, but instead of creating the path and finding out it's information I want to loop over each path and get the same. This should be the same as the loop above only without explicitly calling lineSubPathArray and its parts.
for (var i = 0; i < srcDoc.pathItems[0].subPathItems.pathPoints.length; i++) // wrong I think
{
var b = srcDoc.pathItems[0].entireSubPath[i].anchor; // wrong
alert(b);
}
Almost: you need to iterate through subPathItems which consist of pathPoints:
var srcDoc = activeDocument;
var workPath = srcDoc.pathItems[0];
var i, k, b;
for (i = 0; i < workPath.subPathItems.length; i++) {
for (k = 0; k < workPath.subPathItems[i].pathPoints.length; k++) {
b = workPath.subPathItems[i].pathPoints[k].anchor;
alert(b);
}
}

realm react-native: how to query correctly an array of strings

can someone show me how to query an array of strings with realm in react-native?
assume i have an array like the following:
const preferences = ["automatic","suv","blue",eco]
What I want is to get realm results where ALL strings in the attribute "specifications" of Cars is in "preferences".
E.g.: If an instance of Cars.specifications contains ["automatic","suv"]
a result should be returned.
But if an instance of Cars.specifications contained ["automatic,"suv","green"] this instance shouldn't be returned.
The length of preferences can vary.
Thank you very much.
Update:
What i tried is the following:
const query = realm.objects("Cars").filtered('specifications = preferences[0] OR specifications = preferences[1]')
As you see it is an OR operator which is surely wrong and it is hardcoded. Looping with realm really confuses me.
This code will work!
const collection = realm.objects('Cars');
const preferences = ["automatic","suv","blue","eco"];
let queryString = 'ANY ';
for (let i = 0; i < preferences.length; i++) {
if (i === 0) {
queryString += `specifications CONTAINS '${preferences[i]}'`;
}
if (i !== 0 && i + 1 <= preferences.length) {
queryString += ` OR specifications CONTAINS '${preferences[i]}'`;
}
}
const matchedResult = collection.filtered(queryString);
example of function to test if a word is inside an array of word
function inArray(word, array) {
var lgth = array.length;
word = word.toLowerCase();
for (var i = 0; i < lgth; i++) {
array[i] = (array[i]).toLowerCase();
if (array[i] == word) return true;
}
return false;
}
const preferences = ["automatic","suv","blue","eco"];
const specifications = ["automatic","suv"] ;
const specifications2 = ["automatic","suv", "boat"] ;
function test(spec,pref){
for (var i in spec){
if(!inArray(spec[i],pref)){
return false ;
}
}
return true;
}
console.log(test(specifications,preferences));
console.log(test(specifications2,preferences));
https://jsfiddle.net/y1dz2gvu/

How to get One value from an array (protractor)?

Is it possible to get One value from an array such as:
Array
(
[id] = 100917
[sid] = SM0ddb860df74148f19f57b314bfc80b39
[date_created] = 2016-02-10 12:04:08
[date_updated] = 2016-02-10 12:04:08
[date_sent] =
[to] = +996559138088
[from] = +15674434357
[body] = Confirmation code: 75ba76
[status] = queued
[direction] = outbound-api
[price] =
[price_unit] = USD
)
I need somehow to get a value of "75ba76" (in confirmation code string) using:
[to] = +996559138088
When i try to select it, i see:
http://prntscr.com/a1cngn
Any ideas?..
Thanks.
You can use string and array operations to get the value that you need, as text in html elements are stored as strings by default. filter() function can be used to get the <pre> element that has the number you specify in arrString variable below. Here's how -
var arrString = "[to] = +996559138088";
var reqValue;
element.all(by.css('pre')).filter(function(ele){
return ele.getText().then(function(str){
return str.search(arrString) > -1;
});
}).getText().then(function(val){ //returns array as a string
reqValue = val.split('\n').filter(function(eachEle){return eachEle.search(/body/i)>-1}).toString().split(' ').pop();
//reqValue holds the data that you require
});
Though code looks a little weird, it should do the job. Hope it helps.
With a strong brainstorm i solved the problem using the next code. It's maybe seems to be huge, but it works great!
it("get temp password", function () {
browser.get("http://api.test.yalla.ng/sms.php?db=stena_kg");
var preElement = element.all(by.css('pre'));
var matchPhone = browser.params.phones.matchPhone;
var matchPass;
var elementIndex = 0;
parseNextElement();
function parseNextElement() {
preElement.get(elementIndex).getText().then(function (text) {
parseElementData(text);
if(!matchPass){
elementIndex++;
parseNextElement();
}else{
onMatch();
}
});
}
function parseElementData(data){
var dataArr = data.split("\n");
var phoneTxt = "";
var passTxt = "";
for(var i = 0; i<dataArr.length; i++){
var str = dataArr[i];
var splitStr = str.split(" ");
if(str.match(/\[to\]/)){
phoneTxt = splitStr[splitStr.length - 1];
}
if(str.match(/\[body\]/)){
passTxt = splitStr[splitStr.length - 1];
}
}
console.log(phoneTxt, passTxt);
if(phoneTxt == matchPhone){
matchPass = passTxt;
}
}
function onMatch(){
console.log("COMPLETE!!!", matchPass);
}
}, 600000);
});

Get resolved SPUser IDs from Sharepoint 2010 PeoplePicker

I try to get selected user IDs from people picker control as below:
function GetUserIdsFromPP() {
var xml = _picker.find('div#divEntityData');
var visiblefor = new Array();
xml.each(function (i, row) {
var data = $(this).children().first('div').attr('data');
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(data);
}
var uid = xmlDoc.getElementsByTagName('Value')[0].firstChild.nodeValue;
visiblefor.push(uid);
});
return visiblefor;
}
The problem is that sometimes XML doesn't contain <Key>SPUserID</Key><Value>1</Value> and I get FQUN (user login with domain name).
What is the better way to resolve selected SPUserIds from PeoplePicker control?
This is how resolve emails from people picker control on client side
function GetEmailsFromPicker() {
var xml = _picker.find('div#divEntityData');
var result = new Array();
xml.each(function (i, row) {
var data = $(this).children().first('div').attr('data');
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(data);
}
var emailIndex = -1;
for (var i = 0; i < xmlDoc.childNodes[0].childNodes.length; i++) {
var element = xmlDoc.childNodes[0].childNodes[i];
var key = element.childNodes[0].childNodes[0].nodeValue;
if (key == 'Email') {
var uid = xmlDoc.childNodes[0].childNodes[i].childNodes[1].childNodes[0].nodeValue;
result.push({ EMail: uid });
break;
}
}
});
return result;
}
Use the above answer, but...
Replace this with an appropriate Jquery or Javascript element name.
var xml = _picker.find('div#divEntityData');

How can I do this all in one query? Nhibernate

I have a list of Ids and I want to get all the rows back in one query. As a list of objects(So a List of Products or whatever).
I tried
public List<TableA> MyMethod(List<string> keys)
{
var query = "SELECT * FROM TableA WHERE Keys IN (:keys)";
var a = session.CreateQuery(query).SetParameter("keys", keys).List();
return a; // a is a IList but not of TableA. So what do I do now?
}
but I can't figure out how to return it as a list of objects. Is this the right way?
List<TableA> result = session.CreateQuery(query)
.SetParameterList("keys", keys)
.List<TableA>();
Howeever there could be a limitation in this query if number of ":keys" exceed more than 1000 (incase of oracle not sure with other dbs) so i would recommend to use ICriteria instead of CreateQuery- native sqls.
Do something like this,
[TestFixture]
public class ThousandIdsNHibernateQuery
{
[Test]
public void TestThousandIdsNHibernateQuery()
{
//Keys contains 1000 ids not included here.
var keys = new List<decimal>();
using (ISession session = new Session())
{
var tableCirt = session.CreateCriteria(typeof(TableA));
if (keys.Count > 1000)
{
var listsList = new List<List<decimal>>();
//Get first 1000.
var first1000List = keys.GetRange(0, 1000);
//Split next keys into 1000 chuncks.
for (int i = 1000; i < keys.Count; i++)
{
if ((i + 1)%1000 == 0)
{
var newList = new List<decimal>();
newList.AddRange(keys.GetRange(i - 999, 1000));
listsList.Add(newList);
}
}
ICriterion firstExp = Expression.In("Key", first1000List);
ICriterion postExp = null;
foreach (var list in listsList)
{
postExp = Expression.In("Key", list);
tableCirt.Add(Expression.Or(firstExp, postExp));
firstExp = postExp;
}
tableCirt.Add(postExp);
}
else
{
tableCirt.Add(Expression.In("key", keys));
}
var results = tableCirt.List<TableA>();
}
}
}