text:
Q: Node itself can serve static files without express or any other module..? I am beginner in the field of node js.No idea how to send simple request from url
Like :- http://localhost:9999/xyz/inde.html
my file hierarchy is
server.js
xyz(folder)-
          |->index.html

And get the html page from my server.Which is running at post 9999
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end();
}
http.createServer(onRequest).listen(9999);
console.log("Server has started.");

I know i can send string(having html template) from node js server and send it in response but how to send file without express and any other external module.
Thanks

A:

const http = require('http');
const fs = require("fs");
const path = require("path");

function send404(response){
  response.writeHead(404, {'Content-Type': 'text/plain'});
  response.write('Error 404: Resource not found.');
  response.end();
}

const mimeLookup = {
  '.js': 'application/javascript',
  '.html': 'text/html'
};

const server = http.createServer((req, res) => {
  if(req.method == 'GET'){

    let fileurl;
    if(req.url == '/'){
      fileurl = 'index.html';
    }else{
      fileurl = req.url;
    }
    let filepath = path.resolve('./' + fileurl);

    let fileExt = path.extname(filepath);
    let mimeType = mimeLookup[fileExt];

    if(!mimeType) {
      send404(res);
      return;
    }

    fs.exists(filepath, (exists) => {
      if(!exists){
        send404(res);
        return;
      }

      res.writeHead(200, {'Content-Type': mimeType});
      fs.createReadStream(filepath).pipe(res);

    });

  }
}).listen(3000);
console.log("Server running at port 3000");

A: its very simple, node already provide fs module from which u can read that html
file and append
on response obj like this:
response.writeHead(200, {"Content-Type": "text/plain"});
//here is the code required
fs.readFile("./xyz/index.html", (err,fileContent) =>
{
  response.end(fileContent);
});

but the problem here is you will only get the HTML document
not the resources inside that HTML files which are stored in
different folders like if you have this code in your index.html
<link rel="stylesheet" href="../css/index.css" />
this index.css will not be allowed by the node server.
But i guess your question is solved.

A: I don't agree with the assertion in the accepted answer:

"It's ridiculous to attempt to create a node application without npm dependencies"

as having zero dependencies allows you to deploy an app to a system that runs node by just copying the javascript file(s), and without running npm install.
An example of when I found this useful in real life was writing a public API to compute the amount of income tax a business needs to withold from an employee's pay. You can read all about this fascinating topic here but in essence I had an api that was passed a gross income and returned how that gross income should be split between net income and tax.
I did this with one solitary index.js file, no package.json, and need to npm install:
index.js:
http = require('http');
url = require('url');
const port = 80; // make this a number over 1024 if you want to run `node` not run `sudo node`
const debug = true;
const httpServer = http.createServer((request, response) => {
  response.setHeader('Content-Type', 'application/json');
  const parsedUrl = url.parse(request.url, true);
  let pathName = parsedUrl.pathname;
  if (pathName==='/favicon.ico') {
    // chrome calls this to get an icon to display in the tab. I want to ignore these request. They only happen when testing in a browser,
    // not when this api is called in production by a non-browser.
    if (debug) console.log('Browser requested favicon.ico')
    response.end();

  } else {
    if (debug) console.log('Request on path ' + pathName);
    const elements = pathName.split('/');
    if (elements.length == 3 && elements[0] === '' &&  elements[1]==='witholdcalc') {
      const grossString = elements[2];
      const gross = Number.parseInt(grossString);
      if (isNaN(gross)) {
        response.writeHead(400).end(JSON.stringify({error:'Gross salary must be an integer. found: ' + grossString}));
      } else {
        /*
         * The computation of the amount to withold is more complicated that this, but it could still be hard coded here:
         * For simplicity, I will compute in one line:
         */
        const withold = Math.floor((gross<1000)?0:((gross-1000)*.2));
        response.writeHead(200).end(JSON.stringify({net: (gross-withold), withold: withold, elements:(debug?elements:undefined)}));
      }
    } else {
      if (debug) console.log('Invalid path was: ' + pathName,elements);
      response.writeHead(404).end();
    }
  }
});
httpServer.listen(port), () => {
  console.log(`PAYG listening at http://localhost:${port}`)
}

I then could execute sudo node install.js on my linux computer, and in a browser, hit http://localhost/witholdcalc/6000, and it would return {"net":5000,"withold":1000} when debug is set to false.

A: Heads up for anyone attempting to serve static files without Express or any other framework:
There is no benefit to skipping Express, in terms of performance or productivity. The only exception is to gain an understanding of how the server and client communicate with each other. Frameworks like Express abstract away all of those complexities, and beginners may not fully understand how they work.
Here is my approach to serving static files using Node.js only. Actually, the reason I did this is because a coding test I was given stipulated no framework whatsoever.

*

*First, decide what the URL path for those static files should look like. I want mine to be accessible under /assets/ path, such as https://example.com/assets/main.css, https://example.com/assets/cat.jpg.

*Decide the REGEX for matching those URL.
`const assetPattern = /^/assets/[a-zA-Z]+.[a-zA-Z]+/;
The formula above will match urls which contains /assets/[filename].[file extension.

*Create a server with Node.js, taking a callback function as a parameter.

// ...
const http = require('http')
const server = http.createServer(requestListener).

*Extract url path, get the corresponding file path and configure your server to send the correct MIME types to the browser.

const path = require('path');
// ...
const requestListener = (req, response) => {
  // get the relative url for the request. For example, relative url for a request
  // to https://example.com is /.
  const { url } = req;
  if (url.match(assetPattern)) {
  // Inside the project directory, the static files are located under the
  // /public/assets directory.
    const filePath = `./public/${url}`;
  // Get the extension name aka the string after the dot. For example, a url like
  // https://example.com/assets/main.css will result in extension name of css.
    const extname = String(path.extname(filePath)).toLowerCase();
    const mimeTypes = {
      '.html': 'text/html',
      '.js': 'text/javascript',
      '.css': 'text/css',
      '.json': 'application/json',
      '.png': 'image/png',
      '.jpg': 'image/jpg',
      '.gif': 'image/gif',
      '.svg': 'image/svg+xml',
      '.wav': 'audio/wav',
      '.mp4': 'video/mp4',
      '.woff': 'application/font-woff',
      '.ttf': 'application/font-ttf',
      '.eot': 'application/vnd.ms-fontobject',
      '.otf': 'application/font-otf',
      '.wasm': 'application/wasm',
    };
    const contentType = mimeTypes[extname] || 'application/octet-stream';
    staticFileHandler(req, response, filePath, contentType);
  }
}

*Serve the static files with fs module

const fs = require('fs')
// ...
const staticFileHandler = (req, res, filePath, contentType) => {
  fs.readFile(filePath, (err, content) => {
    if (err) {
      res.writeHead(500);
      res.end(`Sorry, check with the site admin for error: ${err.code}`)
    } else {
      res.writeHead(200, { 'Content-Type': contentType }); // indicate the request was successful
      res.end(content, 'utf-8');
    }
  }
}

A: It's ridiculous to attempt to create a node application without npm dependencies, because the base of nodejs is just that -- a base. Unless you feel like implementing entire protocols, you're better off using a minimal, well maintained npm module that does that for you. That said, here is the very basic thing you asked for (without MiME, eTags, caching, etc, etc):
var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function(req, res) {
    var stream = fs.createReadStream(path.join(basePath, req.url));
    stream.on('error', function() {
        res.writeHead(404);
        res.end();
    });
    stream.pipe(res);
}).listen(9999);


text:
Q: Search FHIR resource by internal reference DSTU2 documentation does not describe ability to search resources by internal references. Is there any way to find the below resource having contained Practitioner resource and internal reference on it like:
[base]/fhir/Patient?careprovider:Practitioner=ContainedId or
[base]/fhir/Patient?careprovider=ContainedId

{
 "resourceType" : "Patient",
 "id" : "ContainedTestPatient",
 "careProvider" : [{
  "reference" : "#ContainedId"
 }],
  "contained" : [{
    "resourceType": "Practitioner",
    "id": "ContainedId",
    "name": {"text": "Good doctor INC"}
  }]
}

A: Actually DSTU2 documentation does specify how to search for values in contained resources, see http://www.hl7.org/fhir/search.html#contained. It's done with a chained search and looks like this:
[base]/Patient?careprovider._id=ContainedId

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count the number of lattice paths from (0,0) to (x,y) in recursion Does anyone know how can i write a recursive function that gets unsigned integers x, y and returns how many paths are to the point x,y from 0,0 in C??
there is only one step every time: up or right.
The limit of the steps are in the rectangle:
(0,0), (0, x), (0,y), (x,y)

A: Sorry, this isn't C, but you should understand it very well.. Whatever starts with dollar is a variable, the rest is similar.
function path($x, $y){
    if($x==0 && $y==0){ /* && is logical AND operator */
        return 1;
    // here's first (and only) edge case. If X and Y is 0, that means were are already where we want to be. We assume there's one path from the position you are on to the same position you are on.
    }

    $count=0;

    if($x>0){
        $count+=path($x-1, $y); // Here, we ask how many paths go from position (x-1, y) to zero, if the X is not zero already..
    }
    if($y>0){
        $count+=path($x, $y-1); // here same stuff for Y, if Y is not zero, let's recurse into (x, y-1)
    }

    return $count; // in those conditions above, the result is added into COUNT variable
}

$x=6;
$y=4; // some input

print path($x, $y); // here it all starts, with the original input numbers

There's no math behind it, it's a recursion. In each run of the path() function, the path function runs another instance of the path function, and that runs another and that runs another.... Always with the position one less than current, in one dimension and then one less in the other dimension. Only if the recursion already reached the (0,0) position, it will return 1, which will be added to the count variable in previous instance, that will be added to count variable in yet previous instance, and so on and so on, until it returns that to the print function.
Note: the function doesn't go from (0,0) to (x,y) but from (x,y) to (0,0). But the result is the same.

A: A Java solution :
/**
 * Compute the number of ways you can get from 0,0 to x,y
 *
 * @param x grid width
 * @param y grid height
 * @return number of lattice paths
 */
public long compute(int x, int y) {
    // there's only 1 way you can reach a point which is on some edge
    if (x == 0 || y == 0) {
        return 1;
    }
    /* Otherwise apply back recursion, i.e. take the last step (when you reach x,y) :
    you can get there only by moving from x-1,y (right) or from x,y-1 (up).
    So the result would be the number of ways you can get to x-1,y plus the number
    of ways you can get to x,y-1 */
    return compute(x - 1, y) + compute(x, y - 1);
}

As the area of the grid grows (x and y) the algorithm become very slow, because you compute the same value a lot of times due to the recursion, so you might want to cache :
Map<Pair, Long> cache = new HashMap<>();

public long compute(int x, int y) {
    Pair pair = new Pair(x, y);
    if (cache.containsKey(pair)) {
        return cache.get(pair);
    }
    if (x == 0 || y == 0) {
        return 1;
    }
    long result = compute(x - 1, y) + compute(x, y - 1);
    cache.put(pair, result);
    return result;
}

Pair is a simple POJO following the equals() and hashCode() Contract.


text:
Q: User denied permission to read his own home directory Note: Username modified for public post.
I have a linux server on which I have root privileges. There is a user account "privuser" which can only be SSHed into using SSH keys. But, due to some user changes, privuser cant read his own directory anymore. Neither can I in-spite of being root!
[root@server ~]# id privuser
    uid=29772(privuser) gid=509(abc) groups=509(abc),1519(ghi)

[root@server ~]# groups privuser
privuser : abc ghi

[root@server ~]# su - privuser
su: warning: cannot change directory to /usr/home/xyz/abc/privuser: Permission denied
Your password expires on never
-bash: cd: /usr/home/xyz/abc/privuser: Permission denied
cannot cd to home directory /usr/home/xyz/abc/privuser
-bash: /usr/home/xyz/abc/privuser/.bash_profile: Permission denied
-bash-4.1$ exit
logout
-bash: /usr/home/xyz/abc/privuser/.bash_logout: Permission denied

I cant see those files even as Root.
[root@server ~]# ls -alh /usr/home/xyz/abc/privuser/
ls: cannot access /usr/home/xyz/abc/privuser/: Permission denied

However, /usr/home/xyz/abc/privuser is an NFS mount, so I can check from directly on the NFS server that, the directory and files are indeed owned by that UID.
How do I find out what is going on here?
EDIT: (Adding ls output)
testuser is another user in the server belonging to the same group - abc as the trouble making user(privuser), and here is what I can ls from testuser.
[testuser@server ~]$ ls -alh /usr/home/xyz/abc/
total 196K
drwxr-s--- 37 root       xyz     4.0K Nov  2 15:47 .
drwxr-xr-x  9 root       root    4.0K Feb  1  2016 ..
drwx------  5 testuser   abc     4.0K Nov 29 14:12 testuser
drwxr-xr-x 13 privuser   abc     16K  Jan  4 21:05 privuser
.....

testuser, belonging to the same group abc can see the files of privuser.
testuser@server ~]$ ls -alh /usr/home/xyz/abc/privuser
total 124K
drwxr-xr-x 13 privuser abc      16K  Jan  4 21:05 .
drwxr-s--- 37 root     **xyz**      4.0K Nov  2 15:47 .. <========== !!
drwxr-xr-x  2 privuser abc      4.0K Jan  4 12:38 arkiv20180104
-rw-------  1 privuser abc      15K  Jan  4 21:05 .bash_history
-rw-r--r--  1 privuser abc      99   Jan  4 12:31 .bashrc
drwxr-xr-x  3 privuser abc      4.0K Jan  4 12:42 .conda
drwx------  2 privuser abc      4.0K Jan 23  2017 .ssh
....

Solution:
privuser did not belong to the group xyz in spite of its home directory being located in a directory owned by xyz.
I added privuser to the xyz group and the permissions problem went away.


text:
Q: Could I pass annotation to child class which extends it? I'm lazy person... i just want the simplest way, now i'm learning android room. This might be answered here "Why is it not possible to extend annotations in Java?", but it seems like to try pass annotation to another annotation, right? So, Could i pass annotation to the child class for example, here is my parent class 'Model':
@Entity
public abstract class Model implements Parcelable{
    @Nullable
    @PrimaryKey
    private Object id;

    public String toJSON(){
        return new Gson().toJson(this);
    }

    public <T> T getId(Class<T>type) {
        if(type.equals(Integer.class)||type.equals(int.class)) {
            return (T) Integer.valueOf(new Double(Double.parseDouble(String.valueOf(id))).intValue());
        }
        else if(type.equals(Long.class)||type.equals(long.class)) {
            return (T) Long.valueOf(new Double(Double.parseDouble(String.valueOf(id))).longValue());
        }
        else if(type.equals(Double.class)||type.equals(double.class)) {
            return (T) Double.valueOf(id.toString());
        }else if(type.equals(UUID.class)){
            return (T) UUID.fromString(String.valueOf(id));
        }
        return type.cast(id);
    }

    public <T> void setId(T id) {
        this.id = id;
    }
}

I tried to pass @Entity to child class.
public class Movie extends Model {
    public static final String IDENTIFIER = Movie.class.getSimpleName();
    @SerializedName("popularity")
    private double popularity;
    @SerializedName("vote_count")
    private long voteCount;
    @SerializedName("video")
    private boolean video;
}

Because my data access object cannot detect my 'Movie' class, except i'm added Entity annotation
@Dao
public interface FavMovieDAO {
    @Query("SELECT * FROM Movie WHERE id = :movieId")
    public Movie find (int movieId);
}

If there is no way, i'll declare my entire model class as an Entity... :/. Thanks in advance.


text:
Q: Multi-statement scripts in elasticsearch I have indexed a document
PUT test/_doc/1
{
    "counter" : 1,
    "tags" : ["red"]
}

I am using script to update my content of the documents
POST test/_doc/1/_update
{
    "script" : {
        "source": "ctx._source.tags.add(params.tag)",
        "lang": "painless",
        "params" : {
            "tag" : "blue"
        }
    }
}

POST test/_doc/1/_update
{
    "script" : "ctx._source.new_field = 'value_of_new_field'"
}

This two scripts are working fine individually, I want to use these two script statements in a single "_update" API.  Is it possible to do this?

A: You can simply add semicolons between statements, like this:
{
  "script": {
    "source": "ctx._source.tags.add(params.tag); ctx._source.new_field = 'value_of_new_field';",
    "lang": "painless",
    "params": {
      "tag": "blue"
    }
  }
}


text:
Q: how to fix the error while fetching the data from the database I am working in react.js and node.js I use fetch API to get the data from my backend. but It shows the error which is
TypeError: Failed to fetch
    at submit (Login.js:11:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070:1)
    at executeDispatch (react-dom.development.js:8243:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:8275:1)
    at processDispatchQueue (react-dom.development.js:8288:1)
    at dispatchEventsForPlugins (react-dom.development.js:8299:1)
    at react-dom.development.js:8508:1

and the code of the login.js file is.
import React from 'react';
import { useState } from 'react';
import logo from '../images/logo.png';
export default function Login() {
  const [credentials, setCredentials] = useState({ email: '', password: '' });

  const submit = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(`https://localhost:3000/api/user/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: credentials.email,
          password: credentials.password,
        }),
      });
      const json = await response.json();
      console.log('data is ', json);
    } catch (err) {
      console.log(err);
    }
  };
  const onchange = (e) => {
    setCredentials({ ...credentials, [e.target.name]: e.target.value });
  };
  return (

Welcome

          <form className='my-2' onSubmit={submit}>

              <input
                type='email'
                className='form-control'
                name='email'
                onChange={onchange}
                value={credentials.email}
                id='email'
                placeholder='Enter email'
              />

              <input
                type='password'
                className='form-control'
                id='password'
                onChange={onchange}
                value={credentials.password}
                name='password'
                placeholder='Password'
              />

            <button className='btn btn-none '>
              Forgotten Passowrd ?
            </button>
            <button type='submit' className='btn btn-primary form-control my-2'>
              Login
            </button>
          </form>

          Conntinue with

              <button className='btn btn-dark form-control'>Facebook</button>

              <button className='btn btn-dark form-control'>Gmail</button>

  );
}

anyone can solve this problem or tell me why this error is occurring?I have added the whole code of the login.js file in which I find some errors but I can't solve it. so please tell me the issue to solve the problem.

A: The error occurs because we use HTTPS protocol instead of HTTP. when you change the protocol then everything is fine.


text:
Q: Refactoring the safe access to a Dictionary.Value My goal is to refactore the safe access to a Dictionary.Value .
I have a Json with dynamical property so I parsed it to a Dictionary<string, string> ~x9000 items:
var values = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);

Trying to map this to the buissness object like:
foreach (var item in values)
{

    var temp = new BuissnessObject();

    string idString, nameString, typeString, address1String, address2String,
        address3String, cityString, postalCodeString, phoneNumberString,
        openAfter8pmString, openOnSundayString, parkingString
        // + 25 lines of string equivalent of BuissnessObject properties.
        ;

    if (item.TryGetValue("id", out idString)) temp.id = idString;
    if (item.TryGetValue("name", out nameString)) temp.name = nameString;
    if (item.TryGetValue("type", out typeString)) temp.type = typeString;

    if (item.TryGetValue("address1", out address1String)) temp.address1 = address1String;
    if (item.TryGetValue("address2", out address2String)) temp.address2 = address2String;
    if (item.TryGetValue("address3", out address3String)) temp.address3 = address3String;
    if (item.TryGetValue("city", out cityString)) temp.city = cityString;
    if (item.TryGetValue("postalCode", out postalCodeString)) temp.postalCode = postalCodeString;
    if (item.TryGetValue("phoneNumber", out phoneNumberString)) temp.phoneNumber = phoneNumberString;

    if (item.TryGetValue("openAfter8pm", out openAfter8pmString))
        temp.openAfter8pm = bool.Parse(openAfter8pmString);

    if (item.TryGetValue("openOnSunday", out openOnSundayString))
        temp.openOnSunday = bool.Parse(openOnSundayString);

    if (item.TryGetValue("parking", out parkingString))
        temp.parking = bool.Parse(parkingString);

    if (item.TryGetValue("reception", out receptionString))
        temp.reception = bool.Parse(receptionString);
    // ....

    // Block Dynamic properties
    temp.exceptionalDays = new List<DateTime>();

    foreach (var k in item)
    {   // Exemple: Key = exceptionalDay_YYYY_mm_dd ;  Value = True
        if (k.Key.StartsWith("exceptionalDay") && bool.Parse(k.Value))
        {
            var dateRaw = k.Key.Split('_').Skip(1).ToArray();
            if (dateRaw.Count() == 3)
            {
                var date = new DateTime(int.Parse(dateRaw[0]), int.Parse(dateRaw[1]), int.Parse(dateRaw[2]));
                temp.exceptionalDays.Add(date);
            }
        }
    }

    result.Add(temp);
}

I' am looking for a better way to map those 2 entities. Either I deserialise Twice: 1rst for the non dynamical property ignoring the dynamical one , then just for the dynamical.
Or I found a way to shorten the mapping like :
private static T GetSafe<T>(Dictionary<string, string> item, string key)
{
    if (item.TryGetValue(key, out string value))
    {
        var converter = TypeDescriptor.GetConverter(typeof(T));
        if (converter != null)
        {
            return (T)converter.ConvertFromString(value);
        }
        // Impossible to convert value of key {} - with value ={} for  type={}
        throw new Exception(String.Format("Impossible de convertir la valeur de {0} - avec la valeur {1} !", key,value, typeof(T).FullName));
    }
    else
    {
        //Impossible de load the value of key {} - this key doesn't exist
        throw new Exception(String.Format("Impossible de charger la valeur de {0} - Cette clé n'existe pas !", key));
    }
    throw new NotImplementedException();
}

And a way to loop on the property of BuissnessObject exept for the one in a List.
How do I foreach trought BuissnessObject properties name ?

A: You can use reflexion. Given the class BuissnessObject:
class BuissnessObject
{
    public String Foo { get; set; }
    public String Bar { get; set; }

    public override string ToString()
    {
        return $"Foo : {Foo}, Bar : {Bar}";
    }
}

And this little helper:
private static PropertyInfo[] GetProperties(object obj)
{
    return obj.GetType().GetProperties();
}

You can use this code:
var businessObject = new BuissnessObject();

var dic = new Dictionary<string, string>()
{
    {"Foo", "value1" },
    {"Bar", "value2" },

};
// Get property array
var properties = GetProperties(businessObject);

foreach (var p in properties)
{
    string name = p.Name;

    // Skip what you want to skip
    if(myListOfIgnoredProp.Contains(name))
        continue;

    // Feed what you want to feed
    if (dic.TryGetValue(name, out var value))
    {
        if(p.PropertyType == typeof(string))
            p.SetValue(businessObject, value);
        else if (p.PropertyType == typeof(bool))
            p.SetValue(businessObject, bool.Parse(value));
        //And so on...
    }
}

If you call businessObject.ToString(), you'll get:

Foo : value1, Bar : value2


text:
Q: Choose author credentials for git repositories based on some subdirectory I work simultaneously for different employers. And I have to use different credentials in commits base on the employer. I could easily run git config author.email and git config author.name in each repository. But I'd like to do it globally as there are many repositories for each employer and new ones appear quite regularly.
I arrange all repositories in two folders. i.e. ~/projects/<employer_name1>/<project_name> and ~/projects/<employer_name2>/<project_name>.
So what I'd like to do is to make git automatically choose correct commit credentials based on the location of the current repository (which employer subdirectory it is).
Found the answer myself. Added this to .bashrc:
function git() {
  case $(readlink -f .)/ in
    $(readlink -f /home/cryo/projects/fun-box)/*) GIT_AUTHOR_NAME=my_name GIT_AUTHOR_EMAIL=my@email.com /usr/bin/git $*;;
    *) /usr/bin/git $*;;
  esac
}

A: Have a centralized mechanism for creating repos. Like some script in your path etc. whereby you do:
repo create -e employer -n name

or something like that.
The repo command ( just an example, nothing to do with the one from Android ) will create the repo for you in the necessary location and read a config file and set the credentials for that repo based on the employer etc.

A: You can set the user.name and user.email, among any other settings at the repo level. Just script it if you like.

A: Add a top level repo for each employer. Make each new project a submodule of this repo. This should allow you not to worry about the name and email settings for each project from now on.


text:
Q: how to regroup entities having relationship with each other and display them in one page? I'm getting started with jhipster, I create entity "shop" this entity has OneToMany relationship with the entity "command"; each "command" has a OneToMany relationship with the entity "product" and a ManyToOne relationship with the entity "Client". In fact every shop is composed of a group of command, every command is composed of a group of products and every command is associated to a Client. In my application, my goal is to display in one page the details of a shop, the list of all products and the client that commanded every product. For the moment I generated my entities but I don't know how to start specially that it is the first time that I used jhipster.
 All ideas are welcome.
 Thanks

A: By default, the resources generated by JHipster return  only the root objects.
For instance, ShopResource returns only Shop objects without their linked list of Product because the generator does not know what you want to do with it so it takes a minimal approach: the relationships between entities are lazy-loaded.
So first thing is to make sure that your related objects are loaded by ShopResource, have a look at your entities annotations. Learn about JPA/Hibenrnate.
Once you are sure related entities are loaded, they should be serialized in JSON, you can check this in the API docs menu of JHipster which uses swagger-ui.
Then, create your view and controller in angular and you should be able to refer to linked objects using shop.products notation.


text:
Q: Correct mysql query result
This is the result table of mysql query:
SELECT m.movieID, m.title, m.released_date_order, mt.movie_trailer_id
FROM movie m
LEFT JOIN movie_trailer mt ON mt.movieID = m.movieID
WHERE m.status !=0
  AND (m.released_date_order >= '2013-10-20' AND m.released_date_order <= '2014-10-20')
ORDER BY mt.movie_trailer_id IS NOT NULL , mt.movie_trailer_id ASC , m.title

But it's close to the result i want.
The result should be,
1) Display first the movies that has NULL values in movie_trailer_id column.
2) Then sort them by m.title in ASC order.
3) After the result in 1 and 2, then display the movies that doesn't have NULL values in the movie_trailer_id column.
4) And lastly, sort them also by m.title in ASC order.
As you can see on the table, the movies with NOT NULL values aren't sorted in the proper way. Anyone can give me the correct query?


text:
Q: checkbox Default Value "Checked" giving undefined value using jquery 1.9.1 here is the jquery code :
    var htmlCopyDialog = "";
   if ($("#main7 option:selected").text() != "Service Only") {

i am setting checkbox as checked by default after checking condition and calling function:
if(maintainCopyCheckbox)
        {

      htmlCopyDialog += '<input type="checkbox" name="isService" id="isService" checked ="checked" data-theme="d"/>';
     htmlCopyDialog += 'This is to be a service quote';
      showCallNumber(maintainCopyCheckbox);
      }
      else
        {
    htmlCopyDialog += '<input type="checkbox" onclick="showCallNumber(maintainCopyCheckbox);" name="isService" id="isService" data-theme="d"/>';
      htmlCopyDialog += 'This is to be a service quote';
           }

    }
     htmlCopyDialog += '
';

in function:
var setFlagForCheckbox = 0;

function showCallNumber(maintainCopyCheckbox1) {
    console.log("showCallNumber method call" + maintainCopyCheckbox1);
    if (maintainCopyCheckbox1) {
        console.log("if first condition" + $('#isService').defaultChecked);
        if ($("#isService").defaultChecked) {

            console.log("inside if condition" + maintainCopyCheckbox1);
        }
    }
}

here is the Log:

11-03 18:05:09.820: I/Web Console(8324): if first conditionundefined
  at file:///android_asset/www/js/survey/infoqueries.js:1062

can someone help me why its giving me undefined ....
     console.log("if first condition" + $('#isService').defaultChecked);
    i also have tried .is(:checked)   and .prop   both are giving me undefined.

A: $("#isService") returns a jQuery object which does not have the defaultChecked property, it is a property of the dom element. So you need to access the dom element reference, in this case $("#isService")[0] gives you the dom element with id isService.
console.log("if first condition" + $("#isService")[0].defaultChecked);
if ($("#isService")[0].defaultChecked) {

UPDATE:
Looks like there is a much basic problem because the showCallNumber method is invoked before the underlying html elements area added to the dom, so $("#isService") will not return any elements. You need to call the method showCallNumber only after the the html structure is added to the dom structure


text:
Q: Acrobat Failed to Load core DLL without any rootkits I am having an issue with an enduser getting this error.
After a brief Google search, I found the article here.  When I launch Adobe Acrobat X I recieve the following error:

Acrobat Failed to Load core DLL.

I ran the rootkit removal tool, a scan with SEP, a scan with MalwareBytes, I did the clean uninstall/reboot/reinstall from the tool provided, and to no avail, it still provides me with the same error.

A: I think you should remove Acrobat, then run the removal tool, then re-install Acrobat.
If that doesn't work, then a work around includes (and you didn't state what OS, so this is for Windows since the link in your post is for a Windows fix)

Here is a work around until I figure out the cause.  Copy all the FILES, not folders, from C:\Program Files (x86)\Adobe\Reader x.x\reader to C:\

Source

A: I resolved this issue by installing the 32-bit (x86) Microsoft Visual C++ 2010 Redistributable Package.
I figured this out by running Dependency Walker on AcroRd32.dll. There were several errors indicating that a 32-bit DLL was trying to load the 64-bit MSVC 2010 runtime DLLs. Installing the x86 redistributable package fixed the issue.


text:
Q: crossing out using different colour How to cross out a sentence using a horizontal line in a colour different from the text?
I found this useful question about how to cross out a sentence, but I cannot figure out how to use colour with this solution. The cancel package allows that, as described here, but would not do a horizontal line.

A: Too long for a comment.
The second answer in that thread is a working example.
If you want to change the color when using the soul package you can use the command \setstcolor:
\documentclass{article}
\usepackage{soul,xcolor}

\begin{document}

\setstcolor{red}

\st{Some overstruck text}

\end{document}

The ulem package does not support coloring directly, but looking at its manual, you can find that it is possible to define a new command like
\newcommand\redsout{\bgroup\markoverwith{\textcolor{red}{\rule[0.5ex]{2pt}{0.4pt}}}\ULon}

so that
\documentclass{article}
\usepackage[normalem]{ulem}
\usepackage{xcolor}

\begin{document}

\newcommand\redsout{\bgroup\markoverwith{\textcolor{red}{\rule[0.5ex]{2pt}{0.4pt}}}\ULon}

\redsout{Some overstruck text}

\end{document}

produces the same result as the above one.


text:
Q: Is it possible to create a tree of a tree of trait objects that implement common functionality, maybe slightly differently? I would like to construct a parse tree of different node types that share functionality via a trait. I need different types because different kinds of nodes might have slightly different types of fields. For example, a branch node like a paragraph does not hold text directly; only via its child Text nodes does it have access to its concrete contents.
With this in mind, I've made the following specifications:
use std::cell::RefCell;
use std::rc::{Rc, Weak};

/// ### Parent
/// A shorthand for an optional (parent might not exist)
/// weak reference to a parent node.
type Parent<T> = Option<Weak<RefCell<T>>>;

/// ### Children
/// Shorthand for a vector of owned child nodes.
/// Empty vector indicates no children.
/// Leaf nodes will assert this.
type Children<T> = Vec<Rc<RefCell<T>>>;

/// ### Document
/// Document root node
pub struct Document<T: Node> {
    id: usize,
    id_counter: NodeId,
    parent: Parent<T>,
    children: Children<T>,
    // -- snip --
}

/// ### trait Node
/// A trait defining functionality for general document tree nodes.
pub trait Node {
    type ID;
    type Parent;
    type Children;

    fn new() -> Self;
}

impl<T: Node> Node for Document<T> {
    type ID = usize;
    type Parent = Parent<T>;
    type Children = Children<T>;

    fn new() -> Self {
        let mut id_counter = NodeId::new();

        Document {
            id: id_counter.assign(),
            id_counter: id_counter,
            parent: None,
            children: Vec::new(),
            // -- snip --
        }
    }
}

/// ### NodeId
/// A global counter of document nodes
#[derive(Debug)]
pub struct NodeId {
    id: usize,
}

impl NodeId {
    /// ### new
    /// A NodeId constructor. In the beginning,
    /// there are 0 Nodes.
    pub fn new() -> Self {
        NodeId { id: 0 }
    }

    /// ### increment
    /// Increments the `NodeId` counter by 1.
    pub fn increment(&mut self) {
        self.id += 1;
    }

    /// ### get
    /// Return a copy of the NodeId counter.NodeId
    pub fn assign(&mut self) -> usize {
        let current = self.id;
        self.increment();
        current
    }
}

However, Rust will not let me construct a new empty document tree in a test. The code
#[test]
fn new_document_node() {
    let doc = Document::new();

    assert_eq!(0, doc.id);
}

results in the error
error[E0282]: type annotations needed for `Document<T>`
  --> src/lib.rs:85:15
   |
85 |     let doc = Document::new();
   |         ---   ^^^^^^^^^^^^^ cannot infer type for type parameter `T`
   |         |
   |         consider giving `doc` the explicit type `Document<T>`, where the type parameter `T` is specified

Adding a type annotation does not help:
let doc: Document<T: Node> = Document::new();

results in
error[E0658]: associated type bounds are unstable
  --> src/lib.rs:85:23
   |
85 |     let doc: Document<T: Node> = Document::new();
   |                       ^^^^^^^
   |
   = note: see issue #52662 <https://github.com/rust-lang/rust/issues/52662> for more information
   ^^^^^^^^^^^^^^^^^^^^^

error[E0107]: wrong number of type arguments: expected 1, found 0
  --> src/lib.rs:85:14
   |
85 |     let doc: Document<T: Node> = Document::new();
   |              ^^^^^^^^^^^^^^^^^ expected 1 type argument

error[E0229]: associated type bindings are not allowed here
  --> src/lib.rs:85:23
   |
85 |     let doc: Document<T: Node> = Document::new();
   |                       ^^^^^^^ associated type not allowed here

Is it possible to create a tree of objects that implement common functionality, maybe slightly differently? For example, my leaf node types have no children, so their get_children() -> Option<Vec<Children>> method would return an empty vector.
Is this at all achievable at least somewhat ergonomically in Rust?


text:
Q: datepicker onClose issue From researching on this site, I found a way to use 2 datepickers. If you pick a date on the first one, the second one will automatically show with the selected date as new minDate. You can see this in action on my test server here: http://www.zinius.nl/trips
The issue I'm having occurs in this situation:
Select the Check-in-date field, but don't select a date and click somewhere else. You won't be
able to get the Check-in-date field datepicker pop-up back up again until you refresh the entire page or first select the Check-out-date.
This is the code I am using:
$( "#datepicker1" ).datepicker({
showOn: 'both',
buttonImage: 'images/ico/calendar.png',
buttonImageOnly: true,
minDate: 0,
firstDay: 0,
dateFormat: 'mm-dd-yy',
changeMonth: false,
numberOfMonths: 1,
onClose: function( selectedDate ) {
    var minDate = $(this).datepicker('getDate');
    var newMin = new Date(minDate.setDate(minDate.getDate() + 1));
    $( "#datepicker2" ).datepicker( "option", "minDate", newMin );
    $( "#datepicker2" ).datepicker( "show" );
}
});
$( "#datepicker2" ).datepicker({

showOn: 'both',
buttonImage: 'images/ico/calendar.png',
buttonImageOnly: true,
minDate: '+1d',
changeMonth: false,
firstDay: 0,
dateFormat: 'mm-dd-yy',
numberOfMonths: 1,
onClose: function( selectedDate ) {
}
});

I tried replacing the onClose with onSelect. This solves the issue, but when I select a date on datepicker1, datepicker2 appears and disappears in a flash.
Does anyone have a solution to get this working properly?
Thank you,
Guilliano

A: Try to change your onClose function on the first datePicker with
...,
onClose: function( selectedDate ) {
  var minDate = $(this).datepicker('getDate');
  if(minDate){
    var newMin = new Date(minDate.setDate(minDate.getDate() + 1));
    $( "#datepicker2" ).datepicker( "option", "minDate", newMin );
    $( "#datepicker2" ).datepicker( "show" );
  }
}

A: Looking at the console, I can see this error being logged:

Cannot call method 'getDate' of null

It means your statement:
var minDate = $(this).datepicker('getDate');

is causing the problem. What you can do is to first check if the selectedDate (passed to the onClose callback) is valid or not, before attempting to getDate on it.
onClose: function(selectedDate) {
    if (selectedDate) {
        ...
    }
}


text:
Q: Numpy save taking too long in large dataset I'm trying to save a numpy array to disk but the saving process never seems to end, and the terminal keeps hanging without showing me the final print message of 'done'. I can tell the array is correctly formed by checking its shape right before the saving function.
I wonder if I'm doing anything wrong or if this would be expected with numpy.save given the size of the dataset.
Is there a more efficient way of doing this either with numpy or h5py?
# Xy_array is a 3D array of 10,000 images, each 224 x 224

Xy_array = np.asarray(lst)
f = open('./data/data.npy', 'wb')
np.save(f, Xy_array)
f.close()
print('done')


text:
Q: How to easily hide all content and display a message for mobile devices on html page I have this very basic todo list app. (http://www.hackerpup.com/todo/index.html) It was really just an intro project to practice jQuery. I'm happy with the result however, it is very ugly on mobile devices and until I reconfigure it to look okay on mobile I'd like it to not be available on mobile devices.
Is there an easy way to hide all the content on my page and just display a simple message instead for mobile devices? Even as simple as text saying "Sorry this page is not made for mobile devices".
(I'm happy to do this with css, javascript/jquery or anything that will work).
Thanks

A: In your link you have been using bootstrap, so you can easily solve your problem by bootstrap

My all element

My Text

A: Since you're utilizing Bootstrap, you can use its responsive utilities:

    Sorry this page is not made for mobile devices

Anyway, this is not the best solution. You should just continue to allow users to continue using your site even with a mobile web browser ;-)


text:
Q: Rewowrking method with stream usage Is there a possibility to rework below method using only streams?
public static Map<String, Long> getPeopleFromLines(List<String> lines) {
    Map<String, Long> namesWithCounts = new HashMap<>();
    for (String line : lines) {
        String[] words = line.split(",");
        String name = words[3];
        Long count = Long.parseLong(words[4]);
        if (namesWithCounts.containsKey(name)) {
            namesWithCounts.put(name, namesWithCounts.get(name) + count);
        } else {
            namesWithCounts.put(name, count);
        }
    }
    return namesWithCounts;
}

A: And here is yet another way for your learning enjoyment.

*

*stream the lines

*split on a comma and stream the arrays.

*group based on indexed item 3.

*and sum via a collector on item 4.

public static Map<String, Long> getPeopleFromLines(List<String> lines) {
    return lines.stream().map(line -> line.split(","))
        .collect(Collectors.groupingBy(arr -> arr[3],
                 Collectors.summingLong(arr -> Long.valueOf(arr[4]))));
}

A: Not only is it possible, it's surprisingly straightforward:
public static Map<String, Long> getPeopleFromLines(List<String> lines) {
    return lines.stream()
            .map(line -> line.split(","))
            .collect(Collectors.toMap(
                    words -> words[3],
                    words -> Long.parseLong(words[4]),
                    Long::sum));
}


text:
Q: Xamarin Grid columns with dynamic width: object occupies the wrong column despite assignment I am attempting to create a grid in Xamarin forms with two columns that each take up half of the screen. I have implemented my XAML as follows
<Grid VerticalOptions="End" HorizontalOptions="CenterAndExpand" BackgroundColor="#3F4045" Margin="0,0,0,0">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="5*"/>
        <ColumnDefinition Width="5*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Rectangle Grid.Row="0" Grid.ColumnSpan="2" VerticalOptions="Center" HorizontalOptions="CenterAndExpand" BackgroundColor="#3F4045"/>
    <Grid Grid.Row="1">
        <Grid Grid.Column="0" HorizontalOptions="Start">
            <Frame BackgroundColor="#FCFCFC" CornerRadius="0" Margin="0" Padding="0">
                <Entry TextColor="#3F4045" BackgroundColor="#FCFCFC" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" PlaceholderColor="#3F4045" Placeholder="Last Name, First Name"/>
            </Frame>
         </Grid>
         <Grid Grid.Column="1" HorizontalOptions="Start">
             <Frame BackgroundColor="#FCFCFC" CornerRadius="0" Margin="0" Padding="0">
                 <Button TextColor="#3F4045" BackgroundColor="#FCFCFC" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" Text="Upload Records"/>
             </Frame>
         </Grid>
     </Grid>
</Grid>

The two frames are supposed to each take up half of the second row with a small amount of space between them. However, when the app loads, they each take up half of the first column with a small amount of space between them. I experimented by changing the width of the second column from 5* to 8* and, as I expected, both of the frames shrunk so together they took up 5/13 of the screen, meaning that they are actually both in the first column. Here are pictures of the problem and the test I did with widths 5* and 8* for reference:

Is there something I'm missing in setting Horizontal/VerticalOptions in the frames or grid tags? Thank you for the help!

A: The solution was removing the frames from the Grid tags and making them children of the parent grid directly, using Grid.Row and Grid.Column to assign them to the proper locations.
<Grid VerticalOptions="End" HorizontalOptions="CenterAndExpand" BackgroundColor="#3F4045" Margin="0,0,0,0">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="5*"/>
        <ColumnDefinition Width="5*"/>
    </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Rectangle Grid.Row="0" Grid.ColumnSpan="2" VerticalOptions="Center" HorizontalOptions="CenterAndExpand" BackgroundColor="#3F4045"/>
    <Frame Grid.Row="1" Grid.Column="0" BackgroundColor="#FCFCFC" CornerRadius="0" Margin="0" Padding="0">
        <Entry TextColor="#3F4045" BackgroundColor="#FCFCFC" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" PlaceholderColor="#3F4045" Placeholder="Last Name, First Name"/>
    </Frame>
    <Frame Grid.Row="1" Grid.Column="1" BackgroundColor="#FCFCFC" CornerRadius="0" Margin="0" Padding="0">
        <Button TextColor="#3F4045" BackgroundColor="#FCFCFC" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" Text="Upload Records"/>
    </Frame>
</Grid>

Here is the updated code.


text:
Q: Is there a way to quickly modify individual color values in an image? For example, I have a CGImageRef and I want to shift all pixels which are red to orange. Or to put it in other words: I want to apply a value function on every pixel in an image, which modifies the pixel based on the RGBA values it has. So the value function would calculate the new component values for that pixel based on the current component values and some algorithm applied to it.
I know how I could code that by hand with about 100 lines of code, but I wonder if there is a easier and maybe even faster way?
I believe Brad Larson has mentioned somewhere that things like this can be done on the GPU easily and fast. However, I must support iOS 3.2 so it should not get too fancy.
Would be happy about any ideas.
Thanks!

A: As far as I know there are no built in functions to achieve what you want.
The easiest way to get GPU acceleration when doing custom image manipulations on the pixel level is using the Accelerate.framework. Accelerate will use the 'best execution path' based on available hardware.
However... the port to iOS was only done for iOS4
(disclaimer: I have little to no experience nor knowledge of everything that's possible in OpenGL, so take my answer as limited within the Core Graphics realms of iOS)


text:
Q: UIDevice systemVersion sometimes contains the OS name I have a problem with the method [[UIDevice currentDevice] systemVersion]. We have a report with devices using the app, and sometimes we get a string like "iPhone OS 6.1.3".
I don't know if there is another property for getting just the number (6.1.3) or if I have to implement a method to remove the first part.
Also I don't know exactly how many type of strings can I receive from several devices.
Thanks in advance for your help,
Regards

A: just do a regular expression to grab solely the number.
some simple expression like \b[0-9].[0-9](.[0-9])?\b or something like that.
This can be applied through an NSRegularExpression.
Something like this
NSError *error;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"\b[0-9].[0-9](.[0-9])?\b" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *version = [[expression matchesInString:[[UIDevice currentDevice] systemVersion]] objectAtIndex:0];


text:
Q: How to move a given number of random files on Unix/Linux OS I'm facing this simple task but, I'm also wondering about what's the easiest and short way to do it.
My proposal is move a given numer of random files from a directory to another. This task is part of the creation of two datasets I need for machine learning: a training set and a testing set. My goal is move away 10% of the file from a directory in order to get the datasat agaist which I could test my categorizer, and obtain a training set from the source directory.
So, what's the most compact typing for this "move n random files" task?
Thanks in advance - as usual -

A: Use a combination of shuf and xargs (it's a good idea to look at their documentation with man):
shuf -n 10 -e * | xargs -i mv {} path-to-new-folder

The command above selects 10 random files of the current folder (the * part) and then move them to the new folder.
Update
Although longer, one might find this version even simpler to understand:
ls | shuf -n 10 | xargs -i mv {} path-to-new-folder

shuf just generates a random permutation of the standard input, limiting the results to 10 (like using head, but probably faster).

A: You could use bash random generator that generates an int between 0 and 32767 to choose if a file must be put in set1 or set2.  That would do:
for file in ./*; do
  val=$RANDOM
  if test $val -gt 3276; then
    mv "$file" ../set1
  else
    mv "$file" ../set2
  fi
done

A: Alternative version with find to avoid problems with folders.
It copies 31415 randomly chosen files into /home/user/dir/
find . -maxdepth 1 -type f | sort -R | head -31415 | xargs cp -t /home/user/dir/

A: You can shuffle the file list using shuf or sort -R.
But you still need to take a subset, which you
can do with head/tail.

A: The question is pretty old, but for the record this works on OSX.
You have to install gshuf with brew install coreutils, then use:
tenpercent=$((`ls | wc -l` * 10/100))

ls | gshuf -n $tenpercent | xargs -I {} mv {} destination/path/

A: You can also do this with Python. I find this easier.
Here is a python script I use to move a random percent of images that also gets associated label datasets typically required for CV image datasets. Note this moves the files because I do not want my test training dataset in my training dataset.
I use the below for Yolo training sets as labels and images are in the same directory and the labels are txt files.
import numpy as np
import os
import random

#set directories
directory = str('/MauiData/maui_complete_sf_train')
target_directory = str('/MauiData/maui_complete_sf_test')
data_set_percent_size = float(0.07)

#print(os.listdir(directory))

# list all files in dir that are an image
files = [f for f in os.listdir(directory) if f.endswith('.jpg')]

#print(files)

# select a percent of the files randomly
random_files = random.sample(files, int(len(files)*data_set_percent_size))
#random_files = np.random.choice(files, int(len(files)*data_set_percent_size))

#print(random_files)

# move the randomly selected images by renaming directory

for random_file_name in random_files:
    #print(directory+'/'+random_file_name)
    #print(target_directory+'/'+random_file_name)
    os.rename(directory+'/'+random_file_name, target_directory+'/'+random_file_name)
    continue

# move the relevant labels for the randomly selected images

for image_labels in random_files:
    # strip extension and add .txt to find corellating label file then rename directory.
    os.rename(directory+'/'+(os.path.splitext(image_labels)[0]+'.txt'), target_directory+'/'+(os.path.splitext(image_labels)[0]+'.txt'))

    continue

A: Typically, we do this with a python script or a Java program. Either of these can use a proper RNG to make the random decisions, and then invoke the necessary calls to move files around.

A: With the zsh shell:
mv -- *(oe['REPLY=$RANDOM'][1,10]) /path/to/destination/

Where we use the oe glob qualifier to order the glob expansion based on the evaluation of the given code (which here returns a random value), and select the first 10.
On recent GNU systems, and with a shell with support for ksh-style process substitution (ksh93, zsh, bash) you can do:
xargs -r0a <(ls -U --zero | shuf -zn10) mv -t /path/to/destination --

ls -U --zero can be replaced with printf '%s\0' * is GNU ls is too old to support --zero. With the difference that if there's no non-hidden file in the current directory, you'll get an error about the failure to move a file called *.
xargs -r0a <(shuf -zen10 -- *) mv -t /path/to/destination --

Could also be used as a more correct/reliable/efficient variation on @boechat107's answer, though with the added caveat that you may run into a Argument list too long error upon attempting to  execute shuf if there's a large number of non-hidden files in the current working directory. The printf-based approach above should be fine in that regard as printf is generally built in the shells and so not affected by that limitation of the execve() system call.
To move 10% as opposed to 10, with zsh:
files=(*(Noe['REPLY=$RANDOM']))
mv -- $files[1,$#files/10] /path/to/destination/

(10% rounded down).


text:
Q: Why is my WebApplicationFactory hanging for 5 minutes before timing out? I'm trying to add some integration tests to my existing .net 6.0 project, but keep running into issues
Right now if I run the test, it hits the line await host.RunAsync(CancellationToken.None); in Program.cs and then just hangs forever and seemingly does nothing
Have I misunderstoof something? If not how can I troubleshoot this?
Program.cs
public /*static*/ class Program
{
    public static async Task Main(string[] args)
    {
        var host = BuildWebHost(args);

        await host.InitialiseAsync(CancellationToken.None);

        await host.SeedAsync(CancellationToken.None);

        await host.RunAsync(CancellationToken.None); // hangs here
    }
}

Tests.cs
[Fact]
public void Test1Async()
{
    using (var application = new WebApplicationFactory<Program>()
        .WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                // set up servises
            });
        }))
    {
        var c = application.CreateClient(); // hangs here
    }
}

It does eventually time out and give me this error

Message:
System.InvalidOperationException : Timed out waiting for the entry point to build the IHost after 00:05:00. This timeout can be modified using the 'DOTNET_HOST_FACTORY_RESOLVER_DEFAULT_TIMEOUT_IN_SECONDS' environment variable.

Stack Trace:
HostingListener.CreateHost()
<>c__DisplayClass10_0.b__0(String[] args)
DeferredHostBuilder.Build()
WebApplicationFactory1.CreateHost(IHostBuilder builder) DelegatedWebApplicationFactory.CreateHost(IHostBuilder builder) WebApplicationFactory1.ConfigureHostBuilder(IHostBuilder hostBuilder)
WebApplicationFactory1.EnsureServer() WebApplicationFactory1.CreateDefaultClient(DelegatingHandler[] handlers)
WebApplicationFactory1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) WebApplicationFactory1.CreateClient(WebApplicationFactoryClientOptions options)
WebApplicationFactory`1.CreateClient()
UnitTest1.Test1Async() line 35

A: Even though you didn't share the code for BuildWebHost() method I assume it is something like this public static IWebHostBuilder BuildWebHost(string[] args).
If so then simply rename this method to CreateWebHostBuilder. Name of the method is important because WebApplicationFactory internally is looking for it.
Straight from the summary on the constructor:
/// The <see cref="WebApplicationFactory{TEntryPoint}"/> will find the entry point class of <typeparamref name="TEntryPoint"/>
/// assembly and initialize the application by calling <c>IWebHostBuilder CreateWebHostBuilder(string [] args)</c>
/// on <typeparamref name="TEntryPoint"/>.

Source: https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs#L24


text:
Q: Getting an element tree broken down from an XML I have an XML and I am try to break down the elements so that it shows the path of every element. I have put an example of the code below and what the output I want to see.
The XML data is as per the below.
<a:Clients>
    <a:Client1>
        <a:Initial>
          <a:FirstName>data</a:FirstName>
          <a:LastName>data</a:LastName>
        </a:Initial>
        <a:FirstName>data</a:FirstName>
        <a:MiddleName />
        <a:LastName>data</a:LastName>
        <a:Title>Mr</a:Title>
        <a:MaritalStatus>Divorced</a:MaritalStatus>
        <a:MaidenName>data</a:MaidenName>

I want to output it so it shows as
Clients/Client1
Clients/Client1/Initilal
Clients/Client1/Initial/FirstName
etc So I want to get all the elements of my xml to appear in this order for a large XML document. I dont want any data that sits inbetween the tags, Just the element paths.
I have written the below code in vs 2015 - Console Application to try and output it in this order but it is not working correctly. The c# code im using is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            XNamespace ns = "http://www.test.net/author/1.0";
            XDocument doc = XDocument.Load("test.xml");
            var allElements  = doc.Descendants();
           foreach (var element in allElements)
           Console.WriteLine(allElements);
           Console.ReadLine();
        }
    }
}

The output im currently getting is:
Output
I have looked over Stack Overflow for answers but nothing seems to be exactly what I need and the ones I have tried have not worked either. Not sure if there is an easier way to do this?
Help would be greatly appreciated

A: I managed to do it in reversed order:
Client1/Clients
So i just entered all into a list and print it in reversed order later to be in the right order.
        XDocument doc = XDocument.Load("test.xml");
        var allElements = doc.Descendants();
        var elemants = doc.Elements();

        foreach (var element in allElements)
        {
            var current = element;
            List<string> names = new List<string>();
            while (current.Parent != null)
            {
                names.Add(current.Name.LocalName);
                current = current.Parent;
            }
            names.Add(current.Name.LocalName);
            names.Reverse();
            foreach(var name in names)
                Console.Write(name + "/");
            Console.WriteLine();
        }

I hope thats what you need.


text:
Q: Printer is not printing colour on Ubuntu 18.04 I have Linux Ubuntu 18.04 on my HP 650 laptop.
I have a printer Samsung C48W attached via wifi.
I can make printouts from Linux Ubuntu, but only MONOCHROME, i.e. no colours.
The printer itself is ok. I works fine from Windows.
I downloaded the latest driver package V1.00.39_01.17 from HP, and installed it.
That did not help.
If I understood correctly the driver is a PostScript driver.
The printer is set to "Auto" under "Emulation type". I also tried the explicit "PostScript" setting, but no change.
Still no colours on the printout, just monochrome.
Any ideas what to do?

A: Using any browser, access the CUPS admin page at http://localhost:631/admin/.
LeftClick on Manage Printers.
LeftClick on your printer name.
Note: sometime, during this process you will be prompted for a Username/Password - use your login credentials.
In the Administration drop-down list (LeftClick and Hold), select the `Set Default Options' item.
Ensure that the Output Mode is set to Color.

A: I had the same problem made more confusing as a Test Print page would come out perfectly but all my images would come out in monochrome. I tried suggestions from this board and other sources but none solved the problem. So I used CUPS to delete the printer (Epson L220). Once done I used CUPS to find the printers on my system and then proceeded to install it (with the L220 using the driver for the L210) Problem solved!

A: I had a similar problem on Ubuntu 20.04. test page would print in colour but applications wouldn't. The only solution I found is in each app the check the "Black & White" setting in the Advanced tab when I click print:

Somehow this seems to get reset all the time to "On"


text:
Q: There is a sort of window closing upon launching my app, only in Android versions higher than 6. Is it about the Permissions? I have an Activity with a library that asks for its own permissions that happen to collide with my required permissions, so I just override onRequestPermissionsResult() and let that library ask the permissions instead. The override is as follows:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Log.i("perms", permissions.length+" "+requestCode);
        int indexOfReadStorage = 0;
        for(int i = 0 ; i < permissions.length; i++)
        {
            Log.i("perms_len", permissions[i]+" "+requestCode);
            if(permissions[i].contains("READ_EXTERNAL_STORAGE"))
            {
                indexOfReadStorage = i;
            }
        }
        if (grantResults.length > 0 && grantResults[indexOfReadStorage] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted
            Log.i("read_ext_storage_perm", "granted");
            populateFolderList();
        } else {
            // Permission Denied
            //Toast.makeText(this, "READ_EXT_STORAGE Denied", Toast.LENGTH_SHORT).show();
        }
    }
}

Where requestCode == 4 (in my code my own requestCode for the READ_EXTERNAL_STORAGE permission is set to 102).
However, now I have some kind of window closing animation right after I launch the app the second time and after that. This doesn't happen when I tested the app in Lollipop, so it must be something in Marshmallow that makes this happen, and I'm suspecting it's the permissions check in the library.
Is it true? If it is, how do I resolve this? If it isn't, what might be the real cause?

A: Turns out it was due to the library requesting permission at the beginning of the activity with VmaxSDK.init(this) in onCreate() [said library was VMAX].
So I just moved it to the next Activity, and it all goes fine.


text:
Q: Can I combine more than one function in a single line in SQL? What I want to do is simply to use more than 1 function in a single query. I'm new to SQL so I'm sorry if I'm getting some words wrong.
select cognom from emp where length(cognom) = 10, replace(cognom, ' ', '*');

A: Yes, you can, as long as you respect the syntax. The 'line' does not mean anything because you can write all your query in a single line, even if it's not recommended to facilitate the comprehension.
In your case, what its wrong is your replace() that should either be in the select part to manipulate output data, or match a where statement.
In fact, you can have as many function as you need, which could be something like this:
SELECT col1, func1(col2) as txt2, func2(col3) as text3
  FROM your_table
 WHERE col1 = 12
   AND func4(col5) = 'XYZ'

A: It's unclear exactly what you require but preumably you are looking for the following
select replace(cognom, ' ', '*') as cognom
from emp
where length(cognom) = 10;


text:
Q: ng-model return undefined with directive I try to get value from html input tag in a directive, and always get undefined,
this is my code:
var app = angular.module('templateApp', []);

app.controller('Ctrl', function ($scope, $http, $sce) {

  $scope.DataList = "";

  $http.post("http://localhost/Service.svc/GetDataMysql", { valval: 0 })
       .then(function (data) {
           if (data.data) {
             $scope.Data = Enumerable.From(data)
                        .Select(function (x) { return x })
                        .ToArray();
             $scope.DataList = $scope.Data[0].Value;
           }
         });
});

app.run(function ($http, $templateCache) {
    $http.get('Template.html', {
        cache: $templateCache
     });
 });

 app.directive('myDir', ['$parse', '$http', '$compile', '$templateCache',      '$location',
    function ($parse, $http, $compile, $templateCache, $location) {
        var linker = function (scope, element, attrs, ngModel) {
       element.bind('click', function () {

           var ddd = scope.selectedvalue;
           scope.DataList = Enumerable.From(scope.DataList)
           .Where(function (x) {
               return x.LeafParentId == leafParentId
           }).ToArray()

           $compile(element.contents())(scope);
       });
   };

   return {

       templateUrl: 'Templates.html',
       transclude: true,
       restrict: "E",
       scope: {
           selectedvalue: '=ngModel'
       },

       link: linker
   };
    }]);

this is my template:

    <input type="button" name="" id="1"
           ng-value="checkData(DataList[0].Name)"
 ng-model="selectedvalue" />

    <input type="button" name="" id="2"
           ng-value="checkData(DataList[1].Name)"
 ng-model="selectedvalue" />

    <input type="button" name="" id="3"
           ng-value="checkData(DataList[2].Name)"
 ng-model="selectedvalue" />

and this is my html:

             <ng-dir ></ng-dir>

the directive work fine but when I click on one of the input tags the ng-model always returns undefined.
var ddd = scope.selectedvalue;

How can I get the value from the directive input tag?


text:
Q: Google plus token and gcm registration token For my application, I need token for logging in with google plus. Now, I dont know where to get the token. Is google plus token the same as gcm token?

A: you need to read this section of the docs about how to get an auth key to send to your server
https://developers.google.com/identity/sign-in/android/backend-auth
private class GetIdTokenTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
        Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
        String scopes = "audience:server:client_id:" + SERVER_CLIENT_ID; // Not the app's client ID.
        try {
            return GoogleAuthUtil.getToken(getApplicationContext(), account, scopes);
        } catch (IOException e) {
            Log.e(TAG, "Error retrieving ID token.", e);
            return null;
        } catch (GoogleAuthException e) {
            Log.e(TAG, "Error retrieving ID token.", e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        Log.i(TAG, "ID token: " + result);
        if (result != null) {
          // Successfully retrieved ID Token
          // ...
        } else {
          // There was some error getting the ID Token
          // ...
        }
    }

}


text:
Q: Iterate over java.util.BitSet in Scala What is the best answer for iterating over a java BitSet in Scala?
I currently have this:
var setBit = -1
Iterator.continually { setBit = bitSet.nextSetBit(setBit + 1); setBit }
      .takeWhile(_ >= 0)

What is the most accepted way to do this?
The reason I am not confident about this approach is because of the mutable setBit declaration and the setBit = bitSet.nextSetBit(setBit + 1); setBit part.

A: Use .iterate instead of .continually. Then there's no need for a mutable var.
Iterator.iterate(bitSet.nextSetBit(0))(x => bitSet.nextSetBit(x+1))
        .takeWhile(_ >= 0)


text:
Q: Questions regarding Task Programming What are the main differences between the following conventions.
First:
Task myTask = new Task(()=>
{
     // executable statements
});
myTask.Start();

Second:
Task.Run(()=>
{
  // executable statements
});

Third:
  Task.Factory.StartNew(() =>
  {
       // executable statements
  });

A: Firstly, this information is avalible with a simple google.
A. From MSDN "Task.Factory.StartNew" vs "new Task(...).Start"

With TPL, there are several ways to create and start a new task.  One way is to use the constructor for task followed by a call to the Start method, e.g.
new Task(...).Start();

and the other is by using the StartNew method of TaskFactory, e.g.
Task.Factory.StartNew(...);

This begs the question... when and why would you use one approach versus the other?
In general, I always recommend using Task.Factory.StartNew unless the particular situation provides a compelling reason to use the constructor followed by Start.  There are a few reasons I recommend this.  For one, it's generally more efficient.  For example, we take a lot of care within TPL to make sure that when accessing tasks from multiple threads concurrently, the "right" thing happens.  A Task is only ever executed once, and that means we need to ensure that multiple calls to a task's Start method from multiple threads concurrently will only result in the task being scheduled once.  This requires synchronization, and synchronization has a cost.  If you construct a task using the task's constructor, you then pay this synchronization cost when calling the Start method, because we need to protect against the chance that another thread is concurrently calling Start.  However, if you use Task.Factory.StartNew, we know that the task will have already been scheduled by the time we hand the task reference back to your code, which means it's no longer possible for threads to race to call Start, because every call to Start will fail.  As such, for StartNew we can avoid that additional synchronization cost and take a faster path for scheduling the task.

B. From MSDN Task.Run vs Task.Factory.StartNew

So, in the .NET Framework 4.5 Developer Preview, we've introduced the new Task.Run method.  This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters.  It's a shortcut.  In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters.  When you pass an Action to Task.Run:
Task.Run(someAction);

that's exactly equivalent to:
Task.Factory.StartNew(someAction,
    CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

In this way, Task.Run can and should be used for the most common cases of simply offloading some work to be processed on the ThreadPool (what TaskScheduler.Default targets).  That doesn't mean Task.Factory.StartNew will never again be used; far from it.  Task.Factory.StartNew still has many important (albeit more advanced) uses.  You get to control TaskCreationOptions for how the task behaves.  You get to control the scheduler for where the task should be queued to and run.  You get to use overloads that accept object state, which for performance-sensitive code paths can be used to avoid closures and the corresponding allocations.  For the simple cases, though, Task.Run is your friend.

I hope this helps.


text:
Q: Yield statement in generator causes skipped lines of code I am writing a generator in python. It behaves strangely in that if I leave the yield statement where it is, then the print function at the top of the function is never called. If I remove the yield function, the print statement happens as expected. Currently this is the code.
def eachMovement(self):
        print "Each Movement..."

        if not self.isComplete():
            raise ValueError("DressageScore.eachMovement:  dressage score must be designated as complete.")

        for i in range(0, len(self.__iMovementScores)):
            yield (self.__iMovementScores[i], self.__iMovementComments[i])

Removing yield fixes this problem. What am I doing wrong here? For clarification, I am running Python 2.7.5. Please do not persuade me to do this a different way, my class requires the use of a generator. Thanks!
SOLUTION:
Since I was doing Test Driven Development, I wrote the raise valueerror test before I wrote the rest of the function. After fully transforming eachMovement into a generator, my test case failed because it was not set up to test a generator. Silly mistake on my part. Here is the test case that now completes no problem. Thanks for all of your help
def test1300_910_EachMovementNotComplete(self):
    myGen = self.dsRider.eachMovement()

    self.assertRaises(ValueError, myGen.next)

A: If you simply invoke the generator function it will return generator object and it will not execute the function. You need to use next function on the generator object or someother function which can call next function on the generator object like list.
def myGen():
    print "Welcome"
    for i in range(10):
        yield i

print myGen()
print list(myGen())
print next(myGen())

Output
<generator object myGen at 0x7f1548366aa0>
Welcome
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Welcome
0

Normally generators are used for iteration (because once a generator is exhausted, it is not use. A new generator object has to be created for the next iteration.), so the best usage would be like this
for num in myGen():
    print num

Output
Welcome
0
1
2
3
4
5
6
7
8
9

A: I suspect you're simply calling my_obj.eachMovement(), correct?
Generators, unlike functions, do something called "lazy evaluation". Basically, Python will avoid running through the function until it absolutely needs to (which is useful, since it lets you write generators that return an infinite amount of elements, allowing the user to take only what they need, in contrast to normal functions, which would choke on similar inputs).
You need to do something like either:
>>> my_gen = my_obj.eachMovement()
>>> print next(my_gen)
Each Movement...
0  # whatever value

...or something like:
>>> for i in my_obj.eachMovement():
        print i
Each Movement...
0
1
# etc

Either method will force Python to actually evaluate the generator, since it requires the data in order to continue functioning.

A: yield in Python is a style of lazy evaluation, which in short means that successive elements of a sequence are only executed as they are needed.
For example, the builtin Python (2.7) function xrange is a generator, Python's term for a lazy evaluator.
In the same way you use xrange, you need to use your function:
for movement in eachMovement:
    # Do stuff with movement


text:
Q: Traffic Performance Testing Webpages Under Specified Conditions As the title implies, I would like to be able to simulate traffic to a collection of webpages that I have created for loadbalancing and bottleneck issues. I would like to mimic typical HTTP requests relative to the upload/download speed of the user. Furthermore, I would like to be able to perform extreme tests assuming a certain amount of storage and bandwidth on a server(s).
How I should go about doing this?

A: Look at Apache Flood: hhttp://httpd.apache.org/test/flood/
Good description: http://www.clove.org/flood-presentation/flood.pdf


text:
Q: Why can't I create a CSS gradient background in sharepoint 2010? I am trying to add a gradient background to a div in a page I'm making in Sharepoint 2010. The code below is working perfectly when I edit the html source and preview the page, but once I click the Save & Close button at the top left, the gradient disappears. Does sharepoint 2010 not allow gradients?

PAYROLL LEADERSHIP TEAM

A: No; it's just that SharePoint strips out any script tags unless you're using the Script Editor web part.


text:
Q: Getting all let bindings of module with reflection I've tried to get all let binding fields of an F# module but am struggling.
System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
|> Seq.collect(fun t -> t.GetFields())

but it doesn't seem to return the bindings. (the code is abbreviated and the types are only modules)

A: Assuming you want just the let bindings and not any types defined inside the module, you can use the following filters on the module type members:
open System.Reflection
open System.Runtime.CompilerServices

module Test =
    type Marker = interface end

    let x = 3

    let f x = x * x

    let m = List.map

let moduleType = typeof<Test.Marker>.DeclaringType

moduleType.GetMembers()
|> Array.filter (fun m -> m.DeclaringType = moduleType)
|> Array.filter (fun m -> m.IsDefined(typeof<CompilerGeneratedAttribute>, true) |> not)
|> Array.filter (fun m -> m.MemberType <> MemberTypes.NestedType)
|> Array.map (fun m -> m.Name)

This will give you back:  [|"f"; "m"; "x"|]


text:
Q: How to place a node in a sequence after calculating total sum of it's attribute I am very new in XSLT transformation...  I have an xml file like the following :-
<OTA_CruiseReq>
 <GuestCounts>
     <GuestCount Quantity="2"/>
     <GuestCount Quantity="3"/>
     <GuestCount Quantity="1"/>
     <GuestCount Quantity="1"/>
     <GuestCount Quantity="1"/>
 </GuestCounts>
</OTA_CruiseReq>

Now.. I want to create an XSLT that would calculate the total number of quantity of GuestCount and result in following output xml :-
<PersonNos>
            <PersonNo>1</PersonNo>
            <PersonNo>2</PersonNo>
            <PersonNo>3</PersonNo>
            <PersonNo>4</PersonNo>
            <PersonNo>5</PersonNo>
            <PersonNo>6</PersonNo>
            <PersonNo>7</PersonNo>
            <PersonNo>8</PersonNo>
</PersonNos>

That is it will calculate the total number of quantity and display the <PersonNo> till that sequence ... for example here total quantity of GuestCount  is 2+3+1+1+1 =8 .. so <PersonNo> will be displayed from 1 to 8 ...
I tried the following :-
<xsl:template match="/">
  <PersonNos>
    <xsl:for-each select="sum(OTA_CruiseReq/GuestCounts/GuestCount/@Quantity)">
       <PersonNo><xsl:value-of select="position()"/></PersonNo>
     </xsl:for-each>
       </PersonNos>
</xsl:template>

But for each doesn't support any number .. please help to resolve it in a very way

A: Firstly, your sum expression is not quite right. You are summing the @Quantity attributes, so it should look like this:
sum(OTA_CruiseReq/GuestCounts/GuestCount/@Quantity))

Now, you have tagged this XSLT 2.0, which means you can use a 'for' loop with an incremented counter, like so
<xsl:for-each select="1 to xs:integer(sum(OTA_CruiseReq/GuestCounts/GuestCount/@Quantity))">

Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
    <xsl:output method="xml" indent="yes" />

<xsl:template match="/">
 <PersonNos>
     <xsl:for-each select="1 to xs:integer(sum(OTA_CruiseReq/GuestCounts/GuestCount/@Quantity))">
        <PersonNo><xsl:value-of select="position()"/></PersonNo>
     </xsl:for-each>
 </PersonNos>
 </xsl:template>
</xsl:stylesheet>

On the otherhand, if you are actually only using XSLT 1.0, then you will need a recursive template to do the incrementing.
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />

    <xsl:template match="/">
        <PersonNos>
            <xsl:call-template name="person">
                <xsl:with-param name="end" select="sum(OTA_CruiseReq/GuestCounts/GuestCount/@Quantity)" />
            </xsl:call-template>
        </PersonNos>
    </xsl:template>

    <xsl:template name="person">
        <xsl:param name="start" select="1" />
        <xsl:param name="end" />

        <xsl:if test="not($start > $end)">
            <PersonNo><xsl:value-of select="$start"/></PersonNo>
            <xsl:call-template name="person">
                <xsl:with-param name="start" select="$start + 1" />
                <xsl:with-param name="end" select="$end" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Help ! What is the equation? I have $2$ Variables:

*

*Job ($A, B, C$)

*Age (Young, Adult, Old)

Total population for job is $100$,
total population for age is $100$
Job $A$ has $20\%$ of population
Job $B$: $30\%$
Job $C$: $50\%$
Young age is $10\%$ of population
Adult: $50\%$
Old: $40\%$
Young Age only working in Job $A$ & $B$
Adult only working in Job $A$ & $C$
Old only working in Job $B$ & $C$
How could I find the right number for each intersection of these variables? What is the equation?
If I count it manually, I'll find:

*

*Young age in Job $A$: $4$ people

*Young age, Job $B$: $6$

*Adult, Job $A$: $16$

*Adult, Job $C$: $34$

*Old, Job $B$: $24$

*Old, Job $C$: $16$

A: You can make a grid to show the data you are given.  The numbers on the borders are the sums of the rows or columns.  You can put a $0$ in the cells that you know do not have anybody in them.  Now you can put a variable in each blank cell.  From the two in the A row you get an equation $a+b=20$.

You can write six equations in six unknowns.  Unfortunately there is a dependence between them, so there is not a single solution.  You can see this because $a,d,e=1, b,c,f=-1$ would sum to zero in all the edge cells, so you can add or subtract any multiple of this (until some variable goes below $0$) and get another solution.
Another solution besides the one you found is
1. Young age in Job $A$: $3$ people
2. Young age, Job $B$: $7$
3. Adult, Job $A$: $17$
4. Adult, Job $C$: $33$
5. Old, Job $B$: $23$
6. Old, Job $C$: $17$


text:
Q: aam-opencv compile failed with OpenCVConfig.cmake
Following is the link to the project http://code.google.com/p/aam-opencv/
I am trying to compile this project on Ubuntu 12.04 with OpenCV 2.4.9. I have generated the CMake files successfully but when I start to compile it using make I get compilation error . I am using the new OpenCVConfig.cmake which I copied from /usr/local/share/OpenCV folder for compilation.I have made the necessary changes in CMakeLists.txt too. Any Help will be appreciated.
I am getting the following dump on compile.
[  5%] Building CXX object CMakeFiles/qt-aamtrainer.dir/src/main.cpp.o
In file included from /home/aam-opencv-read-only/include/lkFitting.h:22:0,
                 from /home/aam-opencv-read-only/src/main.cpp:34:
/home/aam-opencv-read-only/include/delaunay.h:130:44: error: 'CvSubdiv2DEdge' has not been declared

/home/aam-opencv-read-only/include/delaunay.h:135:5: error: 'CvSubdiv2D' does not name a type

/home/aam-opencv-read-only/include/delaunay.h:137:5: error: 'CvSubdiv2D' does not name a type

A: OpenCV 2.4.3 is the current official & stable release, not 2.4.9.
To solve that compiling error, simply edit delaunay.h and add:
#include "opencv2/legacy/legacy.hpp"


text:
Q: React  tag issue Thanks for reading this. I am starting to learn React and in an exercise I am following, the goal is create a component that renders an URL an goes to it. My component stands like this:
import React from 'react';

export default (props) => (

URL:

{props.url}

);

For a test, I render my component like this:
<Url
  url="https://www.google.com/"
/>

I am working using Webpack dev-server. The problem is when I click the link. I don't know why it takes me to http://localhost:8080/%7Bprops.url%7D instead of google page. What is wrong my code? How should I do it the right way? The example does not explain anything about this. Thank you again.

A: Try rendering href={props.url} without the " double quote characters:
export default (props) => (

URL:

      {props.url}

);

That way it will not encode the quote characters, but rather render the props.href string value.
Hopefully that helps!

A: Make sure to remove the quotes for the href
export default (props) => (

URL:

{props.url}

);

A: You should try and do a callback function onClick of your P tag like so:

goToUrl() {
  window.location.assign('https://www.google.com/')
}


text:
Q: gcc: CLOCK_REALTIME is undeclared I was trying to run the C code that I found on this website
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define n 2048

double A[n][n];
double B[n][n];
double C[n][n];

int main() {

    //populate the matrices with random values between 0.0 and 1.0
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {

            A[i][j] = (double) rand() / (double) RAND_MAX;
            B[i][j] = (double) rand() / (double) RAND_MAX;
            C[i][j] = 0;
        }
    }

    struct timespec start, end;
    double time_spent;

    //matrix multiplication
    clock_gettime(CLOCK_REALTIME, &start);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    clock_gettime(CLOCK_REALTIME, &end);
    time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0;
    printf("Elapsed time in seconds: %f \n", time_spent);
    return 0;
}

But when I compile it gcc says:
main.c:27:19: error: 'CLOCK_REALTIME' undeclared (first use in this function)
 clock_gettime(CLOCK_REALTIME, &start);
               ^~~~~~~~~~~~~~

I used gcc-g++ from MinGW as described in this tutorial.
I just copied the C code from the tutorial page and compiled it using
gcc -O3 main.c -o matrix

(my source file is named main.c).
Possible important information: I am on Windows 10.
EDIT: Compilation works just fine on Ubuntu 20.04 (as described in the article). However, can you help me get it to compile on Windows?

A: Here's what I've got for a benchmark program I'm working on:
typedef long long ticks_t;

static ticks_t ticks_per_second;

#if OS_Windows
static ticks_t get_timer_resolution()
{
    LARGE_INTEGER freq;
    if (!QueryPerformanceFrequency(&freq)
            || !freq.QuadPart) {
        printf("Error: cannot get Windows timer resolution.\n");
        exit(123);
    }
    return freq.QuadPart;
}

inline static ticks_t get_ticks()
{
    LARGE_INTEGER ticks;
    if (!QueryPerformanceCounter(&ticks)) {
        printf("Error: cannot get Windows timer count.\n");
        exit(123);
    }
    return ticks.QuadPart;
}
#else       // NOT WINDOWS, should be Linux / Unix
static ticks_t get_timer_resolution()
{
    return 10000000;
}

inline static ticks_t get_ticks()
{
    struct timespec t;
    clock_gettime(CLOCK_REALTIME, &t);
    return (long long)t.tv_sec * 10000000 + (t.tv_nsec + 50) / 100;
}

#endif

[...]

int main() {
    [...]
    ticks_per_second = get_timer_resolution();

Then use get_ticks() just before and after what I need to time, take the difference, and scale as needed using ticks_per_second, e.g.
    nticks = nticks * 1000000 / ticks_per_second;   // convert to microsecs


text:
Q: no luck with javax timer with Jlabel I'm still having issues with updating the JLabel using a timer. I can't seem to figure out what I am missing. the global second variable stays at zero so I am guessing the timers working but not updating the GUI window?
 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Globals
{
    public static int seconds = 0;
}

class main
{
    public static void main(String Args[])
    {

        //text timeline = new text();
        JFrame testing = new JFrame();
        frame textdes = new frame();
        testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testing.setSize(1000,1000);
        testing.setVisible(true);

        Countdown timer = new Countdown();
        Timer countdown = new Timer(5000, timer);
        countdown.start();

        JLabel countdowntext = new JLabel();
        countdowntext.setText("Now its :" + Globals.seconds);
        testing.add(countdowntext);
        testing.add(textdes);

    }
}

class frame extends JFrame
{
    class Countdown implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            Globals.seconds++;
        }
    }
}

A: You're setting the text of the label only once in the program. Then the timer changes the value of a variable, but doesn't do anything with the label. It should do:
Globals.seconds++;
countdowntext.setText("Now its :" + Globals.seconds);

Here's a complete example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Globals {
    public static int seconds = 0;
}

class Main {
    public static void main(String Args[]) {

        //text timeline = new text();
        JFrame testing = new JFrame();
        testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testing.setSize(1000,1000);
        testing.setVisible(true);

        JLabel countDownLabel = new JLabel();
        countDownLabel.setText("Now it's : " + Globals.seconds);
        testing.add(countDownLabel);

        CountDown countdown = new CountDown(countDownLabel);
        Timer timer = new Timer(5000, countDown);
        timer.start();
    }
}

class CountDown implements ActionListener {
    private JLabel countDownLabel;

    public CountDown(JLabel countDownLabel) {
        this.countDownLabel = countDownLabel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Globals.seconds++;
        this.countDownLabel.setText("Now it's : " + Globals.seconds);
    }
}

A: Try this -
public class MainFrame{
    JFrame frame = new JFrame("Main frame");
    JPanel panel = new JPanel();
    JLabel countdownText  = new JLabel();

    int seconds = 0;

    public MainFrame() {
        Timer timer = new Timer(5000, new Countdown());
        timer.start();

        panel.add(countdownText);

        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setPreferredSize(new Dimension(320,240));
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        countdownText.setText("Now its :" + seconds);
    }

    class Countdown implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            seconds++;
            countdownText.setText("Now its :" + seconds);
        }
    }

    public static void main(String [] args){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainFrame();
            }
        });
    }
}