lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
Imagine that I have a variable called incomingValue and I 'm getting a number from an API as it 's value . The values are between 0 to 1 and I 'm setting two other variables depending on this value using bunch of if statements like you see below . In the actual implementation , I have around 10 if statements checking f...
var incomingValue ; // Set by an APIvar setValueName ; var setValueIcon ; if ( incomingValue < 0.10 ) { setValueName = 'something ' ; setValueIcon = 'something.png ' } if ( incomingValue > 0.09 & & incomingValue < 0.20 ) { setValueName = 'somethingElse ' ; setValueIcon = 'somethingElse.png ' ; }
How can I refactor this bunch of if statements ?
JS
I 'm doing an exercise which i 'm no being able to solve . I need to get the maximum accumulated profit by buying and selling bitcoins . I have a function ( A , Y ) which receive an A = array of different prices during time and a Y = feeRestrictions : Note : If a bitcoin was bought at 0 and sold at 1 , we would have ad...
A = [ 7200,7050,7300,7500,7440,7200,7300,7280,7400 ] //expected result 550Y = 50A [ 3 ] - A [ 1 ] - Y = 7500 - 7050 - 50 = 400A [ 8 ] - A [ 5 ] - Y = 7400 - 7200 - 50 = 150result = 550 //maximum accumulated profit function solution ( A , Y ) { if ( A.length < 2 ) { return 0 ; } var minIndex = ( A [ 0 ] > A [ 1 ] ) ? 1 ...
javascript - return the maximum accumulated profit
JS
I 'm using Smart table i want to keep matched rows on top of other rows in table using angularjs ( 1 ) , in my case i have been matching string from table column , on the basis of matched string I 'm changing row background color , but i want to show those colored rows on top of the other rows , so that I 'm able see m...
< tr ng-repeat= '' emp in employees | orderBy : set_color '' ng-style= '' set_color ( emp ) '' > var myApp = angular.module ( 'myApp ' , [ ] ) .controller ( 'employeeController ' , function ( $ scope ) { var employees = [ { `` Name '' : `` Alfreds Futterkiste '' , `` City '' : `` Berlin '' , `` Country '' : `` Germany ...
How to keep matched row on top of other rows in table using angularjs ?
JS
why the result is undefined ? i thought it is supposed to be ' [ object Object ] '
var foo = { } ; foo.c = foo = { } ; console.log ( foo.c ) ;
why the program 's result is undefined ?
JS
I keep running into situations where I end up nesting very many reduce functions to drill down into an object . It 's hard to pull out the logic because at the bottom I need access to the various keys traversed along the way . Essentially , I 'm looking for a better way to achieve the following : I would like to write ...
import { curry } from 'lodash/fp'import { fromJS } from 'immutable'const reduce = curry ( ( fn , acc , it ) = > it.reduce ( fn , acc ) ) describe ( 'reduceNested ' , ( ) = > { const input = fromJS ( { a1 : { b1 : { c1 : { d1 : { e1 : 'one ' , e2 : 'two ' , e3 : 'three ' } , d2 : { e1 : 'one ' , e2 : 'two ' , e3 : 'thre...
Nested Reduce Functions / Recursion / Functional Programming / Tree Traversal
JS
I was trying to benchmark the gain/loss of `` caching '' math.floor , in hopes that I could make calls faster . Here was the test : My results from the test : The variance is random , of course , but for the most partIn all cases [ this shows time taken ] : [ takes longer ] mathfloor > Math.floor > window.mathfloor [ i...
< html > < head > < script > window.onload = function ( ) { var startTime = new Date ( ) .getTime ( ) ; var k = 0 ; for ( var i = 0 ; i < 1000000 ; i++ ) k += Math.floor ( 9.99 ) ; var mathFloorTime = new Date ( ) .getTime ( ) - startTime ; startTime = new Date ( ) .getTime ( ) ; window.mfloor = Math.floor ; k = 0 ; fo...
Local Variables take 7x longer to access than global variables ?
JS
This is the html part of the code : The function below takes the last block , removes it and creates another one to put it at the top.With the code below I tried to set the snake position eqal to head 's position so every time a new block becomes the head the snake moves by one block.When I call the function turnRight ...
< div class= '' snake '' > < div class= '' body '' > < /div > < /div > //The snake turns rightvar turnRight = function ( ) { blocks_moved++ ; $ ( '.snake ' ) .children ( ) .last ( ) .remove ( ) ; $ ( ' < div > < /div > ' ) .addClass ( 'body ' ) .prependTo ( '.snake ' ) .css ( 'top ' , 0 + ' % ' ) .css ( 'left ' , xPos ...
How to set a div position to depend on another div position ?
JS
If you have the following code : I am trying to add a class to the A tags with images inside.So I haveHowever , now I want to add an extra check . I want to add the class ONLY if the image src + a href wrapping it are the same or `` similar '' ( they only have the thumbnail size at the end i.e -150x150 ) . In other wor...
< div class= '' container '' > < a href= '' http : //testing.test/photo.jpg '' > < img src= '' http : //testing.test/photo.jpg '' > < /a > < a href= '' http : //testing.test/photo.jpg '' > < img src= '' http : //testing.test/photo-450x450.jpg '' > < /a > < a href= '' http : //testing.test/photo.jpg '' > < img src= '' h...
compare img src + a wrap url strings to see if they are `` similar ''
JS
I am migrating an existing program to use async/await ( via Babel 's bluebirdCoroutines ) in order to learn this style . I have been looking at this tutorial.I am a bit troubled by the following behavior . This snippet works as expected : Re-written as follows , it still works but the fist operation is not parallel any...
let parts = [ ] ; let urlsP = urls.map ( ( url , index ) = > { return dlPart ( url , index , tempDir ) ; } ) ; for ( let urlP of urlsP ) { // Parallel ( yay ! ) parts.push ( await urlP ) ; } for ( let part of parts ) { // Sequential await appendFile ( leFile , part ) ; } let index = 0 ; let parts = [ ] ; for ( let url ...
ES7 async/await conceptual issue
JS
First of all , I 'm new to both WCF services and dropzone JS , but I 'm trying to combine the two to create a simple image uploader . I 've got my WCF working correctly for the metadata that I 've uploaded to through it ( so I know it 's passing things cross domain correctly ) , but the Stream that I 've captured from ...
data : image/png ; base64 , iVBORw0KGgoAAAANSUhEUgAAAOYAAADbCAMAAABOUB36AAAAwFBMVEX ... LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5T1RUV0I1RFZZdTVlM2NTNQ0KQ29udG ... < div class= '' col-lg-12 '' > < form action= '' http : //localhost:39194/ImageRESTService.svc/AddImageStream/ '' class= '' dropzone '' id= '' dropzone '' > < /form ...
Dropzone JS Upload to WCF Getting Wrong Data
JS
I have the following structure and I need to wrap the div around .item.In some place there is two items and in some place there is single item : I need output in this format : I tried with the following code but it wraps all code to single class .
< div class= '' section '' > < div class= '' heading '' > < /div > < div class= '' item '' > < /div > < div class= '' item '' > < /div > < div class= '' heading '' > < /div > < div class= '' item '' > < /div > < div class= '' item '' > < /div > < div class= '' heading '' > < /div > < div class= '' item '' > < /div > < ...
jQuery/js wrap near div with same classes into single div
JS
I 'm using Google Charts ' Annotation Chart to display data . Everything 's working but it 's not showing the volume section , as seen in this google finance chart that , I believe , uses the same chart.Here 's what I have so far , but I do n't know how to include that section : This is what the google finance chart lo...
google.charts.load ( 'current ' , { 'packages ' : [ 'annotationchart ' ] } ) ; google.charts.setOnLoadCallback ( drawChart ) ; function drawChart ( ) { var data = new google.visualization.DataTable ( ) ; data.addColumn ( 'date ' , 'Date ' ) ; data.addColumn ( 'number ' , 'Col1 ' ) ; data.addColumn ( 'string ' , 'Col2 '...
Add section to annotation chart ?
JS
I 'm using a modal from the Kube CSS & JS framework ( 6.5.2 ) with a form inside it . When I hit enter , the modal closes without submitting the form . Edit : this does n't happen when focused on password or search inputs - changing the type from 'text ' to 'password ' fixes the issue.JS : I 'd like the form to submit ...
< ! DOCTYPE html > < html > < head > < title > Basic Template < /title > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < ! -- Kube CSS -- > < link rel= '' stylesheet '' href= '' dist/css/kube.css '' > < /head > < body > < h1 > Hello , world ! < /h1 > < d...
Kube modal closes when pressing enter in form
JS
I 'm currently using Function.apply to call a function with a dynamic number of arguments , but I do not have access to the original context , and have no desire to set the context myself . What I would like , is to be able to call a function with a variable number of arguments , keeping the original context . Perhaps ...
function MulticastDelegate ( ) { var handlers = [ ] ; this.event = { subscribe : function ( handler ) { if ( typeof ( handler ) === 'function ' ) { handlers.push ( handler ) ; } } , unsubscribe : function ( handler ) { if ( typeof ( handler ) === 'function ' ) { handlers.splice ( handlers.indexOf ( handler ) ,1 ) ; } }...
Calling a Javascript function with an unknown number of arguments with original context
JS
-- -Update -- -- After experimenting more with this , I 've determined that the contentScript I have written is not the problem here . For example , if I reduce the extension to merely : The button will still appear when I run the extension through the SDK , but will not appear when I install the xpi in a current firef...
var buttons = require ( 'sdk/ui/button/action ' ) ; var data = require ( `` sdk/self '' ) .data ; var self = require ( `` sdk/self '' ) ; var button = buttons.ActionButton ( { id : `` library-link '' , label : `` External Resource Locator '' , icon : self.data.url ( `` icon-16.png '' ) , } ) ; var buttons = require ( '...
firefox extension works through sdk but not when installed in browser - compatibility issue ?
JS
Here you can see the same video is loading twice . Its an autoplaying video , that I just want to use a 2nd time at the bottom of the page ( first is top of page ) . How to prevent the browser to download it a 2nd time ? https : //tools.pingdom.com/ # ! /cQ1xMb/https : //bm-translations.de/km.phpQuestion is regarding t...
< video autoplay= '' autoplay '' loop= '' loop '' class= '' imgWindowwidth center '' > < source src= '' ./bilder/krystian-manthey-referenzen.mp4 '' type= '' video/mp4 '' / > < /video >
how to prevent same video loading twice if its just the same video a 2nd time
JS
Use reduce to find number of times an items is in an array.The array could have arrays inside recursively.bar ( foo , 4 ) would return 3 .
var foo = [ 1 , [ 2 , 3 , 4 ] , 4 , [ 5,6,7 ] , 4 ] ;
Use reduce to shorten array
JS
Here is a sample angular directive to prevent typing non-numeric keys ( StackOverflow answer ) .I want to write something like this fiddle to use the is-number directive in several inputs . Please consider that since I have various different directives in my inputs , I can not use the same template as suggested in the ...
var $ scope ; var app = angular.module ( 'myapp ' , [ ] ) ; app.controller ( 'Ctrl ' , function ( $ scope ) { $ scope.myNnumber1 = 1 ; $ scope.myNnumber2 = 1 ; } ) ; app.directive ( 'isNumber ' , function ( ) { return { require : 'ngModel ' , link : function ( scope , element ) { scope. $ watch ( element.ngModel , func...
Angular directive : Allow just numbers
JS
I have a small problem with a object that uses jquery . since jquery overwrites the this pointer I cant call my sub methods without resorting to save the this pointer in a that variable is this a preferred way or is there a better solution ? Is there a way to save the this pointer in the object ( like a class method wi...
//from javscript the good partsif ( typeof Object.create ! == 'function ' ) { Object.create = function ( o ) { var F = function ( ) { } ; F.prototype = o ; return new F ( ) ; } ; } var Tester = { printData : function ( text ) { console.log ( text ) } , start : function ( ) { var that = this ; jQuery ( 'id ' ) .click ( ...
javascript internal method calls when using jquery
JS
I have such script When I run it and change system time back for one hour , the timeout not fires . If I change time forward for one hour , timeout works correctly.Time is changed by external program which makes call like ioctl ( rtcFd , RTC_SET_TIME , & newTime ) ; How to fix this problem ? We use Node.js v0.10.15 on ...
setTimeout ( function ( ) { console.log ( `` Timeout '' ) ; } , 1000 * 60 ) ;
Node.js setTimeout not fired after system time change
JS
Using the material design lite library to create dialogs , which essentially uses the underlying < dialog > element , is there any way to dismiss the dialog by clicking on its backdrop ? ( When clicking the dialog contents themselves it should not be dismissed ) .https : //jsfiddle.net/fyjbvbqq/Clicking anywhere on the...
< dialog > Hi < /dialog > < button > show < /button > document.querySelector ( `` button '' ) .addEventListener ( `` click '' , ( ) = > document.querySelector ( `` dialog '' ) .showModal ( ) ) ;
Dismiss html dialog element by clicking the backdrop
JS
I am currently working on a JavaScript ( pure js ) based game . The game contains 5 large sprite sheets ( e.g . 2861 × 768 and 4096 × 4864 ) . When the game starts , all 5 sprite sheets are preloaded to canvas elements . Three of those 5 sprites represent together one animation , where each sprite contains 75 frames . ...
nw.js v0.12.3io.js v1.2.0Chromium 41.0.2272.76commit hash : 591068b-b48a69e-27b6800-459755a-2bdc251-1764a45
NW/Node Webkit - Image decodes even if it is already visible
JS
I am currently dealing with in issue in writing a recrusive function to order some json data . I have several nested arrays of objects which i need to order into single slides . The structure is similar to the following : I have written a recursive function : This outputs : However instead of retrieving the data for my...
[ { `` title '' : `` a '' , `` children '' : [ { `` title '' : `` a-a '' , `` children '' : [ { `` title '' : `` a-a-a '' } , { `` title '' : `` a-a-b '' } ] } , { `` title '' : `` a-b '' , `` children '' : [ { `` title '' : `` a-b-a '' } , { `` title '' : `` a-b-b '' } ] } ] } , { `` title '' : `` b '' , `` children '...
Ordering recursive function results in arrays of arrays
JS
I am trying to pass data from Google Map InfoWindow to Info Page . I am able to pass and access the data.However , every time when the infoWindow is being reopen , the page will fire i+1 , overlaying each other . For example first time InfoWindow opened , Apply button clicked , it will go to Info Page . Closing the Inf...
import { Injectable } from ' @ angular/core ' ; import { Http } from ' @ angular/http ' ; import 'rxjs/add/operator/map ' ; import { App } from 'ionic-angular ' ; constructor ( public http : Http , public app : App , ) { } addMarker ( lat : any , lng : any , listingID : any ) : void { let latLng = new google.maps.LatLn...
ionic 2/ Angular 2 - Fail to pass data from Google Maps InfoWindow to page
JS
I 'm using react-native-material-menu 's popup for showing menu options.But the issue is , it 's not working for multiple scenarios.I mean when I click on first menu button , the same methods gets triggered and hence the same menu is opened every time.What should be the better approach for to handle this particular sce...
_menu = null ; setMenuRef = ref = > { this._menu = ref ; } ; hideMenu = ( ) = > { this._menu.hide ( ) ; } ; showMenu = ( ) = > { this._menu.show ( ) ; } ; < FlatList data= { this.state.clientsList } renderItem= { ( { item } ) = > { return ( < View style= { styles.caseItem } > < Card style= { styles.card } > < CardItem ...
Multiple Component with Same Function Name in React Native
JS
I am using this code : where General.dateFormat is a format MM.dd.yyyy stored in my language JSON file . But it is printed as 5 22 , 2017 AenerPMl.22PMteFor35PMt | trPMn24lPMte I think there is an issue with multiple pipe . If I replace General.dateFormat | translate with MM.dd.yyyy it works as it should . How do I giv...
{ { today | date : 'General.dateFormat | translate ' } }
Angular 2 date pipe
JS
I have a mobile application that prints star ratings . Here is my codeclass star on displays colored starclass star half displays half colored starclass star display not colored starAssuming that { { item.rating } } is 2.50. how do I manipulate that in the span class that it prints 2 colored stars , half star and 2 and...
< ion-list *ngFor= '' let item of ListOfitems '' > { { item.rating } } < div class= '' stars '' > < span class= '' star on '' > < /span > < span class= '' star half '' > < /span > < span class= '' star '' > < /span > < /div > < /ion-list >
Displaying star rating
JS
why ? 100.toString is not same as 100.toString ( ) . So why in the second case I am not getting the function as returned value ?
100 [ 'toString ' ] //does not fail100.toString //fails
100.toString vs 100 [ 'toString ' ]
JS
I 'd like to inject lodash by name , something like this : but say I want to rename the import , I want do something like this : oris there a way to do this with either ES6/ES7/ES8 or TypeScript ? Note that this DI framework does more work than just require ( ' x ' ) ... it will try to inject other values first , if no...
let val = function ( lodash ) { // lodash will be injected , simply by using require ( 'lodash ' ) ; } ; let val = function ( { lodash : _ } ) { } ; let val = function ( lodash as _ ) { } ;
Dependency injection library - renaming injected values
JS
I have two large array of objects like : and another almost equal array.These two arrays can also have thousands of objects , for example 20k.I have to compare them and find the objects that are in the first array but not in the second oneNow i 'm doing : This works , but it blocks the UI of my app for a few seconds.Is...
const array1 = [ { userId : 83232932 , name : 'Tom ' , profile_pic : 'http : //.. ' , age : 24 , gender : ' F ' } , { userId : 2413535 , name : 'Sam ' , profile_pic : 'http : //.. ' , age : 31 , gender : 'M ' } ] const missing = array1.filter ( function ( item1 ) { return ! array2.some ( function ( item2 ) { return ite...
Compare two large arrays of objects effectively and find the differences
JS
in javascript this will get us 5other languages like C++ , java , c # ... . will simply give an error that the i variable is n't defined in the context.So why the for loop counter does n't get destroyed after exiting the loop in javascript ?
for ( var i=0 ; i < 5 ; i++ ) { } alert ( i ) ;
Why the for loop counter does n't get destroyed after exiting the loop in javascript ?
JS
I have a Windows Store App that creates a secondary tile . When the tile is clicked , I want the app to perform , what is effectively , an off-line function ( that is , I do n't want to go back into the app , but want the app to do something and then exit ) . So in this case I want to launch the e-mail client , for exa...
app.addEventListener ( `` activated '' , function ( args ) { if ( args.detail.kind === activation.ActivationKind.launch ) { if ( args.detail.arguments ! == `` '' ) { // Activation arguments are present that // were declared when the secondary tile was pinned to Start . args.setPromise ( WinJS.UI.processAll ( ) .done ( ...
Windows Store App - Executing a single task when launched from a secondary tile
JS
A friend showed me that ( at least , in the google chrome console ) the following statement prints true : And indeed , 1/Math.pow ( 0.9999999999999999 , Number.MAX_SAFE_INTEGER ) is 2.718281828459045.This ca n't be a coincidence ? ! Could someone explain what is going on behind the scenes to make this work ? According ...
1/Math.pow ( 0.9999999999999999 , Number.MAX_SAFE_INTEGER ) === Math.E n = 0.0000000000000001 ( 1 - n ) ^MAX_INT = 1 + ( MAX_INT choose 2 ) * n + ( MAX_INT choose 3 ) * n^2 + ... + n^MAX_INT
Math.E equals 0.99 ... . ^ max int
JS
I am programming a personal website with AngularJS ( for my training ) . I use the Carousel from UI-Bootstrap like this : HTML : AngularJS : When I test this code in local it works but when I upload the website on the server it does not work ... I have an error 404 : Moreover , if I use the images without JS but with c...
< carousel interval= '' interval '' no-wrap= '' false '' > < slide ng-repeat= '' slide in slides '' active= '' slide.active '' > < img class= '' img-responsive '' ng-src= '' { { slide.image } } '' > < div class= '' carousel-caption '' > < h4 > { { slide.text } } < /h4 > < /div > < /slide > < /carousel > angular.module ...
Error 404 GET Image when I use AngularJS
JS
what is the significance of the hash ( # ) here , how does it relate to the .js file :
< script src= '' foo.js # bar=1 '' > < /script >
What does the hash ( # ) mean after a .js file ?
JS
The following method : works on all browsers , for some reason , I need the setTimeout ( f,0 ) call for firefox , this method is called on an ajax partial load on MVC , without this call , the editor hangs on firefox and the page breaks ( clicking on stuff results on exceptions most often than not ) . with the call , e...
Init : function ( selector , settings ) { setTimeout ( function ( ) { var s = { width : '100 % ' , script_url : '/Content/Scripts/tiny_mce/tiny_mce.js ' , theme : `` advanced '' , plugins : `` autolink , lists , pagebreak , style , layer , table , paste , directionality , noneditable , visualchars , xhtmlxtras , templa...
setTimeout ( f,0 ) equivalent ? why does it solve cross-browser issues ?
JS
Please take a look at the following JavaScript . I 've taken stuff out of it , so you may focus on the essence of the problem.You 'll notice that I call the prepPath function twice in a row , passing in the exact same string . In firefox and IE8 , this function alerts true each time ( as expected ) . But , in Chromium ...
< script type= '' text/javascript '' > function prepPath ( str ) { var regX = / [ ^\s/ '' '\\ ] . * [ ^\s/ '' '\\ ] /g ; if ( regX.test ( str ) ) { alert ( `` true : `` + str ) ; } else { alert ( `` false ; `` + str ) ; } } prepPath ( `` /desktop '' ) ; // alerts : true prepPath ( `` /desktop '' ) ; // alerts : false <...
Chrome V8 Bug ? Function Acting different after being called a 2nd time
JS
I need a date format like this : yyyy-MM-dd_HH.mm.ss.fffffffAnd I tried this : And output is this : 2014-3-2_23.0.29.840How can I get ten millionths of a second so my output will be something like following ? 2014-3-2_23.0.29.8401111For some reasons I ca n't use libraries such as moment.js.Thanks .
var currentdate = new Date ( ) ; var fileName = currentdate.getFullYear ( ) + '- ' + currentdate.getMonth ( ) + '- ' + currentdate.getDate ( ) + ' _ ' + currentdate.getHours ( ) + ' . ' + currentdate.getMinutes ( ) + ' . ' + currentdate.getSeconds ( ) + ' . ' + currentdate.getMilliseconds ( ) ;
How do I get ten millionths of a second in JavaScript ? `` fffffff ''
JS
Reading the documentation on Symbols in JavaScript , and also testing in a few environments ( Chrome , Firefox , Node.js ) , I 've realized that my understanding of implicit string conversion is flawed.I was always under the impression that the object 's toString ( ) method was called when attempting to convert to a st...
var sym = Symbol ( `` test '' ) ; try { console.log ( sym + `` ing '' ) ; } catch ( error ) { console.error ( error ) ; } TypeError : Can not convert a Symbol value to a string
Symbols : How does implicit string conversion work in JavaScript ?
JS
Is there a function that can replace a string within a string once at a specific index of the string ? Example : and the resultant output would be `` my text is my text and your big text ''
var string1= '' my text is my text and my big text '' ; var string2= '' my '' ; string1.replaceAt ( string2 , '' your '' ,2 ) ;
Javascript using .replace ( ) at a specific index of the search
JS
I am trying to make a grid of a non-fixed number of squares ( 5000-6000 ) . Each box should be at least 4x4px tall with a gap of 1px . The grid should use the entire page , so you don ’ t have to scroll . Every element should be as big as possible so there is less white space . The number of columns or rows should be d...
var html = `` '' ; for ( i=0 ; i < 5000 ; i++ ) { html += ` < div class= '' box '' > < /div > ` ; } document.getElementById ( `` grid '' ) .innerHTML += html ; .wrapper { max-width : 100 % ; max-height : 100 % ; display : grid ; grid-gap : 1px ; grid-template-columns : repeat ( auto-fill , minmax ( 4px , 1fr ) ) ; grid...
CSS big grid of non-fixed number of squares in one page
JS
I am building a chrome extension using Flutter Web , which is just a simple ListView on the home screen and basic CRUD operations . I am using dart : js package to call methods from a JS file which performs some operations on the Firebase Realtime Database.Adding a new entry to the database is working through the add (...
import 'dart : js ' as js ; import 'dart : convert ' ; import 'package : flutter/material.dart ' ; import 'AddAttendee.dart ' ; void main ( ) = > runApp ( MyApp ( ) ) ; class MyApp extends StatelessWidget { @ override Widget build ( BuildContext context ) { return MaterialApp ( title : 'Google Flutter Meet Attendance '...
How to receive data back to flutter when calling a method using js.context.callMethod ( ) ?
JS
I have a grid and I would like to add a tree if a name is equal to “ Beto Carlx ” Does anyone know how to make this happen ? Thank you in advance ! Here ’ s my code : LIVE DEMOI 'm trying to use this simple tree :
columns : [ { header : 'NAME ' , renderer : function ( val , metadata , record ) { var recordName = record.get ( 'name ' ) ; if ( recordName === `` Beto carlx '' ) { return `` TEST '' ; } return recordName ; } , dataIndex : 'name ' , } ] , var store = Ext.create ( 'Ext.data.TreeStore ' , { root : { expanded : true , ch...
How to render tree
JS
Can somebody explain to me the difference between the following two statements ? andThe debugger is Chrome gives me : And how can I get a variable of type of test2 , from of variable of the type of test1 ?
let test1 = new CustomComponent ( ) ; let test2 = < CustomComponent / > for test1CustomComponent { props : undefined , context : undefined , refs : Object , updater : Object , state : Object… } for test2Object { $ $ typeof : Symbol ( react.element ) , key : null , ref : null , props : Object , type : function… }
JSX vs component class instancing
JS
Here is my structure in inside àpp/pods : When a error occurs , ember does not load the error route.Instead it tries to load a sub-route like index_error or user_error but these do not exist.How do i force Ember to load the root error route on any error ? Ember v2.1Ember-Cli v1.13.8
|-application|-index|-error|-user||-index||-view||-edit
Ember.js - Error States in Pod structure
JS
I 'm learning JavaScript and I came across this snippet , which demonstrates type detection : I do n't understand what the empty curly brackets are for in the first line , so I remove them like this : And the code still works . But in the following code , if I change var tellAge=getAge to var tellAge= { } .getAge , I g...
var toClass = { } .toString // Copy a reference to toString for objects into toClass variablealert ( toClass.call ( [ 1,2 ] ) ) // [ object Array ] alert ( toClass.call ( new Date ) ) // [ object Date ] var toClass = toString function getAge ( ) { alert ( this.age ) ; } var p1 = { age:1 } ; var tellAge=getAge ; tellAge...
What does assigning to { } .toString mean ?
JS
( http : //eloquentjavascript.net/07_elife.html ) Im having a hard time understand what the Grid methods we added .get and .set even do.Firstly , lets go through an example case . var grid = new Grid ( 5,5 ) ; now space is an array of 25 elements . And of course width and height are 5.Now the question is what is the me...
function Vector ( x , y ) { this.x = x ; this.y = y ; } Vector.prototype.plus = function ( other ) { return new Vector ( this.x + other.x , this.y + other.y ) ; } var grid = [ `` top left '' , `` top middle '' , `` top right '' , `` bottom left '' , `` bottom middle '' , `` bottom right '' ] ; function Grid ( width , h...
Setting up a grid . Eloquent js chapter 7
JS
Hello I am trying to run this code but every time I open my webpage it does n't load and I do n't get the text I echo with php in the file `` money.php '' . But if I open the console in my browser and run the code it does load . Does anyone know how I could fix this ?
< script type= '' text/javascript '' > $ ( ' [ data-update ] ' ) .each ( function ( ) { var self = $ ( this ) ; var target = self.data ( 'update ' ) ; var refreshId = setInterval ( function ( ) { self.load ( target ) ; } , self.data ( 'refresh-interval ' ) ) ; } ) ; < /script > < div data-update= '' money.php '' data-r...
JavaScript wo n't load when opening my webpage
JS
I just tried the following in a node.js console : Which means that the = part of the < = is treated the same way == is , not === . Which made me immediately try < == hoping it would do what you would hope it would . But it does n't exist.Then I tried the following : Then I started to observe even stranger behaviour : W...
> 5 < = `` 5 '' true > 5 < `` 6 '' true > 5 < [ 6 ] true
Are there type-safe equivalents to the comparison operators in JavaScript ?
JS
Just out of curiosity..I have this JS code : Notice the commented var item which leaves the loop with implicitly declared item variable . If I run this code on FireFox , the result of alert is : 0 : a,1 : b,2 : cIf I run the same code in Internet Explorer , the result is:0 : c,1 : c,2 : cHere is jsfiddle : https : //js...
var someExternalArray = [ { id : 1 , name : ' a ' } , { id : 2 , name : ' b ' } , { id : 3 , name : ' c ' } ] ; var newArray = [ ] //var item ; for ( var i = 0 ; i < someExternalArray.length ; i++ ) { item = new Object ( ) ; item.id = someExternalArray [ i ] .id ; item.name = someExternalArray [ i ] .name ; newArray.pu...
Implicitly global `` item '' variable - difference between Internet Explorer and FireFox
JS
I was looking over the js source code for Scrabb.ly.I 've noticed that they would do something like so for each of their distinct `` classes '' : Some code from the middle has been omitted but this should give you the general idea.What is the purpose of the the following : ( function ( ) { // code } ) ( ) ; Is this the...
var Board = ( function ( ) { var self = { } ; // settings for board self.options = { debug : true , addedPlayTiles : function ( ) { } , clearedPlayTiles : function ( ) { } } ; // set to true once the board has been setup self.isSetup = false ; // quick access to square elements self.squares = { } ; self.squareCount = 0...
What is this design pattern known as in JavaScript ?
JS
When we use MobX flow decorated functions , flowtype thinks this is of type any and does no type checking.However , if we bind this to the generator , flow understands the type of this is MyComponent.My question is how can we ensure that these methods are type checked.Is there any linting rule to ensure we bind ( this ...
class MyComponent extends Component < * > { actionMethod = flow ( function* ( ) { yield this.notAMethod ( ) ; } ) ; } class MyComponent extends Component < * > { actionMethod = flow ( ( function* ( ) { yield this.notAMethod ( ) ; } ) .bind ( this ) ) ; }
Mobx Flow functions are not type checked by FlowType without .bind ( this )
JS
As per Jquery API documentation : .position ( ) Returns : ObjectDescription : Get the current coordinates of the first element in the set of matched elements , relative to the offset parent.This method does not accept any arguments.Reference hereBut somewhere i found using this : An object has been passed to position m...
$ ( `` # position1 '' ) .position ( { my : `` center '' , at : `` center '' , of : `` # targetElement '' } ) ;
Jquery position method
JS
I load a PDF file when user clicks a button using jQuery , but it opens the document starting from the first page ( as it is always ) .I would like to link a specific page depending of the needed chapter . Is it there any way to do this nice to have thing ? Here is how I open the document :
$ ( ' # btnManual ' ) .click ( function ( ) { window.open ( 'documentation/test.pdf ' ) ; } ) ;
How can I link a page in a local PDF file ?
JS
I am fetching data from database using ajax . In this data , I have a textarea which I want to align at the bottom of every page and every textarea have different data . I tried CSS positions , it 's only working for the first page because I have different data in every textarea.Js Fiddle
var response = { row1 : [ { group : 'Group A ' } ] , row2 : [ { team : 'Team A ' , player : 'Jema ' , result : 43 , note : 'won ' } , { team : 'Team B ' , player : 'Deno ' , result : 34 , note : 'lost ' } , { team : 'Team B ' , player : 'Niob ' , result : 56 , note : 'lost ' } , { team : 'Team B ' , player : 'Skion ' ,...
Align div at the bottom of the print page
JS
I 'm working with some code that adds and removes various CSS classes on the same object . The code looks something like : I suspect I might be able get away with chaining these two snippits into something like object_to_change.removeClass ( 'ready ' ) .addClass ( 'not_ready ' ) ; But I have to wonder : besides legibil...
function switch_states ( object_to_change ) { if ( object_to_change.hasClass ( 'ready ' ) { object_to_change.removeClass ( 'ready ' ) ; object_to_change.addClass ( 'not_ready ' ) ; } else { object_to_change.removeClass ( 'not_ready ' ) ; object_to_change.addClass ( 'ready ' ) ; } }
Under what conditions do chained jQuery objects offer performance gains ?
JS
Is there a way to get my replacer called before an object 's own toJSON transforms it , so that I can work with the original object rather than its JSON-friendly form , without overriding the toJSON on the object or its prototype , pre-processing the object , or writing my own version of JSON.stringify ? For example : ...
var obj = { d : new Date ( ) } ; snippet.log ( getType ( obj.d ) ) ; // `` [ object Date ] '' var json = JSON.stringify ( obj , function ( key , value ) { if ( key === `` d '' ) { snippet.log ( getType ( value ) ) ; // `` string '' < == Want to see a Date here } return value ; } ) ; function getType ( value ) { var to ...
Call the replacer *before* the object 's toJSON ?
JS
I 'm a bit confused about loading and playing sound effects . My game is setup in different states , first the Preloader state makes sure all images and sounds are loaded . The GameState is the main game , this state is re-started for each next level . There are different levels but the state is the same , it just chan...
mygame.Preloader.prototype = { preload : function ( ) { this.loadingbar_bg = this.add.sprite ( 80 , 512 , `` loadingbar_bg '' ) ; this.loadingbar_fill = this.add.sprite ( 80 , 512 , `` loadingbar_fill '' ) ; this.load.setPreloadSprite ( this.loadingbar_fill ) ; // load sounds this.load.audio ( `` button '' , [ `` snd/b...
Phaser warning `` Audio source already exists '' when mp3 sound sample is played consecutively
JS
I have a div that needs to be identified using a line and box ( which will contain a message ) like in the below mockup image.2 and 3 ( Line and a rectangular box ) are fixed to each other and draggable and 1 ( Line ) can be stretched to any direction . I have created the box but I am not able to figure out how can I a...
const $ b1 = $ ( `` # box1 '' ) ; const $ b2 = $ ( `` # box2 '' ) ; const $ line = $ ( `` # line '' ) ; const coordinates = function ( ) { debugger ; const x1 = $ b1.offset ( ) .left ; const y1 = $ b1.offset ( ) .top + $ b1.height ( ) /2 ; const x2 = $ b2.offset ( ) .left + $ b1.width ( ) /2 ; const y2 = $ b2.offset ( ...
Tool tip in html
JS
I 'm building a report dashboard using C # and JQuery Datatables . One of the reports on the page contains an update panel with a drop down list . When the user changes the selection , the data refreshes based on the ddl selection . Within each block there is also a link that makes a server side call to export the data...
< div id= '' dTopProducts '' class= '' dashboardDiv '' style= '' height:400px ; width:485px ; margin-top : 15px ; margin-bottom:15px ; margin-right : 15px ; '' runat= '' server '' > < asp : UpdatePanel ID= '' upProducts '' runat= '' server '' > < Triggers > < asp : AsyncPostBackTrigger ControlID= '' ddlProductsSector '...
jQuery Datatables ASP.NET issue
JS
I 'm trying to code a masonry layout ( please do n't suggest using a library and yes , I know about the new Firefox CSS masonry feature , but I need better support ) starting from a CSS grid layout.The HTML looks something like this , a section with a bunch of images of various aspect ratios : The styling is pretty bas...
< section class='grid -- masonry ' > < img src='black_cat.jpg ' alt='black cat'/ > < ! -- and so on , more images following the first -- > < /section > $ w : Min ( 8em , 100 % ) ; $ s : .5rem ; .grid -- masonry { display : grid ; grid-template-columns : repeat ( auto-fit , $ w ) ; grid-gap : $ s ; padding : $ s ; > * {...
Repositioning items using getBoundingClientRect ( ) data
JS
I was just viewing stackoverflow page source and I have a few simple questions ; 1 ) What is the purpose of this ? DO search engines see this or something else ? 2 ) ? v=3731 Why is this added to the end of some javascript and stylesheet files , is it to prevent the browser from caching these items ? And if I am correc...
< link rel= '' search '' type= '' application/opensearchdescription+xml '' title= '' Stack Overflow '' href= '' /opensearch.xml '' > < script type= '' text/javascript '' src= '' /content/js/master.js ? v=3731 '' > < /script > < link rel= '' canonical '' href= '' http : //stackoverflow.com/questions/1180651/php-array-an...
Please help me understand a few things found in the SO page source
JS
Sometimes when a customer is charged , there is a duplicate transaction created . We need to find those transactions so that they can be dealt with . Everything about the transaction should be identical , except the transaction id and the time at which it occurred , as there can be up to a minute delay.i need to Find a...
var transac = [ { id : 3 , sourceAccount : ' A ' , targetAccount : ' B ' , amount : 100 , category : 'eating_out ' , time : '2018-03-02T10:34:30.000Z ' } , { id : 1 , sourceAccount : ' A ' , targetAccount : ' B ' , amount : 100 , category : 'eating_out ' , time : '2018-03-02T10:33:00.000Z ' } , { id : 6 , sourceAccount...
Filter Array of object based in duplicate keys
JS
I 've written a function which makes an asynchronous request using jQuery.Syntax might be slightly wrong as I 'm using notepad , but hopefully you get the idea.I call the function : Both requests get sent and processed by the server . Two responses get sent back , which is what I expect . However , I would expect conta...
var Site = { asyncRequest : function ( url , containerId ) { $ .ajax ( { url : url , onSuccess : function ( data ) { $ ( containerId ) .html ( data ) ; } } ) ; } } Site.asyncRequest ( 'someurl ' , container1 ) ; Site.asyncRequest ( 'someurl ' , container2 ) ;
Asynchronous callbacks
JS
I 'm trying to refactor my code to ES6 . I 'm using angular-meteor and ng-table . Before refactoring , the data is shown on the table . However , after refactoring to ES6 syntax , the data does n't show anymore . This is a snippet of the refactored code : The const data is getting populated but getData is n't getting c...
class MyController { constructor ( $ scope , $ reactive , NgTableParams , MyService ) { 'ngInject ' ; $ reactive ( this ) .attach ( $ scope ) ; this.subscribe ( 'myCollection ' ) ; this.myService = MyService ; this.helpers ( { items ( ) { return this.myService.getItems ( ) ; } , itemTableParams ( ) { const data = this....
ES6 angular-meteor ng-table getData function not called
JS
I 'm facing yet another issue.I 'm using firebase db to store text and firebase storage to store files . And here comes my issue.Q : How to fetch a correct image from storage when fetching particular element from database ? Here 's my attempt : As you can see , first what Im doing is uploading the image and when it 's ...
const storageRef = firebase.storage ( ) .ref ( 'companyImages/companyImage ' + 123 ) ; ^^^^^^^^^^^^ I dont have access to id yet : ( const task = storageRef.put ( companyImage ) ; task.on ( 'state_changed ' , ( ) = > { const percentage = ( snap.bytesTransferred / snap.totalBytes ) * 100 ; // ^^^^^^^^^^^^ not sure if i ...
Relation between storage and database - Firebase
JS
I have the following html : How can i use jQuery to add take total deposits , subtract the withdrawals and append it to the p.total ?
< div class= '' balance '' > < div class= '' heading '' > < p class= '' total '' > < span > 00 < /span > < /p > < /div > < div class= '' instance withdrawal '' > < h3 > Random < /h3 > < p > desc < /p > < p class= '' amount '' > $ 350. < span > 00 < /span > < /p > < /div > < div class= '' instance deposit '' > < h3 > Ad...
Get dollar total of all elements with class using jQuery
JS
Possible Duplicate : Interesting test of Javascript RegExp Regular expression test ca n't decide between true and false ( JavaScript ) Example of issue . When ran inline the results are as I would expect . But when stored as a variable it skips the middle span element.Mark up : Given : I understand there is no reason t...
// Inline RegExpfunction getToggleClasses ( ) { var toggler = [ ] , elements = document.getElementsByTagName ( `` * '' ) , i=0 , len = elements.length ; for ( i ; i < len ; i++ ) { if ( /toggler/g.test ( elements [ i ] .className ) ) { toggler.push ( elements [ i ] ) ; } } document.getElementById ( 'results ' ) .innerH...
Why does the same RegExp behave differently ?
JS
There are a number of puzzles that are variant of the classic `` 7 Bridges of Konigsberg '' puzzle where you must find a route through a set of rooms without ever using a door twice.Here is an example of one without a solution ... . and is a slightly modified puzzle that does have a solution , as you can see here.I 'm ...
// I renamed `` groups '' to rooms to make the code more clear.var rooms = { 1 : [ ' A ' , ' B ' , ' C ' , 'D ' ] , //1 : [ ' A ' , ' B ' , ' C ' , 'D ' , ' P ' ] , 2 : [ ' E ' , 'D ' , ' F ' , ' G ' ] , 3 : [ ' F ' , ' I ' , ' J ' , ' H ' ] , //3 : [ ' F ' , ' I ' , ' P ' , ' J ' , ' H ' ] , 4 : [ ' I ' , 'M ' , ' N '...
Canonical algorithm for `` visit each door once '' problems
JS
I guess this is two questions . I am still having trouble with the reduce method , I get the simple way of using it reduce ( [ 1,2,3 ] , function ( a , b ) { return a + b ; } , 0 ) ; //6Using it with anything other than numbers really confuses me . So how would I build a contains function using reduce in place of the f...
function contains ( collection , target ) { for ( var i=0 ; i < collection.length ; i++ ) { if ( collection [ i ] === target ) { return true ; } } return false ; } contains ( [ 1 , 2 , 3 , 4 , 5 ] , 4 ) ; //true
How do I build a contains function using reduce instead of a for loop in JavaScript ?
JS
So EmptyObject + EmptyArray evaluates to 0 . ( Disclaimer : I do n't fully understand why this is . ) Okay , now I want to assign this 0 to a variable ! Seems pretty easy : Well , maybe not so easy . Googles a bit ... Aha ! { } in this context is actually a code block , not an empty object . So lem me make it look more...
> > { } + [ ] 0 > > var a = { } + [ ] ; undefined > > a '' [ object Object ] '' > > var a = { } + [ ] ; undefined > > a '' [ object Object ] ''
Assigning ` { } + [ ] ` to a variable
JS
We all know that CSS prefix for Mozilla ( Gecko ) , when we refer that property using DOM , is Moz . For example : MozTransform.I have a list of prefixes used in CSS for different browsers , but I also want to know the prefixes used when referring them using DOM.List of CSS prefixes :
-moz -- webkit -- apple -- o -- xv -- ms -- mso -- atsc -- wap -- khtml -- prince -- ah -- hp -- ro -- rim -- tc-
CSS prefixes for different browsers ?
JS
I 'm try to add dynamically packery item by click method . All every thing is working fine except on a single click packery add three new items . My question is how to add one item on single click ? MethodDemoThanks.EditAfter page load grid items is Five . See the picture below.When click the Append items button packer...
var $ grid = $ ( '.grid ' ) .packery ( { itemSelector : '.grid-item ' } ) ; $ ( '.append-button ' ) .on ( 'click ' , function ( ) { // create new item elements var $ items = getItemElement ( ) .add ( getItemElement ( ) ) .add ( getItemElement ( ) ) ; // append elements to container $ grid.append ( $ items ) // add and ...
Packery appended methods add three items . How to add one item ?
JS
SVGs are ugly please review my : JSFIDDLE LINKHTML : CSS : Question : If we overlap these 2 svgs , What would the JS function be to highlight only the svg circles that have parts of alaska ( red ) in them in them ? review description below for more infoLet 's say you have a complex shape like the outline of alaska.Lets...
< svg version= '' 1.1 '' class= '' overlap-svg '' id= '' alaska '' > < /svg > < svg version= '' 1.1 '' class= '' overlap-svg '' id= '' grid '' > < /svg > .overlap-svg { position : absolute ; left:0 ; top : 0 ; }
Transform complex svg shapes into a circle abstraction
JS
Ok say we have this : what I want to do is define printName , something like this : where makePrintName is a functor , something like this : is this possible with ES6 ? My editor and TypeScript is not liking thisNOTE : using ES5 , this was easy to do , and looks like this : Using class syntax , currently the best thing...
class Car { constructor ( name ) { this.kind = 'Car ' ; this.name = name ; } printName ( ) { console.log ( 'this.name ' ) ; } } class Car { constructor ( name ) { this.kind = 'Car ' ; this.name = name ; } // we want to define printName using a different scope // this syntax is close , but is *not* quite correct printNa...
Create ES6/ESNext prototype function with different scope ( not an inline function )
JS
I 'm trying to get data from import.io servers but till now I got nothing . But when I use another api from another server with same code I get the data . Can you tell me what I 'm doing wrong.This is working code , the problem is that I got nothing from import.io servers . but when I use another url from another servi...
document.addEventListener ( 'deviceready ' , onDeviceReady , false ) ; function onDeviceReady ( ) { //console.log ( 'device is ready ' ) ; $ .ajax ( { type : 'GET ' , url : 'https : //api.import.io/store/data/6847842b-a779-46ba-874a-d1cfdcef2e3e/_query ? input/webpage/url=http % 3A % 2F % 2Fwww.girabola.com % 2F % 3Fp ...
How can I get data from my import.io api servers
JS
I 've got a javascript function 'doAll ' , which is supposed to write all the text that was put between < p > , < /p > tags . In my code it is used in two ways.It works correctly when I just call it at the end of the page . However it should also be triggered out when click-button event occurs . For some reason it does...
< ! DOCTYPE html > < html > < head > < script > function returnList ( x ) { return document.getElementsByTagName ( x ) ; } function writeList ( x ) { var i = 0 ; while ( x [ i ] ) { document.write ( x [ i++ ] .innerHTML + ' < br/ > ' ) ; } } function doAll ( x ) { writeList ( returnList ( x ) ) ; } < /script > < /head ...
Javascript function works in unexpected way
JS
It might be a dumb question . I googled it but ca n't find the answer . Variable declaration is not allowed as parameter of a function as below.But function declaration is being allowed as a parameter of a function as below.Can anyone please help me to understandWhy variable declaration is not allowed as a parameter of...
function t ( a ) { alert ( a ) ; } t ( var x = 1 ) ; // Uncaught SyntaxError : Unexpected token vart ( let x = 1 ) ; // Uncaught SyntaxError : missing ) after argument listt ( x = 1 ) ; // working fine and later I am able to access x alsoconsole.log ( x ) ; // printing 1 function callback ( str , f1 , f2 ) { if ( str =...
Why is variable declaration not allowed as a parameter , but function declaration is ?
JS
Given a SELECT element : I want to select the OPTION element with the value `` bar '' .This does n't work : However , this does work : Why ? Live demo : http : //jsfiddle.net/YbfqZ/2/
< select > < option > foo < /option > < option > bar < /option > < option > baz < /option > < /select > $ ( 'option [ text= '' bar '' ] ' ) .attr ( 'selected ' , true ) ; $ ( 'option : [ text= '' bar '' ] ' ) .attr ( 'selected ' , true ) ;
jquery : [ ] selector ?
JS
If I have two types of rows : header rows and data rows . and any row should compose of 18 columns.The number of data rows is based on the number of header rows for example : and so onI want to loop over the columns of the data rows and map to the related header col data : Let 's take The second example : I have two he...
If I have 2 header rows , I should have ( 2 datarows : the first one map to the first header row , the second one map to the second header row + 2 datarows : the first one map to the first header row , the second one map to the second header row + 1 data rows for total : maps to the first header row ) = 5 datarows per ...
How to loop conditionally to map header rows to data rows
JS
I 'm Implementing the ajaxStart event to show a modal saying `` loading '' .But , the big problem is this modal conflicts with jQuery Autocomplete , just does n't show the list of results on autocomplete.My autocomplete is : And I 'm handling Ajax events with this : How I can disable this modal for autocomplete or some...
$ ( `` # txtInput '' ) .autocomplete ( { minLength : 3 , source : `` autocomplete '' , multiple : true , select : function ( event , ui ) { $ ( `` # cie '' ) .val ( ui.item.label ) ; $ ( `` # id '' ) .val ( ui.item.id ) ; $ ( `` # addItem '' ) .prop ( 'disabled ' , false ) ; return false ; } } ) ; $ ( `` # dlgWait '' )...
ajaxStart cancels jQuery Autocomplete
JS
I have four canvas in my screen , positioned two above and two below.Each one have a button that makes possible to maximize the canvas , hiding the others.This button is positioned above each canvas , with absolute position based on offsetTop and offsetLeft of the canvas.However , when I maximize or minimize a canvas ,...
window.onload = function ( ) { resizeAll ( ) ; window.addEventListener ( 'resize ' , resizeAll , false ) ; } ; function resizeAll ( ) { vue. $ refs.panelOne.resizeDefault ( ) ; // ... vue. $ refs.panelN.resizeDefault ( ) ; } resizeDefault ( ) { let dimensions ; if ( this.expanded ) { dimensions = getScreenDimensions ( ...
HTML offsetLeft delays to change
JS
I know automatic semi-colon injection is a contentious issue but I would prefer if I could disable it on my Node.js based server.Script : With result : Or anything similar .
var foo = bar ( ) var baz = foo+1 ; [ Error ] Expected ' ; ' before var on line # 2
Way to stop ASI on Node.js and have it err ?
JS
I 'm not talking about complex race conditions involving the network or events . Rather , I seem to have found out that the += operator is not atomic in V8 ( Chrome 58 , or Node 8 ) .The code below aims to run two so-called threads in parallel . Each `` thread '' calls repeatedly a function that returns its number para...
function sleep ( ms ) { return new Promise ( resolve = > setTimeout ( resolve , ms ) ) ; } // Return the passed number after sleeping that many secondsasync function n ( c ) { await sleep ( c * 1000 ) ; console.log ( 'End ' , c ) ; return c ; } let acc = 0 ; // global// Call n repeatedly and sum up resultsasync functio...
Race condition in JavaScript with compound assignment
JS
Using the AngularJS framework , how do I have the `` Submit '' button both update the current entity as well as clear the anchor ID - I basically want to rapid-fire add entries , but it always turns my add form into an edit form . Here 's my current div which is n't working , it 's like it 's ignoring the $ anchor.task...
< div > Description : < input name= '' task.desc '' ng-required > < br > < a href= '' # '' ng-action= '' task. $ save ( ) ; $ anchor.task=null '' > Save < /a > < input type= '' button '' value= '' Add New '' ng-action= '' $ anchor.task=null '' > < /div >
How to submit new entity as well as clear $ anchor.task ?
JS
I 'm very confused about this program . I bought a book called `` Node JS , MongoDB , and AngularJS Web Development '' by Brad Dayley . I found a program to demonstrate something called closure , and it shows this program as an example . This is only the first part of the program.I 've been trying to figure out how thi...
function logCar ( logMsg , callback ) { process.nextTick ( function ( ) { callback ( logMsg ) ; } ) ; } var cars = [ `` Ferrari '' , `` Porsche '' , `` Bugatti '' ] ; for ( var idx in cars ) { var message = `` Saw a `` + cars [ idx ] ; logCar ( message , function ( ) { console.log ( `` Normal Callback : `` + message ) ...
Callback ( ) Node Js
JS
I imagine I 'm missing something in yuidoc documentation or misunderstanding usage . I can not seem to find a way to include a link to an external site/page in my documentation.In a comment block , I 'd like to have something like this :
/** * Creates a blah-blah for blah-blahing blah . * * @ constructor * @ param { object } blah * * Follow recommendations at : * @ link < a href= '' http : //blah.com/boop '' > Boop < /a > */
How to add add external links in yuidoc ( grunt-contrib-yuidoc )
JS
https : //jsfiddle.net/3oda22e4/6/myFunction increments a variable and returns something . If I use a function like that in an if statement that contains the variable which it increments , the condition would be order-dependent.Is it good or bad practice to do this , and why ?
var a = 1 ; function myFunction ( ) { ++a ; return true ; } // Alert pops up.if ( myFunction ( ) & & a === 2 ) { alert ( `` Hello , world ! `` ) ; } // Alert does not pop up.if ( a === 3 & & myFunction ( ) ) { alert ( `` Hello , universe ! `` ) ; }
Is it bad practice to use a function that changes stuff inside a condition , making the condition order-dependent ?
JS
I am looking for a function that will do something like this in Angular : I know $ eval does something similar to this , but it can not have double braces inside of it .
var testValues = { name : 'John Doe ' , number : 15 } somefunction ( 'Hello , { { name } } , you are { { number } } years old ' , testValues ) // returns 'Hello , John Doe , you are 15 years old '
Angular evaluate expression as if it were in the HTML
JS
Test in chrome !
parseInt ( 123123123123123123123123 ) ; //return 1parseInt ( 123123123123123123123123123 ) ; //return 1parseInt ( 123123123123123123123123123123 ) ; //return 1
Why parsing a very large number to integer return 1
JS
I want to replace all the occurrences of [ h2 ] [ /h2 ] in a JavaScript stringFor example , I haveI want to get - > hiiso far I tried
var mystring = 'hii [ h2 ] [ /h2 ] ' ; mystring.replace ( / [ h2 ] [ \/h2 ] /g , `` '' ) ;
Replace all string occurrences
JS
Clicking the facebook login button in the login form correctly brings up the fb login popup , but after entering credentials the pop-up closes and nothing happens . Clicking the button again without reloading the pages confirms that the fb account is connected as browser console prints : FB.login ( ) called when user i...
LOGIN_REDIRECT_URL = '/'LOGOUT_REDIRECT_URL = '/'DEFAULT_FROM_EMAIL = `` [ removed for stackoverflow ] '' ACCOUNT_EMAIL_REQUIRED = TrueSOCIALACCOUNT_EMAIL_REQUIRED = TrueACCOUNT_UNIQUE_EMAIL = TrueACCOUNT_EMAIL_VERIFICATION = 'mandatory'SOCIALACCOUNT_EMAIL_VERIFICATION = `` mandatory '' SOCIALACCOUNT_QUERY_EMAIL = True...
Debugging AllAuth : social account not logging user in despite connecting successfully
JS
I have this that works fine on my laptop , but not on mobile iOS.However , on mobile it as a few rows , but mostly it overflows to the right . Like it will have 2 or 3 rows but then 15 or 20 items per row ( when only 2 or 3 fit on screen ) . I have n't been able to get it working since I do n't have a good system to de...
* { /* normalize */ padding : 0 ; margin : 0 ; border : 0 ; color : inherit ; font-size : inherit ; font-weight : inherit ; text-transform : inherit ; font-family : inherit ; -webkit-font-smoothing : antialiased ; -webkit-text-size-adjust : none ; background : 0 0 ; min-height : 0 ; user-select : none ; box-sizing : bo...
flex-wrap : wrap not working on mobile iOS
JS
I have a weird problem with AngularJS and a REST webservice.This is my code : When calling this , I 'm getting an error and the .error is executed , but the e object is null.In the console , I 'm getting this error : When doing the DELETE request in postman ( the same one which gets called by my code ) , I 'm getting t...
$ http.delete ( appSettings [ 'baseUrl ' ] + 'pricelistitem/ ' + article.itemNumber + '/ ' + article.acc ) .error ( function ( e ) { console.log ( e ) ; } ) ; XMLHttpRequest can not load < url > . No 'Access-Control-Allow-Origin ' header is present on the requested resource . Origin 'http : //localhost:5000 ' is theref...
$ http.delete returns error without information
JS
I have a user agreement screen . Basically a HTML view with an iframe and a button . I want to enable the button when the user scrolls to the bottom . This works for all desktop browsers , IE , Chrome , Safari but does n't work on mobile safari or chrome on ios devices . It seems that the 'scrolling ' event does n't ge...
( function ( ) { angular.module ( 'myapp ' ) .directive ( 'textAgreement ' , function ( $ timeout , ActivityLogService ) { return { restrict : ' A ' , scope : { onscrollCallback : ' & onscrollCallback ' , onloadCallback : ' & onloadCallback ' } , compile : function ( tElement ) { return function ( scope , element ) { /...
AngularJS directive for a user agreement view , detect enabling button , does not work on mobile safari
JS
I am trying to trigger an ajax call on change of a dropdown menu ( at client_script.php ) . The ajax call will send some values to server_script.php and it will change a div section of the client_script.php . The problem is the server script is kept in a local directory such as blocks/latestgrades/server_script.php . W...
http : //localhost/umoodle http : //localhost/umoodle/ < something_i_dont_want_here > /
How to manipulate URL inside ajax call ?
JS
I would like that after I click on the submit button with new values inside input fields , my network d3.js plot would get updated based on the new graph generated by new input values . Here in the following , you can find my example code : GenerateGraph.js This file contains a bunch of functions which generate a graph...
function degree ( node , list ) { var deg=new Array ( ) ; for ( var i=0 ; i < node.length ; i++ ) { var count=0 ; for ( var j=0 ; j < list.length ; j++ ) { if ( node [ i ] ==list [ j ] [ 0 ] || node [ i ] ==list [ j ] [ 1 ] ) { count++ ; } } deg.push ( count ) ; } return deg ; } function randomGraph ( n , m ) { //creat...
Combining angularJS and d3.js : Refreshing a plot after submitting new input parameters
JS
Why is it when I write { } .key = 0 in the chrome console I get an error : But when I encapsulate the above expression in parentheses ( ( ) ) I get no error : What exactly is going on here ? I would have thought the same error I got in the first scenario still applied to the second ? Image of console output :
> { } .key = 0 > Uncaught SyntaxError : Unexpected token . > ( { } .key = 0 ) > 0
Why does adding parentheses prevent an error ?
JS
I 've been using jQuery to create HTML elements and then adding them to an XML document , like this : This is the output ( on Chrome 24 ) : Here 's the JSFiddle link . Unfortunately , I 'm having two problems.When I try to create an element with the name like child , it correctly creates a element with the tagName chil...
var doc = $ ( $ .parseXML ( ' < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < root/ > ' ) ) ; var docRoot = doc.find ( `` root '' ) ; var childEl = $ ( `` < child > '' ) ; docRoot.append ( childEl ) ; var imageEl = $ ( `` < image > '' ) ; docRoot.append ( imageEl ) ; var xmlString = doc.context.xml || new XMLSer...
jQuery creates incorrect element for image tag
JS
Just asking to understand how it works : It returns a very weird output . I think that My name is is a string within an array and everything else is just a string ( correct me if I am wrong ) .My Question is , what is the point of that and when would it make sense to use a function like that ? Also I would be glad if s...
function say ( something ) { return something ; } let name = ` Reza ` ; console.log ( say ` My name is ` , name , ' ! ' ) ;
Function without parentheses returns a weird output