I keep getting an error in a simple for loop trying to insert value from one array to another. My JS code is as:  var myApp = angular.module('myApp', []); myApp.controller('UserCtrl', function($http) {     let vm = this;     var datetime = [];     var venuename = [];     var venuecity = [];     var venuecountry = [];     var url = [];      var arr = [];     var id = "secret key";     vm.searchText;     var i=0;      vm.getByID = function() {          $http.get("https://rest.bandsintown.com/artists/" + vm.searchText + "?app_id="+id)         .then(response =&gt; {             console.log(response.data)             vm.name = response.data.name             vm.thumb = response.data.thumb_url             vm.fb = response.data.facebook_page_url             vm.up = response.data.upcoming_event_count             $http.get("https://rest.bandsintown.com/artists/" + vm.searchText + "/events" + "?app_id="+id)             .then(response2 =&gt; {                 console.log(response2.data)                 vm.arr = response2.data                 console.log(vm.up)                 console.log(vm.arr[0].datetime)                 console.log(vm.arr[1].datetime)                 for (i = 0; i &lt;=(vm.up-1); i++){                     vm.datetime[i] = vm.arr[i].datetime;                     vm.venuename[i] = vm.arr[i].venue.name;                     vm.venuecity[i] = vm.arr[i].venue.city;                     vm.venuecountry[i] = vm.arr[i].venue.country;                     vm.url[i] = vm.arr[i].url;                 }                 console.log(vm.up)             })         })     } });   The datetime part of the arr returns just as i want it to. I just cant store it into the new array. What im trying to do is that the array 'arr' contains all the objects of concerts of an artist. I want to display the individual details, for that I need to store each element in a new array, and repeat to create and show separate event details. Im a newbie at this and any help would be appreciated. Thanks in advance!
6952
What's the best way of checking if an object property in JavaScript is undefined?
115517
I wanted to suggest an edit for  given to , but it was denied because "Edits must be at least 6 characters."  However, given the edit I was suggesting is very important to the syntax of the solution, I think it is relevant even though it contains only 3 characters. See the answer posted by knittl and notice the variable $value is used as both function input and in the foreach loop. I simply suggested changing the function parameter's name to $values in the 3 locations it is used, but was denied, leaving the post incorrect.  Note: I do realize I could have suggested an entirely different variable name thus allowing the edit, but similar situations have arisen in the past where a simple fix of just a few characters make a significant difference. After all, Stack Overflow is a coding website and syntax is very important.
109364
I have a method which takes params object[] such as:  void Foo(params object[] items) {     Console.WriteLine(items[0]); }   When I pass two object arrays to this method, it works fine:  Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[]   But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:  Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[]   How do I pass a single object[] as a first argument to a params array?
65747
I'm running a REST API which is returning the below:  "id" : "fdgsdgsdsdgsdg",    "pageevents" : [ {        "name" : "test",        "number" : "0123442",        "homepage" : "www.test.com"     } ],     "goals" : [ {        "name" : "test",        "number" : "0123442",        "homepage" : "www.test.com"     } ] } ]   Im using the below code to de-serialize it, so i can display it as a pageblocktable on a visualforce page however im getting the error :      System.JSONException: Illegal value for primitive   public List&lt;maMoments&gt; getMomentsActivity() {     Id contactId;     if (contactId == null) {         contactId = '0030O00001sqXJr';     }      String contactIdString = String.valueOf(contactId);     String jsonResponse = this.AutomationDetailsMoments(contactIdString);     system.debug(jsonResponse);     List&lt;maMoments&gt; mAutomation = (List&lt;maMoments&gt;) JSON.deserialize(jsonResponse, List&lt;maMoments&gt;.class);     system.debug(mAutomation);     for(maMoments emailStructure : mAutomation){      }      return mAutomation; }  public string AutomationDetailsMoments(String contactId) {     contactId = '0030O00001sqXJr';     Http h = new Http();     HttpRequest req = new HttpRequest();     req.setEndpoint('https://virtserver.swaggerhub.com/mickjdavies/Example/1.0.0/interestingmoments');     req.setMethod('POST');     req.setBody(contactId);      // Send the request, and return a response     HttpResponse res = h.send(req);     system.debug(res.getBody());     return res.getBody(); }  private class maMoments {     public String contactId;     public String id;     public List&lt;String&gt; goals;     public String name;     public String homepage;     public String phone; }
29559
How do I remove all attributes which are undefined or null in a JavaScript object?  (Question is similar to  for Arrays)
123025
Can anyone help with this. I'm not sure at all what I'm doing wrong but i get an error Missing $ inserted.                   $ on the 2nd line with c)\  The rest of the text works fine and there are no $ signs that are not already paired in previous parts  \noindent c)\\ coordinates = (99,85),(190,220),(286,383)\\ \begin{align} error&amp;= \left | y-(a+bx) \right |\\ E&amp;= \left | y-(475.5+1.253x) \right |\\ (99,85): E&amp;=\left | 85-(475.5-1.253(99) \right |\\ &amp;=\left | 85-(351.5) \right |\\ &amp;=266.5\\ (190,220): E&amp;=\left | 220-(475.5-1.253(190) \right |\\ &amp;=\left | 220-(237.5) \right |\\ &amp;=17.5\\ (286,383): E&amp;=\left | 383-(475.5-1.253(286) \right |\\ &amp;=\left | 386-(117.2) \right |\\ &amp;=265.8\\ \end{align} $\therefore$ \text{Next location is "The Reservoir" at (190,220)} \end{document}
104870
I've been working on this task (see screenshot).     Here's my answer to it so far:  var sum_pairs=function(ints, s){   //your code here    var ptr_1 = 0,       ptr_2 = 0,       i = 0,       j = 0,       len = ints.length,       j_min = len,       arr_sum = [];    for (i; i &lt; len-1; i++){     for (j = i+1; j &lt; len; j++){       if(ints[i] + ints[j] === s){         if (j &lt; j_min){           j_min = j;           arr_sum = [parseInt(ints[i]), parseInt(ints[j])]         }       }     }   }  return ( (arr_sum.length === 0)? undefined : arr_sum );   }   However, while the tests all pass, it throws an STDERR about 'optimising the code':    How might I be able to optimise my code further?
80203
This error should be a simple one but I cant seem to make it work. The problem lies in the fact that this very same code works earlier in the program. I don's see any reason for it to be sending an error on this instance and not the four previous ones. Reference the code below, and feel free to provide any criticism you may have as it should make me better. If it matters, I am using Sharp Develop 2.2.  Here is an example of the code that works:  void calc2Click(object sender, EventArgs e) {     if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_e.Text))     {         MessageBox.Show("Enter either kVA and Voltage or FLA and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);     }                 if (!String.IsNullOrEmpty(tb2_kva.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_kva.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * 1000) / (1.732050808m * y); //the m at the end of the decimal allows for the multiplication of decimals                 tb2_fla.Text = z.ToString();             tb2_fla.Text = Math.Round(z,2).ToString();     }         else     {         if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_fla.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * y * 1.732050808m) / 1000; //the m at the end of the decimal allows for the multiplication of decimals               tb2_kva.Text = Math.Round(z,2).ToString();      }   Here is the example of the code that sends the error in the subject line of this post:  void Calc4Click(object sender, EventArgs e) {         if (!String.IsNullOrEmpty(tb4_fla.Text) &amp;&amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_kw.Text) &amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_e.Text))         {   //If values are entered improperly, the following message box will appear         MessageBox.Show("Enter either FLA and Voltage or kW and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);         }              if (!String.IsNullOrEmpty(tb4_fla.Text)&amp;&amp; !String.IsNullOrEmpty(tb4_e.Text)&amp;&amp; String.IsNullOrEmpty(tb4_kw.Text))         {//If the user eneters FLA and Voltage calculate for kW              decimal x, y, z;             x = decimal.Parse(tb4_fla.Text);             y = decimal.Parse(tb4_e.Text);             z = (x*y)*(.8 * 1.732050808m);             tb4_kw.Text = Math.Round(z,0).ToString();          }                         if (!String.IsNullOrEmpty(tb4_kw.Text) &amp;&amp; !String.IsNullOrEmpty(tb4_e.Text) &amp;&amp; String.IsNullOrEmpty(tb4_fla.Text))         {;//If the user enters kW and Voltage calculate for FLA             decimal x, y, z;             x = decimal.Parse(tb4_kw.Text);             y = decimal.Parse(tb4_e.Text);             z = (1000 * x)/(y * 1.732050808m)* .8;             tb4_fla.Text = Math.Round(z,0).ToString();         }      }   I appreciate any help that I can get.  Thank you.
65543
This is a simple component, not sure what I am missing, this is exactly referred in the docs:   Component:  &lt;aura:component &gt;     &lt;aura:handler name="init" action="{!c.navigate}" value="this"/&gt; &lt;/aura:component&gt;   JSController:  ({     navigate : function(component, event, helper) {         var urlEvent = $A.get("e.force:navigateToURL");         urlEvent.setParams({             "url": 'https://www.google.com/maps/place/'         });         urlEvent.fire();     } })   Error:  This page has an error. You might just need to refresh it. Action failed: c:navigatetoURlcmp$controller$navigate [Cannot read property 'setParams' of undefined] Failing descriptor: {c:navigatetoURlcmp$controller$navigate}
30794
I have written code like below and all works fine, but while submitting the form I get the error below. I am trying to filter the second dropdown based on the first drop down selection.     An illegal choice has been detected. Please contact the site administrator.   How do I overcome that error?       function dynamic_location_dropdown_form_alter(&amp;$form, $form_state, $form_id) {   if($form_id == 'product_node_form') {    $location_options = array();    if(isset($form['field_destination']['und']['#default_value'][0])) {     $destination = $form['field_destination']['und']['#default_value'][0];   }   else {     $destination = 0;   }    $location_options = dynamic_location_dropdown_locations($destination);    $form['field_destination']['und']['#ajax'] = array(     'event' =&gt; 'change',     'wrapper' =&gt; 'squadron-wrapper',     'callback' =&gt; 'dynamic_location_dropdown_ajax_callback',     'method' =&gt; 'replace',   );   $form['field_product_location']['#validated'] = true;   $form['field_product_location']['und']['#prefix'] = '&lt;div id="squadron-wrapper"&gt;';   $form['field_product_location']['und']['#suffix'] = '&lt;/div&gt;';   $form['field_product_location']['und']['#options'] = $location_options;   } }  function dynamic_location_dropdown_ajax_callback($form, $form_state) {   $country_id = $form['field_destination']['und']['#value'];   $form['field_product_location']['#validated'] = true;   $form['field_product_location']['und']['#options'] =  dynamic_location_dropdown_locations($country_id);    return $form['field_product_location']; }  function dynamic_location_dropdown_locations($destination_id) {   $nodes = array();   $nodes[''] = '- None -';   if($destination_id != '') {     $select = db_query("       SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created       FROM {node} node       LEFT JOIN {field_data_field_location_country} field_data_field_location_country        ON node.nid = field_data_field_location_country.entity_id        AND (field_data_field_location_country.entity_type = 'node'        AND field_data_field_location_country.deleted = '0')       WHERE (( (node.status = '1')        AND (node.type IN  ('location'))        AND (field_data_field_location_country.field_location_country_nid = $destination_id)))       ORDER BY node_title ASC     ");     $nodes[''] = '- None -';     foreach ($select as $node) {       $nodes[$node-&gt;nid] = $node-&gt;node_title;     }   }    return $nodes; }
122930
I'm comparing two list given in the list to see if the item.name exists in both for loop. If not then add into a list to show the error for the missing names.  set&lt;id&gt; setAssetIds = new set&lt;id&gt;(); list&lt;Asset_Store__c&gt;  assets = [select id,name......]; for(Asset_Store__c item : assets ) {     setAssetIds.add(item.id);  }   list&lt;Meter__c&gt;  meters = [select id,name......where id in : setAssetIds];  //now comparing the two lists for(Asset_Store__c a : assets) {    for(Meter__c m : meters)    {      if(a.Name != m.Name)      {        //not matched...        break;      }     } }   the problem with the above approach is that, its not finding the correct name.
49131
I'm playing with a trigger exercise, that consists of creating a trigger to create 10 Opportunities whenever a account with more than 100 employees are created. I made the following: trigger AccountTrigger on Account (after insert) {     List&lt;Contact&gt; Contacts = new List&lt;Contact&gt;();     for (Account acct : Trigger.new){                for(integer i = 0; i &lt; 2; i++){             Contact cont    = new Contact();             cont.LastName   = acct.Name+ i;             cont.AccountId  = acct.Id;             Contacts.add(cont);         }         insert Contacts;      if (acct.NumberOfEmployees &gt; 99){         List&lt;Opportunity&gt; Opportunities = new List&lt;Opportunity&gt;();         for(integer i = 0; i &lt; 10; i++){             Opportunity opp = new Opportunity();             opp.Name        = acct.Name + i;             opp.CloseDate   = system.today()+ 30;             opp.StageName   = 'Open';             opp.AccountId   = acct.Id;             Opportunities.add(opp);         }         insert Opportunities;     }                      }  }   And I'm getting the following error: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?:  I didn't created any, or changed the dupe rule of account neither Opportuinities. Can you help me understand what kind of error is this? And how can I change the trigger to workaround it? Thanks in advance!!
26657
Below is my code to read items from a document library.  var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID"; $.ajax({       url: url,       method: "GET",       headers: {           "Accept": "application/json; odata=verbose"       },       success: function(data) {           $.each(data.d.results, function(index, item) {             arrayCustomerID[index] = item.customerID;         });       },       error: function(data) {           console.log("error");       }   });     This work for the normal case but what should I do so that it works if I have more than 5000 items in the document library.
135
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:  int[] terms;  for(int runs = 0; runs &lt; 400; runs++) {     terms[] = runs; }   For those who have used PHP, here's what I'm trying to do in C#:  $arr = array(); for ($i = 0; $i &lt; 10; $i++) {     $arr[] = $i; }
85939
I have successfully created . Handy to avoid multiple calls to GAS services whit ordinary getRange calls.  While the code perfectly works in javascript, it throws an error in Google Apps Script upon saving.  The offending code is:  return matrix.slice(startRow, endRow + 1).map(i =&gt; i.slice(startCol, endCol + 1))   GAS seems rejecting code in the .map function.
50717
I want to do simple thing - I want to iterate over list of two objects and use displayColumns as dynamic keys to get values from selectList object:  &lt;aura:attribute name="displayColumns" type="String[]"/&gt; &lt;aura:attribute name="selectList" type="Object[]"/&gt;   &lt;table&gt;     &lt;aura:iteration items="{!v.selectList}" var="elem"&gt;     &lt;tr&gt;         &lt;aura:iteration items="{!v.displayColumns}" var="col"&gt;             &lt;td&gt;{!elem[col]}&lt;/td&gt;         &lt;/aura:iteration&gt;     &lt;/tr&gt;     &lt;/aura:iteration&gt; &lt;/table&gt;   In pure JS I would do: elem[col.value], but in lightning compiler returns:      expecting a positive integer, found 'col' at column 6 of expression:   elem[col.value]: Source   Is there any workaround without creating proper object structure in controller?
4667
Getting error with this code but I can't figure it out  trigger LeadConvert on Lead (after insert) {     list leadsToConvert = new list();      Database.LeadConvert lc;     string convertedStatus = '';     list convertStatusList = new list();     convertStatusList = [Select Id, MasterLabel                          from LeadStatus where IsConverted=true limit 1];     if(convertStatusList.size() &gt; 0){         convertedStatus = convertStatusList[0].MasterLabel;         }     else{              convertedStatus = 'Closed - Converted';          }      for(Lead l : trigger.New){         if(l.AutoConvert__c == true){             lc = new database.LeadConvert();             lc.setLeadId(l.ID);             lc.setDoNotCreateOpportunity(true);              lc.setConvertedStatus(convertedStatus);             leadsToConvert.add(lc);         }     }      list lcrList = new list();     lcrList = Database.convertLead(leadsToConvert); }