methods of Underscore.js in parse cloud code - javascript

I am trying to retrieve random 200 objects from the array returned to me by query.find() method. First i tried to implement all random number generation and all . And just now i got introduced to underscore.js method "_.sample" .
But something is going wrong. I dont have much knowledge of underscore.js. So if someone could help that will be great.
When i try to sun _.sample method it give me the error :
TypeError: Object function (e){if(e instanceof T)return e;if(!(this instanceof T))return new T(e);this._wrapped=e} has no method 'sample'
Someone please explain what exactly this error is. I tried searching but didn't get explanatory content. Thank you in advance.
Here's the code :
var queryPhrases = new Parse.Query("Phrases");
queryPhrases.select("phraseId");
queryPhrases.find().then(function(phrases){
var arrayOfUnused = _.sample(phrases,request.params.count);
user.add("usedPhrases",arrayOfUnused);
user.save();
response.success(arrayOfUnused) ;
});

Parse Cloud Code includes an outdated version of Underscore, but frustratingly, I can't find anything stating which version. While Underscore no longer ships with the Parse Javascript SDK as of v1.6.0 (late 2015), previously it had only used UnderscoreJS v1.4.4 (early 2013), so I'd expect Cloud Code to be using something from around then.
Adding the latest Underscore source to your Cloud Code is always an option, and then require it like any other of your own files.
Alternatively, I used the following to show a list of functions available in the included Underscore Cloud Code module.
var _ = require('underscore');
var availableFunctions = _.functions(_);
console.log('Available Underscore Functions: ' + JSON.stringify(availableFunctions));

Thanks a lot guys for your responses. I couldn't find the reason or the solution to run _.sample in my code. So i implemented it the other way. Here's what i did.
var arrayOfUnused = _.first(_.shuffle(phrases),request.params.count);
This works. :-)

Related

JavaScript JSON - Value from nested data - SyntaxError in CodePens debug mode

I am no JavaScript expert, but after a long time of reading, experimenting and the power of Google and especially the results of stackoverflow I managed to work with the data of a REST API.
I made everything with CodePen, because it's nice to understand what I was doing.
Now I came to a problem that I can't solve myself. I tried to google it, but I think I just don't know the right keywords.
My problem is a SyntaxError which only occurs in debug mode. But I think my main problem is, that I understand how to get all values and work with all Object.keys and Object.values but not the correct way to get 1 specific value.
Uncaught SyntaxError: Unexpected token '['
The JSON file looks like this:
[{"label":"Value","next":Value, ...},{"label":"Value","next":Value, ...}, ...]
My JavaScript Code looks like this:
const api_url = 'external json file';
async function getBrowsersData() {
const response_api_url = await fetch(api_url_api_url);
const data_api_url = await response_api_url.json();
const data = data_api_url.[0].label;
The SyntaxError comes from the [0], what is the explained way here, if I understand it right.
If I use ["0"] as described here, I get a SyntaxError in CodePen without Debug Mode.
Can someone please explain how I select the first label and, more importantly, why this works in CodePen, but not in its debug mode?
A link with a detailed description would help me too. I know it's probably a very simple question, but I am stuck and out of keywords I could search.
I have read this excellent and very detailed answer several times, but I do not understand my mistake.
Can you provide the codepen? It's hard to see exactly what you're doing wrong without full sample data
A quick issue I see is this though:
const data = data_browsers_30.[0].label;
should probably be:
const data = data_browsers_30[0].label;
That's the reason you get the SyntaxError; you don't need the . before [0].
if you think the label key is the issue this syntax is generally also valid:
const data = data_browsers_30[0]["label"]

How does mongodb create database/collection on the fly

Mongodb is cool enough to create the database/collection on the fly, if we run a code similar to
db.store.save({a: 789});
It automatically creates store collection and add a document to it.
My javascript understanding says it is not possible to call a method on an undefined property of db object. It should have resulted in some kind of error/exception.
I am curious to understand the happenings behind the scene and if there is any helpful link please point me to those. Googling did not help me much.
In JavaScript there is a way to define a function that will be executed when an undefined method is called.
Example:
var o = {
__noSuchMethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); }
};
o.foo(1, 2, 3);
o.bar(4, 5);
o.baz();
// Output
// foo (1, 2, 3)
// bar (4, 5)
// baz ()
Note this is a non-standard feature and today only works in Firefox.
I do not know how MongoDB implemented this feature, but I'm just responding in order to report that can be done this way.
Fot more details see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/noSuchMethod
As I recall in a NodeJS environment you must do something like this to actually create a record: db.get('collectionName').insert({..something...}); or db.get('collectionName').save({...something...}); but you don't get to use the collection name as a property of db.
The line you're mentioning is only used in MongoDB shell, which is not Javascript.
I guess you're misunderstanding what's MongoDB shell and what's a MongoDB driver.
So long story short MongoDB (driver) is not able to access an undefined property.
EDIT
In response to your comment..
MongoDB JS driver's GitHub page pretty much points out how to insert a field and always uses the syntax I mentioned: https://github.com/mongodb/node-mongodb-native
As for what you're using in the shell it's pretty clear that you can't just use Javascript in a command shell. So I guess I'll point you to a place in which you can see in what language was MongoDB developed: http://www.mongodb.org/ pretty much the first line says it's written in C++.
Hope this helps clarify your question

How to set locale in JavaScript, for example for toLocaleUpperCase()?

I'd like to use the JavaScript toLocaleUpperCase() method to make sure that the capitalization works correctly for the Turkish language. I cannot be sure, however, that Turkish will be set as the user's locale.
Is there a way in modern browsers to set the locale in run time, if I know for sure that the string is in Turkish?
(I ran into this problem while thinking about Turkish, but actually it can be any other language.)
There isn't really anything much out there but I came across this JavaScript setlocale function script that you might find useful.
You unfortunately cannot set locale during runtime. All hope is not lost though, there are many good libraries on npm for you to use. Check out https://www.npmjs.com/package/upper-case and https://www.npmjs.com/package/lower-case for example, it will work for many other languages too.
If that's too much, you can roll your own simple library:
var ALL_LETTERS_LOWERCASE = 'abcçdefgğhıijklmnoöprsştuüvyz';
var ALL_LETTERS_UPPERCASE = 'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ';
function toLowerCaseLetter(letter) {
letter_index = ALL_LETTERS_UPPERCASE.indexOf(letter);
return ALL_LETTERS_LOWERCASE[letter_index];
}
function toLowerCase(my_str) {
var lower_cased = ''
for (letter of my_str) {
lower_cased += toLowerCaseLetter(letter);
}
return lower_cased;
}
console.log(toLowerCase('ÇDEFGĞHIİJKLMNOÖPRSŞTUÜ'))
Very similar for upper case version.
This option may not have existed back in 2013 but may help new visitors on this topic:
According to MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase) the function toLocaleUpperCase takes an optional parameter 'locale'.
Setting the right language tag is a topic on its own (https://www.w3.org/International/articles/language-tags/). Simplest example looks like this
'selam dünya'.toLocaleUpperCase('tr'); // SELAM DÜNYA

Version 1 UUID Node.js binding?

I was trying to export https://github.com/LiosK/UUID.js into a module, but I'm having a rough time - version 4 is worthless to me (use case Cassandra) - does anybody know of a binding for these types of uuids? I can't seem to find one on Google...maybe someone has implemented what's out there?
Thanks!
I think you can just use /dist/uuid.core.js with a slight modification as follows:
add the following line and save:
exports.UUID = UUID;
now in another file use:
var UUID = require("path/to/the/uuid.core.js");
console.log(UUID.generate());
hope that helps
J
https://github.com/broofa/node-uuid now supports v1 format IDs. FWIW.

How can I make vim's taglist plugin show useful information for javascript?

I've recently abandoned mouse-driven, platform-specific GUI editors and committed entirely to vim. The experience so far has been fantastic, but I'm stuck when it comes to Javascript.
The ever-popular taglist utility (using Exuberant Ctags) has been great for everything but Javascript. With the language's overly-free form and structure, taglist could only pick up a handful of functions when I opened it up -- only those defined in the format:
function FUNCNAME (arg1, arg2) {
but no variables or function objects defined like:
var myFunc = function (arg1, arg2) {
So I googled a bit and found the following definition set for ctags, which I put in my ~/.ctags file:
--langdef=js
--langmap=js:.js
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\{/\1/,object/
--regex-js=/([A-Za-z0-9._$()]+)[ \t]*[:=][ \t]*function[ \t]*\(/\1/,function/
--regex-js=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*([^])])/\1/,function/
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\[/\1/,array/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^""]'[^'']*/\1/,string/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^'']"[^""]*/\1/,string/
After that, running ctags from the command line was fantastic. It found every function and object that I needed it to find.
The problem is that the taglist.vim plugin isn't seeing those new results. When I open my javascript file in vim and hit :TlistToggle, I get the exact same meager handful of functions I got before. I hit 'u' to update the list, with no effect.
Digging into taglist.vim, I found this:
" java language
let s:tlist_def_java_settings = 'java;p:package;c:class;i:interface;' .
\ 'f:field;m:method'
" javascript language
let s:tlist_def_javascript_settings = 'javascript;f:function'
...which implies we're only looking at one specific kind of output from the ctags utility for javascript. Unfortunately, I'm not savvy enough with taglist or vim in general (yet) to discover what change I can make to get all those wonderful ctags command-line results to show up in vim.
Help appreciated!
Got it! I dove into the taglist.vim code for awhile, and this is what I found:
taglist.vim forces ctags to use the same filetype that vim is using. So even though the ~/.ctags snippet I found via google is assigning my much-needed definitions to the new "js" language and applying it to files that end in .js, taglist is forcing ctags into using the "JavaScript" filetype that vim is using -- which is built right into ctags already.
The solution is to change the ~/.ctags file from what I've posted above to this:
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*new[ \t]+Object\(/\1/o,object/
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\{/\1/o,object/
--regex-JavaScript=/([A-Za-z0-9._$()]+)[ \t]*[:=][ \t]*function[ \t]*\(/\1/f,function/
--regex-JavaScript=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*\([^\]\)]*\)/\1/f,function/
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*new[ \t]+Array\(/\1/a,array/
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\[/\1/a,array/
--regex-JavaScript=/([^= ]+)[ \t]*=[ \t]*[^""]'[^'']*/\1/s,string/
--regex-JavaScript=/([^= ]+)[ \t]*=[ \t]*[^'']"[^""]*/\1/s,string/
which alters the pre-existing JavaScript language definition directly, rather than creating a new language definition within ctags. Now, when taglib forces vim's registered filetype, the new definitions are used. Also missing from the previously posted ~/.ctags lines was the "kind" letter that Al mentioned in his answer, so those are included in my updated version as well.
From there, drop the following into your ~/.vimrc to activate the new types:
let g:tlist_javascript_settings = 'javascript;s:string;a:array;o:object;f:function'
All-in-all, the new regex lines aren't perfect -- they'll definitely need some tweaking to avoid a lot of false positives, and it might be nice to separate out constants and such. But now, at least, I have the ability to do that :).
Edit: Added instructions on how to activate types without editing the plugin, and vastly improved the main ctags function regex to avoid some false-positives.
Edit 2: Added more array and object definitions to the ctags regex.
I ran into this post on a google search, and although your findings are excellent, I think we can improve them. This is the results of a bit of hacking on your solution:
.ctags
--regex-JavaScript=/^var[ \t]+([a-zA-Z0-9_$]+) = \[/\1/a,array/
--regex-JavaScript=/^var[ \t]+([a-zA-Z0-9_$]+) = \{/\1/o,object/
--regex-JavaScript=/^var[ \t]+([a-zA-Z0-9_$]+) = (^{^[)+/\1/r,var/
--regex-JavaScript=/^[ \t]*(this\.)?([A-Za-z0-9_$()]+)[ \t]*[:=][ \t]*function[ \t]*\(\)/\2/u,function/
--regex-JavaScript=/^[ \t]*function ([a-z0-9]+[A-Za-z0-9_]*)/\1/u,function/
--regex-JavaScript=/^[ \t]*([A-Za-z0-9]+)\.prototype\.([a-z0-9]+[A-Za-z0-9_]*)/\1 : \2/u,function/
--regex-JavaScript=/^[ \t]*function ([A-Z]+[A-Za-z0-9_]*)/\1/o,object/
.vimrc
let g:tlist_javascript_settings = 'javascript;r:var;s:string;a:array;o:object;u:function'
This gets rid of a few more false positives, and adds some more features in, as a tradeoff for getting rid of some of the more problematic regexes. I'll keep updating if I find I need more.
Edit: I've gotten everything working really nicely now; I feel like this result is solid. The only major deficiency is that it doesn't work on comma separated variable definitions. That seems particularly nasty. Maybe another day. :)
Note also that I changed the .vimrc. This isn't because I'm a freak; it's because somehow taglist or ctags or something has some default values set, and if you don't change it, then you get a lot of doubles where functions and vars are concerned, which really drives me insane (I pay super attention to detail.. :P )
Edit: More tweaks. It picks up on prototype function declarations now, and doesn't do some other stupid stuff.
The best-practice solution, which is also very new, neat and easy way to get JavaScript source-code browsing / tag-list in Vim, is using Mozilla's DoctorJS (formerly known as jsctags).
See my answer for this question for more info.
Enjoy. :)
I've not used javascript or taglist much, but looking through :help taglist-extend, it looks like your definitions (listed above) rename the javascript output to js, so you'll probably need something like (in your vimrc):
let tlist_js_settings = 'js;f:function;m:method'
This is assuming that the ctags 'kind' is 'f' for function and 'm' for method. Have a look at your tags file and see what the 'kind' column looks like. By way of example, my C code tags file includes this line:
ADC_CR1_AWDCH_0 .\LibraryModules\CMSIS\Headers\stm32f10x.h 2871;" d
This is a #define of a symbol ADC_CR1_AWDCH_0, which is in the listed file at line 2871. The 'd' is the ctags 'kind' for a defined name. Hopefully that will give you enough to get you going.
As an aside, I'm not sure whether the override will work correctly, so it might be worth naming your file 'myfile.mjs' and changing your langmap to js:.mjs until it's working properly. Then at least you'll know whether your problems are associated with misidentification of files or the actual parsing.
Hi thanks to Tom Frost for his question and research, I think there is a little problem with the 4th line regexp of your final answer:
--regex-JavaScript=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*\([^\]\)]*\)/\1/f,function/
Doesn't worked for me, I pulled it a bit and now works ok:
--regex-JavaScript=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*\([^\)]*\)/\1/f,function/
PD. The others answers' regexps posted here doesn't work at all at least for me :-?
To avoid duplicate entries from ctags' built in javascript support I define 'js' language as in original post and help taglist use ctags with it. I also make sure that tagnames are stripped from some less useful bits (quotes, "this.", ".prototype"). I don't use object/array/string/var regexps, but it's easy to combine my regexps with the other suggestions.
~/.ctags:
--langdef=js
--langmap=js:.js
--regex-js=/["']?(this\.)?([A-Za-z0-9_$]+)["']?((\.prototype)?(\.[A-Za-z0-9_$]+))?[ \t]*[:=][ \t]*function/\2\5/f,function/
--regex-js=/function[ \t]+([A-Za-z0-9_$]+)/\1/f,function/
~/.vimrc:
let g:tlist_javascript_settings = 'js;f:function'

Categories