text:
Q: Node.js, Docusign, and Heroku "errorCode":"AUTHORIZATION_INVALID_TOKEN","message":"The access token provided is expired, revoked or malformed." I'm currently using the JWT auth flow for the docusign api. Everything works locally, but it doesn't work when deployed to Heroku. The gist is there's a webhook triggered by Copper CRM which then generates a JWT that gets traded for an access token to make the api calls to do some work finding the proper template and sending an envelope. I logged out the access token that gets generated and IT WORKS FINE MAKING THE SAME API CALL IN POSTMAN, but the api calls made through heroku give the error:
"errorCode":"AUTHORIZATION_INVALID_TOKEN","message":"The access token provided is expired, revoked or malformed."
Here's the code for generating the JWT and making the request to get the access token:
import jwt from 'jsonwebtoken';
import request from 'superagent';

export const createJWT = async() => {
    const iat = new Date().getTime() / 1000;
    const exp = new Date().setDate(new Date().getDate() + 2) / 1000;
    return jwt.sign({
        iss: process.env.DOCUSIGN_INTEGRATION_KEY,
        sub: process.env.DOCUSIGN_API_USERNAME,
        iat: iat,
        exp: exp,
        aud: 'account-d.docusign.com',
        scope: 'signature impersonation'
    },
        process.env.DOCUSIGN_PRIVATE_KEY,
        {
            algorithm: 'RS256'
        });
};

export const getAccessTokenFromJWT = async(jwt) => {
    const res = await request.post(`https://account-d.docusign.com/oauth/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${jwt}`)
      .catch(err => console.log(err));
    return res.body.access_token;
};

Here's the code for the first api call the webhook makes - the one that gives the error.
import request from 'superagent';
import dotenv from 'dotenv';

dotenv.config();

export const findTemplateIdByCohortName = async (cohortName, access_token) => {
    const url = `${process.env.DOCUSIGN_BASE_PATH}/v2.1/accounts/${process.env.DOCUSIGN_ACCOUNT_ID}/templates?search_text=${cohortName}`;
    const result = await request.get(url)
      .set({
          Authorization: `Bearer ${access_token}`
      });
    if(result.body.envelopeTemplates) {
        return result.body.envelopeTemplates[0].templateId;
    } else {
        return null;
    }
};

Here's the route that handles the webhook (I'm using module import syntax):
import express from 'express';
import { useTemplate } from '../request/docusign/docusign-methods.mjs';
import opportunities from '../request/prosperworks/opportunities.mjs';
import people from '../request/prosperworks/people.js';
import customFields from '../request/prosperworks/custom-fields.mjs';
import { findTemplateIdByCohortName } from '../request/docusign/templates.mjs';
import { findSentEnvelopesByStudentEmail, voidEnvelope, findTemplateFromEnvelopeTemplateUri } from '../request/docusign/envelopes.mjs';
import { createJWT, getAccessTokenFromJWT } from '../request/docusign/token.mjs';

const router = express.Router();

export default router
  .post('/copper/opportunity/updated', express.json(), async (req, res, next) => {
      const { body } = req;
      console.log('webhook received', body);
      const jwt = await createJWT();
      const access_token = await getAccessTokenFromJWT(jwt);
      console.log(access_token);
      if(!Object.keys(body.updated_attributes).length) return res.send('irrelevant webhook');
      if(body.updated_attributes.custom_fields['94620'] || body.updated_attributes.stage[0] === 'Interview Scheduled' && body.updated_attributes.stage[1] === 'Accepted') {
          try {
              const opportunity = await opportunities.get(body.ids[0]);
              const cohortId = opportunity.custom_fields.find(field => field.custom_field_definition_id === 94620).value;
              const cohortName = customFields.getCohortNameById(cohortId);
              const templateId = await findTemplateIdByCohortName(cohortName);
              const person = await people.findById(opportunity.primary_contact_id);
              const email = person.emails[0].email;
              const { name } = person;
              const sentEnvelopes = await findSentEnvelopesByStudentEmail(email, access_token);
              await Promise.all(
                sentEnvelopes.filter(envelope => {
                    return envelope.emailSubject.includes('Enrollment Agreement');
                })
                .map(envelope => {
                    if(envelope.status === 'sent') return voidEnvelope(envelope.id, access_token);
                })
              );
              const sentEnvelopesTemplates = await Promise.all(sentEnvelopes.map(envelope => {
                  return findTemplateFromEnvelopeTemplateUri(envelope.templatesUri, access_token);
              }));
              const templateAlreadyUsedCheck = sentEnvelopesTemplates.reduce((outerAcc, templateArr) => {
                  if(templateArr.reduce((innerAcc, template) => {
                      if(template.templateId === templateId) innerAcc=true;
                      return innerAcc;
                  }, false)) {
                      outerAcc=true;
                  }
                  return outerAcc;
              }, false);
              console.log(templateAlreadyUsedCheck);
              if(templateAlreadyUsedCheck) return res.send('envelope already sent');
              const envelope = await useTemplate({
                  basePath: process.env.DOCUSIGN_BASE_PATH,
                  accessToken: access_token,
                  accountId: process.env.DOCUSIGN_ACCOUNT_ID,
                  envelopeArgs: {
                      templateId: templateId,
                      signerEmail: email,
                      signerName: name
                  }
              });
              return res.send(envelope);
          }
          catch(err) {
              console.log(err);
              next(err);
          }
      } else {
          return res.send('irrelevant webhook');
      }
  });

A: A couple questions on this:

*

*Are you using the same integration key when you try this locally vs on Heroku?

*I noticed your env is hardcoded to aud: 'account-d.docusign.com'. Did you mean to use the demo env both locally and in Heroku?

My understanding here is that all of this works fine when you run locally on Postman, but after you deploy in Heroku then you see the authorization error. Is my understanding accurate?
Thanks!

A: It turns out the problem was that I wasn't passing access_token to the function that makes the api call.


text:
Q: highlight text box border color for few seconds? Hi i want to highlight a text box border color for few seconds , afterwards i want to change it back to  white color. is ther a way for addClass function to specify time also. Any other way ?tried with http://jsfiddle.net/RW2s4/7/ not working

A: You can use switchClass, something like:
$("#element").switchClass("removeThisClass", "addThisClass", 1000)

Demo Fiddle: HERE
Reference:JQuery Docs

A: This little script added the class 'highlight' for two seconds to the input field:
$('#text').change(function() {
    var jElement = $(this);
    jElement.addClass('highlight');
    setTimeout(
        function() { jElement.removeClass('highlight'); },
        2000
    );
});

Also see this example.
Or here the combination of your and mine solution.

A: Highlight div on click slide to div
$('.box').click(function() {
    var jElement = $(this);
    jElement.addClass('highlight');
    setTimeout(
        function() { jElement.removeClass('highlight'); },
        500
    );
    //$(window).scrollTop($('.box3').offset().top,100);
    $("html, body").delay(100).animate({
        scrollTop: $('.box2').offset().top
    }, 2000);

});

    <button>http://jsfiddle.net/tyPct/198/    </button>

A: See live   Demo
$(function(){

  setTimeout(ChangeBorder, 2000);

  function ChangeBorder() {
     $(".highlight").css({"border-color":"red"});
  }
});

A: Check jquery animate function which animates the element after some interval:
http://api.jquery.com/animate/
demo: http://jsfiddle.net/umSkg/2/
$(document).ready(function(){
    var ogColor = $("#inpt").css("border-left-color");
    $("#trggr").click(function(){
        var inpt = $("#inpt");
        var delay = 1000;
        inpt.animate({ borderColor: "#EAC117" }, delay,function(){
        //revert after completing
        inpt.animate({ borderColor: ogColor }, delay);
        });
    });

});

A: Use the effect function
$('#component').effect("highlight", {color: 'red'}, 2000);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I grab an http response from a flash object? I know that certain flash objects send HTTP requests to their intended domain. How do I grab the flash object's server's response and store it in a variable in Javascript? I have no code because I'm completely unsure of what to do.

A: You cannot directly capture HTTP traffic between a Flash object and its host from JavaScript, for several reasons, one of them being security. You can, however, make calls between the Flash object and the SWF container (in this case, the browser running JavaScript) through ExternalInterface. This requires coordination between the two sides but it works well, as long as browser version and configuration together allow it to execute.


text:
Q: How to keep a normative Software Engineering when many .py files import duplicated packages? I write some utility/ tool .py files, but it import many duplicated packages. And I will import these .py files in the rest .py files.
For example:
# tool_a.py
import a
from b import b_1
import c
from e import e_1
# some implementations in a.py.
... ...
... ...

# tool_b.py
import b
import c
from d import d_1
# some implementations in b.py
... ...
... ...

# tool_c.py
import c
import d
import e
# some implementations c.py
... ...
... ...

# And there are so many tools files like this
... ...
... ...

# Class A
import tool_a
import tool_b
# some implementations in Class A
... ...
... ...

# Class B
import tool_a
import tool_c
# some implementations in Class B
... ...
... ...

# And there are so many Class implementation files will include these tool files just like here
... ...
... ...

So if I just import these tools files one by one in each class file it will import so many duplicated packages and cause dependency problems
Sure it is a bad way, but I don't know how to solve the terrible packages dependency problems.
Could anyone help me ?

A: I don't think you need to worry about the multiple imports. If you tell python to import a module that is already imported, it will just access the cached module from when it was initially imported. The best practice is to just import the modules where you need them and not worry if the same module is imported in several files.


text:
Q: Need to write a unix script to FTP one .dat file I am new to unix (KSH) and I need to write a unix script to FTP one .dat file from one server location to another server location. Kindly  help to write such code.
"From- server A, Location - vic/folder/day.dat
TO - Server B, Location - sam/folder"

A: Probably you need to take a time to learn use of expect command and scripting. Wikipedia's expect page has a lot of samples about how to use it.


text:
Q: A shorter way to set up links in Wordpress posts? It bugs me that every time I add a link in the content area of a Wordpress page or post, I have to type the entire  text as opposed to quick formats available in php or the css file, such as .
Is writing out the entire domain every time the only way to set the link up, or am I missing out on a shortcut?

A: Besides using the "Add Media" button above the text entry, there is no default way to enter that little info. You can register some short code so you could write it like [img src="myimage.jpg"] in your text editor.
functions.php
function img_func( $atts ) {
    extract( shortcode_atts( array(
        'src' => 'something'
    ), $atts ) );
    $route = 'http://mywebsite.com/images/'.$src;
    return $route;
}
add_shortcode( 'img', 'img_func' );


text:
Q: Continuum limit of $ \sum_{r=1}^\infty \sum_{z=1}^\infty a_r |r z \rangle \langle r z | = \sum_{l=1} b_l |l \rangle \langle l | $? Background
Using bra-ket notation consider the identity (for integer $r$) :
$$ \sum_{z=1}^\infty |r z \rangle \langle r z |  =   I \otimes \underbrace{\begin{bmatrix}
    0 & 0 & 0 & 0 \\
    0 & 0 & 0 & 0\\
    0 & 0 & \ddots & 0 \\
    0 & 0 &0 & 1
  \end{bmatrix}}_{\dim r}
$$
with $I$ begin the identity matrix. Multiplying an arbitrary constant $a_r$ both sides:
$$ \sum_{z=1}^\infty a_r |r z \rangle \langle r z | = I \otimes   \underbrace{\begin{bmatrix}
    0 & 0 & 0 & 0 \\
    0 & 0 & 0 & 0\\
    0 & 0 & \ddots & 0 \\
    0 & 0 &0 & a_r
  \end{bmatrix}}_{\dim r}
$$
Now, summing over $r$:
$$ \sum_{r = 1}^\infty \sum_{z=1}^\infty a_r |r z \rangle \langle r z | dz = I \otimes \sum_{r = 1}^\infty   \underbrace{\begin{bmatrix}
    0 & 0 & 0 & 0 \\
    0 & 0 & 0 & 0\\
    0 & 0 & \ddots & 0 \\
    0 & 0 &0 & a_r
  \end{bmatrix}}_{\dim r}
$$
Let us explicitly handle the R.H.S:
$$
 \begin{bmatrix}
    a_1 & 0 & 0 & 0 \\
    0 & a_1 & 0 & 0\\
    0 & 0 & \ddots & 0 \\
    0 & 0 &0 & a_1
  \end{bmatrix}
+
\begin{bmatrix}
    0 & 0 & 0 & 0 \\
    0 & a_2 & 0 & 0\\
    0 & 0 & \ddots & 0 \\
    0 & 0 &0 & a_2
  \end{bmatrix}
+ \dots
$$
Hence with  $b_r = \sum_{i|r} a_i $
$$ \sum_{r=1}^\infty  \sum_{z=1}^\infty a_r |r z \rangle \langle r z |  =   {\begin{bmatrix}
    b_1 & 0 & 0 & 0 \\
    0 & b_2 & 0 & 0\\
    0 & 0 &  b_3 & 0 \\
    0 & 0 &0 & \ddots
  \end{bmatrix}}  = \sum_{l=1} b_l |l \rangle \langle l |
$$
Question
Is the above proof correct?  With  $b_r = \sum_{i|r} a_i$:
$$ \sum_{r=1}^\infty  \sum_{z=1}^\infty a_r |r z \rangle \langle r z |  = \sum_{l=1} b_l |l \rangle \langle l |
$$
Is there a continuum limit of this formula? Does  $ \sum_{z=1}^\infty |r z \rangle \langle r z |$ have a continuum analog?


text:
Q: parse.com how can I change the createdAt date via the dashboard I have a data class.
As an object is added to the class the createdAt date is generated.
I want to change this date manually via the dashboard.  However, when I select the createdAt column for a particular row, it doesn't seem to be editable.  Is there some way of making this column editable ?
Thanks,
Guy

A: You cannot. See: https://www.parse.com/docs/data#data-browser:
Data Browser
The Data Browser is the web UI where you can update and create objects in each of your apps. Here, you can see the raw JSON values that are saved that represents each object in your class.
[...]
When using the interface, keep in mind the following:
[..]

*

*The objectId, createdAt, updatedAt fields cannot be edited (these are set automatically).
[..]*


text:
Q: How to ensure pointers don't point to the same place Running the following code, it get 57 57 printed out, what I need is 56 57. I know this is because the pointers are pointing to the same location, but how do I avoid this?
int (*spriteArray[10])[8][8];
int i = 0;

void setup()
{
   Serial.begin(9600);
}

void loop()
{

someOtherMethod();
i++;
someOtherMethod();

someMethod();

  delay(100000);
}

void someOtherMethod()
{
    int sprite[8][8];
    spriteArray[i]= &sprite;

    sprite[0][0] = 56+i;

}
void someMethod()
{

  Serial.println(*spriteArray[0][0][0]);
  Serial.println(*spriteArray[1][0][0]);

}

A: In someOtherMethod you store a pointer to a local variable, and that pointer is not valid after the function returns. Dereferencing this pointer causes undefined behavior.


text:
Q: Segmentation fault while reading a file into a linked list I'm using a function that returns a pointer to the next word in the file to create a linked list of the unique strings in the file. I haven't gotten to the part where I need to increment the count for each duplicate because I'm getting a "Segmentation fault (core dumped)" error while trying to print the strings in the list. Right now I'm guessing that it has something to do with me not properly handling the NULL at the end of the file, but I really don't know what I would do to fix that. Any help on this issue would be very much appreciated and thank you for your time.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#define MAX_WORD_LEN 256

struct list {
    int count;
    char string[MAX_WORD_LEN];
    struct list *next;
};

char* getNextWord(FILE* fd) {
    char c;
    char wordBuffer[MAX_WORD_LEN];
    int putChar = 0;

    while((c = fgetc(fd)) != EOF) {
        if(isalnum(c)) break;
    }
    if (c == EOF) return NULL;

    wordBuffer[putChar++] = tolower(c);

    while((c = fgetc(fd)) != EOF) {
        if(isspace(c) || putChar >= MAX_WORD_LEN -1) break;

        if(isalnum(c)) {
            wordBuffer[putChar++] = tolower(c);
        }
    }
    wordBuffer[putChar] = '\0';
    return strdup(wordBuffer);
}

int main() {

    char filename[50];
    printf("Enter the file name: \n");
    scanf("%s\n", filename);
    FILE *file = fopen(filename, "r");
    struct list *head, *tail, *curr;
    head = NULL:
    char *newWord;
    while((newWord = getNextWord(file)) != NULL) {

        strcpy(curr->string, newWord);
        free(newWord);
        if(head == NULL)
            head = curr;
        else
            tail->next = curr;
        tail = curr;
        tail->next = NULL;
    }
    fclose(file);
    for(curr = head; curr != NULL; curr = curr->next) {
        printf("%s\n", curr->string);
    }

    return 0;

}

A: Take a close look at the following snippet:
struct list *head, *tail, *curr;
head = NULL:
char *newWord;
while((newWord = getNextWord(file)) != NULL) {

    strcpy(curr->string, newWord);

You are accessing a member of the object pointed to by curr, but what object is that? It is never initialized, it's quite likely the first access through it that you're seg-faulting. To solve it, set it to a new node each time through:
struct list *head, *tail, *curr;
head = NULL;
char *newWord;
while((newWord = getNextWord(file)) != NULL) {
    curr = malloc(sizeof(struct list));
    strcpy(curr->string, newWord);


text:
Q: Is it possible to bind a jquery call to two CSS selectors? I want to bind a mouseout call to two CSS selectors so that if I've moved my mouse from one AND the other element, then I call something else. Is this even possible?

A: You can use something like
$("#selector1, #selector2").bind("mouseout", function(){
    // code goes here
});

Read Multiple Selector ("selector1, selector2, selectorN")

A: $('.class1, .class2').mousemove(callbackFunction);

jQuery selectors work just like CSS. Just use a comma to separate the classes.


text: Q: Comparing categorical variable results across multiple time points I'd like to compare categorical variable results across multiple time points. In the example below, group 3 has a drop in positives from 14 to 4. As I understand it, contingency table tests such as the Fishers exact test or Chi-squared test are not appropriate because 100% of all samples have been tested at each time point. ANOVA is not appropriate either as I am not comparing means. What would be the most appropriate statistical test?  Thank you


text:
Q: How can i set the bounds of the PowerPoint slide background image via interop I need to use the below highlighted properties of fill in interop PowerPoint. I am trying this in C#. I found the below codes to set the slide background,
slide = presentation.Slides[1];

slide.FollowMasterBackground = MsoTriState.msoFalse;

slide.Background.Fill.UserPicture("Image.jpg");

Now the picture is stretched and center aligned. But I could not update the bounds as highlighted in the below screenshot,

Any one of you help me to do this.
Thanks in advance.
Thanks,
M.Ramaraj


text:
Q: Get the Current Time from Latitude and Longitude Using GeoNames API I  am currently creating application which requires Current Time From the Country.
I have latitude and longitude of different Country.
I have use following Link to get the Current Time
http://api.geonames.org/timezone?lat=21.7679&lng=78.8718&username=demo
(demo user name is by default and used only for testing because it has query limit)
I got the current Time but when Daylight Saving Time is ON. Is that API gives me the correct Time? If not then how could i get the current Time.
In some of the API I get the current time like earthtool(not implemented DST). But i could not Test because currently there is no DST Implemented so how can i test in this case?
I am Creating Application in .NET with C# 4.0
If any other API then please Tell Me but first priority to GeoNames API.

A: I would be very surprised if that didn't reflect the current local time. The results for Sao Paolo (which is currently observing DST) seem to agree with that:
<geonames>
  <timezone tzversion="tzdata2012f">
  <countryCode>BR</countryCode>
  <countryName>Brazil</countryName>
  <lat>-23.0</lat>
  <lng>-46.0</lng>
  <timezoneId>America/Sao_Paulo</timezoneId>
  <dstOffset>-3.0</dstOffset>
  <gmtOffset>-2.0</gmtOffset>
  <rawOffset>-3.0</rawOffset>
  <time>2012-12-17 10:48</time>
  <sunrise>2012-12-17 06:14</sunrise>
  <sunset>2012-12-17 19:47</sunset>
  </timezone>
</geonames>

However, another alternative would be to use the GeoNames API to get the time zone ID, and then use Noda Time for everything to do with that time zone. (Disclaimer: I'm the primary developer of Noda Time.)
You can't just use the BCL's TimeZoneInfo class directly, as that doesn't support TZDB the time zone IDs that GeoNames provides (e.g. "Asia/Kolkata"). You could just use a mapping (CLDR provides one) but in my experience the Windows time zone information has some disturbing oddities.
If you just need to know the current time, GeoNames is probably fine -


text:
Q: Login-AzureRmAccount unattended I have a Powershell script to set app config setting, like this:
Set-AzureRMWebApp -Name $SiteName -ResourceGroupName $ResourceGroupName -AppSettings $settings

This script will be used by VSTS Release-Management in Azure but also by developers within their VS2015 IDE.
The PS script has a command 'Login-AzureRmAccount' which will show a popup on their local dev machine, that's ok.
But this script is also used by Release-Management using a PS task, but I get an error when kicking off a release:
'Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation'.
How can I prevent the dialog in VSTS only ?
(note that the Set-AzureRMWebApp seems to works fine, but only the prevention of the dialog results in the task error).

A: You need to parameterise the login section of your script so this only runs if it isn't being ran by a dev. When devs run it, call it with a switch to say so.
Then you can do something like
$secret = yourServicePrincipalKey
$azureApplicationId = yourServicePrincipalID
if (!switch)
{
$password = ConvertTo-SecureString -String $secret -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($azureApplicationId, $password)
$access = Login-AzureRmAccount -Credential $creds -ServicePrincipal -TenantId $tenantId
}

You can see that Login-AzureRmAccount has the -servicePrincipal switch enabled

A: This is the fix that works:
if ([Environment]::UserInteractive -and
        !([Environment]::GetCommandLineArgs() |? {$_ -ilike '-NonI*'}))
{
    Login-AzureRmAccount
}


text:
Q: How can I prevent bad inputs when storing phone numbers as strings? I am creating a phonebook program that can read VCards. The problem is with phone numbers. Normally, they will be like this in the United States:
0771234560
But if the phone number is from a foreign country, it would look like this.
+94771234560 or maybe (22)772324000
Now there are + and () signs to deal with! I am currently converting phone numbers (VCards contain them as Strings) to numbers. However, if I take allow phone numbers as strings, then a user could do something crazy, like insert a name as a phone number in the contact form.
How can I store phone numbers as strings but prevent problematic entries?

A: Don't use a numeric type for phone numbers, stick with a String.
Do some form of input validation. Define some restrictions on your phone numbers, and when reading the card, check the String against your format: if the phone number doesn't match your restrictions, then reject it.
Search around this site for questions/answers regarding phone number validation.

A: What would adding two phone numbers mean? So, IMO, not a number.
You should still attempt to validate, but if you want to accept any and all arbitrary international numbers, including local conventions for how they're written, that'll be frustrating.

A: Definitely use a string, but validate it. Just because it's a string doesn't mean you have to accept any data. You should consider using a regular expression (or perhaps a series of regular expressions) to validate the data.
Don't just limit it to specific characters - for example, you don't want to accept ")0(" as a phone number - use sensible patterns. The Wikipedia page on local conventions for phone numbers may prove helpful on this front - or you could look for other sources. You may also want to consider being somewhat lenient, as not everyone will follow exact patterns. There's a delicate balance to be achieved though.


text:
Q: javascript color randomizer does not work I want to change the color of the circles every time I refresh the page
JavaScript code:
var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('cirkel1').style.background = random_color;

CSS code:
div {display: inline-block; margin-left: 10px;}

#cirkel1 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

#cirkel2 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

#cirkel3 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

#cirkel4 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

and HTML code:

but for some reason it doesn't seem to work.

A: Your code is not working because   var random_color = colors[Math.floor(Math.random() * colors.length)];
give you one color at a time and and store it in random_color to get random color for or every circle you need to call it whenever you need a new random color
please read comment in my code for understand how it is working

var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
//document.getElementById('cirkel1').style.background = random_color;
var x = document.getElementsByClassName("cir"); // read all circle by class name
for(var i=0;i<x.length;i++ ){
// loop through every circle and every time generate a new random color
 x[i].style.background = colors[Math.floor(Math.random() * colors.length)];
    console.log( x[i])
}

div {display: inline-block; margin-left: 10px;}

    #cirkel1 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

    #cirkel2 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

    #cirkel3 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

    #cirkel4 { width: 100px; height: 100px; background: red; -moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px; }

A: You need to create a random number generator function and call it each time.
var randomNumber = function(){
  return Math.floor(Math.random() * colors.length)
}

then
document.getElementById('cirkel1').style.backgroundColor = color[randomNumber()];

demo

A: This works for me, but you are only updating the first circle.
document.getElementById('cirkel1').style.background = random_color;

If I change the code to:
var colors = ['#ff0000', '#00ff00', '#0000ff'];
function randomColor(){
    return colors[Math.floor(Math.random() * colors.length)];
}
document.getElementById('cirkel1').style.background = randomColor();
document.getElementById('cirkel2').style.background = randomColor();
document.getElementById('cirkel3').style.background = randomColor();
document.getElementById('cirkel4').style.background = randomColor();

I get different colours.
This changes the random_colour to be a function.
Here is the jsFiddle: http://jsfiddle.net/kgjertsen/mf7myuxs/


text:
Q: Initialize a hydrator result set and aggregate in ZF2 I am joining two tables and have successfully managed to write a hydrator that outputs the following array:
    $sql = new Sql($this->dbAdapter);
    $select = $sql->select('misc_damage');
    $select->where(array('vehicle_id = ?' => $id))->order('date_added DESC');
    $select->join('user','user.user_id = misc_damage.added_user_id',
            array(
                'user_display_name' => 'display_name',
                'user_email' => 'email',
                'user_username' => 'username'
                ),
    'left');

    $stmt = $sql->prepareStatementForSqlObject($select);
    $result = $stmt->execute();

    if ($result instanceof ResultInterface && $result->isQueryResult()) {

        $hydrator = new AggregateHydrator();
        $hydrator->add(new ClassMethods());
        $hydrator->add(new \Application\Hydrator\UserHydrator());

        $miscDamage = $hydrator->hydrate($result->current(), new \Application\Model\Miscdamage());
        var_dump($miscDamage);
        die();
    }

This produces 1 result:
/var/www/zf-skeleton/module/Application/src/Application/Mapper/ZendDbSqlMapper.php:95:
object(Application\Model\Miscdamage)[655]
  protected 'id' => string '97' (length=2)
  protected 'vehicle_id' => string '3' (length=1)
  protected 'added_user_id' => string '1' (length=1)
  protected 'description' => string 'sdfsdsdf' (length=8)
  protected 'date_added' => string '2016-04-15 08:19:17' (length=19)
  protected 'date_repaired' => null
  protected 'repaired_user_id' => null
  protected 'status' => string '0' (length=1)
  protected 'user' =>
    object(Application\Model\User)[664]
      protected 'user_id' => string '1' (length=1)
      protected 'username' => null
      protected 'email' => string 'alex@home.com' (length=13)
      protected 'display_name' => string 'Alex' (length=4)

There should be multiple results as each vehicle can have multiple damage entries. How would I go about using HydratingResultSet with my AggregateHydrator? I would also like to initialize the result: return $resultSet->initialize($result);
Any help is appreciated!

A: I found out how to do this. Need to use HydratingResultSet and Reflection:
    use Zend\Stdlib\Hydrator\Reflection as ReflectionHydrator;

    if ($result instanceof ResultInterface && $result->isQueryResult()) {

        $hydrator = new AggregateHydrator();
        $hydrator->add(new ClassMethods());
        $hydrator->add(new \Application\Hydrator\UserHydrator());

        $resultSet  = new HydratingResultSet(new ReflectionHydrator, new \Application\Model\Miscdamage());
        $resultSet->setHydrator($hydrator);

        return $resultSet->initialize($result);

    }


text:
Q: How to get a field's type by using CDT parser I'm trying to extract c++ source code's info.
One is field's type.
when source code like under I want to extract info's Type when info.call() is called.
Info info;
//skip
info.call(); //<- from here

Trough making a visitor which visit IASTName node, I tried to extract type info like under.
public class CDTVisitor extends ASTVisitor {

    public CDTVisitor(boolean visitNodes) {
        super(true);
    }

    public int visit(IASTName node){
        if(node.resolveBinding().getName().toString().equals("info"))
            System.out.println(((IField)node.getBinding()).getType());
            // this not work properly.
            //result is "org.eclipse.cdt.internal.core.dom.parser.ProblemType@86be70a"

        return 3;
    }
}

A: Assuming the code is in fact valid, a variable's type resolving to a ProblemType is an indication of a configuration problem in whatever tool or plugin is running this code, or in the project/workspace containing the code on which it is run.
In this case, the type of the variable info is Info, which is presumably a class or structure type, or a typedef. To resolve it correctly, CDT needs to be able to see the declaration of this type.
If this type is not declared in the same file that's being analyzed, but rather in a header file included by that file, CDT needs to use the project's index to find the declaration. That means:

*

*The AST must be index-based. For example, if using ITranslationUnit.getAST to create the AST, the overload that takes an IIndex parameter must be used, and a non-null argument must be provided for it.

*Since an IIndex is associated with a CDT project, the code being analyzed needs to be part of a CDT project, and the project needs to be indexed.

*In order for the indexer to resolve #include directives correctly, the project's include paths need to be configured correctly, so that the indexer can actually find the right header files to parse.
Any one of these not being the case can lead to a type resolving to a ProblemType.

A: Self response.
The reason I couldn't get a binding object was the type of AST.
When try to parse C++ source code, I should have used ICPPASTTranslationUnit.
There is no code related this, I used IASTTranslationUnit as a return type of AST.
After using ICPPASTTranslationUnit instead of IASTTranslationUnit, I solved this problem.

A: Yes, I figure it out! Here is the entire code which can index all files in "src" folder of a cpp project and output the resolved type binding for all code expressions including the return value of low level API such as memcpy. Note that the project variable in following code is created by programatically importing an existing manually configured cpp project. I often manually create an empty cpp project and programatically import it as a general project (once imported, Eclipse will automatically detect the project type and complete the relevant configuration of CPP project). This is much more convenient than creating and configuring a cpp project from scratch programmatically. When importing project, you'd better not to copy the project or containment structures into workspace, because this may lead to infinitely copying same project in subfolder (infinite folder depth). The code works in Eclipse-2021-12 version. I download Eclipse-For-cpp and install plugin-development and jdt plugins. Then I create an Eclipse plugin project and extend the "org.eclipse.core.runtime.applications" extension point.
In another word, it is an Eclipse-Application plugin project which can use nearly all features of Eclipse but do not start the graphical interface (UI) of Eclipse. You should add all cdt related non-ui plugins as the dependencies because new version of Eclipse does not automatically add missing plugins any more.
        ICProject cproject = CoreModel.getDefault().getCModel().getCProject(project.getName());
        // this code creates index for entire project.
        IIndex index = CCorePlugin.getIndexManager().getIndex(cproject);

        IFolder folder = project.getFolder("src");
        IResource[] rcs = folder.members();
        // iterate all source files in src folder and visit all expressions to print the resolved type binding.
        for (IResource rc : rcs) {
            if (rc instanceof IFile) {
                IFile f = (IFile) rc;
                ITranslationUnit tu= (ITranslationUnit) CoreModel.getDefault().create(f);
                index.acquireReadLock(); // we need a read-lock on the index
                ICPPASTTranslationUnit ast = null;
                try {
                    ast = (ICPPASTTranslationUnit) tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
                } finally {
                    index.releaseReadLock();
                }
                if (ast != null) {
                    ast.accept(new ASTVisitor() {
                        @Override
                        public int visit(IASTExpression expression) {
                            // get the resolved type binding of expression.
                            IType etp = expression.getExpressionType();
                            System.out.println("IASTExpression type:" + etp + "#expr_str:" + expression.toString());
                            return super.visit(expression);
                        }
                    });
                }
            }
        }


text:
Q: How to make my query more efficient in C# using MongoDB I have a method that on click produces an excel file with information in it. I have been asked to pull images from the data base and add them within the excel file as well. This is how I am pulling the images
ProductImages = new List<ProductImageAndMeta>();
var flyerBlocks = await FlyerBlockRepository.FindAllInAllPageByFLyerIdAsync(selectedFlyer.Id);
var ComposerDataImages = await ComposerDataFilesRepo.GetAllFlyerImages(FlyerId);

foreach (var ComposerDataImage in ComposerDataImages)
{
  var ProductImage = new ProductImageAndMeta();
  ProductImage.Id = ObjectId.Parse(ComposerDataImage.Id);
  Stream stream = await ComposerDataFilesRepo.OpenDataAsync(ComposerDataImage.Filename);
  ProductImage.Image = await BaseBarParser.ConvertToMemoryStram(stream);
  ProductImage.Filename = ComposerDataImage.Filename;
  ProductImage.metadata = ComposerDataImage.metadata;
  ProductImages.Add(ProductImage);
}

This is my GetAllFlyerImages method:
public async Task<IEnumerable<ComposerDataFiles>> GetAllFlyerImages(string FlyerId)
{
  //var filter = Builders<ComposerDataFiles>.Filter.Empty;
  //return (await Collection.FindAsync(filter)).ToList();
  var filter = Builders<GridFSFileInfo>.Filter.Where(f => f.Metadata["flyerId"] == FlyerId && f.Metadata["type"] == "ProductImage");
  var dataRecords = await FindDataAsync(filter);

  var results = dataRecords.ToList();
  List<ComposerDataFiles> images = new List<ComposerDataFiles>();

  foreach (var result in results)
  {
    var image = new ComposerDataFiles();
    image.Id = result.Id.ToString();
    image.Filename = result.Filename;
    image.metadata = BsonSerializer.Deserialize<ComposerDataFilesMetadata>(result.Metadata);
    images.Add(image);
  }
  return images;
}

This is my Open DataAsyncMethod:
public async Task<GridFSDownloadStream> OpenDataAsync(string filename)
{
  var file = await FindOneDataAsync(filename);
  if (file == null)
    return null;
  return await _bucket.OpenDownloadStreamAsync(file.Id);
}

How can I make this process quicker and more efficient? Any help would be appreciated.


text:
Q: Why Angular is not loading anything when query param is passed in the URL? I have an angular app that is integrated with Microsoft single sign on lib azure/msal-browser and azure/msal-angular
my app-routing.module.ts looks like the following:
  {
    path:'clients',
    component: ClientSearchComponent,
    data: { title: 'Client Search' },
    canActivate: [MsalGuard]
  },
  {
    path: 'clients/:id',
    component: ClientDetailsComponent,
    resolve: {
      tab: ClientDetailsResolver,
      headerData: ClientDetailHeaderDataResolver
    },
    canActivate: [MsalGuard],
    children: [
      {
        path: 'demographics',
        component: ClientIdentInfoComponent,
        data: { title: 'Client Demographics' },
        resolve: { client: ClientIdentInfoResolver },
        canDeactivate: [ ClientIdentInfoGuard ],

      },
      {
        path: 'insurances',
        component: ClientInsuranceComponent,
        data: { title: 'Client Insurances' },
        resolve: { insurances: InsuranceInfoResolver },
      },
      {
        path: '',
        redirectTo: 'demographics',
        pathMatch: 'full'
      }
  }

I have an external service where users click on a button and gets redirected to another page (not a new tab). After they put in their username and hit submit, the service then redirects them to my application with the following url:
mydomain.com/clients?code=zcwZmVmMDJkYjJmZmQtOGIz_PF84_0be990f3-c9a9-483d-b0ca-f87b327c76b3&state=7f1934f6-4te0-4687-ac81-47316c60efe5

for some reason, my application is not displaying anything, even a console.log('whatever') on the level of the app.component.ts is not showing.
ngOnInit() {
    console.log('whatever'); // Not reachable

    const currentPath = this.location.path();
    // Dont perform nav if in iframe or popup, other than for front-channel logout
    this.isIframe = BrowserUtils.isInIframe() && !window.opener && currentPath.indexOf("logout") < 0; // Remove this line to use Angular Universal
    this.setLoginDisplay();

    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) => status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe(() => {
        this.setLoginDisplay();
        this.checkAndSetActiveAccount();
      })
  }

if I changed the query param code to literally ANTYHING then the app works just fine and it displays the page. Unfortunately, I cannot control the param name code from the third-party app. It seems like my app is having a problem with the query param code if it was passed in the url.
The IPublicClientApplication logger is showing that my app is going into an infinite loop
Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - Event callback registered with id: f39e816c-5bc5-4fa5-8629-c440356cfdf5
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - Guard - canActivate
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - MSAL Guard activated
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Info - Emitting event: msal:handleRedirectStart
app.module.ts:122 Log Level:::::2
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - Emitting event to callback f39e816c-5bc5-4fa5-8629-c440356cfdf5: msal:handleRedirectStart
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - BroadcastService - msal:handleRedirectStart results in setting inProgress to handleRedirect
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - handleRedirectPromise called
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - getAllAccounts called
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - handleRedirectPromise has been called for the first time, storing the promise
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Info - handleRedirectPromise called but there is no interaction in progress, returning null.
app.module.ts:122 Log Level:::::2
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Info - Emitting event: msal:handleRedirectEnd
app.module.ts:122 Log Level:::::2
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - Emitting event to callback f39e816c-5bc5-4fa5-8629-c440356cfdf5: msal:handleRedirectEnd
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - BroadcastService - msal:handleRedirectEnd results in setting inProgress to none
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - getAllAccounts called
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - Guard - at least 1 account exists, can activate or load
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Info - Guard - Hash contains known code response, stopping navigation.
app.module.ts:122 Log Level:::::2
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - Guard - canActivate
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - MSAL Guard activated
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Info - Emitting event: msal:handleRedirectStart
app.module.ts:122 Log Level:::::2
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - Emitting event to callback f39e816c-5bc5-4fa5-8629-c440356cfdf5: msal:handleRedirectStart
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - BroadcastService - msal:handleRedirectStart results in setting inProgress to handleRedirect
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - handleRedirectPromise called
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - getAllAccounts called
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - handleRedirectPromise has been called previously, returning the result from the first call
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-browser@2.14.2 : Verbose - getAllAccounts called
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - Guard - at least 1 account exists, can activate or load
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Info - Guard - Hash contains known code response, stopping navigation.
app.module.ts:122 Log Level:::::2
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - Guard - canActivate
app.module.ts:122 Log Level:::::3
app.module.ts:121 Message:::::[Tue, 24 May 2022 18:05:01 GMT] :  : @azure/msal-angular@2.0.0 : Verbose - MSAL Guard activated

I am using popup not redirect for the auth
my app.module.ts looks like this
export function loggerCallback(logLevel: LogLevel, message: string) {
  console.log('Message:::::' + message);
  console.log('Log Level:::::' + logLevel);
}

export function MSALInstanceFactory(): IPublicClientApplication {
  return new PublicClientApplication({
    auth: {
      clientId: '<clientId>',
      authority: 'https://login.microsoftonline.com/<tid>',
      redirectUri: '/',
      postLogoutRedirectUri: '/'
    },
    cache: {
      cacheLocation: BrowserCacheLocation.LocalStorage,
      storeAuthStateInCookie: isIE, // set to true for IE 11. Remove this line to use Angular Universal
    },
    system: {
      allowRedirectInIframe: true,
      loggerOptions: {
        loggerCallback,
        logLevel: LogLevel.Verbose,
        piiLoggingEnabled: true
      }
    }
  });
}

export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string>>();
  const baseUrl = environment.apiUrl;
  protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
  protectedResourceMap.set(baseUrl, ['<clientId>/.default']);

  return {
    interactionType: InteractionType.Popup,
    protectedResourceMap
  };
}

export function MSALGuardConfigFactory(): MsalGuardConfiguration {
  return {
    interactionType: InteractionType.Popup,
    authRequest: {
      scopes: ['clientId/.default']
    },
    loginFailedRoute: '/unauthorized'
  };
}

and the providers array looks like this
providers: [
    CdkColumnDef,
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    },
    {
      provide: MSAL_INSTANCE,
      useFactory: MSALInstanceFactory
    },
    {
      provide: MSAL_GUARD_CONFIG,
      useFactory: MSALGuardConfigFactory
    },
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: MSALInterceptorConfigFactory
    },
    MsalService,
    MsalGuard,
    MsalBroadcastService
  ],
  bootstrap: [AppComponent, MsalRedirectComponent]

Have any of you had this problem before?

A: I see you're using MSAL, you can set the logger to show more details to see if it's the interceptor that is causing troubles:
export function loggerCallback(logLevel: LogLevel, message: string) {
  console.log(message);
}

export function MSALInstanceFactory(): IPublicClientApplication {

  return new PublicClientApplication({
    auth: {...your auth parms...},
    cache: {... your cache parms ...},
    system: {
      loggerOptions: {
        loggerCallback,
        logLevel: LogLevel.Debug,
        piiLoggingEnabled: true
      }
    }
  });
}

This gave us more insights in what was causing issues with the routing.


text:
Q: Oracle XML - How to escape text between tags. If i have a CLOB column with the following xml document
<xml>
<Country>Trinidad & Tobago </Country>
</xml>

I want to escape the ampersand but not the tags.
I know i can use this approach:
Select DBMS_XMLGEN.CONVERT(country) from country_list;

The above query escapes all the special characters. i.e. < > and &. Is there a way i can only escape anything that is between the  tags. I.e. the output after escaping is
<xml>
<Country>Trinidad & Tobago </Country>
</xml>

A: Use REGEXP_REPLACE in a manner similar to the following:
SELECT REGEXP_REPLACE(COUNTRY,
                      '(<.*>.*)(&)(.*</.*>)',
                      '\1&\3') AS REPLACEMENT_TEXT
  FROM COUNTRY_LIST;

SQLFiddle here
Share and enjoy.


text:
Q: Adding external plug ins to gedit in Windows I am using gedit 3.20.1 with Windows 7. I'm unable to add external plugins to gedit. Specifically, I'm trying to add gedit-latex-3.2.1 plugin, but so far all plug ins I've used have not worked.

*

*I add the appropriate files to "C:\Program Files\gedit\share\gedit\plugins"

*Restart gedit

*Go to Preferences --> Plugins and the latex (or whatever) plugin is not there.

Is it just that these plug ins don't work with Windows, or am I missing something?

A: Use "C:\Program Files\gedit\lib\gedit\plugins"


text:
Q: how to hide parent div from 2 child divs? I have a parent div and 2 nested child divs. I want to hide the first child div and the parent div when the second child div doesn't contain any content.I was wondering how this could be done?
I want to hide #portfolio when .portfolio-works-container div is empty.

A: Try this:
jQuery(document).ready(function($){
    if($.trim($('.portfolio-works-container').html()).length == 0){
         $('#portfolio').hide();
    }
});

Please check this : jsfiddle url

A: You can use:
if($('.portfolio-works-container').contents().length == 0) {
    $('#portfolio').hide()
}

A: Use .is() and :empty() selector. Try this:
if($(".portfolio-works-container").is(':empty')){
   $("#portfolio").hide();
}

A: Since you are already using jQuery (as the question is tagged):
if ($('.portfolio-works-container').html()=='')
    $('#portfolio').hide();

A: IN order to hide parent div you need to find the parent element using parent() function of jquery.
In below code you will check if div is empty then find parent divs and hide them
if( !$.trim($('.portfolio-works-container').html()) ) {
   $(this).parent().hide();
   $(this).parent().parent().hide();

}


text:
Q: How can I make a WireBox injected dependency available to a constructor method? In this example, I have a model object called test.cfc which has a dependency testService.cfc.
test has WireBox inject testService through a property declaration.  The object looks like this:
component {

     property name="testService" inject="testService";

     /**
     *  Constructor
     */
     function init() {

         // do something in the test service
         testService.doSomething();

         return this;

     }

 }

For reference, testService has a single method called doSomething() which dumps out some text:
component
     singleton
{

     /**
     *  Constructor
     */
     function init() {

         return this;

     }

     /**
     *  Do Something
     */
     function doSomething() {

         writeDump( "something" );

     }

 }

The problem is, WireBox doesn't seem to inject testService until after the constructor init() method fires.  So, if I run this in my handler:
prc.test = wirebox.getInstance(
     name = "test"
);

I get the following error message: Error building: test -> Variable TESTSERVICE is undefined.. DSL: , Path: models.test
Just for sanity sake, if I modify test so that testService gets referenced after the object is constructed, everything works fine.  The problem seems to be isolated to constructor methods.
How can I make sure my dependencies can be referenced in my object constructor methods?  Thanks for your assistance!

A: Due to the order of construction, you can't use property or setter injections in the init() method.  Instead, you can access them in the onDIComplete() method.  I realized the WireBox docs only had a passing reference to this, so I have added this excerpt:
https://wirebox.ortusbooks.com/usage/injection-dsl/id-model-empty-namespace#cfc-instantiation-order
CFC Building happens in this order.

*

*Component is instantiated with createObject()

*CF automatically runs the pseudo constructor (any code outside the a method declaration)

*The init() method is called (if it exists), passing any constructor args

*Property (mixin) and setting injection happens

*The onDIComplete() method is called (if it exists)

So the proper version of your CFC would be as follows:
component {

     property name="testService" inject="testService";

     /**
     *  Constructor
     */
     function init() {
         return this;
     }

     /**
     *  Called after property and setter injections are processed
     */
     function onDIComplete() {
         // do something in the test service
         testService.doSomething();
     }

 }

Note, it would also be acceptable to switch to constructor injection, but my personal preference is property injection due to the reduced boilerplate of needing to receive the argument and persist it locally.
https://wirebox.ortusbooks.com/usage/wirebox-injector/injection-idioms


text:
Q: Split a paragraph to separate one or two digit numbers with PowerShell I'm attempting to parse and format some text from an HTML file into Word. I'm doing this by capturing each paragraph into an array and then writing it into the word document one paragraph at a time. However, there are superscripted references sprinkled throughout the text. I'm looking for a way to superscript these references in the new Word file and thought I would use regex and split to make this work. Here is an example paragraph:
$p = "This is an example sentence.1 The number is a reference note that should be superscripted and can be one or two digits long."

Here is the code I tried to split and select the digit(s):
[regex]::Split($p,"(\d{1,2})")

This works for single and double digits. However, if there are more than two digits, it still splits it, but moves the extra numbers to the next line. Like so:
This is an example sentence.
10

0
The number is a reference note that should be superscripted and can be one or two digits long.

This is important because there are sometimes larger numbers (3-10 digits) in the text that I don't want to split on. My goal is to take a block of text with reference note numbers and seperate out the notes so I can perform formatting functions on them when I write it out to the Word file. Something like this (untested):
$paragraphs | % {
    $a = @([regex]::Split($_,"(\d{1,2})"))
    $a | % {
        $text = $_
        if ($text -match "(\d{1,2})")
        {
            $objSelection.Font.SuperScript = 1
            $objSelection.TypeText("$text")
            $objSelection.Font.SuperScript = 0
        }
        Else
        {
            $objSelection.Style="Normal"
            $objSelection.TypeText("$text")
        }

    }
        $text = "`v"
        $objSelection.TypeText("$text")
        $objSelection.TypeParagraph()
}

EDIT:
The following regex expression works when I test it with the above loop in it's own script:
"(?<![\d\s])(\d{1,2})(?!\d)"

However, when I run it in the parent script, I get the following error:
Cannot find an overload for "Split" and the argument count: "2"
$a = [regex]::Split($_,"(?<![\d\s])(\d{1,2})(?!\d)")

How would I go about troubleshooting this error?

A: You may use
[regex]::Split($p,"(?<![\d\s])(\d{1,2})(?!\d)\s*")

It only matches and captures one or two digits that are neither followed nor preceded with another digit, and not preceded with any whitespace char. Any trailing whitespace is matched with \s* and is thus removed from the items that are added into the resulting array.
See this regex demo:

Details

*

*(?<![\d\s]) - a negative lookbehind that fails the match if, immediately to the left of the current position, there is a digit or a whitespace

*(\d{1,2}) - Group 1: one or two digits

*(?!\d) - that cannot be followed with another digit (it is a negative lookahead that fails the match if its pattern matches immediately to the right of the current location)

*\s* - 0+ whitespaces.


text:
Q: How to generate list of Java EE web services? Problem
I need to document all of our Java EE application's web services.
Our application is a Maven project. I need to include information such as:

*

*Service Name

*Module

*Package

*Class

*Method

*Code Usages [if possible]

Currently I am trying to do it the manually way of scouring the code for occurrences of @WebService & @WebServiceClient and writing it into a spreadsheet. But this process is excruciating.
Efforts
I have tried looking at the Java Enterprise tab in IntelliJ, I got my hopes up for a second but then I noticed that it repeats many web services throughout the various Maven modules. Also, I haven't found a way to export the list of web services so I'd have to write them each manually anyway.
I briefly looked at the ASM project (as suggested by @JF_Meier), but that seems like too steep of a learning curve to be feasible right now. I get frowned upon when I go off on a tangent and spent more time on an "efficient" process rather than just getting on with it.
I looked at Maven, hoping there would be something like a mvn dependency:tree, but for web services. I have yet to find something of the sorts.
Question
Is there more efficient way to generate a list of web service in a Maven / Java EE applcation?

A: You can use a library like asm to scan the byte code for annotations.
It allows you to walk through the code with a visitor. Then you can look for annotations like @WebService.


text:
Q: How to send metadata from grpc-gateway to go grpc server? How can I send metadata from grpc-gateway to grpc server?
On the client(grpc-gateway):
func (c *Client) MiddlewareAuth(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()

        ...

        ctxOut := metadata.NewOutgoingContext(ctx, metadata.New(map[string]string{
            "key":    "value",
        }))

        r = r.WithContext(ctxOut)

        h.ServeHTTP(w, r)
    })
}

On the server:
func (s *Server) List(ctx context.Context, request *pb.Request) (*pb.Response, error) {
    md, _ := metadata.FromIncomingContext(ctx)
    fmt.Println(md)

    return &pb.Response{
        Ok: true
    }, nil
}

A: It's possible to map HTTP headers to gRPC metadata, as described here
This should work:
// in Client.MiddlewareAuth
r.Header.Set("Grpc-Metadata-My-Data", "...")

// in Server.List
md.Get("grpcgateway-My-Data")

A: You might not like the default mapping rule and might want to pass through all the HTTP headers, for example:

*

*Write a HeaderMatcherFunc.

*Register the function with WithIncomingHeaderMatcher
e.g.
func CustomMatcher(key string) (string, bool) {
 switch key {
 case "X-Custom-Header1":
 return key, true
 case "X-Custom-Header2":
 return "custom-header2", true
 default:
 return key, false
 }
}

mux := runtime.NewServeMux(
 runtime.WithIncomingHeaderMatcher(CustomMatcher),
)

To keep the the default mapping rule alongside with your own rules write:
func CustomMatcher(key string) (string, bool) {
 switch key {
 case "X-User-Id":
 return key, true
 default:
 return runtime.DefaultHeaderMatcher(key)
 }
}

It will work with both:
$ curl --header "x-user-id: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...

and
$ curl --header "X-USER-ID: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...

To access this header on gRPC server side use:
userID := ""
if md, ok := metadata.FromIncomingContext(ctx); ok {
 if uID, ok := md["x-user-id"]; ok {
 userID = strings.Join(uID, ",")
 }
}

Also, you should check out the tutorial series on gRPC-Gateway, i.e., https://grpc-ecosystem.github.io/grpc-gateway/docs/tutorials/.


text:
Q: Compact if statement C++ I just would like to be sure that I can write a compact if with a or condition in the following way:
const ST c_is = ((kg==0) || (kg==nktot)) ? 0 : 10;

The purpose is to set c_is to 0 if kg is 0 or nktot and 10 otherwise.
Could you confirm me that it is ok?

A: Yes, it's ok.
From the most readable to the most obscure:
// give more meaningful names, as it is only you know what these ids mean
constexpr ST set_is(ST kg)
{
    if (kg == 0 || kg == nktot)
        return 0;
    return 10;
}

constexpr ST c_is = set_is(kg);

constexpr ST c_is = ((kg==0) || (kg==nktot)) ? 0 : 10;

constexpr ST c_is = [=] {
    if (kg == 0 || kg == nktot)
        return 0;
    return 10;
}();

constexpr ST c_is = (kg !=0 && kg !=nktot) * 10;

A: You can do it branchlessly with
10 * !!kg * (kg != nktot)

Although there is nothing wrong with the expression you present, and my way might be considered a premature optimisation, or only slightly easier to read than James Joyce's Finnegans Wake.

A:
The purpose is to set c_is to 0 if kg is 0 or nktot and 10 otherwise.
Could you confirm me that it is ok?

It is ok.


text:
Q: RISC-V Implement a discrete function without branching Consider the discrete-valued function f defined on integers in the set {-3, -2, -1, 0, 1, 2, 3}. Definition:
f(-3) = 6
f(-2) = 61
f(-1) = 17
f(0) = -38
f(1) = 19
f(2) = 42
f(3) = 5

I am trying to implement a function "f" in RISC V that does not use branchings nor jumps to evaluate the function. a0 will be the value to evaluate in f, [ essentially: f(a0) ], while a1 will point to the address of the output array (see code below).
My code so far:
.globl f

.data
neg3:   .asciiz "f(-3) should be 6, and it is: "
neg2:   .asciiz "f(-2) should be 61, and it is: "
neg1:   .asciiz "f(-1) should be 17, and it is: "
zero:   .asciiz "f(0) should be -38, and it is: "
pos1:   .asciiz "f(1) should be 19, and it is: "
pos2:   .asciiz "f(2) should be 42, and it is: "
pos3:   .asciiz "f(3) should be 5, and it is: "

output: .word   6, 61, 17, -38, 19, 42, 5
.text
main:
    la a0, neg3
    jal print_str
    li a0, -3
    la a1, output
    jal f               # evaluate f(-3); should be 6
    jal print_int
    jal print_newline

    la a0, neg2
    jal print_str
    li a0, -2
    la a1, output
    jal f               # evaluate f(-2); should be 61
    jal print_int
    jal print_newline

    la a0, neg1
    jal print_str
    li a0, -1
    la a1, output
    jal f               # evaluate f(-1); should be 17
    jal print_int
    jal print_newline

    la a0, zero
    jal print_str
    li a0, 0
    la a1, output
    jal f               # evaluate f(0); should be -38
    jal print_int
    jal print_newline

    la a0, pos1
    jal print_str
    li a0, 1
    la a1, output
    jal f               # evaluate f(1); should be 19
    jal print_int
    jal print_newline

    la a0, pos2
    jal print_str
    li a0, 2
    la a1, output
    jal f               # evaluate f(2); should be 42
    jal print_int
    jal print_newline

    la a0, pos3
    jal print_str
    li a0, 3
    la a1, output
    jal f               # evaluate f(3); should be 5
    jal print_int
    jal print_newline

    li a0, 10
    ecall

# f takes in two arguments:
# a0 is the value we want to evaluate f at
# a1 is the address of the "output" array (defined above).
#
f:

    #store the value of a0 in temp register
    add t0, a0, x0

    #store numerical value to get correct output index
    addi t1, x0, 3

    #add the numerical value 3 to the argument value
    #to get the correct output array index value
    add t2, t1, t0

    #store size of int
    addi t3, x0, 4

    #index the output array
    mul t4, t2, t3
    add t4, t4, t2

    lw ra, 0(t4)

    jr ra

print_int:
    mv a1, a0
    li a0, 1
    ecall
    jr    ra

print_str:
    mv a1, a0
    li a0, 4
    ecall
    jr    ra

print_newline:
    li a1, '\n'
    li a0, 11
    ecall
    jr    ra

It is clear that adding the value of 3 to the passed in argument a0 will index correctly to the output array. I am unsure if I did this correctly in my code and would like some advice.

A: I can spot two bugs in your implementation of f:

*

*add t4, t4, t2: Here you are adding the address offset in the array t4 = (a0 + 3) * 4 to the index in the array (t2 = a0 + 3), when instead you want to add the offset and the array pointer (a1):
add t4, t4, a1.

*lw ra, 0(t4): Here you are loading the value from the array into the return address register ra, which holds the address of the instruction to jump back (return) to in the calling function, and is used by jr ra.
Instead you want to load the value into a0, which is the canonical return value register:
lw a0, 0(t4).

There are some possible improvements:
    #store the value of a0 in temp register
    add t0, a0, x0

    #store numerical value to get correct output index
    addi t1, x0, 3

    #add the numerical value 3 to the argument value
    #to get the correct output array index value
    add t2, t1, t0

*

*There is no reason to copy a0 to t0, just use a0 directly in the last instruction.

*There's also no reason to load the immediate value 3 into t1, just turn the last instruction into an addi.

Combined, the replacement for the above three instructions is this one instruction:
    # add 3 to argument value
    addi t2, a0, 3

There is more:
    #store size of int
    addi t3, x0, 4

    #index the output array
    mul t4, t2, t3
    add t4, t4, a1     # t2 replaced by a1, see above

You may have noticed that there is no muli instruction, so the immediate value 4 must be loaded into register t3 before multiplying.
Furthermore, mul is part of the M-extension (not supported by all processors), and multiplication is generally a complicated, slow operation.
Therefore I propose to replace multiplication by 4 with a left shift by 2, which exploits the binary representation of integers and produces the same result - at least for unsigned values.
The computed index should always be >= 0, so this is safe.
There is a left shift immediate instruction slli, which is part of all base RISC-V ISAs, and shifting is usually faster than multiplication.
The three instructions above can be replaced by just two:
    # index the output array
    # (multiply by 4 / left shift by 2, then add array address)
    slli t4, t2, 2
    add  t4, t4, a1     # t2 replaced by a1, see above

Now combining all bug fixes and improvements, the whole function takes just five instructions instead of eight:
# a0: argument value ; a1: array address
f:
    # add 3 to argument value
    addi t2, a0, 3

    # index the output array
    # (multiply by 4 / left shift by 2, then add array address)
    slli t4, t2, 2
    add  t4, t4, a1     # t2 replaced by a1, see above

    # load value from output array
    lw a0, 0(t4)        # ra replaced by a0, see above

    # return to calling function
    jr ra

Now, let's take a final look at what a modern compiler like clang 11 with optimizations can produce (godbolt.org) when we give it the same function implemented in C:
#include <stdint.h>
int32_t f(int32_t a0, int32_t a1[]) {
    return a1[a0 + 3];
}

Here's the result with some comments I added:
f:
    # multiply argument value by 4
    slli a0, a0, 2

    # add array address
    add  a0, a0, a1

    # load array value at three places (= 12 bytes) further
    lw   a0, 12(a0)

    # return to calling function
    ret

This is only four instructions, let's discuss this:

*

*ret is just a short-hand notation for jr ra, same as what we have.

*Register a0 is reused by all instructions. This is perfectly legal.
A benefit of using a0 is that this register can be used by the compressed instructions of the C-extension. The tN registers cannot.

*The compiler used the same trick I proposed to replace addi and mul with slli.

*The initial addi t2, a0, 3 is missing.
Instead, the compiler internally multiplied the constants 3 and 4 and used the resulting value 12 as the immediate value in lw a0, 12(a0).
The original address calculation was (a0 + 3) * 4 + a1. The compiler transformed this into a0 * 4 + a1 + 12, which is equivalent. Then it moves the addition of 12 into the address generation step of the lw instruction, thereby saving the addi instruction.


text:
Q: Как изменить поведение JsonDecoder у меня в json строке есть datetime.datetime. Мне требуется, чтобы JsonDecoder парсил datetime.datetime, как объект. Я уже нашёл, как это можно сделать:
import ast
import datetime
from operator import attrgetter

value_from_db = "datetime.datetime(2019, 6, 10, 00, 00)"

expr, = ast.parse(value_from_db).body
dt_value = datetime.datetime(*map(attrgetter('n'), expr.value.args))

print(dt_value)

Теперь мне нужно, чтобы при использование json.loads, это делалось автоматически.
Пример того, как должно работать:
json_string = '{"last_updated": {"$gte": datetime.datetime(2022, 1, 19, 0, 0)}}'
dct = json.loads(json_string)
print(dct) # -> {"last_updated": {"$gte": datetime.datetime(2022, 1, 19, 0, 0)}}

Заранее спасибо!

A: Object_hook выполняется после десериализации, поэтому вам все равно нужен валидный json. Но вы можете передать datetime объект в виде строки и сделать следующим образом:
import json
import datetime

def objHook(dst):
    for k,v in dst.items():
        if isinstance(v, str) and v.startswith('datetime.datetime'):
            args = v.replace('datetime.datetime(', '').replace(')','').replace(' ', '').split(',')
            args = map(int, args)
            dst[k] = datetime.datetime(*args)
    return dst

json_string = '{"last_updated": {"$gte": "datetime.datetime(2022, 1, 19, 0, 0)"}}'
dct = json.loads(json_string, object_hook=objHook)
print(dct)  #  {'last_updated': {'$gte': datetime.datetime(2022, 1, 19, 0, 0)}}


text:
Q: XORing Colors and their usage? I have read that a xor b is: (a.(not)b +  (not)a.b) and clearly (a xor a)=0 or False
So the Truth Table is:
a|b|a xor b
-----------
0|0|   0
0|1|   1
1|0|   1
1|1|   0

after all of above, what's the xor operation in colors. I know that the colors are hexadecimal numbers.
And What's They Usage in ControlPaint.DrawReversibleLine in BkColor parameter?

A: First of all your truth table is wrong:
It give 1 of a!=b, 0 otherwise.
Second the point used in graphics is (at least was in Pascal :) you can draw a shape and each pixel's color will be Original_pixel_color XOR shape_color. If you do this twice, the shape disappears because double XOR gives you the original input.
I used it e.g. when I was drawing something in simple graphic editor. When you create the object using mouse you can simply draw it using this special XOR usage without need to remember the background, because you can erase it simply by drawing it again (when for example sizing or moving the object dragged by mouse).
Hope this helps :)

A: Each bit of the color is individually XOR-ed.  That typically means 8 bits of red, 8 green, 8 blue, and within a color, each bit is worth half as much as the one next to it.
So for example, light gray XOR red yields kind of a sea blue:
R        G        B            R        G        B         R        G        B
CC       CC       CC       XOR FF       00       00
11001100 11001100 11001100  ^  11111111 00000000 0000000 = 00110011 11001100 11001100
                                                           33       CC       CC


text:
Q: Asp.net MVC 3 Remote Validation Issues Every time remote validation fires on my form, I get the following url...not what I expected:
http://localhost:13927/Validation/ValidateAnswer?%5B0%5D.Episodes%5B0%5D.Questions%5B0%5D.Answers%5B0%5D.AnswerText=undefined&%5B0%5D.Episodes%5B0%5D.Questions%5B0%5D.Answers%5B0%5D.Id=undefined
The controller is correct.  The action is correct, but the parameters are not what I expected.  Any ideas as to how I can correct this?  The signature for the validation action is public JsonResult ValidateAnswer(string answerText, int id).
Here is the Model:
public class Answer
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Please enter an answer.")]
    [Remote("ValidateAnswer", "Validation", AdditionalFields = "Id")]
    public string AnswerText { get; set; }
}

Here is the Page:
@using (Html.BeginForm("/", "Home", FormMethod.Post, new {id="frm"}))
    {
        for (var p = 0; p < Model.Count; p++)
        {

                @for (var i = 0; i < Model[p].Episodes.Count; i++)
                {

                        @Html.EditorFor(model => model[p].Episodes[i])

                }

        }
    }

Here is the Editor Referenced:

@Model.EpisodeType, which started on @Model.StartDate and ended on @Model.EndDate

@Html.HiddenFor(model=>model.Id)
@for (var i = 0; i < Model.Questions.Count; i++ )
{

        @Model.Questions[i].QuestionText

        @{ var theClass = string.Concat("autocomplete", Model.Questions[i].IsYesNo ? "yesno" : Model.Questions[i].IsTime ? "time" : ""); }
        @Html.TextBoxFor(model=>model.Questions[i].Answers[0].AnswerText, new {@class=theClass, question=Model.Questions[i].Id.ToString()})
        @Html.ValidationMessageFor(model=>model.Questions[i].Answers[0].AnswerText)
        @Html.HiddenFor(model => model.Questions[i].Id)

}

A: I had the same problem. Ultimately, I traced it back to line 309 in jquery.validate.unobtrusive.js:
return $(options.form).find(":input[name='" + paramName + "']").val();

This jQuery call returns 0 objects, possibly because the name it's filtering for (your input name) contains square brackets, which confuse the jQuery parser.
You can fix it by replacing it with this line:
return $(options.form).find(":input[id='" + options.element.id + "']").val();

The above is filtering by id, so no weird characters to trip up jQuery.


text:
Q: The old issue of overleft/rightarrow revisited, and my own approach I want to try to communicate what I want to achieve with the following code example. I would like to have one left- and right-command for this functionality, which compiles in reasonable time. I am happy with the aesthetics achieved by the routines below. I apologize if that question could be solved using other answers from the site. Thank you for taking a look at it!
\documentclass{amsart}
\usepackage{amsmath}
\usepackage{stackengine}

\newcommand\constantoverleftarrow[1]{\stackengine{0pt}{$\smash{\mbox{\scriptsize\ensuremath{\overleftarrow{\normalsize\hphantom{D}\vphantom{#1}}}}}$}{$#1$}{O}{l}{F}{F}{L}}

\newcommand\constantoverrightarrow[1]{\stackengine{0pt}{$\smash{\mbox{\scriptsize\ensuremath{\overrightarrow{\normalsize\hphantom{D}\vphantom{#1}}}}}$}{$#1$}{O}{l}{F}{F}{L}}

\newcommand\constantfootoverleftarrow[1]{\stackengine{0pt}{$\smash{\mbox{\tiny\ensuremath{\overleftarrow{\footnotesize\hphantom{D}\vphantom{#1}}}}}$}{$#1$}{O}{l}{F}{F}{L}}

\newcommand\constantfootoverrightarrow[1]{\stackengine{0pt}{$\smash{\mbox{\tiny\ensuremath{\overrightarrow{\footnotesize\hphantom{D}\vphantom{#1}}}}}$}{$#1$}{O}{l}{F}{F}{L}}

\newcommand\constantunsmashedoverleftarrow[1]{\stackengine{0pt}{$\mbox{\scriptsize\ensuremath{\overleftarrow{\normalsize\hphantom{D}\vphantom{#1}}}}$}{$#1$}{O}{l}{F}{F}{L}}

\newcommand\constantunsmashedoverrightarrow[1]{\stackengine{0pt}{$\mbox{\scriptsize\ensuremath{\overrightarrow{\normalsize\hphantom{D}\vphantom{#1}}}}$}{$#1$}{O}{l}{F}{F}{L}}

\begin{document}

I write longer sentences which have inline math and wrap over several lines. It might happen that I speak about a derivative $\constantoverleftarrow{D_{x_1\cdots x_n}}$ and put it inside the text. It is important for me that the arrow of such a formula does not expand over the indices. I used the smashed version of my own arrow here because I do not want that the lines spread apart.

Of course, it might as well happen that I speak about a derivative
\[
\constantunsmashedoverleftarrow{D_x}
\]
which occurs in display math. Here, I use the unsmashed version of my own arrow because I want the spacing to be ordinary. This is important, in particular if I have display math with several lines or even boxes around the math from empheq package.\footnote{A derivative $\constantfootoverrightarrow{D_y}$ in a footnote needs to be smaller.} (It might also be important for deliminators. But there, I usually control the size myself and do not use the $\left(\right)$ version. This seems less important to me.)

The experts from \TeX Stackexchange might notice: Such a macro does not always work. Indeed, it will not adjust to subscripts for example, like $\int_{\constantoverrightarrow{D_z}}$. However, I do not need this. I don't have to worry about all the functionality but only about the one I really use.

I finally want to remark: My document may have around 200 to 300 arrows. And using the code above in the preamble takes a lot of time to compile.

\end{document}

Related, related, related.

A: I think this works for me by combining egreg's and Steven's solution. It compiles fast while the above in the question gets timeout. I smash it twice which I forgot in the question. It seems like things get not spread assymetrically at top and bottom now. It is probably not optimal but I can work with it.
\newcommand\constantoverrightarrow[1]{\colas#1\endcolas}
\def\colas#1#2\endcolas{\stackengine{0pt}{}{$\smash{\overrightsmallarrow{#1}}$}{O}{l}{F}{T}{L}%
  \smash{\phantom{#1}#2}}

\newcommand\constantoverleftarrow[1]{\cola#1\endcola}
\def\cola#1#2\endcola{\stackengine{0pt}{}{$\smash{\overleftsmallarrow{#1}}$}{O}{l}{F}{T}{L}%
  \smash{\phantom{#1}#2}}

\makeatletter
\newcommand{\overleftsmallarrow}{\mathpalette{\overarrowsmall@\leftarrowfill@}}
\newcommand{\overrightsmallarrow}{\mathpalette{\overarrowsmall@\rightarrowfill@}}
\newcommand{\overarrowsmall@}[3]{%
  \vbox{%
    \ialign{%
      ##\crcr
      #1{\smaller@style{#2}}\crcr
      \noalign{\nointerlineskip\vskip0.4pt}%
      $\m@th\hfil#2#3\hfil$\crcr
    }%
  }%
}
\def\smaller@style#1{%
  \ifx#1\displaystyle\scriptstyle\else
    \ifx#1\textstyle\scriptstyle\else
      \scriptscriptstyle
    \fi
  \fi
}
\makeatother


text:
Q: The file not exist exception in Java I try to upload file from web, and the file are stored in the file system.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(
        @RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            File file1 = new File(name + ".upload");
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(file1));

            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name
                    + "-uploaded !";
        } catch (Exception e) {
            e.printStackTrace();
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name
                + " because the file was empty.";
    }
}

the above code work well. But when I try to use absolute directory, it fail, the code like
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(
        @RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            File file1 = new File("c:/" + name + ".uploaded");
            file1.getParentFile().mkdirs();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(file1));

            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name
                    + "-uploaded !";
        } catch (Exception e) {
            e.printStackTrace();
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name
                + " because the file was empty.";
    }
}

It throw file not exists exception, and I have already create dirs. Does someone know the reason? Thanks!

A: Change your code block to the following
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody String handleFileUpload(
          @RequestParam("name") String name,
          @RequestParam("file") MultipartFile file) {

            String yourUploadDirectory = "uploads";

      if (!file.isEmpty()) {
          try {
              byte[] bytes = file.getBytes();
              File file1 = new File("c:/" + yourUploadDirectory + "/" + name + ".uploaded");

              // You must write this line so that the designated file is first created, otherwise getParentFile() will throw error.
              file1.createNewFile();

              file1.getParentFile().mkdirs();
              BufferedOutputStream stream = new BufferedOutputStream(
                      new FileOutputStream(file1));

              stream.write(bytes);
              stream.close();
              return "You successfully uploaded " + name + " into " + name
                      + "-uploaded !";
          } catch (Exception e) {
              e.printStackTrace();
              return "You failed to upload " + name + " => " + e.getMessage();
          }
      } else {
          return "You failed to upload " + name
                  + " because the file was empty.";
      }
  }

It is always good to have a dedicated folder for uploads..


text:
Q: Override "action swipe" I have a problem. I have an ionic and angular app and I need to override the "swipe back" action to take it to a particular view. I have this code:
this.navController.navigateBack([url]);

But I don't know where to put it, since I can't find a way to override that action.
Thanks!


text:
Q: Connecting to locahost from android device using a hostname with dynamic IP addresses (Changing Constantly) CONTEXT OF QUESTION:
I have a computer running a local webpage on a WAMP server. The computer is connected to a wireless connection.
I have an android tablet that is connected to the same wireless network.
PURPOSE (WHAT I WANT TO DO):
I want to be able to access the local webpage on the WAMP server using a hostname through my APP.
WHAT I HAVE ALREADY TRIED:
I can already address the webpage from my app by using the ip address of the computer (http://192.168.x.x/Webpage_Name). However, since my ip is dynamic (changing constantly) this implementation will not work. Please correct me if I am wrong.
My idea was to use edit the hostfile of the computer. However, my understanding is that a hostfile is static meaning that it can not resolve hostnames to changing ip addresses (it only stores an ip address and its corresponding host name). Furthermore the hostfile would not be on the Android device so the android device would not be able to connect to the server using the hostname specified in the hostfile. Please correct me if I am wrong.
My second idea was to use a DynamicDNS service. However, my only problem with that is if I want a free third party service to provide the DNS my webpage information would have to go through the internet. I want this webpage to remain local so I think DNS would not be an option. Please correct me if I am wrong.
My third idea was to first create a TCP connection between the Computer and Android device through the app. Then I would send the IP address of the computer in a string from the computer to the android device. Then the android device could use the ip address that was sent to connect to the local server. Now my understanding is that you need the ip address and port to create a TCP connection between the android device and the computer and this is why I think this implementation will not work. Since I need to hard code the ip address in this option aswell the problem persists.
MAIN QUESTION (WHAT I WANT TO KNOW FROM YOU GUYS):
Does anyone know of any other options to solve this problem? If I have wrongly understood one of the options (WHAT I HAVE ALREADY TRIED section) above and you think there is a way to make them work, please let me know.

A: I found a solution to this problem. I create a multicast socket client-server system between the computer running the WAMP and the mobile device. The computer would behave as the server and the mobile device would behave as the client. Once the connection is established I get the ip address of the computer in the server-side code. Then I send the ip address as a string from the computer to the client (mobile device) through the multicast socket. Then the mobile device creates the proper URL to the specified webpage on the WAMP server using the ip address provided and loads that URL.
See this page http://docs.oracle.com/javase/tutorial/networking/datagrams/broadcasting.html for example code for the server client system.