text:
Q: Using C++ for loop to create different nodes of a linked list Class in the memory and how to return its head? When I run this, it prints the same addresses? Also, how can I return its starting or head? Thank you in advance.
#include <iostream>
using namespace std;

class Node{
    public:
        int data;
        Node *next;

        Node(int value){
             data = value;
        }
};

int main(){
    system("cls");

    Node* temp = nullptr;

    for(int i = 0; i<5; i++){
        Node newNode(i);
        newNode.next = temp;
        temp = &newNode;
        cout<< &newNode << "\n"; //here it always prints the same addresses
    }
}


text:
Q: R ggplot Coincidence plot I'm working on a database of patients with multiple conditions and am trying to create a graphic showing associations between these conditions. More specifically, i'd like to obtain something like below:

My data is organized as:
 mal1 mal2 mal3 etc.
 0    0    1
 1    1    0
 0    1    0 etc.

I create the data as I want it to be shown using the following code:
X <- as.matrix(hdat2)
out <- crossprod(X)
diag(out) <- 0

And i create the plot with:
out<- melt(out)
out$value[which(out$value==0)]<-NA
g <- ggplot(data.frame(out), aes(Var1, Var2)) + geom_point(aes(size = value), colour = "black") + theme_bw() + xlab("") + ylab("")
g + scale_size_continuous(range=c(2,10))+

As a result i obtain this plot

I'd like to hide the symetric half of the plot, which i think is misleading (similarly as how, i correlation matrices i can hide the symetric half). However, i'm not sure about how to do it.
Could anyone help ?
Thanks

A: First, some reproducible data:
mat <-
  data.frame(
    malA = sample(0:1, 100, TRUE, c(0.2,0.8))
    , malB = sample(0:1, 100, TRUE, c(0.3,0.7))
    , malC = sample(0:1, 100, TRUE, c(0.4,0.6))
    , malD = sample(0:1, 100, TRUE, c(0.5,0.5))
  )

out <- crossprod(as.matrix(mat))
diag(out) <- 0

Here is an example limiting down to just the half you are interested in using dplyr:
toPlotHalf <-
  melt(out) %>%
  mutate_each(funs(factor(.))
              , starts_with("Var")) %>%
  filter(as.numeric(Var1) < as.numeric(Var2))

ggplot(toPlotHalf
       , aes(Var1, Var2)) +
  geom_point(aes(size = value), colour = "black") +
  theme_bw() + xlab("") + ylab("") +
  scale_size_continuous(range=c(2,10))

Note, however, that in this way your plot is going to be dominated by particular maladies that are very common. Alternatively, you can present the percentage of people with each malady that have the other malady (note that now the reciprocal points are not (necessarily) the same size:
toPlot <-
  prop.table(out, 1) %>%
  melt() %>%
  filter(value > 0)

ggplot(toPlot
       , aes(Var1, Var2)) +
  geom_point(aes(size = value), colour = "black") +
  theme_bw() + xlab("") + ylab("") +
  scale_size_continuous(range=c(2,10))

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: Calling a function within a return string I'm trying to call a function within a string return statement. Both are in the same class. However, I'm obviously not calling it right because it doesn't work :)
private static function doSomething(){
   $d['dt'] = //unix time stamp here;

   return '
'.time_since($d['dt']).'
';
}

function time_since(){
   //return 'string';
}

Any help is appreciated! Thanks

A: First, you are calling time_since() and your function is time_stamp().
Second, in PHP you need to explicitly call it like $this->time_stamp() - it does not resolve it to object scope like C++ does.
Third, you cannot call a regular method from the static function because the object is not instantiated - make time_stamp() static too. If you do this, it needs to be invoked like self::time_stamp().

A: Is the code meant to use time_since() when the other method you have listed is time_stamp()?


text:
Q: How do I use a function from one lisp file to solve for something in another lisp file? I'm new to lisp and my professor gave some .lisp files to play around with.
http://pastebin.com/eDPUmTa1 (search functions)
http://pastebin.com/xuxgeeaM (water jug problem saved as waterjug.lisp)
The problem is I don't know how to implement running functions from one file to solve problems from another. The most I've done is compiled functions from one file and played around with it in the terminal. I'm not sure how to load 2 files in this IDE as well as how I should run the function. I'm trying, for example, to run the breadth-first-search function to solve the problem to no avail.
I'm currently using emacs as the text editor SBCL as the common lisp implementation along with quicklisp and slime.

A: Assuming each file is in its own buffer, say f1.lisp and f2.lisp, then you only have to call slime-compile-and-load-file when you are in each buffer. This is bound by default to C-c C-k. You have to compile the first file first, because it contains definitions for the second one.
But, your second file (f2.lisp) has two problems: search for (break and (bread and remove those strings. Check if the forms around them have their parenthesis well balanced.
Take care of warning messages and errors while compiling your file.
Then, if you want to evaluate something directly from the buffer, put your cursor (the point) after the form you want to evaluate, and type C-x C-e (imagine the cursor is represented by % below):
(dump-5 (start-state *water-jug*))%

This will print the result in the minibuffer, in your case something like #<JUG-STATE {1004B61A63}>, which represents an instance of the JUG-STATE class. Keep a window open to the REPL buffer in case the functions write something to standard output (this is the case with the (describe ...) expression below).
If instead you do C-c I, this will ask you which expression you want to inspect, already filled with the form before the point. When you press enter, the inspector buffer will show up:
#<JUG-STATE {1004BD8F53}>
--------------------
Class: #<STANDARD-CLASS COMMON-LISP-USER::JUG-STATE>
--------------------
 Group slots by inheritance [ ]
 Sort slots alphabetically  [X]

All Slots:
[ ]  FIVE = 0
[ ]  TWO  = 2

[set value]  [make unbound]

Read http://www.cliki.net/slime-howto.


text:
Q: MySQL NOT EXITS condition not working Hello I am trying to execute a mysql query but getting error which I can't understand. The query I am using is
INSERT INTO summary (oid,tab,cost) VALUES('1','7','40') WHERE NOT EXISTS (SELECT * FROM summary WHERE cusid ='1')

I am using this tutorial as my reference, http://www.techonthenet.com/mysql/exists.php
This is the structure of the summary table

This is the error message

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use new 'WHERE NOT EXISTS (SELECT * FROM summary WHERE cusid = 1)' at line 1

A: It is not exits. Change it to exists.
INSERT INTO summary (oid,tab,cost) VALUES('1','7','40') WHERE NOT EXISTS (SELECT * FROM summary WHERE cusid ='1')
                                                                     ^

Also you can't use NOT EXISTS with your above query, you can with a subquery.


text:
Q: Is it possible to roll a dynamically-generated Javascript array (Node) into a Bash array? So I'm currently rolling a few different env variables into a Docker container using the following syntax:
Node script:
    process.env['VAR1'] = 'someArbitraryValue';
    process.env['VAR2'] = 'anotherArbitraryValue';

which then execs a bash script that looks like this:
params=()

[[ ! -z "$VAR1" ]] && params+=(-e "VAR1=$VAR1")
[[ ! -z "$VAR2" ]] && params+=(-e "VAR2=$VAR2")

docker run "${params[@]}"

That works just fine since I know the names of those env variables in advance and I can just hardcode the bash command to grab their values and insert them into params. However, what I'd like to be able to do is allow for a dynamically-generated list of variables to be added to the params list.
In other words, I run some function that returns an array that looks like:
var myArray = ['VAR3=somevalue', 'VAR4=anothervalue']

and is then passed into params by iterating through its contents and appending them. Since you can't set an array as an env variable in Bash, I'm not exactly sure if this is possible.
Is there a way to perform this operation, or am I out of luck?

A: If I'm not missing anything, yes; using child_process.execFile() (also see execFileSync()), you can pass elements of myArray as positional parameters to the bash script and do whatever you want with them in there.
const { execFile } = require('child_process');
// define "myArray" about here
const child = execFile('./myscript.sh', myArray, (error, stdout, stderr) => {
    if (error) {
        throw error;
    }
    console.log(stdout);
});
// ...

#!/bin/bash -
params=()

for param; do
    params+=(-e "${param}")
done

docker run "${params[@]}"


text:
Q: WARNING: :tensorflow:5 out of the last 5 calls triggered tf.function retracing during Machine Learning Crash Course by Developers.google I'm following "Introduction to Machine Learning Crash Course" held by Google.
Keras and Tensorflow is used in coding exercises. In one of the beginning exercises on linear regression, i have this code where a simple linear regression model using just 1 variable is created.
training_df = pd.read_csv(filepath_or_buffer="https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv")
training_df["median_house_value"] /= 1000

def build_model(my_learning_rate):
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Dense(units=1, input_shape=(1, )))
    model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=my_learning_rate),
                 loss="mean_squared_error", metrics=[tf.keras.metrics.RootMeanSquaredError()])
    return model

def train_model(model, df, feature, label, epochs, batch_size):
    history = model.fit(x = df[feature],
                        y = df[label],
                        batch_size = batch_size,
                        epochs = epochs)

    trained_weight = model.get_weights()[0]
    trained_bias = model.get_weights()[1]

    epochs = history.epoch
    hist = pd.DataFrame(history.history)
    rmse = hist["root_mean_squared_error"]

    return trained_weight, trained_bias, epochs, rmse

def plot_the_model(trained_weight, trained_bias, feature, label):
    plt.xlabel("feature")
    plt.ylabel("label")

    random_examples = training_df.sample(n=200)
    plt.scatter(random_examples[feature], random_examples[label])

    x0 = 0
    y0 = trained_bias
    x1 = random_examples[feature].max()
    y1 = trained_bias + (trained_weight * x1)
    plt.plot([x0, x1], [y0, y1], c="r")

    plt.show()

def plot_the_loss_curve(epochs, rmse):

    plt.figure()
    plt.xlabel("Epoch")
    plt.ylabel("Root MSE")

    plt.plot(epochs, rmse, label="Loss")
    plt.legend()
    plt.ylim([rmse.min()*0.97, rmse.max()])
    plt.show()

We define this functions to create the model, train the model, plot the model, and plot the loss.
In order to make prediction using the model, we define this last function to make the actual prediction.
Then I choose hyperparameters and i create a synthetic feature to make the prediction.
def predict_house_values(n, feature, label):
    # predict house value based on a feature
    batch = training_df[feature][10000:10000+n]
    predicted_values = my_model.predict_on_batch(x=batch)
    print("feature      label          predicted")
    print("value        value          value")
    print("             in thousand    in thousand")
    print("----------------------------------------")
    for i in range(n):
        print("%5.0f %6.0f %15.0f" % (training_df[feature][10000 + i],
                                   training_df[label][10000 + i],
                                   predicted_values[i][0] ))

training_df["rooms_per_person"] = training_df["total_rooms"] / training_df["population"]

my_feature = "rooms_per_person"
my_label = "median_house_value"
learning_rate = 0.01
epochs = 50
batch_size = 30

my_model = build_model(learning_rate)
weight, bias, epochs, rmse = train_model(my_model, training_df,
                                         my_feature, my_label,
                                         epochs, batch_size)

plot_the_loss_curve(epochs, rmse)
plot_the_model(weight, bias, my_feature, my_label)
predict_house_values(15, my_feature, my_label)

I Run this last block of code to predict the median_house_value using the room_per_person feature.
Everything works fine, but a warning appears.

WARNING:tensorflow:5 out of the last 5 calls to triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.

I think that the issue might be in for loop inside the predict_house_values function, but I am not sure.
How can I improve the code to avoid getting this warning? And can tracing/retracing of tf.function cause more serious issues in more complex problems?


text:
Q: Best practices to store user information in Redis I'm building a simple web application where I need to store user information when logged in.
The information that I need to store is in json format like:
User:{'name': 'John', roles:[1,2,3]}
I was thinking in storing the information with a combination of user + {user_id} like:
User_1: {'name': 'John', roles=[1,2,3]}
I needed to know if this is a good practice (thinking in retrieving the information fast) or if there is another alternative.

A: Option 1:
Using key: value pair.
"User_1": "name: John, roles=[1,2,3]"

Time complexity: O(1).
[x] But after getting the data from Redis you have to parse it again.
Option 2:
Using separate keys for name and roles.
"User_1_name": "John",
"User_1_roles": [1,2,3]

Time complexity: O(1) per request. In total for your example case it's constant.
[x] Extra call for same user.
Option 3:
Using hash.
user_1: {
    "name": "John",
    "roles": [1, 2, 3]
}

Time complexity: O(N). Where N is the number of fields in hash. But for your example case it's constant.
In my opinion using a hash will be the best option.

A: I guess your question is about the key, not value.
It's good practice to save user with user+id key.
And if you have another identify attribute for your user(Email for example), you'll need to map all users to their email.
So each user will have these keys in Redis:
User_1: {'name': 'John', roles:[1,2,3], 'email': 'blabla@test.com'}
User_blabla@test.com_id: 1
When you needed to find user by email, you can get the user id by reading the User_blabla@test.com_id(which it's value is equal to user's id 1), then get the User_1.


text:
Q: How can I create a function in python that counts the coincidences between two lists? If in the first list an element is repeated, and in the second list this element also appears, this might be counted as 1 coincidence
Example:
>>> comptaCoincidencies(['verd', 'groc', 'blau', 'vermell'], ['marro', 'blau', 'blanc', 'negre'])
0
>>> comptaCoincidencies(['verd', 'groc', 'blau', 'vermell'], ['blanc', 'negre', 'verd', 'groc'])
2
>>> comptaCoincidencies(['verd', 'groc', 'blau', 'vermell'], ['vermell', 'blau', 'groc', 'verd'])
4
>>> comptaCoincidencies(['verd', 'verd', 'verd', 'verd'], ['vermell', 'blau', 'groc', 'verd'])
1

I have done this:
def comptaCoincidencies(l1, l2):
    """
    Donades dues llistes, retorna el nombre d'elements coincidents entre le llistes
    >>> comptaCoincidencies(["verd", "verd"], ["blau", "blau"])
    0
    >>> comptaCoincidencies(["verd", "vermell"], ["verd", "blau"])
    1
    >>> comptaCoincidencies(["verd", "blau"], ["blau", "verd"])
    2
    """
    comptador = 0
    for i in range(0, len(l1)):
        if l1[i] in l2:
            comptador = comptador + 1
    return comptador

A: This will return a set of the duplicated elements
set(filter(set(lst1).__contains__, lst2))

and adding the len will calculate its length so the count of the duplicate elements
len(set(filter(set(lst1).__contains__, lst2)))

Update based on @Willem Van Onsem comment
set(lst1) & set(lst2)


text:
Q: fail to connect to Hbase with java api Can I use java api to connect to Hbase in a standalone mode(without Hadoop)?
Here is my code, and I was wondering how to make it work. Should I set some property to the variable 'config'?
I have these installed locally : Hbase-0.98.0   Hadoop 2.2.0
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;

public class MyLittleHBaseClient {
  public static void main(String[] args) throws IOException {

    // maybe I should do some configuration here, but I don't know how
    Configuration config = HBaseConfiguration.create();

    HTable table = new HTable(config, "myLittleHBaseTable");

    Put p = new Put(Bytes.toBytes("myLittleRow"));

    p.add(Bytes.toBytes("myLittleFamily"), Bytes.toBytes("someQualifier"),
      Bytes.toBytes("Some Value"));

    table.put(p);

    Get g = new Get(Bytes.toBytes("myLittleRow"));
    Result r = table.get(g);
    byte [] value = r.getValue(Bytes.toBytes("myLittleFamily"),
      Bytes.toBytes("someQualifier"));

    String valueStr = Bytes.toString(value);
    System.out.println("GET: " + valueStr);

    Scan s = new Scan();
    s.addColumn(Bytes.toBytes("myLittleFamily"), Bytes.toBytes("someQualifier"));
    ResultScanner scanner = table.getScanner(s);
    try {

      for (Result rr = scanner.next(); rr != null; rr = scanner.next()) {

        System.out.println("Found row: " + rr);
      }

    } finally {

      scanner.close();
    }
  }
}

A: If your hbase-site.xml in standalone mode is empty(), you don't have to set any thing. If have overridden anything in the hbase-site.xml, better add that hbase-site.xml instead of setting parameter separately.
Configuration config = HBaseConfiguration.create();
config.addResource("<HBASE_CONF_DIR_PATH>/hbase-site.xml");


text:
Q: what is difference between data center manager and data center administrator can anyone bring out the difference between what is expected from a Data Center Manager and a Data Center Administrator?

A: Titles vary by every place you might work...
Regardless, the DC Manager is probably responsible for the entire data center, has multiple supervisors and others below them.  May only be responsible for certain aspects of the DC such as only cabinets and servers, or could actually be responsible for the entire facility, much like a General Manager type of position.  Again this all varies.
The DC administrator is someone who would report to one of the aforementioned supervisors or managers.  This person is often responsible for actually making changes to things, monitoring devices and deploying new stuff.
Again, this all varies across the board but should give you a good separation of responsibilities from a general view point.


text:
Q: angular 8 a variable is modified in onchanges event , but when i want to access it i find that is not changed i have a application in angular , and i have a component with custem property  "modeInsert", and i detect change of this property in ngOnChanges() event , like this:

import { Component, OnInit, Input, ViewChild,  OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-update-cv',
  templateUrl: './update-cv.component.html',
  styleUrls: ['./update-cv.component.css']
})
export class UpdateCVComponent implements OnInit ,OnChanges {

  constructor() { }

  mode:boolean;

  ngOnInit() {
  }

  ngOnChanges(changeRecord: SimpleChanges): void {
    if(typeof changeRecord.modeInsert !== 'undefined'){
      this.mode=changeRecord.modeInsert.currentValue;
      console.log("changeRecord._modeInsert :"+this.mode);
    }
  }

  @Input() modeInsert: boolean;

  @ViewChild('closebuttonUpdateCV',{static: false}) closebuttonUpdateCV;
  onUpdateCV(cv){
    console.log(" onUpdateCV mode ="+this.mode)
    if(this.mode){
      console.log(" mode = ajout")
    }else {
      console.log(" mode = modif")
    }
    this.closebuttonUpdateCV.nativeElement.click();
  }
}

,This variable changes its value in Onchanges Event, but when I try to reach its value, I find that it has not changed, like in methode onUpdateCV(cv).

A: You will get current and previous values in ngOnChanges
ngOnChanges(changes: SimpleChanges) {
      for (let propName in changes) {
        let chng = changes[propName];
        let cur  = JSON.stringify(chng.currentValue);
        let prev = JSON.stringify(chng.previousValue);
      }
    }

A: The reason is that I put two copies of this component, one in the menu and the other in another component, so when I called may compenet from the other component, I would have called the version on the menu , and the variable this.mode is undifained.
and this is the templet of may component, is a modal form:

        <button type="button" #closebuttonUpdateCV class="close" data-dismiss="modal"
        aria-label="Close">
          ×
        </button>

      <form #fcv="ngForm" (ngSubmit)="onUpdateCV(fcv.value)">

            nom:
            <input type="text" class="form-control" placeholder="nom"   name="nom" ngModel>

            prenom:
            <input type="text" class="form-control" placeholder="prenom"   name="prenom" ngModel>

            Etat civile :
            <input type="text" class="form-control" placeholder="Etat civile" name="etatcivile"  ngModel>

            Adress :
            <input type="text" class="form-control" placeholder="Adress" name="adress" ngModel>

            Email :
            <input type="text" class="form-control" placeholder="Email"  name="email" ngModel>

            Tel :
            <input type="text" class="form-control" placeholder="Tel." name="tel" ngModel>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
          <button type="submit" class="btn btn-primary">Sauvgarder</button>

      </form>

but in this case what i do for caling the copy what i ned


text:
Q: Using data from hidden table column Is there a way to access cell data in a table column if the entire column is hidden. I produced my table using visual studio and the data is sourced from oracle. Any advice would be great.

A: Well, if you set a column to be invisible in .NET , it won't be displayed in your HTML code so obviously there's no way to get anything from it in javascript (as you tagged you question javascript I presume that's what you're trying to achieve).
Either you treat this data server-side, in .NET, either you let the column appear in your HTML and just hide it with css...


text:
Q: Как получить изображение из набора в редакторе? Работаю в Android Studio. Можно конечно поместить изображения для кнопки в res/drawable. Но я использую изображение кнопки из набора в редакторе. Как мне в коде обращаться к этим изображениям, например "R.drawable.ic_lock_power_off"? (так не срабатывает).
Нашел:
setImageResource(android.R.drawable.ic_lock_lock);

A: К системным ресурсам надо обращаться через android.R класс системы, а не через R класс вашего проекта, который генерится в основном пакете вашего проложения. Т.е надо так (для данной конкретной картинки):
android.R.drawable.ic_lock_lock


text:
Q: Adaptive Radix Tree Since 1 week, I have found one interrested topic called :
Adaptive Radix Tree,
I found it is very useful techniques used to index memory specially in modern hardware architectures .
Actually I could not understand one point in page 4 , called Node48.
I have attached a picture of what I mean.
http://s30.postimg.org/nff1am2r5/xadaptive_radix.png
also this is the main page of the article :  http://www-db.in.tum.de/~leis/papers/ART.pdf
So could anybody who is more smart than me to explain that for me, I would be very happy.
Thanks.

A: I believe that you understand how NODE_4 and NODE_16 works.
In NODE_4 and NODE_16, they put 4 to 16 8-bit keys in the first part of a node. The cost of searching a key are 32 bits and 128 bits that can fit into a regular register and a SIMD register.
However, if we use same way in NODE_48, the cost of searching is read 384 bits that cannot even fit into 256-bit SIMD register. So, Viktor Leis et al. use a child index instead of keys in the first part of NODE_48. The child index contains 256 8-bit offsets that represent the position of a pointer. Eg. If you want to search 103 (it could be 0 to 255) in a NODE_48, the program would:

*

*jump to the 103rd slot in the child index (start from 0th)

*read the value from 103rd slot and assume it is 5

*jump to the 5th slot in the child pointer

*read the pointer value from 5th slot and go to the next node

It does 2 offset calculations instead of 48 (SIMD) selections.
Addition:
For Accessing the 103th element in NODE_4 (or NODE_16):

*

*read the "key" part of the NODE in which there are 4 keys (or 16 in NODE_16) which present the key of the child pointers.

*execute a SIMD instruction to compare 103 with all 4 keys.

*if one of the keys (let say 3rd key) is 103, follow the 3rd child pointer

*if none of the keys is 103, return not found.


text:
Q: xsd to class (C#) in visual studio 2019 I am following a tutorial, in one step it opens "VS2012 arm cross tools command prompt" and executes
xsd file.xsd /classes

I can't find "VS2012 arm cross tools command prompt" on my computer (my guess it's because I'm using VS2019) so I open the "Developer command prompt for VS 2019" instead, but when I run the command, I get an error:

"xsd" is not recognized as an internal or external command, program or executable batch file

Can someone tell me how I can create a class from an xsd file in VS 2019? Thank you for your time.

A: Once you have installed the Windows SDK. The following could be of help to you...it is .NET Core. Browse to the xsd.exe and add a reference to it in VS 2019.
class Program
{
    static void Main(string[] args)
    {
        var rgs = new string[]
        {
            @"PathToYourDLL\My.dll",
            "/type:ClassNameToGen"
        };

        AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
        {
            string error = e.Exception.ToString();

            var typeLoadException = e.Exception as ReflectionTypeLoadException;

            if (typeLoadException != null)
            {
                foreach (var exception in typeLoadException.LoaderExceptions)
                {
                    error += Environment.NewLine + Environment.NewLine + exception.ToString();
                }
            }

            Console.WriteLine(error);
        };

        XsdTool.Xsd.Main(rgs);

        Console.ReadLine();
    }
}


text:
Q: Execute certain JavaScript depending on URL A client wants to measure the conversion rate of his Magento webshop through Google Adwords via snippets on the success page of the shop. The Webshop is multilingual with every language having a different URL but they are all based on one Magento installation.
For every language / country they have a different AdWords campaign with their own conversion measurement and therefore their own code snippet.
I know I need to identify users via the URL and then insert the correct snippet accordingly, but how do I do this? Javascript or PHP? Could someone please give me hint.
My first try
<?php

$currentDomain = $_SERVER['HTTP_HOST']

if ('shop.domain1.com' == $currentDomain) {
    include('domain1script.php');
} elseif ('shop.domain2.com' == $currentDomain) {
    include('domain2script.php');
} elseif ('shop.domain3.com' == $currentDomain) {
    include('domain3script.php');
} elseif ('shop.domain4.com' == $currentDomain) {
    include('domain4script.php');
}
?>

with domain1script.php being:
<script type="text/javascript">
    "scriptstuff"
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
    "noscriptstuff"
</noscript>

A: You can do it with either php, or javascript.
For the sake of simplicity and keeping your JS nice and short I would use PHP. $_SERVER['REQUEST_URI'] should return what you're looking for. :)
This can be achieved in javascript as well, I believe window.location.href contains what you would want to parse?


text:
Q: able to run unsigned app on jailbroken iOS I'm developing an app for jailbroken iOS devices using Xcode 4.3 (altered by JailCoder), testing on an iPod Touch 4G, currently running iOS 5.1.1, previously 5.0.1. I noticed recently I'm able to run my app on my iPod without using either ldid or a self-signing certificate with codesign to bypass code-signing requirements (as described on http://www.saurik.com/id/8). I don't have either the security.mac.proc_enforce or security.mac.vnode_enforce security checks disabled.
So why would I be able to run unsigned code on my iPod? This didn't seem to change when I upgraded from 5.0.1 to 5.1.1. My beta testers are unable to run my app on their 5.1.1 systems when not signed with a self-signing certificate. What could be different on my system? Could it be differing methods we used to jailbreak our devices?

A: To run unsigned code on an iDevice, it needs to be jailbroken. To easily install your custom app and debug it from Xcode (or give it to somebody else) the easiest way is to package an IPA and sync it via iTunes. However, it requires AppSync (mainly used for piracy, sadly).

A: The iOS 5.1.1 jailbreak didn't patch the code signing need to run executables. AFAIK no one apparently cared enough to do so, which means many discomfort for those who build on iOS some software as ./configure scripts obviously doesn't work. If an executable is not codesigned (or fake-codesigned), it will receive a SIGKILL.


text:
Q: Editing HTML with VBScript in an HTA I have an HTA (html application) for adding network printers.  It consists of some check boxes with printer names, and a button that initiates the install.
Befuddling to me is that the output_area.innerHTML call within the If statement does nothing (though the printer does install properly), while the output_area.innerHTML call outside of the If statement works just fine.

 <input type="checkbox" name="printer-name">Printer Name
 <input type="button" value="Add Printer" onClick="AddPrinterSub">

While the printer is installing, the output_area div shows nothing; after the install is complete, it shows "Printer install complete."

A: This is kind of hard to explain, but when you change the DOM in a script, the DOM doesn't actually change until the script finishes executing. You never see "Installing printer-name" because the div is only set to this text while the script is executing. If you want to see the status message, you need to break the script into two parts: one to initialize the long-running task, and the other to actually execute the task.
In order to do this, you can use the function SetTimeout, which sets an event to execute a function after a delay. In this case, we don't need a delay - we only care that SetTimeout lets us start executing a function after the current script finishes executing, giving the DOM a chance to refresh, so we use a delay of 0.
Sub AddPrinterSub()
    If printer_name.Checked Then
        SetTimeout "AddPrinter ""\\server-name\printer-name""", 0
        output_area.innerHTML = "Installing printer-name"
    End If
end sub

Sub AddPrinter(printer_path)
    Set Network = CreateObject("WScript.Network")
    Network.AddWindowsPrinterConnection printer_path
    output_area.innerHTML = "Printer install complete."
End Sub

A: While your Sub is executed, the browser does not update the display. You can use

  <input type="checkbox" name="printer-name">Printer Name
  <input type="button" value="Add Printer" onClick="AddPrinterSub">

to prove that the update 'works' as soon as you put (the .HTA version of) .Sleep into your loop.
You must decide whether the detailed display is worth the extra work and - if yes - whether shelling out or using setTimeout for the installation is more appropriate.


text:
Q: How can I redirect this to a slug url in django? So I have one detail view and one function in my views.py. So i have included the form in detail view template list_detail.html. and upon posting the form successfully. It redirects to all page(homepage basically). Now I want it to redirect to detailview page which is like this. and for that I need to pass the slug value of that List models specific object. But can build the logic here. I am new to django.
path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'),
path('all',views.all, name='all'),
path('create_comment',views.create_comment, name='create_comment'),

class TheirDetailView(DetailView):
    model = List
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        modell = Review.objects.all()
        context["modam"] = modell
        return context

def create_comment(request):
    context = {}
    form = ReviewForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('app:all')
    else:
        context['form'] = form
        return render(request, "app/create_comment.html", context)

A: def create_comment(request):
    # context = {}
    form = ReviewForm(request.POST or None)
    id_List = request.POST["List"]
    slug = List.objects.filter(id=int(id_List)).values("slug").first()
    if form.is_valid():
        form.save()
        return redirect("app:list_detail", slug=slug["slug"])

A: Hey did some google and found this in stackoverflow link added this line replacing my redirect under my create_comment function if form.is_valid statement
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

So my function looks like this
def create_comment(request):
    context = {}
    form = ReviewForm(request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    else:
        context['form'] = form
        return render(request, "app/create_comment.html", context)

Weirdly enough its said in the post that it wont work in incognito/private mode but just checked and it does. But even in some articles its discouraged to use this referrer so still looking for a better solution to this. Thanks everyone.


text:
Q: iOS - If app has launched for the first time - Presenting ModalView I figured out how to present two differnt view controllers at the time of app launch and it works fine if I dont present them modally. somehow it shows blank view controller if I change code.
From ->     self.window.rootViewController = landingVC;
To->        [self.window.rootViewController presentViewController:landingVC animated:YES completion:nil];
Here's the complete code in my app delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *tabbarController = [storyboard instantiateViewControllerWithIdentifier:@"TabBarViewController"];
UIViewController *landingVC = [storyboard instantiateViewControllerWithIdentifier:@"LandingViewController"];

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"]) {

        self.window.rootViewController = tabbarController;
 } else {
  [self.window.rootViewController presentViewController:landingVC animated:YES completion:nil];
      }

[self.window makeKeyAndVisible];
return YES;
}

AFAIK, thats how modalVC should be shown. I've already verified storyboardIDs and checked "use storyboardIDs" for both viewcontrollers.

A: What you're doing is setting the root view controller as the tabbarController if the app has been launched before, otherwise you're telling the app's root view controller (which hasn't been set and doesn't exist yet) to present the view controller.
I would be willing to guess that if you put NSLog(@"%@", self.window.rootViewController); above the presentViewController line, you would get back nil, meaning you're trying to tell nil to do something, which of course won't work.
I just tried this and it works:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    UIViewController *testRootVC = [UIViewController new];
    testRootVC.view.backgroundColor = [UIColor blueColor];
    self.window.rootViewController = testRootVC;

    [self.window makeKeyAndVisible];

    if (YES) {
        UIViewController *testModalVC = [UIViewController new];
        testModalVC.view.backgroundColor = [UIColor redColor];
        [testRootVC presentViewController:testModalVC animated:YES completion:nil];
    }

    return YES;
}


text:
Q: How to make a !default case in C On a micro-controller program I have a few instructions that I would like to execute for every case in a switch except the default. I do not, however, want to write a function call or use a macro for every case.
Because this is for a micro-controller running at 3-7Mhz, speed and code space are important.
For example:
switch(letter)
{
case a:
    ShowApple();
    printf("You entered an english letter.");
    break;
case b:
    ShowBananna();
    printf("You entered an english letter.");
    break;
...
case z:
    ShowZebra();
    printf("You entered an english letter.");
    break;
default:
    printf("You did not enter an english letter. Silly human!");
    break;
}

A: int was_default_picked;

was_default_picked = 0;
switch (letter)
{
// ...

default:
    was_default_picked = 1;
}

if (!was_default_picked)
{
    // Your logic goes here
}

A: I'm going to go to hell for this...
switch (foo) {
default:
    /* code for default case */
    break;
    if (0) { case 'a':
        /* ... */
    } if (0) { case 'b':
        /* ... */
    } if (0) { case 'c':
        /* ... */
    }
    /* common code for non-default cases */
}

A: Why don't you use an array of function pointers indexed by a letter instead of switch? That would be both more space and speed efficient. And, IMO, more readable.
static void (*fn_table['z' - 'a' + 1])(void) = {
    &ShowApple,
    &ShowBananna,

    ...,

    &ShowZebra,
};

if (letter < 'a' || 'z' < letter)
{
    printf("You did not enter an english letter. Silly human!");
}
else
{
    (*fn_table[letter - 'a'])();
    printf("You entered an english letter.");
}

A: If it's really the last statement in each case, you could simply execute it afterward using an if statement:
int wasEnglish = 1;
switch(letter)
{
case a:
    ShowApple();
    break;
case b:
    ShowBananna();
    break;
...
case z:
    ShowZebra();
    break;
default:
    wasEnglish = 0;
    break;
}

if (wasEnglish)
{
    printf("You entered an english letter.");
}
else
{
    printf("You did not enter an english letter. Silly human!");
}


text:
Q: How to upload bulk data to Parse backend I am developing an app which basically is like a wallpaper app.
I want to use Parse as the back end. How do I make different categories and upload large number of files to each category? I tried with uploading one at a time manually, but with large number of files it is cumbersome.

A: If you have your wallpaper objects in an array can do it like this:
for(wallPaper *wallpaper in someArray) {

        PFObject *wallpaper = [PFObject objectWithClassName:@"wallpaper"];
        wallpaper[@"title"]=wallpaper.title;
        UIImage *image = wallpaper.image;
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        PFFile *imageFile = [PFFile fileWithName:@"wallpaper.jpg" data:imageData];
        [imageFile saveInBackground];
        [wallpaper setObject:imageFile forKey:@"wallpaperImage"];
        [wallpaper saveInBackground];

    }

You could also have a separate class "category". Each object in "category" has the category name i.e. "beaches" then have a PFRelation "members" pointing to which wallpapers belong to that category.


text:
Q: Creating Trusted hosts on D-Link DGS-1510-20 I'm trying to setup my D-Link DGS-1510-20 so that they can only be managed from specific IP addresses.
I assume I use "Trusted host" under "Security", but nothing there seems to give me what I would expect to see. I can't find any documentation to describe the process, but I'm sure it can be done. Anyone got any experience doing this on these switches?


text:
Q: JavaScript and iframes: dangerous for my website? In order to see a live preview of another website that users link to on my website, I'm using iframes.
However, this is probably not the best solution, as a website is loaded directly into mine, with every JavaScript element etc that is on the linked page.
My question: how dangerous is it to do such a thing? What is the worst case scenario that could happen? Could a linked site just by using JavaScript (or other technologies) do any serious harm to my site or my user's data?

And then, the second part of my question is, of course, about the website preview.
All I found so far are scripts that contain more than one php and js file in order to load a website preview picture.
Isn't there an easier way to do this? What do you suggest?

A:
how dangerous is it to do such a thing?

Some websites do not like to be embedded using frames. Such websites can possibly take over the full browser by ensuring it is loaded in the topmost window. Aside from that, as long as your website and the website you are loading aren't from the same domain, they won't be able to access your cookies, DOM etc. So its pretty safe in that respect.

about the website preview

There aren't many fool proof mechanisms other than generating the preview image server side - as I believe the scripts you've seen do.


text: Q: Grothendieck group of admissible $p$-adic representations Let $K$ be a $p$-adic local field; $G = \mathop{\mathrm{Gal}}(\overline K | K)$; $\tau \in \{\text{HT}, \text{dR}, \text{crys}\}$, $B_\tau$ the corresponding period ring; $\mathop{\mathrm{Rep}}_{\mathbf Q_p}^\tau(G) \subseteq \mathop{\mathrm{Rep}}_{\mathbf Q_p}(G)$ the full subcategory of $B_\tau$-admissible representations. Is it true that $\mathbf K_0(\mathop{\mathrm{Rep}}_{\mathbf Q_p}(G)) = \mathbf K_0(\mathop{\mathrm{Rep}}_{\mathbf Q_p}^\tau(G))$?


text:
Q: Problem running Python code in Jupyter Notebook: GoodReadsScraper I would like to start by letting you know that I am a layperson. I only started working with Python a few weeks ago, so I am new to this and am not yet familiar with quite a lot of the necessary terminology. I would be very grateful for your help!
I want to try out Omar Einea's Goodreads Reviews Scraper (https://github.com/OmarEinea/GoodReadsScraper). I followed his instructions and installed beautifulsoup4, langdetect, selenium and lxml using pip.
I copy-pasted part of his code from reviews.py to a Jupyter Notebook to test it out and ran the following cell:
from Tools import SafeThread
from bs4 import BeautifulSoup
from langdetect import detect
from Browser import Browser
from Writer import Writer

However, I got the following error:
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-4dc46ca353f6> in <module>
----> 1 from Tools import SafeThread
      2 from bs4 import BeautifulSoup
      3 from langdetect import detect
      4 from Browser import Browser
      5 from Writer import Writer

ImportError: cannot import name 'SafeThread' from 'Tools' (unknown location)

I thought that perhaps I had to install tools first, so I ran
Python Code:
pip install tools

in the command line, but I received the message that it had already been installed:
C:\Users\Lore>pip install Tools
Requirement already satisfied: Tools in c:\users\xxx\appdata\local\programs\python\python38-32\lib\site-packages (0.1.9)
Requirement already satisfied: pytils in c:\users\xxx\appdata\local\programs\python\python38-32\lib\site-packages (from Tools) (0.3)
Requirement already satisfied: six in c:\users\xxx\appdata\local\programs\python\python38-32\lib\site-packages (from Tools) (1.13.0)
Requirement already satisfied: lxml in c:\users\xxx\appdata\local\programs\python\python38-32\lib\site-packages (from Tools) (4.4.2)

Do you have any ideas on how I might be able to solve this problem?
I also have another question. So far I have only worked in/with jupyter notebooks. Is there a better way/place to write and run my Python scripts/commands?
I tried running the entire code from "Reviews.py", by opening it in IDLE and clicking on "run", but that just gave me this:
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
======= RESTART: C:\Users\xxx\Desktop\GoodReadsScraper-master\Reviews.py ======
>>>

Thank you in advance for your kind help and understanding!

A: 'Tools' being referenced in Review.py is this script called 'Tools' in the repository you reference.
What you installed with pip install tools is something not related to that.  You can see it here.
You'd have an easier time if you download all the code in the repository and then try running things while your working directory is set to that directory. In a notebook you can use pwd to print your working directory. You can use %cd to change it.


text:
Q: How to pull this information In SharePoint I can set my "Created By" column to display as "Office", which then shows as this.

My problem is, that I cannot figure out a way to pull what is displayed here to use for a condition in a flow.
SharePoint will not allow me to use "Created By" in a calculated column.
Also nowhere in the flows dynamic content is there a "Created By Office".
Does anyone have any ideas? Please, I have been on this for days now.

A: May be, write a sharepoint designer workflow that will copy text from Created by and copy it to another new text field on item creation.
Once copied, use this new field in your flow for calculation.
Sequence of sharepoint designer and flow trigger can get tricky, so you might want to play around by carrying some tests, to make sure field is updated first and then Flow triggers.


text:
Q: Setting gnome themes inside xfce I have a few apps (such as Aisleriot) that are GNOME based, therefore they use the gnome defaults (which is some light theme), but I use xfce4 with compiz. My xfce theme is a dark one (atolm to be exact). How do I make the theme for these GNOME applications the same as my xfce4 theme? I already tried starting in gnome, setting the theme then switching back, this doesn't fix the problem.

A: If you set change the theme from xfce settings it should affect all GTK apps, including GNOME ones. There was a bug that got fix a while ago in which xfce couldn't set GTK3 themes properly. Otherwise it could be because you're using an old version of the theme which doesn't support GTK3. See if updating xfce or the theme solves the issue.


text: Q: How can I have a collection of emotion stickers in Wordpress comments? I would like to have a collection of stickers for users to select when they add comments in WordPress. How can I do that? I have done some research in Google but cannot find a solution. All I can find is just a plugin of emoji.


text:
Q: How does the Firestore pricing work by big data? In my App the user can note his training in a table. So with the time the table (I use PaginatedDataTable for better performance) can get very big. I saw, that firestore offers 50.000 reads a day for free. Does every single data in the table stands for one read? In this case when the user have a big table with lets say 5.000 entrys, the 50.000 reads would be used very fast, especially when there are more users with much entrys.
Do I get this wrong or how does the counting work?

A: Every time a document is read for your from the server, it counts as one document read. Running a query does not read all documents in the collection though, but only those that are returned by the query.
So if you read all 50,000 documents, that indeed counts as 50,000 document reads. But if you through a query reduce that number and read (say) only 100 documents from the 50,0000, then that only counts as 100 document read.
The only exception here is if a query returns no documents, it still is charged as 1 document read. Oh, and many of the SDKs (iOS, Android, Web) offer a client-side cache, and reads from the cache are of course also not charged.


text:
Q: Отображение части массива в зависимости от размеров экрана vue js У меня есть массив пяти объектов. При изменении размеров экрана мне надо, чтобы массив отображался частично. Например, вместо 4 объектов происходит отображение трех, затем двух, в зависимости от размеров экрана.
Понимаю, что в данной ситуации актуален будет метод slice. Но полная реализация подобного мне непонятна сейчас

A: Если я правильно понял задачу, то один из вариантов реализации, с использованием Bootstrap-Vue
<b-container>
  <b-row>
    <b-col v-for="item in items" sm="4">{{ item }}</b-col>
  </b-row>
</b-container>

    ...
    data() {
      return {
        items: [1, 2, 3, 4, 5]
      }
    }
    ...

Вот ссылка на рабочий пример.

A: Вот набросал готовый пример https://codepen.io/dvomaks/pen/dyPexMQ
new Vue({
  el: '#app',
  data: {
    width: 0,
    height: 0,
    items: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
  },
  computed: {
    cropItems() {
      const l = Math.round(this.width / 100);
      return this.items.slice(0, l);
    }
  },
  created() {
    window.addEventListener('resize', this.handleResize)
    this.handleResize();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  }
});

Для проверки нужно уменьшить окно браузера по ширине. Надеюсь я правильно понял суть задачи.


text:
Q: x, y, z coordinates of an object for a nwc file in forge viewer I am trying to find x,y,z coordinates of an object inside nwc model, and I am using below code.
Despite that this code was working for rvt files, it is not working for nwc model.
Is there a way to get x,y,z coordinates from a nwc model?
getFragmentWorldMatrixByNodeId(nodeId) {
        let result = {
            fragId: [],
            matrix: [],
        };
        let viewer = this.viewer;
        this.tree.enumNodeFragments(nodeId, function (frag) {

            let fragProxy = viewer.impl.getFragmentProxy(viewer.model, frag);
            let matrix = new THREE.Matrix4();

            fragProxy.getWorldMatrix(matrix);

            result.fragId.push(frag);
            result.matrix.push(matrix);
        });
        return result;
    }

A: You mentioned you are looking for the "x,y,z coordinates of an object". What exactly do you mean by that? I'm going to assume that you want the coordinates of the center point of the object's bounding box, as that is what people ask for usually. In your code snippet, however, you're retrieving the entire transformation matrix, not a position.
If the center point of a bounding box works for you, you could obtain it like so:
function getObjectBoundingBox(model, dbid) {
    const tree = model.getInstanceTree();
    const frags = model.getFragmentList();
    let totalBounds = new THREE.Box3();
    tree.enumNodeFragments(dbid, function (fragid) {
        let fragBounds = new THREE.Box3();
        frags.getWorldBounds(fragid, fragBounds);
        totalBounds.union(fragBounds);
    }, true);
    return totalBounds;
}

getObjectBoundingBox(viewer.model, 123).center();


text:
Q: Why is $.datepicker(); not functioning, yet $.hide(); is? I'm using twitter bootstrap (generated through less), jquery and jquery UI. Here are the main imports and script tags on the page:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <style>
      body {
        padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
      }
    </style>
    <link rel="stylesheet/less" href="/assets/less/bootstrap.less">
    <script src="/assets/less/less-1.3.0.min.js"></script>
    <link rel="shortcut icon" type="image/png" href="/assets/images/favicon.png">
    <link type="text/css" href="/assets/stylesheets/jquery-ui-1.8.22.css" rel="stylesheet" />
    <link rel="stylesheet" href="/assets/stylesheets/my.css" />

    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- Le fav and touch icons -->
    <link rel="shortcut icon" href="../assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
  </head>

  <body>
   <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <!-- remember <link> tag for the jqueryUI css-->
    <script src="/assets/javascripts/jquery-1.7.2.min.js"></script>
    <script src="/assets/javascripts/jquery-ui-1.8.22.min.js"></script>
    <script src="/assets/javascripts/bootstrap-transition.js"></script>
    <script src="/assets/javascripts/bootstrap-alert.js"></script>
    <script src="/assets/javascripts/bootstrap-modal.js"></script>
    <script src="/assets/javascripts/bootstrap-dropdown.js"></script>
    <script src="/assets/javascripts/bootstrap-scrollspy.js"></script>
    <script src="/assets/javascripts/bootstrap-tab.js"></script>
    <script src="/assets/javascripts/bootstrap-tooltip.js"></script>
    <script src="/assets/javascripts/bootstrap-popover.js"></script>
    <script src="/assets/javascripts/bootstrap-button.js"></script>
    <script src="/assets/javascripts/bootstrap-collapse.js"></script>
    <script src="/assets/javascripts/bootstrap-carousel.js"></script>
    <script src="/assets/javascripts/bootstrap-typeahead.js"></script>

  <!--Jquery for the invite button datepicker-->
  <script type="text/javascript">
    $(document).ready(function() {
        $("div").hide();
        return false;
    });
    </script>

  </body>
</html>

Note the last  tag, the one hiding the div. This page ends up being blank, as the main div gets hidden (not shown here). If, hoewver I replace that with
<script type="text/javascript">
        $(document).ready(function() {
                $("#datepicker").datepicker();
            $("div").hide();
            return false;
        });
        </script>

Then nothing happens - the divs do not get hidden. I've tried using Firebug, but it starts hanging when I try and inspect the script.
Is it possible that my imports are somehow conflicting?


text:
Q: GroupPrincipal.GetMembers fails when group (or child group if recursive) contains ForeignSecurityPrincipal This is not so much a question as information for anyone experiencing the same problem.
The following error occurs:
System.DirectoryServices.AccountManagement.PrincipalOperationException: An error (87) occurred while enumerating the groups. The group's SID could not be resolved.
at System.DirectoryServices.AccountManagement.SidList.TranslateSids(String target, IntPtr[] pSids)
at System.DirectoryServices.AccountManagement.SidList.ctor(List`1 sidListByteFormat, String target, NetCred credentials)
at System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.TranslateForeignMembers()

When the following code is run and a group or child group contains a ForeignSecurityPrincipal:
private static void GetUsersFromGroup()
{
    var groupDistinguishedName = "CN=IIS_IUSRS,CN=Builtin,DC=Domain,DC=com";
    //NB: Exception thrown during iteration of members rather than call to GetMembers.
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Domain", "Username", "Password"))
    {
        using (GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, groupDistinguishedName))
        {
            using (var searchResults = groupPrincipal.GetMembers(true))//Occurs when false also.
            {
                foreach (UserPrincipal item in searchResults.OfType())
                {
                    Console.WriteLine("Found user: {0}", item.SamAccountName)
                }
            }
        }
    }
}

I raised a support call with Microsoft and they have confirmed it as an issue.  A bug has been raised internally but it has not been confirmed whether this will be fixed.
Microsoft suggested the following workaround code but it performs poorly on groups with a large number of users because of the repeated calls to UserPrincipal.FindByIdentity.
class Program
{
    //"CN=IIS_IUSRS,CN=Builtin,DC=dev-sp-sandbox,DC=local"; //TODO MODIFY THIS LINE ACCORDING TO YOUR DC CONFIGURATION

    static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            Console.WriteLine("Usage: ListGroupMembers \"group's DistinguishedName\"");
            Console.WriteLine("Example: ListGroupMembers \"CN=IIS_IUSRS,CN=Builtin,DC=MyDomain,DC=local\"");
            return;
        }

        string groupDistinguishedName = args[0];

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "dev-sp-dc", "Administrator", "Corp123!");
        List<UserPrincipal> users = new List<UserPrincipal>();
        listGroupMembers(groupDistinguishedName, ctx, users);

        foreach (UserPrincipal u in users)
        {
            Console.WriteLine(u.DistinguishedName);
        }
    }

    //Recursively list the group's members which are not Foreign Security Principals
    private static void listGroupMembers(string groupDistinguishedName, PrincipalContext ctx, List<UserPrincipal> users)
    {
        DirectoryEntry group = new DirectoryEntry("LDAP://" + groupDistinguishedName);
        foreach (string dn in group.Properties["member"])
        {

            DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + dn);
            System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

            object[] objCls = (userProps["objectClass"].Value) as object[];

            if (objCls.Contains("group"))
                listGroupMembers(userProps["distinguishedName"].Value as string, ctx, users);

            if (!objCls.Contains("foreignSecurityPrincipal"))
            {
                UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, dn);
                if(u!=null)  // u==null for any other types except users
                    users.Add(u);
            }
        }
    }
}

The above code could be modified to find foreign security principals causing problems in groups.
Microsoft provided the following information about the foreign security principals:
This is a class of objects in AD which represents a security principal from an external source (so another forest/domain or one of the "special" accounts below).
The class is documented here: http://msdn.microsoft.com/en-us/library/cc221858(v=PROT.10).aspx
And the container is documented here : http://msdn.microsoft.com/en-us/library/cc200915(v=PROT.10).aspx
A FSP is not a real object in AD, but rather a placeholder (pointer) to an object which lives in a different, trusted domain/forest. It can also be one of the "special identities" which are a bunch of well-known accounts who are also classed as FSP's because their SID's are different to the domain SID.
For example the anonymous, Authenticated User, batch and several other accounts as documented here:
http://technet.microsoft.com/en-us/library/cc779144(v=WS.10).aspx

A: Sure this is an old thread, but might help someone.  I used the below code block the solve the problem. the Principal class exposes a property called StructuralObjectClass which tells you what is the AD Class of that principal. I used this to decide whether the object is a user. The GetMembers(true) recursively searches all nested-members in the groupPrincipal in question.
Hope this helps someone.
    List<UserPrincipal> members = new List<UserPrincipal>();
    foreach (var principal in groupPrincipal.GetMembers(true))
    {
        var type = principal.StructuralObjectClass;
        if (type.Contains("user"))
            members.Add((UserPrincipal)principal);
    }

Thanks,
R

A: The accountmanagement library has many saddening defects, this is just another of the many...
One thing you can do to make things slightly faster would be to adjust your LDAP query so that it checks both group membership and object type at the same time as part of the query instead of in the loop.  Honestly I doubt it will make much difference though.
Most of the inspiration for the query came from  How to write LDAP query to test if user is member of a group?.
Query:  (&(!objectClass=foreignSecurityPrincipal)(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))
Note: This is an untested query...
IF there was a way to run an LDAP query in AccountManagement (another gripe of mine) then this would be the end of your troubles as you could run the query and let AccountManagement take it from there, but this option does not exist...
Based on personal experience I don't see any other options if you stick with AccountManagement.  What you could do is dump AccountManagement and use just DirectoryServices.  Under the hood all AccountManagement does is wrap DirectoryEntry objects anyways, you could write a few helper classes to do similar things.

A: As an alternative, you can use this code to get the members:
var pth = "LDAP://ex.invalid/CN=grpName,OU=Groups,OU=whatever,DC=ex,DC=invalid";
var dirEntry = new DirectoryEntry(pth);
var members = dirEntry.Invoke("Members"); //COM object
foreach (var member in (IEnumerable)members) {
    var userEntry = new DirectoryEntry(member); //member is COM object
    var sid = new SecurityIdentifier((byte[]) userEntry.InvokeGet("objectSid"), 0);
    var typ = typeof(System.Security.Principal.NTAccount);
    var account = (NTAccount)sid.Translate(typ);
    Console.WriteLine(account.Value);
}


text:
Q: How can I embed UIViews (or, more specifically, UITextAreas) programmatically in-line with Text? For reasons of reusability, I'm interested in finding a way to programmatically add text and custom UITextFields to a view in an efficient manner, similar to how you can combine strings using NSString's stringWithFormat: and then assign the result to a UILabel's text attribute. Ideally, with 2-3 statements I could write text and include my UITextField Objects in a string, and get an automatically text-wrapped, nicely formatted UIView that I can embed directly into my view. Basically, it would function like a UILabel with the ability to add UIView objects. For an example of the output this image would be a combination of both text and underlined UITextFields:

If this exists, it would allow me to reuse a single UITableViewCell subclass rather than having 5-6 xibs and 3-4 subclasses. I've searched about 2 hours with no real luck for a pre-existing solution, so has anyone ever encountered this problem before and used or released a library to handle this, or is there a simple solution I'm overlooking?
Thank you!

A: you can use CSLinearLayoutView (https://github.com/scalessec/CSLinearLayoutView)
and create a class
@implementation LabledView

+ (UIView*)create :(CGRect) frame view:(UIView*) view labelTitle:(NSString*)labelTitle viewLinearLayoutMakePadding :(CSLinearLayoutItemPadding)viewLinearLayoutMakePadding labelLinearLayoutMakePadding :(CSLinearLayoutItemPadding)labelLinearLayoutMakePadding font:(UIFont*)font textColor:(UIColor*)textColor
{
    CSLinearLayoutView *container = [[CSLinearLayoutView alloc] initWithFrame:frame];
    container.orientation = CSLinearLayoutViewOrientationHorizontal;

    UILabel *label = [[UILabel alloc] init];
    label.textColor = textColor;
    [label setText:labelTitle];
    [label setFont:font];
    [label sizeToFit];

    CSLinearLayoutItem *itemLabel = [CSLinearLayoutItem layoutItemForView:label];
    itemLabel.padding = labelLinearLayoutMakePadding;

    CSLinearLayoutItem *itemView = [CSLinearLayoutItem layoutItemForView:view];
    itemView.padding = viewLinearLayoutMakePadding;

    [container addItem:itemLabel];
    [container addItem:itemView];
    return container;
}

example :
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 260, 40)];

UIView *customView = [LabledView create:CGRectMake(0, 0, 280, 40) view:textField
labelTitle:@"your label" viewLinearLayoutMakePadding:CSLinearLayoutMakePadding(0, 10, 0, 0)
labelLinearLayoutMakePadding:CSLinearLayoutMakePadding(10, 0, 0, 0)
 font:[UIFont fontWithName:@"Helvetica" size:12] textColor:[UIColor blackColor]];

A: You can underline specific ranges of a string with NSAtttibutedString.  You can setAttributedString to UILabel in ios6... So that's the way I'd do it, then it can indeed be in a single label with the desired parts underlined (or in a different font/colour/etc) only. Be careful when you look into attributed string, it's attributes dictionary uses different keys for working with UIKit (these are the ones you need here) to what it uses with CoreText


text:
Q: Laravel Scheduled Commands randomly stop running (but scheduled jobs keep working) I have scheduled some commands and it randomly stops working. They work for ~10 days and stop randomly, and if I restart the server, they start working again for another ~10 days.
protected function schedule(Schedule $schedule) {

   $schedule->command('dump:database')
                ->hourlyAt(0)
                ->environments(['production'])
                ->thenPing("https://example.com/hash");

   $schedule->command('other:command')
          ->daily();

   $schedule->job(new ECheckScheduleChecks())
        ->daily()
        ->environments(['production']);
}

The weird thing is the scheduled Job keeps running.
Also the ->thenPing() gets triggered even though the code inside the commands does not run.
I don't see any issue in the logs and schedule:run works fine.
This issue is driving me crazy. Any ideas what might be the issue?


text:
Q: Node Net.Socket Character Encoding Issue I'm connecting via telnet to an Cisco codec SX20.
My socket connects then gets: ��\u0018�� ��#��\' after connecting. I'm expecting something similar to Password: or login:. Other devices I connect to with node's net.socket work fine though. This is the only chunk that I get; it always looks the same.
I've tried a ton node encoding implementations (native and iconv) - nothing readable. Other clients work fine, like putty (utf8 encoding) or telnet command (auto-discovered?).
Some results: https://gist.github.com/below9k/4dbae508031d586ed7719958b425552c
-- RESOLUTION / EDIT:
I eventually resolved this using https://github.com/blinkdog/telnet-stream
Apparently this unit wanted some minor telnet negotiations before cooperating.
const telnetInput = new TelnetInput()
const telnetOutput = new TelnetOutput()
telnetInput.on('do', function (option) {
    telnetOutput.writeWont(option)
})
telnetInput.on('will', function (option) {
    telnetOutput.writeDont(option)
})
telnetInput.on('data', Meteor.bindEnvironment((data) => {
    console.log(data.toString('utf8'))
}))
socket.pipe(telnetInput)
telnetOutput.pipe(socket)

console.log returns login: - yay
My understand is that I sent the unit a couple of standardized bits of info (more info in the repo above) and that makes it work.

A: I eventually resolved this using https://github.com/blinkdog/telnet-stream
Apparently this unit wanted some minor telnet negotiations before cooperating.
const telnetInput = new TelnetInput()
const telnetOutput = new TelnetOutput()
telnetInput.on('do', function (option) {
    telnetOutput.writeWont(option)
})
telnetInput.on('will', function (option) {
    telnetOutput.writeDont(option)
})
telnetInput.on('data', Meteor.bindEnvironment((data) => {
    console.log(data.toString('utf8'))
}))
socket.pipe(telnetInput)
telnetOutput.pipe(socket)

console.log returns login: - yay
My understand is that I sent the unit a couple of standardized bits of info (more info in the repo above) and that makes it work.
below9k


text:
Q: Regex: get number after and before specific substring I'm new to regex and trying to get number after substring text and before first non-numeric value.
I have:
const str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
str.toLowerCase().match(new RegExp('text (.*)[^0-9]'));
As a result I'm receiving:
["text 321,fasdgasdf", "321,fasdgasd"] but I want only 321.
Thanks in an advance for any help.

A: You could match the digits only in the first capturing group and use word boundaries \b to prevent text and the digits being part of a larger word.
Note to double escape the backslashes when using the RegExp constructor.
\btext (\d+)\b

Regex demo

const str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
let res = str.toLowerCase().match(new RegExp('\\btext (\\d+)\\b'));
console.log(res[1]);

A: Use lookbehind to find number after 'text ':
(?<=text )\d+

Or simply match parts and select second group:
(text )(\d+)

A: You may try splitting twice:

var str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
var num = str.split(/text /)[1].split(/\D/)[0];
console.log(num);

The first spiit leaves us with 321,fasdgasdf, and the second split discards everything from the comma onwards.


text:
Q: How to measure time taken by a function to execute I need to get execution time in milliseconds.

I originally asked this question back in 2008. The accepted answer then was to use new Date().getTime() However, we can all agree now  that using the standard performance.now() API is more appropriate. I am therefore changing the accepted answer to this one.

A: there are multiple ways to achieve this objective :

*

*using console.time
console.time('function');
//run the function in between these two lines for that you need to
//measure time taken by the function. ("ex. function();")
console.timeEnd('function');

*this  is the most efficient way :
using performance.now(), e.g.
var v1 = performance.now();
//run the function here for which you have top measure the time
var v2 = performance.now();
console.log("total time  taken = "+(v2-v1)+"milliseconds");

*use +(add operator) or getTime()
var h2 = +new Date(); //or
var h2 = new Date().getTime();
for(i=0;i<500;i++) { /* do something */}
var h3 = +new Date();   //or
var h3 = new Date().getTime();
var timeTaken = h3-h2;
console.log("time ====", timeTaken);

Here's what happens when you apply the unary plus operator to a Date instance:
         Get the value of the Date instance in question
         Convert it to a Number
NOTE: getTime() gives better performance than unary + operator.

A: use new Date().getTime()

The getTime() method returns the number of milliseconds since midnight of January 1, 1970.

ex.
var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

A: This is a Timer function. If you want to measure the time between multiple things that aren't nested:
function timer(lap){
    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
    timer.prev = performance.now();
}

Similar to console.time(), but easier usage if you don't need to keep track of previous timers.

Usage:
timer()              // set the start
// do something
timer('built')       // logs 'built in: 591.815ms'
// do something
timer('copied')      // logs 'copied in: 0.065ms'
// do something
timer('compared')    // logs 'compared in: 36.41ms'

If you like the blue color from console.time(), you can use this line instead
console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');

A: It may help you.
var t0 = date.now();
doSomething();
var t1 = date.now();
console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")

A: If you need to get function execution time on your local development machine, you can either use your browser's profiling tools, or console commands such as console.time() and console.timeEnd().
All modern browsers have JavaScript profilers built-in.  These profilers should give the most accurate measurement as you do not have to modify your existing code, which could affect the function's execution time.
To profile your JavaScript:

*

*In Chrome, press F12 and select the Profiles tab, then Collect JavaScript CPU Profile.

*In Firefox, install/open Firebug, and click on the Profile button.

*In IE 9+, press F12, click on Script or Profiler (depending on your version of IE).

Alternatively, on your development machine, you can add instrumentation to your code with console.time() and console.timeEnd().  These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console.time().  time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:
function a() {
  console.time("mytimer");
  ... do stuff ...
  var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
}

Note that only Firefox returns the elapsed time in the timeEnd() call.  The other browsers simply report the result to the developer console: the return value of timeEnd() is undefined.
If you want to get function execution time in the wild, you will have to instrument your code.  You have a couple options.  You can simply save the start and end times by querying new Date().getTime():
function a() {
  var start = new Date().getTime();
  ... do stuff ...
  var end = new Date().getTime();
  var dur = end - start;
}

However, the Date object only has millisecond resolution and will be affected by any OS's system clock changes.  In modern browsers, there's a better option.
The better option is to use the High Resolution Time, aka window.performance.now().  now() is better than the traditional Date.getTime() in two important ways:

*

*now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page's navigation.  It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).

*now() is monotonically increasing.  This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls.  Notably, if the OS's system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated.  now() is guaranteed to always be monotonically increasing, so it is not affected by the OS's system time -- it will always be wall-clock time (assuming your wall clock is not atomic...).
now() can be used in almost every place that new Date().getTime(), + new Date andt Date.now() are.  The exception is that Date and now() times don't mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).
Here's an example of how to use now():
function a() {
  var start = window.performance.now();
   ... do stuff ...
  var end = window.performance.now();
  var dur = end - start;
}

now() is supported in Chrome stable, Firefox 15+, and IE10.  There are also several polyfills available.
One other option for measuring execution time in the wild is UserTiming.  UserTiming behaves similarly to console.time() and console.timeEnd(), but it utilizes the same High Resolution Timestamp that now() uses (so you get a sub-millisecond monotonically increasing clock), and saves the timestamps and durations to the PerformanceTimeline.
UserTiming has the concepts of marks (timestamps) and measures (durations).  You can define as many of either as you want, and they're exposed on the PerformanceTimeline.
To save a timestamp, you call mark(startMarkName).  To get the duration since your first mark, you simply call measure(measurename, startMarkname).  The duration is then saved in the PerformanceTimeline alongside your marks.
function a() {
  window.performance.mark("start");
  ... do stuff ...
  window.performance.measure("myfunctionduration", "start");
}

// duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];

UserTiming is available in IE10+ and Chrome25+.  There is also a polyfill available (which I wrote).

A: Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).
Use it and improve it as you want.
Performance: {
    Timer: {},
    Start: function (name) {
        if (console && console.time) {
            console.time(name);
        } else if (window.performance.now) {
            this.Timer[name] = window.performance.now();
        } else {
            this.Timer[name] = new Date().getTime();
        }
    },
    End: function (name) {
        if (console && console.time) {
            console.timeEnd(name);
        } else {
            var result;
            if (window.performance.now) {
                result = window.performance.now() - this.Timer[name];
            } else {
                result = new Date().getTime() - this.Timer[name];
            }
            console.log(name + ": " + result);
        }
    }
}

A: Use this code format
const startTime =new Date().getTime();

//do something
const endTime = new Date().getTime();
console.log(`time taken ${(endTime - startTime)/1000} seconds`);

A: A couple months ago I put together my own routine that times a function using Date.now() -- even though at the time the accepted method seemed to be performance.now() --
 because the performance object is not yet available (built-in) in the stable Node.js release.
Today I was doing some more research and found another method for timing. Since I also found how to use this in Node.js code, I thought I would share it here.
The following is combined from the examples given by w3c and Node.js:
function functionTimer() {
    performance.mark('start')
    functionToBeTimed()
    performance.mark('end')
    performance.measure('Start to End', 'start', 'end')
    const measure = performance.getEntriesByName('Start to End')[0]
    console.log(measure.duration)
}

NOTE:
If you intend to use the performance object in a Node.js app, you must include the following require:

const { performance } = require('perf_hooks')

A: Don't use Date(). Read below.
Use performance.now():
<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>

It works on:

*

*IE 10 ++

*FireFox 15 ++

*Chrome 24 ++

*Safari 8 ++

*Opera 15 ++

*Android 4.4 ++

*etc, etc
console.time may be viable for you, but it's non-standard §:

This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Besides browser support, performance.now seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time.

<rant> Also, DON'T EVER use Date for anything because  it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:

On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......

(Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date.)
Google Spreadsheet's now() function also suffers from this problem.
The only time you'll be using Date is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.

A: Thanks, Achim Koellner, will expand your answer a bit:
var t0 = process.hrtime();
//Start of code to measure

//End of code
var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds

Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).
Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,
var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

});

A: To get precise values you should use Performance interface. It's supported in modern versions of Firefox, Chrome, Opera and IE. Here's an example of how it can be used:
var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")

Date.getTime() or console.time() are not good for measuring precise execution time. You can use them if quick rough estimate is OK for you. By rough estimate I mean you can get 15-60 ms shift from the real time.
Check this brilliant post on measuring execution time in JavaScript. The author also gives a couple of links about accuracy of JavaScript time, worth reading.

A: With performance
NodeJs: It is required to import the performance class
var time0 = performance.now(); // Store the time at this point into time0

yourFunction();   // The function you're measuring time for

var time1 = performance.now(); // Store the time at this point into time1

console.log("youFunction took " + (time1 - time0) + " milliseconds to execute");

Using console.time
console.time('someFunction');

someFunction(); // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction');

A: Use console.time('some label here') before the function and console.timeEnd('some label here') after the function. It will give you the running time of the function.

A: Using  performance.now():
var startTime = performance.now()

doSomething()   // <---- measured code goes between startTime and endTime

var endTime = performance.now()

console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)

In Node.js it is required to import the performance class

importing performance
const { performance } = require('perf_hooks');

Using console.time: (living standard)
console.time('doSomething')

doSomething()   // <---- The function you're measuring time for

console.timeEnd('doSomething')

Note: The string being passed to the time() and timeEnd() methods must match(for the timer to finish as expected).

console.time() documentations:

*

*MDN documentation

*Node.js documentation

A: Use Firebug, enable both Console and Javascript.  Click Profile.  Reload.  Click Profile again.  View the report.

A: A simple solution, you can use add operator also here
 var start = +new Date();
 callYourFunctionHere();
 var end = +new Date();
 var time = end - start;
 console.log('total execution time = '+ time + 'ms');

A: Stopwatch with cumulative cycles
Works with server and client (Node or DOM), uses the Performance API.
Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.
So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.
const perf = typeof performance !== "undefined" ? performance : require('perf_hooks').performance;
const DIGITS = 2;

let _timers = {};

const _log = (label, delta?) => {
    if (_timers[label]) {
        console.log(`${label}: ` + (delta ? `${delta.toFixed(DIGITS)} ms last, ` : '') +
            `${_timers[label].total.toFixed(DIGITS)} ms total, ${_timers[label].cycles} cycles`);
    }
};

export const Stopwatch = {
    start(label) {
        const now = perf.now();
        if (_timers[label]) {
            if (!_timers[label].started) {
                _timers[label].started = now;
            }
        } else {
            _timers[label] = {
                started: now,
                total: 0,
                cycles: 0
            };
        }
    },
    /** Returns total elapsed milliseconds, or null if stopwatch doesn't exist. */
    stop(label, log = false) {
        const now = perf.now();
        if (_timers[label]) {
            let delta;
            if(_timers[label].started) {
                delta = now - _timers[label].started;
                _timers[label].started = null;
                _timers[label].total += delta;
                _timers[label].cycles++;
            }
            log && _log(label, delta);
            return _timers[label].total;
        } else {
            return null;
        }
    },
    /** Logs total time */
    log: _log,
    delete(label) {
        delete _timers[label];
    }
};

A: The best way would be to use the performance hooks module. Although unstable, you can mark specific areas of your code and measure the duration between marked areas.
const { performance, PerformanceObserver } = require('perf_hooks');

const measures = []

const obs = new PerformanceObserver(list => measures.push(...list.getEntries()));
obs.observe({ entryTypes: ['measure'] });
const getEntriesByType = cb => cb(measures);

const doSomething = val => {
  performance.mark('beginning of the process');

  val *= 2;

  performance.mark('after multiplication');

  performance.measure('time taken', 'beginning of the process', 'after multiplication');

  getEntriesByType(entries => {
    entries.forEach(entry => console.log(entry));
  })

  return val;
}

doSomething(4);

Try here

A: process.hrtime() is available within Node.js - it returns a value in nanoseconds
let hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)

A: Here's a decorator for timing functions
It wraps functions so that they get timed each time they get run
Usage:
let test = () => { /* does something */ }
test = timed(test)   // turns the function into a timed function in one line
test()               // run your code as normal, logs 'function test took 1001.900ms'

This is the decorator:
let timed = (f) => (...args) => {
    let start = performance.now();
    let ret = f(...args);
    console.log(`function ${f.name} took ${(performance.now() - start).toFixed(3)}ms`);
    return ret;
}

If you're using async functions you can make timed async and add an await before f(...args), and that should work for those. It gets more complicated if you want one decorator to handle both sync and async functions.

A: var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};

Benchmark
var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

Output
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]

performance.now() is optional - just pass false into StopWatch constructor function.

A: It is possible to use only one variable:
var timer = -performance.now();

// Do something

timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")

timer/1000 - to convert milliseconds to seconds
.toFixed(5) - to trim extra digits

A: To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.
console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
   var time = this._times[label];
   if (!time) {
     throw new Error('No such label: ' + label);
   }
   var duration = Date.now() - time;
   return duration;
};

Now use the code like so:
console.time('someFunction timer');

someFunction();

var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);

This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.

A: export default class Singleton {

  static myInstance: Singleton = null;

  _timers: any = {};

  /**
   * @returns {Singleton}
   */
  static getInstance() {
    if (Singleton.myInstance == null) {
      Singleton.myInstance = new Singleton();
    }

    return this.myInstance;
  }

  initTime(label: string) {
    this._timers[label] = Date.now();
    return this._timers[label];
  }

  endTime(label: string) {
    const endTime = Date.now();
    if (this._timers[label]) {
      const delta = endTime - this._timers[label];
      const finalTime = `${label}: ${delta}ms`;
      delete this._timers[label];
      return finalTime;
    } else {
      return null;
    }
  }
}

InitTime related to string.
return Singleton.getInstance().initTime(label); // Returns the time init
return Singleton.getInstance().endTime(label); // Returns the total time between init and end

A: In my case, I perfer to use @ grammar suger and compile it with babel.
The problem of this method is that function has to be inside object.
Sample JS Code
function timer() {
    return (target, propertyKey, descriptor) => {
        const start = Date.now();
        let oldFunc = descriptor.value;

        descriptor.value = async function (){
            var result = await oldFunc.apply(this, arguments);
            console.log(Date.now() - start);
            return result;
        }
    }
}

// Util function
function delay(timeout) {
    return new Promise((resolve) => setTimeout(() => {
        resolve();
    }, timeout));
}

class Test {
    @timer()
    async test(timout) {
        await delay(timout)
        console.log("delay 1");
        await delay(timout)
        console.log("delay 2");
    }
}

const t = new Test();
t.test(1000)
t.test(100)

.babelrc (for babel 6)
 {
    "plugins": [
        "transform-decorators-legacy"
    ]
 }

A: *

*To start the timer use console.time("myTimer");

*Optional: To print the elapsed time, use
console.timeLog("myTimer");

*Finally, to stop the timer and print the final
time: console.timeEnd("myTimer");
You can read more about this on MDN and in the Node.js documentation.
Available on Chrome, Firefox, Opera and NodeJS. (not on Edge or Internet Explorer).

A: Note: Simplest implementation of pure functional, ES6 method, no extra variables needed, just 3 lines of codes. Handles sync and async codes, so no external libraries needed, works in both JavaScript and Node JS, can even use to test the latency of your APIs
// Create one-liner timer function
let [timer, timingMonitor] = [0, () => timer = !timer ? Date.now() : `${Date.now() - timer}ms`]

// Initiate timer
timingMonitor();

// Your code here
doSomething();

// End timer
console.log(timingMonitor());

// Console output: "102ms", for example

A: Basic TypeScript example that supports marks. Calling start('something') will begin the timer and stop('something') will end the timer and return a formatted string containing elapsed time.
View Flems Example
/**
 * Mark entries
 */
export const marks: { [id: string]: number } = {};

/**
 * Start timing
 */
export const start = (id: string) => {
  return Object.assign(marks, {[id]: Date.now() })[id]
}

/**
 * Clear all
 */
export const clear = () => {
  for (const id in marks) delete marks[id];
};

/**
 * Stop timing and return formatted elapsed time
 */
export const stop = (id: string) => {
  const ms = Date.now() - marks[id];
  delete marks[id];
  return ms > 1000
    ? `${(ms / 1000).toFixed(0)}s ${+ms.toFixed(0).slice(1)}ms`
    : `${ms.toFixed(0)}ms`;
};

The example code is exporting each function. You can drop this into a project and call the methods accordingly from a default as import, eg:
import * as time from './timer.js'

time.start('foo')

// do something

console.log('elapsed time: ' + time.stop('bar'))

A: The accepted answer is wrong !
Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.
var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// JavaScript is not waiting until the for is finished !!
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :
var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
  $.ajax({
    url: 'www.oneOfYourWebsites.com',
    success: function(){
       console.log("success");
    }
  });
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.
Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now

A: As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:
//=-=|Source|=-=//
/**
 * JavaScript Timer Object
 *
 *      var now=timer['elapsed']();
 *      timer['stop']();
 *      timer['start']();
 *      timer['reset']();
 *
 * @expose
 * @method timer
 * @return {number}
 */
timer=function(){
    var a=Date.now();
    b=0;
    return{
        /** @expose */
        elapsed:function(){return b=Date.now()-a},
        start:function(){return a=Date.now()},
        stop:function(){return Date.now()},
        reset:function(){return a=0}
    }
}();

//=-=|Google Advanced Optimized|=-=//
timer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();

Compilation was a success!

*

*Original Size:    219 bytes gzipped (405 bytes uncompressed)

*Compiled Size:    109 bytes gzipped (187 bytes uncompressed)

*Saved 50.23% off the gzipped size (53.83% without gzip