text:
Q: Elegant way to replace tr '\n' '\0' (Null byte generating warnings at runtime) I strongly doubt about the grep best use in my code and would like to find a better and cleaner coding style for extracting the session ID and security level from my  cookie file :
cat mycookie
# Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_127.0.0.1 FALSE   /   FALSE   0   PHPSESSID   1hjs18icittvqvpa4tm2lv9b12
#HttpOnly_127.0.0.1 FALSE   /mydir/ FALSE   0   security    medium

The expected output is the SSID hash :
1hjs18icittvqvpa4tm2lv9b12

Piping grep with  tr '\n' '\0' works like a charm in the command line, but generates warnings (warning: command substitution: ignored null byte in input") at the bash code execution. Here is the related code (with warnings):
ssid=$(grep -Po 'PHPSESSID.*' path/sessionFile | grep -Po '[a-z]|[0-9]' | tr '\n' '\0')

I am using bash 4.4.12 (x86_64-pc-linux-gnu) and could read here this crystal clear explanation :

Bash variables are stored as C strings. C strings are NUL-terminated.
  They thus cannot store NULs by definition.

I could see here and there in both cases a coding solution using read:
# read content from stdin into array variable and a scalar variable "suffix"
array=( )
while IFS= read -r -d '' line; do
  array+=( "$line" )
done < <(process that generates NUL stream here)
suffix=$line # content after last NUL, if any

# emit recorded content
printf '%s\0' "${array[@]}"; printf '%s' "$suffix"

I don't want to use arrays nor a while loop for this specific case, or others. I found this workaround using sed:
ssid=$(grep -Po 'PHPSESSID.*' path/sessionFile | grep -Po '[a-z]|[0-9]' | tr '\n' '_' | sed -e 's/_//g')

My two questions are :
1) Would it be a better way to substitute tr '\n' '\0', without using read into a while loop ?
2) Would it be a better way to extract properly the SSID and security level ?
Thx

A: It looks like you're trying to get rid of the newlines in the output from grep, but turning them into nulls doesn't do this. Nulls aren't visible in your terminal, but are still there and (like many other nonprinting characters) will wreak havoc if they get treated as part of your actual data. If you want to get rid of the newlines, just tell tr to delete them for you with ... | tr -d '\n'. But if you're trying to get the PHPSESSID value from a Netscape-format cookie file, there's a much much better way:
ssid=$(awk '($6 == "PHPSESSID") {print $7}' path/sessionFile)

This looks for "PHPSESSID" only in the sixth field (not in e.g. the path or cookie values -- both places it could legally appear), and specifically prints the seventh field of matching lines (not just anything after "PHPSESSID" that happens to be a digit or lowercase letter).

A: You could also try this, if you don't want to use awk:
ssid=$(grep -P '\bPHPSESSID\b' you_cookies_file)
echo $ssid   # for debug only

which outputs something like
#HttpOnly_127.0.0.1 FALSE / FALSE 0 PHPSESSID 1hjs18icittvqvpa4tm2lv9b12

Then with cut(1) extract the relevant field:
echo $ssid |cut -d" " -f7

which outputs
1hjs18icittvqvpa4tm2lv9b12

Of course you should capture the last echo.
UPDATE
If you don't want to use cut, it is possible to emulate it with:
echo $ssid | (read a1 b2 c3 d4 e5 f6 g7; echo $g7)

Demonstration to capture in a variable:
$ field=$(echo $ssid | (read a1 b2 c3 d4 e5 f6 g7; echo $g7))
$ echo $field
1hjs18icittvqvpa4tm2lv9b12
$

Another way is to use positional parameters passing the string to a function which then refers to $7. Perhaps cleaner. Otherwise, you can use an array:
array=($(echo $ssid))
echo ${array[6]}   # outputs the 7th field

It should also be possible to use regular expressions and/or string manipulation is bash, but they seem a little more difficult to me.


text:
Q: library with keyboard layouts For my daughter (11 months old) I'm currently developing a program that entertains her while she is typing (well, more of smashing it) on the keyboard of my laptop.
It works really nice already and as she and her nephew (same age) seem to like it, I thought that maybe other children might as well.
The problem I now got is the following: when a key is pressed, something is drawn on the screen. The location where the picture is drawn depends on the physical location of the key on the keyboard. So for that I need to know the layout of the connected keyboard. Currently I'm using hardcoded en_US layout but maybe some day an e.g. French kid wants to use it.
On linux I can find the locale using the LANG environment variable and I think I may be able to retrieve the layout from some undocumented file underneath the xorg/x11 files. But I'm looking for a more portable version which works between distributions but also on microsoft windows and maybe even macos x.
I googled for it of course but could not find anything. So does anyone know of a solution in C/C++? If it is full of #ifdef-statements to work on multiple platforms then that is not a problem.
the program this is all about

A: Since you are using SDL already, it would make sense to use the build-in keyboard input handling functionality. This should give you all information you could possibly get via software (from the scancode that the keyboard hardware delivers up to the semantic meaning of the pressed key based on the current keyboard layout).
As keyboard manufacturer are free to build any physical layout of keys (some keyboards do not have any keys at all), a rocksolid solution to get the physical position of a pressed key on all keyboards is close to impossible. And since usually only the meaning of the pressed key is of interest there little to no use cases for which such a library should be developed. Thus, I doubt there are any libraries to help you with that particular problem.
As some commenters mentioned, I think you get a good solution for most keyboards by using the scancode value that you are able to receive using SDL functions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CasperJS, the test page doesn't load totally I'm new to casperjs and I want test the drop-down list from this page :
http://www.spareka.fr/pieces_detachees_accessoires_electromenager
The element is at the top right of page ("Quel type d'appareil?").
So, I run this script :
...
this.fillSelectors("form#search_form_4", {
  ...
  ...
});
...

But my shell display this error : "Form not found"
I checked, and the selector is good. So, I capture the page in the beginning of my script and I notice my page haven't load every elements (the form with id "search_form_4" is not visible).
I thinked my page need time to load, so I use this.wait like this :
...
this.capture("screen01.png");
this.wait(100000, function(){
  this.capture("screen02.pbg");
});
...

But in the end, the screen01 show the same content as the screen02.
I don't understand why the page doesn't load totally when I use CasperJS :/ Can you help me ?
Edit :
My logs :

asus4@asus4-VirtualBox ~/Bureau/tests casper/test $ sudo casperjs script_test.js
  [info] [phantom] Starting...
  [info] [phantom] Running suite: 2 steps
  [debug] [phantom] opening url: http://www.spareka.fr/piece_detachees_accessoires_electromenager, HTTP GET
  [debug] [phantom] Navigation requested: url=http://www.spareka.fr/piece_detachees_accessoires_electromenager, type=Other, willNavigate=true, isMainFrame=true
  [debug] [phantom] url changed to "http://www.spareka.fr/piece_detachees_accessoires_electromenager"
  [debug] [phantom] Navigation requested: url=http://googleads.g.doubleclick.net/pagead/viewthroughconversion/1009678515/?random=1413232851719&cv=7&fst=1413232851719&num=1&fmt=1&guid=ON&u_h=768&u_w=1024&u_ah=768&u_aw=1024&u_cd=32&u_his=1&u_tz=120&u_java=false&u_nplug=0&u_nmime=0&frm=0&url=http://www.spareka.fr/piece_detachees_accessoires_electromenager, type=Other, willNavigate=true, isMainFrame=false
  [debug] [phantom] Navigation requested: url=http://www.google.com/ads/user-lists/1009678515/?fmt=1&num=1&cv=7&frm=0&url=http://www.spareka.fr/piece_detachees_accessoires_electromenager&random=4196938409, type=Other, willNavigate=true, isMainFrame=false
  [debug] [phantom] Navigation requested: url=http://www.google.fr/ads/user-lists/1009678515/?fmt=1&num=1&cv=7&frm=0&url=http://www.spareka.fr/piece_detachees_accessoires_electromenager&random=4196938409&ipr=y, type=Other, willNavigate=true, isMainFrame=false
  [debug] [phantom] Successfully injected Casper client-side utilities
  [info] [phantom] Step anonymous 2/2 http://www.spareka.fr/piece_detachees_accessoires_electromenager (HTTP 200)
  [debug] [phantom] Capturing page to /home/asus4/Bureau/tests casper/test/screen01.png
  [info] [phantom] Capture saved to /home/asus4/Bureau/tests casper/test/screen01.png
  [info] [phantom] Step anonymous 2/2: done in 3227ms.
  [info] [phantom] Step _step 3/3 http://www.spareka.fr/piece_detachees_accessoires_electromenager (HTTP 200)
  [info] [phantom] Step _step 3/3: done in 3228ms.
  [info] [phantom] wait() finished waiting for 10000ms.
  [debug] [phantom] Capturing page to /home/asus4/Bureau/tests casper/test/screen02.png
  [info] [phantom] Capture saved to /home/asus4/Bureau/tests casper/test/screen02.png
  CasperError: Errors encountered while filling form: form not found
  /home/asus4/Bureau/dev/casperjs/modules/casper.js:805 in fillForm
  /home/asus4/Bureau/dev/casperjs/modules/casper.js:880 in fillSelectors
  /home/asus4/Bureau/tests casper/test/script_test.js:28
  /home/asus4/Bureau/dev/casperjs/modules/casper.js:2035 in _check

My code :
var casper = require("casper").create({
  verbose: true,
  logLevel: "debug"
});

casper.start("http://www.spareka.fr/piece_detachees_accessoires_electromenager", function(){

//this.echo(this.getHTML('body'));

  this.on('remote.message', function(msg){
    this.echo("remote.message : " + msg);
  });
  this.on('page.error', function(msg, trace){
    this.echo("Error:   " + msg, "ERROR");
    this.echo("file:    " + trace[0].file, "WARNING");
    this.echo("line:    " + trace[0].line, "WARNING");
    this.echo("function:    " + trace[0]["function"], "WARNING");
    errors.push(msg);
  });

  this.capture("screen01.png");
  this.wait(10000, function(){
    this.capture("screen02.png");
    this.fillSelectors("form#search_form_4", {
  //'input[id="#finalProductType"]':    'Appareil à Fondue',
  //'input[id="#manufacturer"]':        'TEFAL',
    });
  });

A: You should be using "form#search-form-4" instead.
Replace the underscores with dashes. I checked the page you mentioned and it has a form with id="search-form-4".


text:
Q: Visualize a clickable graph in an HTML page I have defined a data structure using pygraph. I can display that data easily as PNG using graphviz.

I would like to display the data graphically, but making each node in the graph clickable. Each node must be linked to a different web page. How would I approach this?
What I would like is:

*

*Assign an href for each node

*Display all the graph as image

*Make each node in the image clickable

*Tooltips for hover event: whenever the cursor is positioned on top of an edge / node, a tooltip should be displayed

A: I believe graphviz can already output an image as a map for use in html.
Check this doc or this one for how to tell graphviz to output a coordinate map to use. It will even append the url you specify, and there even is a version that only uses rectangles for mapping links
Edit:
You can also check this document by LanyeThomas which outlines the basic steps:

Create a GraphViz dot file with the required linking information,
  maybe with a script.
Run GraphViz once to generate an image of the
  graph.
Run GraphViz again to generate an html image-map of the graph.
Create an index.html (or wiki page) with an IMG tag of the graph,
  followed by the image-map's html.
Direct the image-map urls to a Wiki
  page with each node's name - generate the Wiki pages automatically if
  needed.
Optionally, link directly to the class hierarchy image
  generated by DoxyGen. Have the Wiki page link to any additional
  documentation, including DoxyGen docs, images, etc.

A: You can use pygraphviz and cmapx
import pygraphviz
my_graph = pygraphviz.AGraph(id="my_graph", name="my_graph")
my_graph.add_node("node",
                  label="my_node",
                  tooltip="tooltip text \r next line",  # use \r for new line
                  URL="http://ya.ru/",
                  target="_blank")
my_graph.layout(prog='dot')
my_graph.draw(path="my_graph.map", format="cmapx")
my_graph.draw(path="my_graph.svg", format="svg")

then use content of my_graph.map in html

... [content of my_graph.map] ...

A: You could use click maps:

<map name="mygraphmap">
  <area shape="circle" coords="100,100,30" href="f8a08.htm">
  <area shape="circle" coords="200,100,30" href="1d0f.htm">
</map>

You'd obviously have to find out the coordinates somehow.
edit:
You can also use rect or polygon for the shape attribute.
I think you can also add a mouseover or title attribute to the area elements.
more edit:
Or you could make graphviz output svg which can be integrated in the html5 DOM. I mean that you might be able to handle the elements inside a graph as a DOM-object.

A: Most of the suggested solutions involve an Image map format, but that's tricky. Not only that, you won't be able to edit the clickable SVG file in e.g. Inkscape afterwards to customize your drawing.
The SVG files that graphviz generates already have clickable links if you provide URLs. If you're having trouble with them, then perhaps you need to use an <object> tag rather than an  tag:
<object width="100%" data="./example.gv.svg" type="image/svg+xml"></object>

See also Insert clickable SVG image into Sphinx documentation.

A: If you are looking for a graphviz alternative, may be you could use jsPlumb Library. See some samples here
Also checkout JavaScript InfoVis Toolkit


text:
Q: How to rebase this branch? The image below consists of two parts:
the first part is the repository sample model, the second part is the repository state that I want to get using the git rebase.
I didn't forget anything in the second part. This is exactly what I want.

A: In that situation I'd choose to just rebuild branches rather than wandering into ninja rebase attempts :
git checkout -b new-tmp1 master
git cherry-pick h i
git checkout -b new-tmp2 master
git cherry-pick j k

Then if new-tmp1 and new-tmp2 suit your needs, just move old refs :
git branch -f tmp1 new-tmp1
git branch -f tmp2 new-tmp2

A: If the number of commits you want to manipulate is as small as in the picture : use cherry-pick
git checkout tmp1
# make sure you have a clean working directory before running reset --hard :
git reset --hard <e>
git cherry-pick <h> <i>

git rebase has a syntax to select a range of commits :
git checkout tmp1
# you need to mention <g>, the *parent* of the first commit you
# want to replay, not <h>
git rebase --onto <e> <g> tmp1

git checkout tmp2
git reset --hard <k>
git rebase --onto <e> <g> tmp2

a note about git reset --hard :
git reset --hard <target> is one of the few dangerous git commands, that can delete modifications from your disk without saving them somewhere first.
It sets the active commit to <target>, and discards any modifications on all tracked files (that's the dangerous part).
You should at least know the effects before using it.
Some easy ways to avoid loosing your un-committed work are :

*

*git stash your work before using git reset --hard,

*commit your work before using it (even after a git reset, the commit will still be available through git reflog),


text:
Q: Laravel 7 - artisan seed Target class [DatabaseSeeder] does not exist I'm trying to seed my "DatabaseSeeder.php' But when I try to run
php artisan db:seed
I get the error:

Target class [DatabaseSeeder] does not exist.

My code in "DatabaseSeeder.php" looks like this:
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 3)->create()->each(function($u) {
            $u->questions()
              ->saveMany(
                  factory(App\Question::class, rand(1, 5))->make()
              );
        });
    }
}

What I tried so far:
composer dump-autoload

php artisan cache:clear

php artisan optimize

Note: I don't have a User-Made seeder, I'm trying to use the default one (DatabaseSeeder.php), but for some reason, it's telling me that it doesn't exist.

A: With Laravel 7, the composer.json needs the classmap reference in the autoload mapping, because the default seed folder doesn't respect PSR-4: database/seeds (see Laravel Documentation - Database: Seeding)
Check to have this in the composer.json:
"classmap": [
        "database/seeds",
        "database/factories"
    ],

And run composer dump-autoload
See this similar error: Target class [DatabaseSeeder] does not exist - Laravel 7 and Composer 2


text:
Q: mongo save save more than 1 records at ones
    I want to save more than 1 records at one time that means save block of records.
 Is it possible in mongoDB. if yes plz some one tell.
Thanks

A: The java driver's DBCollection supports insert with a List<DBObject> parameter this should be usable from scala as well.
Edit
Cabash also supports a similar insert method that should do the trick.


text:
Q: Intel Skeletal Hand Tracking Library with Kinect I've found this -> http://software.intel.com/en-us/articles/the-intel-skeletal-hand-tracking-library-experimental-release
I think is a good one...the problem is that i don't want to buy the "Creative Interactive Gesture Camera"...instead i want to use my Kinect.
It's not so easy and i need your help. I started with the Init()
this one is the original function :
inline bool Tracker::Init()
{
    if(PXCSession_Create(session.ReleaseRef()) < PXC_STATUS_NO_ERROR || !session.IsValid()) return false;

    for(int i=0; ; ++i) // For valid capture contexts
    {
        PXCSession::ImplDesc desc, filter = { PXCSession::IMPL_GROUP_SENSOR, PXCSession::IMPL_SUBGROUP_VIDEO_CAPTURE };
        if(session->QueryImpl(&filter, i, &desc) < PXC_STATUS_NO_ERROR) break;
        if(session->CreateImpl(&desc, PXCCapture::CUID, (void**)capture.ReleaseRef()) < PXC_STATUS_NO_ERROR || !capture.IsValid()) continue;

        for(int j=0; ; ++j) // For valid devices
        {
            PXCCapture::DeviceInfo dinfo;
            if(capture->QueryDevice(j, &dinfo) < PXC_STATUS_NO_ERROR) break;
            if(capture->CreateDevice(j, device.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;

            for(int k=0; ; ++k) // For valid video streams
            {
                PXCCapture::Device::StreamInfo sinfo;
                if(device->QueryStream(k, &sinfo) < PXC_STATUS_NO_ERROR) break;
                if(sinfo.cuid != PXCCapture::VideoStream::CUID || device->CreateStream(k, PXCCapture::VideoStream::CUID, (void**)stream.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;

                for (int m=0; ; ++m) // For depth buffer profiles of at least 60 FPS
                {
                    PXCCapture::VideoStream::ProfileInfo pinfo;
                    if(stream->QueryProfile(m, &pinfo) < PXC_STATUS_NO_ERROR) break;
                    if(pinfo.imageInfo.format != PXCImage::IMAGE_TYPE_DEPTH || pinfo.frameRateMin.numerator / pinfo.frameRateMin.denominator < 60 || stream->SetProfile(&pinfo) < PXC_STATUS_NO_ERROR) continue;

                    // If we can read at least one frame
                    stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
                    if(sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)
                    {
                        // Obtain useful properties and reserve room for local copies of depth and color images
                        dimx = pinfo.imageInfo.width; dimy = pinfo.imageInfo.height;
                        PXCPointF32 flen; device->QueryPropertyAsPoint(PXCCapture::Device::PROPERTY_DEPTH_FOCAL_LENGTH, &flen);
                        fovx = atan(dimx / (flen.x*2))*2; fovy = atan(dimy / (flen.y*2))*2;
                        color = new unsigned char[dimx*dimy*3];
                        depth = new unsigned short[dimx*dimy];

                        // Initialize tracking library
                        tracker = hsklCreateTracker(HSKL_COORDS_X_RIGHT_Y_DOWN_Z_FWD, HSKL_API_VERSION);
                        hsklSetSensorProperties(tracker, HSKL_SENSOR_CREATIVE, dimx, dimy, fovx, fovy);
                        return true;
                    }
                }
                stream.ReleaseRef();
            }
            device.ReleaseRef();
        }
        capture.ReleaseRef();
    }
    return false;
}

}
this one is mine :
inline bool Tracker::Init()
{
    if(PXCSession_Create(session.ReleaseRef()) < PXC_STATUS_NO_ERROR || !session.IsValid()) return false;

    for(int i=0; ; ++i) // For valid capture contexts
    {
        PXCSession::ImplDesc desc, filter = { PXCSession::IMPL_GROUP_SENSOR, PXCSession::IMPL_SUBGROUP_VIDEO_CAPTURE };
        if(session->QueryImpl(&filter, i, &desc) < PXC_STATUS_NO_ERROR) break;
        if(session->CreateImpl(&desc, PXCCapture::CUID, (void**)capture.ReleaseRef()) < PXC_STATUS_NO_ERROR || !capture.IsValid()) continue;

        for(int j=0; ; ++j) // For valid devices
        {
            PXCCapture::DeviceInfo dinfo;
            if(capture->QueryDevice(j, &dinfo) < PXC_STATUS_NO_ERROR) break;
            if(capture->CreateDevice(j, device.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;

            for(int k=0; ; ++k) // For valid video streams
            {
                PXCCapture::Device::StreamInfo sinfo;
                if(device->QueryStream(k, &sinfo) < PXC_STATUS_NO_ERROR) break;
                if(sinfo.cuid != PXCCapture::VideoStream::CUID || device->CreateStream(k, PXCCapture::VideoStream::CUID, (void**)stream.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;

                for (int m=0; ; ++m) // For depth buffer profiles of at least 60 FPS
                {
                    PXCCapture::VideoStream::ProfileInfo pinfo;
                    //if(stream->QueryProfile(m, &pinfo) < PXC_STATUS_NO_ERROR) break;
                    //if(pinfo.imageInfo.format != PXCImage::IMAGE_TYPE_DEPTH || pinfo.frameRateMin.numerator / pinfo.frameRateMin.denominator < 60 || stream->SetProfile(&pinfo) < PXC_STATUS_NO_ERROR) continue;

                    //Sleep(1000);
                    dimx=(int)K.m_colorWidth;
                    dimy=(int)K.m_colorHeight;
                    fovx=0.99;
                    fovy=0.75;

                    // If we can read at least one frame
                    stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
                    if((sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)||true)
                    {
                        // Obtain useful properties and reserve room for local copies of depth and color images
                        //dimx = pinfo.imageInfo.width; dimy = pinfo.imageInfo.height;
                        //PXCPointF32 flen; device->QueryPropertyAsPoint(PXCCapture::Device::PROPERTY_DEPTH_FOCAL_LENGTH, &flen);

                        //fovx = atan(dimx / (flen.x*2))*2; fovy = atan(dimy / (flen.y*2))*2;
                        color = new unsigned char[dimx*dimy*3];
                        depth = new unsigned short[dimx*dimy];

                        // Initialize tracking library
                        tracker = hsklCreateTracker(HSKL_COORDS_X_RIGHT_Y_DOWN_Z_FWD, HSKL_API_VERSION);
                        hsklSetSensorProperties(tracker, HSKL_SENSOR_IDEAL, dimx, dimy, fovx, fovy);
                        return true;
                    }
                }
                stream.ReleaseRef();
            }
            device.ReleaseRef();
        }
        capture.ReleaseRef();
    }
    return false;
}

}
And this is the original update class :
inline void Tracker::Update()
{
    if(sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)
    {
        PXCImage::ImageData depthData; image->AcquireAccess(PXCImage::ACCESS_READ, &depthData);
        memcpy_s(depth, sizeof(unsigned short)*dimx*dimy, depthData.planes[0], sizeof(unsigned short)*dimx*dimy);
        const unsigned short * conf = reinterpret_cast<const unsigned short *>(depthData.planes[1]);
        for(int i=0; i<dimx*dimy; ++i) color[3*i+2] = color[3*i+1] = color[3*i] = conf[i]>>2; // Can we just use IR here?
        hsklTrackOneFrame(tracker, depth, conf); // Pass data to tracking library
        image->ReleaseAccess(&depthData);
    }

    stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
}

and mine :
inline void Tracker::Update()
{
    if((sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)||true)
    {
        Mat matd(dimy,dimx,CV_16UC1);
        Mat matir(dimy,dimx,CV_16UC1);
        K.getDepth(&matd);
        matir = K.getIR();

        double min,max;
        cv::minMaxLoc(matir,&min,&max);
        Mat exit(dimy,dimx,CV_8UC1);
        matir.convertTo(exit,CV_8U,pow(2.0,8.0)/max);

        memcpy_s(depth,sizeof(unsigned short)*dimx*dimy,(unsigned short*)(matd.ptr()),sizeof(unsigned short)*dimx*dimy);
        const unsigned short * conf = reinterpret_cast<const unsigned short *>(matir.ptr());
        //PXCImage::ImageData depthData; image->AcquireAccess(PXCImage::ACCESS_READ, &depthData);
        //memcpy_s(depth, sizeof(unsigned short)*dimx*dimy, depthData.planes[0], sizeof(unsigned short)*dimx*dimy);
        //const unsigned short * conf = reinterpret_cast<const unsigned short *>(depthData.planes[1]);
    // Can we just use IR here?
        for(int i=0; i<dimx*dimy; ++i) {
            color[3*i+2] = color[3*i+1] = color[3*i] = (exit.at<unsigned char>(i)) ;

        }
        hsklTrackOneFrame(tracker, depth, conf); // Pass data to tracking library
        //image->ReleaseAccess(&depthData);
    }

    stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
}

If i try to run the program there are no errors...but it doesn't track my hand...So any suggestions ?? or is there somebody who is interested and want to share the project with me ?
thanks


text:
Q: filter div by indexOf of classname I need help to filter a ton of populated divs with dynamically filled class names
this is a form to that when a option selected needs to hide all divs that do NOT  have an indexOf the class name of the div

To narrow down the results, fill out the form below.

    Student/Teacher
    <select name="classification" id="classification">
        <option value="" selected>Select...</option>
        <option value="student">Student</option>
        <option value="teacher">Teacher</option>
    </select>

    Education Level
    <select name="level" id="level">
        <option selected>Select...</option>
        <option value="elementary">Elementary School</option>
        <option value="middle">Middle School</option>
        <option value="high">High School</option>
        <option value="college">College</option>
    </select>

    STEM Subject
    <select name="subject" id="subject">
        <option selected>Select...</option>
        <option value="science">Science</option>
        <option value="technology">Technology</option>
        <option value="engineering">Engineering</option>
        <option value="mathematics">Mathematics</option>
    </select>

    Resource Type
    <select name="type" id="type">
        <option selected>Select...</option>
        <option value="sa">Scholarships & Awards</option>
        <option value="as">Academics Support</option>
        <option value="is">Industry Spotlights</option>
        <option value="ce">Career Exploration</option>
        <option value="cs">Career Spotlight</option>
        <option>Professional Organization Resource</option>
    </select>

the div will be cycled dynamically with different class names... 100's of div's looped into and injected with a set class name provided by the database ex: teachermiddletechnologysa

A: There are multiple problems

*

*As @elclanrs said & != &&

*The attribute selector you are using is ends with is wrong as the match can be found anywhere

*Also the combined class selector you are using might produce unexpected results. Why can't you have the class for the div as

*Your string concatenation($('div[class$="'as'"]').show();) is syntactically wrong, it should be $('div[class$="' + as +'"]').show();
Try
var $divs = $('div');
var $filters = $('#classification, #level, #subject, #type').change(function () {
    var filter = $filters.map(function () {
        return this.value && this.value.indexOf('Select...') == -1 ? '[class*=' + this.value + ']' : undefined;
    }).get();
    $divs.hide()
    if (filter.length) {
        $divs.filter(filter.join('')).show()
    }
});

Demo: Fiddle

If you can separate the class names like

  then
var $divs = $('div');
var $filters = $('#classification, #level, #subject, #type').change(function () {
    var filter = $filters.map(function () {
        return this.value && this.value.indexOf('Select...') == -1 ? '.' + this.value : undefined;
    }).get();
    $divs.hide()
    if (filter.length) {
        $divs.filter(filter.join('')).show()
    }
});

Demo: Fiddle


text:
Q: Object doesn't support this property or method: 'xmldoc2.importNode' I am trying to copy nodes from one XML document into another.
Project is a root element inboth documents and I want to select all ItemGroup elements from first document and insert them before Import element in the second document. Unfortunately, I get
Object doesn't support this property or method: 'xmldoc2.importNode'

Here is the code I am using:
Set xmldoc1 = CreateObject("Microsoft.XMLDOM")
xmldoc1.async = false
xmldoc1.load WScript.Arguments(0)

Set xmldoc2 = CreateObject("Microsoft.XMLDOM")
xmldoc2.async = false
xmldoc2.load WScript.Arguments(1)

Set importNode = xmldoc2.selectSingleNode("//Project/Import")

Set nodes = xmldoc1.selectNodes("//Project/ItemGroup")
For Each node In nodes
    Set newNode = xmldoc2.importNode(node, True)
    xmldoc2.insertBefore newNode, importNode
Next

How should I fix the code?
EDIT:
Thanks to @Ekkehard.Horner, I solved the issue. Here is the updated code
Set xmldoc1 = CreateObject("Microsoft.XMLDOM")
xmldoc1.async = false
xmldoc1.load WScript.Arguments(0)

Set xmldoc2 = CreateObject("Microsoft.XMLDOM")
xmldoc2.async = false
xmldoc2.load WScript.Arguments(1)

Set importNode = xmldoc2.selectSingleNode("//Project/Import")

Set nodes = xmldoc1.selectNodes("//Project/ItemGroup")
For Each node In nodes
    Set newNode = node.cloneNode(true)
    xmldoc2.documentElement.insertBefore newNode, importNode
Next

A: The docs for importNode state:

[This sample code uses features that were first implemented in MSXML
  5.0 for Microsoft Office Applications.]

I'd try to use

*

*"Msxml2.DOMDocument" or "Msxml2.DOMDocument.6.0" instead of "Microsoft.XMLDOM"

*.cloneNode instead of .importNode


text:
Q: Jenkins - Posting results to a external monitoring job is adding garbage to the build job log I have a external monitor job that I'm pushing the result of another job to it with curl and base on this link :
Monitoring external jobs
After I create the job I just need to run a curl command with the body encoded in HEX to the specified url and then a build will be created and the output will be added to it but what I get instead is part of my output in clear text and the rest in weird characters like so :
Started
Asking akamai to purge this urls:
http://xxx/sites/all/modules/custom/uk.png     http://aaaaaasites/all/modules/custom/flags/jp.png
<html><head><title>401 Unauthorized</title>    </h�VC��&�G����CV�WF��&��VC�������R&R��BWF��&��VBF�66W72F�B&W6�W&6S�����&�G�����F����F�RW&�F �6�V6�7FGW2�bF�R&WVW7B�2��F�RF��RF�v�B�2��6�Ɩ�r&6�w&�V�B��"F�6�V6�7FGW2�bF�RF�6�W@�v�F��rf�"���F�W&vRF��6O request please keep in mind this is an estimated time
Waiting for another 60 seconds
Asking akamai to purge this urls:
...
..
..

This is how I'm doing it :
export output=`cat msg.out|xxd -c 256 -ps`

curl -k -X POST -d "<run><log encoding=\"hexBinary\">$output</log><result>0</result>  <duration>2000</duration></run>" https://$jenkinsuser:$jenkinspass@127.0.0.1/jenkins/job/akamai_purge_results/postBuildResult -H'.crumb:c775f3aa15464563456346e'

If I cat that file is all fine and even if I edit it with vi I can't see any problem with it.
Do you guys have any idea how to fix this ?
Could it be a problem with the hex encoding ? ( I tried hex/enc/dec pages with the result of xxd and they look fine)
Thanks.

A: I had the same issue, and stumbled across this: http://blog.markfeeney.com/2010/01/hexbinary-encoding.html
From that page, you can get the encoding you need via this command:

echo "Hello world" | hexdump -v -e '1/1 "%02x"'
48656c6c6f20776f726c640a

An excerpt from the explanation:

So what the hell is that? -v means don't suppress any duplicate data
  in the output, and -e is the format string. hexdump's very particular
  about the formatting of the -e argument; so careful with the quotes.
  The 1/1 means for every 1 byte encountered in the input, apply the
  following formatting pattern 1 time. Despite this sounding like the
  default behaviour in the man page, the 1/1 is not optional. /1 also
  works, but the 1/1 is very very slightly more readable, IMO. The
  "%02x" is just a standard-issue printf-style format code.

So in your case, you would do this (removing 'export' in favor of inline variable)

OUTPUT=`cat msg.out | hexdump -v -e '1/1 "%02x"'` curl -k -X POST -d "<run><log encoding=\"hexBinary\">$OUTPUT</log><result>0</result>  <duration>2000</duration></run>" https://$jenkinsuser:$jenkinspass@127.0.0.1/jenkins/job/akamai_purge_results/postBuildResult -H'.crumb:c775f3aa15464563456346e'


text:
Q: How to determine the parameter in a differential equation with some fixed solution Assuming that I have a ODE system with undetermined parameter
$$x''(t) == y(t) x(t)$$
$$y'(t) == 2 - a x(t)$$
and I have some fixed solution condition
$$x(0)=0$$
$$x(10)=8$$
$$y(10)=3.5$$
Is there a way to determine the parameter a,
I tried to solve this ODEs with both NDSolve and DSolve, but it seems not to work.
 NDSolve[{x''[t] == y[t] x[t], y'[t] == 2 - a x[t], x[0] == 0,
  x[10] == 8, y[10] == 3.5}, {x, y}, t]

the output is

NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`.

can somebody help me? Thank you very much.

A: As a first step:
sol = ParametricNDSolve[{x''[t] == y[t] x[t], y'[t] == 2 - a x[t],
   x[0] == 0, x[10] == 8, y[10] == 3.5}, {x, y}, {t, 0, 10}, {a}]

For example a = 1, you can plot
 {Plot[x[a][t] /. a -> 1 /. sol, {t, 0, 10}],
 Plot[y[a][t] /. a -> 1 /. sol, {t, 0, 10}]}

To determine a, the following plots can help:
Plot[Evaluate[Table[y[a][t] /. sol, {a, -1, 1}]], {t, 0, 10},
 PlotRange -> All, PlotLegends -> Automatic]

Plot[Evaluate[Table[x[a][t] /. sol, {a, -1, 1}]], {t, 0, 10},
 PlotRange -> All, PlotLegends -> Automatic]

If you are playing with the value a then verify the bcs and ics!
You never get y[0]==2.5

A: As an extension to the Answer by Willinski, only limited ranges of a are consistent with the boundary conditions in the Question.  So, for instance,
Plot[x[a][10] /. s, {a, -3, 1}]

generates

along with a number of error messages.  Consistent with this figure,  Willinsi's plots show that a == -1 and a == 0 satisfy the boundary condition x[10] == 8, but a == 1 does not.  Warning: Some details of my figure may be incorrect, because Plot samples the function only at a discrete number of points.
Within the wide range for which the figure above shows x[10] == 8 to be satisfied, it is straightforward to obtain y[0], for instance, as a function of a.
ParametricPlot[{a, y[a][0] /. s}, {a, -2.9, -0.6}, AxesLabel -> {"a", "y[0]"}]

One might hope that a could be computed for a particular value of y[0] using the method described in Boundary Value Problems with Parameters.
ss = NDSolve[{x''[t] == y[t] x[t], y'[t] == 2 - a[t] x[t], a'[t] == 0,
    x[0] == 0, x[10] == 8, y[0] == -24, y[10] == 3.5}, {x, y, a}, t]

Unfortunately, this procedure does not work here, generating error message and an answer that does not satisfy the boundary conditions.


text:
Q: Retrieving first value of css property after changing by jquery or javascript Suppose that there is a div element and we are in 760px width. Current margin-top as css property value will be 60px.
CSS:
@media only screen and (min-width: 360px) {
    div.me {
        margin-top: 30px;
    }
}
@media only screen and (min-width: 760px) {
    div.me {
        margin-top: 60px;
    }
}

Then I change the margin-top by jquery to do more stuff. e.g. 80px.
Jquery
$("div.me").css("margin-top", "80px");

I'm searching a solution for: When the user resized the window, Doing reset the element margin-top to first documnet ready value depend on it's media query.
Suppose the user resized to 400px width. So the element should be reset to margin-top: 30px.
I thought to set custom attributes to all elements to save first values in it.
$(document).ready(function () {
    var m = $("div.me").css("margin-top");
    $("div.me").attr("first-margin-top", m);
});

$(window).resize(function () {
    // some stuff to retrieve first value, not important...
});

But There are many elements like this on the page and many media query values for each.. Here I just talked about one element.
Is there a better way to retrieve and reset the element? Any idea?

A: You set the CSS value inline therefore it trumps your media query.  Either do this with jquery or add the !important tag into your css:
@media only screen and (min-width: 760px) {
    div.me {
        margin-top: 60px !important;
    }
}

$(window).resize(function () {
    if($(window).width < 760){
      $("div.me").css("margin-top", "60px");
    }
});

A: Finally I found the answer of my own question. I just changed inline style to "" or removed it. It makes the browser to set margin-top or other properties (if needed) according to media query values again.
$(window).resize(function () {
    $("div.me").css("margin-top", "");
    //or
    $("div.me").removeAttr("style");
});

JsFiddle


text:
Q: Annotate / plot triangle with slope in PGFplots axis environment In journal papers, I often see annotations in figures depicting triangles with certain slopes to emphasize which slopes the different graphs in the figure (approximately) have.
For example

Is there a macro in LaTeX to make such annotations easily? So, given a relative position in the axis and a slope, a triangle with this slope is plotted at the relative position in the axis?

A: % Mind section '4.17 Custom annotations' of the PGFplots manual Revision 1.12 (2015/01/31).
\documentclass[margin=1cm]{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=newest}

%%% START MACRO %%%
\newcommand{\slopeTriangle}[5]
{
    % #1. Relative offset in x direction.
    % #2. Width in x direction, so xA-xB.
    % #3. Relative offset in y direction.
    % #4. Slope dydx.
    % #5. Plot options.

    \pgfplotsextra
    {
        \pgfkeysgetvalue{/pgfplots/xmin}{\xmin}
        \pgfkeysgetvalue{/pgfplots/xmax}{\xmax}
        \pgfkeysgetvalue{/pgfplots/ymin}{\ymin}
        \pgfkeysgetvalue{/pgfplots/ymax}{\ymax}

        % Calculate auxilliary quantities.
        \pgfmathsetmacro{\xA}{\xmin+(#1+#2)*(\xmax-\xmin)}
        \pgfmathsetmacro{\yA}{\ymin+#3*(\ymax-\ymin)}
        \pgfmathsetmacro{\xB}{\xmin+#1*(\xmax-\xmin)}
        \pgfmathsetmacro{\yB}{\yA}
        \pgfmathsetmacro{\xC}{\xA}
        \pgfmathsetmacro{\yC}{\yA+(\xA-\xB)*#4}

        % Define coordinates for \draw.
        \coordinate (A) at (axis cs:\xA,\yA);
        \coordinate (B) at (axis cs:\xB,\yB);
        \coordinate (C) at (axis cs:\xC,\yC);

        % Draw slope triangle.
        \draw[#5]   (A)-- node[pos=0.5,anchor=north] {1}
                    (B)--
                    (C)-- node[pos=0.5,anchor=west] {#4}
                    cycle;
    }
}
%%% END MACRO %%%

\begin{document}
    \begin{tikzpicture}
        \begin{axis}
        [
            xtick={-0.1,0,1,1.1},
            xlabel=$x$,
            ytick={-0.2,0,2,2.2},
            ylabel style={rotate=-90},
            ylabel=$y$,
            unit vector ratio=2 1 1,
            clip=false
        ]
            \addplot[blue,domain=0:1] {x};
            \addplot[red,domain=0:1] {2*x};

            \slopeTriangle{0.65}{0.1}{0.1}{1}{blue}; % USE OF MACRO.
            \slopeTriangle{0.825}{0.1}{0.1}{2}{red}; % USE OF MACRO.
        \end{axis}
    \end{tikzpicture}
\end{document}

A: A MetaPost solution. It happens that I have already devised such a macro for a course I'm currently teaching, which can be applied to any function curve. Here it is, slightly modified and applied to the parabola y = 4x-x^2. The slopes are computed by MetaPost itself and rounded to an arbitrary number of digits with the help of the numprint package. (Since the slopes are known here to have integer values, I've instructed numprint to round them to the nearest integer: \nprounddigits{0}, but it can be changed at will.)
The MetaPost coding has been inserted in a LuaLaTeX program for better convenience:
\documentclass[border=2mm]{standalone}
\usepackage{luamplib}
  \mplibsetformat{metafun}
  \mplibtextextlabel{enable}
  \mplibnumbersystem{double}
\usepackage{numprint}
  \nprounddigits{0}
\begin{document}
  \begin{mplibcode}
    input mpcolornames;
    % Parameters
    numeric u, v, xmin, xmax, xstep, ymin, ymax;
    u = v = 1cm; xmin = -2; xmax = 6; xstep = 0.1;
    ymin = -6; ymax = 6;
    % Graph definition
    vardef f (expr x) = 4x - x**2 enddef;
    path my_graph;
    my_graph = function(2, "x", "f(x)", xmin, xmax, xstep);
    % Macro creating triangle with slope
    def triangle_with_slope(expr p, A) =
      % Basis and height
      h := 1; a := xpart A; b := a + h;
      % Direction
      pair vdir, B;
      vdir = direction ((a-xmin)/xstep) of p;
      B = A + vdir/xpart(vdir);
      % tangent and triangle
      path tangente, Delta_x, Delta_y, triangle;
      Delta_x = (A -- (xpart B, ypart A)) xyscaled (u, v);
      Delta_y = ((xpart B, ypart A) -- B) xyscaled (u, v);
      tangente = (A -- B) xyscaled (u, v);
      triangle = (A -- (xpart B, ypart A) -- B -- cycle) xyscaled (u, v);
      % The drawing
      drawoptions(withcolor DarkRed);
      fill triangle withcolor Pink; draw tangente;
      drawarrow Delta_x; drawarrow Delta_y;
      drawdot A xyscaled (u, v) withpen pencircle scaled 3bp;
      % Labels
      string slope; slope := decimal(ypart(B-A));
      labeloffset := 2bp;
      label. if ypart(B-A)>0: bot else: top fi ("$1$", point .5 of Delta_x);
      freelabel("$\numprint{" & slope & "}$", point .5 of Delta_y, center triangle);
      drawoptions( );
    enddef;
    beginfig(1);
      % Axes
      drawarrow (xmin*u, 0) -- (xmax*u, 0);
      drawarrow (0, ymin*v) -- (0, ymax*v);
      % Graph and triangles with slope
      for i = -1 upto 4: triangle_with_slope(my_graph, (i, f(i))); endfor
      picture parabola; parabola = image(draw my_graph xyscaled (u, v));
      clip parabola to
        ((xmin, ymin) -- (xmax, ymin) -- (xmax, ymax) -- (xmin, ymax) -- cycle)
          xyscaled (u, v);
      draw parabola;
      % Marks
      labeloffset := 5bp;
      label.bot("$x$", (xmax*u, 0)); label.lft("$y$", (0, ymax*v));
      for i = -2 upto 5: if i<>0: draw (i*u, -3bp) -- (i*u, 3bp); fi endfor
      for j = -6 upto 5: if j<>0: draw (-3bp, j*v) -- (3bp, j*v); fi endfor
      label.bot("$1$", (u, 0)); label.lft("$1$", (0, v));
    endfig;
  \end{mplibcode}
\end{document}

Output:


text:
Q: Asp.Net MVC Antiforgery validation fails when non-null usernames differ...is that reasonable? My question is about the MVC Antiforgery system (described here).
Consider a simple app which posts todos to /Todo/Create. The corresponding action method has the ValidateAntiForgeryToken attribute. Consider the following client workflow:

*

*User A logs on and goes to the page to create a todo, but doesn't do it yet.

*User B (physically on the same computer) opens a new tab in the same browser, logs out of User A's account, logs in as User B. The browser then gets User B's validation cookie.

*Some time later, User A switches back to their original tab and hits 'create' on the todo they were making.

In this scenario, the Antiforgery verification will not pass because the form token was meant for User A, while the validation cookie is for User B.
I'm sure there are valid security reasons for this behavior (e.g. a script on another site that manages to login as malicious user so that the 'todo' data is posted to their account instead), but it doesn't stop the above scenario happening for my legitimate users sometimes.
My questions are:

*

*Is there a 'best practices' way to handle this scenario? Is it usually just a case of showing a custom error, telling them to reload the page and/or login again etc?

*Is there any way to know when the out-of-the-box MVC Antiforgery system runs into this error? It seems to only ever throw the same kind of Exception (HttpAntiForgeryException). Would I need to revert to using/modifying their source?

A: I see two ways of handling it:

*

*Use Javascript callback to the server before hitting a button to detect if the user is still logged in. If not - display him a message. It should be relatively easy to do this. But it requires one additional call, and little bit more time to execute your request.

One solution to avoid callbacks could be using html 5 localStorage (and you can support that on other browsers using modernizr, for example). It is shared between tabs. But I'm not sure if this approach is good. Additional research required.

*Catch HttpAntiForgeryException on the server, check if the user is logged in. If the user is not logged in, display him a message.

Usually approach (1) is used. On banking websites they detect with JavaScript when you logged out in other browser tab.


text:
Q: Finding the total area of three squares The picture below is a recent question posted on twitter. Tim Gowers replied that "Got it, but by a fairly brute-force approach."
One way to do it is denoting the sides of the small, medium, large squares as $a$, $a+b$, and $2a+b$, respectively. Then one immediately has
$$
(a+b)+(2a+b)=5\;.\tag{1}
$$
By the inscribed angle theorem, one can then draw a right triangle with hypotenuse of length $5$. By introducing the height with the hypotenuse as the base, one has by similar triangles
$$
\frac{a+b}{3a+b} = \frac{b}{a+b}\;.\tag{2}
$$
It is fairly easy to combine (1) and (2) to get $a=b=1$, which implies that the total area is
$$
1^2+2^2+3^2=14\;.
$$
My solution above assumes that the arc in the picture is a semicircle, which makes the problem relatively easy.
Questions:

*

*If one drops the semicircle assumption [added: and assuming only an arc of a circle], can one still get the same answer?

*If the answer is "no" to the question above, what range of numbers can one have for the area of the three squares?

A: It is always possible to draw a circular arc through three points, so there is a one-parameter family of solutions if the semicircular requirement is dropped.

*

*At one extreme, the middle-sized square has the same size as the largest square, the small square vanishing. Then there are two squares of side length $2.5$, and the area is $5×2.5=12.5$.

*At the other extreme, the two smaller squares are the same size, their side lengths being half that of the largest square. The two smaller squares are of side $\frac53$ and the larger one of side $\frac{10}3$, for an area of $5×\frac{10}3=\frac{50}3=16.\overline6$.

A: Algebraically speaking, there are two ways to solve Equations $(1)$ and $(2)$ simultaneously. One way is $a = b = 1.$ The other is $a=0,$ $b = \frac52.$
You can reject the second solution since it involves a degenerate square.
When the arc is very slightly less than a semicircle, however, you will again get two solutions, both involving three squares of positive dimensions.
In one case $a$ and $b$ will still be nearly $1$; in the other case $a$ will be nearly $0$ and $b$ will be nearly $\frac52.$
If you continue decreasing the angle of the arc, the smaller solution for $a$ increases and the larger solution decreases.
Eventually there is a minimum angle of the arc for which any solution exists, and there is only one solution for that arc.
To find the minimum angle of the arc, note that $b = \frac12(5 - 3a),$ allowing us to reduce the problem to just one variable.
Let the endpoints of the arc be at $\left(\pm\frac52,0\right)$ so that the midpoint of the chord between them is at the origin.
The the center of the  the lower left vertex of the pink square is at
$\left(-\frac32a,a+b\right) = \left(-\frac32a,\frac12(5 - a)\right).$
The segment between $\left(\frac52,0\right)$ and this vertex has slope
$-(5-a)/(5+3a)$ and midpoint $\left(\frac14(5-3a),\frac14(5-a)\right)$.
The perpendicular bisector of this segment (which must pass through the center of the circle) has equation
$$y = \frac14(5-a) + \frac{5+3a}{5-a}\left(x - \frac14(5-3a)\right),$$
which (after simplification) has $y$-intercept $-\frac52(a - a^2)/(5-a).$
The minimum angle of arc occurs at the minimum value of the $y$-intercept.
That minimum occurs when $a = 5 - 2 \sqrt5.$
For an arc slightly larger than a semicircle, the number of solutions depends on how you interpret the constraints. If the pink square is permitted to be larger than the purple square, and if the arc must pass through the leftmost point where the two squares touch, there are usually two solutions, one where the purple square is just large enough for its upper left vertex to touch the arc, and another where the purple square's upper left vertex is outside the circle but the lower left vertex of the pink square touches the arc.
If the pink square cannot be larger than the purple square, or if the arc must pass through the lower left vertex of the pink square, then there is only one solution for any arc that is more than a semicircle.
To find the range of possible total areas, assuming the pink and purple squares must both have positive side lengths and that they must exactly occupy one side of the blue square as shown in the figure,
the total area is a function of the edge of the pink square,
\begin{align}
 A = f(a) &= a^2 + (a+b)^2 + (2a+b)^2 \\
&= a^2 + \left(\frac12(5-a)\right)^2 + \left(\frac12(5+a)\right)^2 \\
&= \frac12(3a^2 + 25).
\end{align}
Now the range of areas depends on how you specify the problem.
Note that the area is minimized when $a = 0$ (or as $a$ approaches zero, if you do not allow degenerate squares) and is an increasing function of $a$ for $a \geq 0.$
Hence the lower bound of the area will occur at the lower bound of $a.$
For arcs less than a semicircle, if you allow both solutions when two solutions are available, there are arcs yielding all values of $a$ such that $0 < a < 1.$
The lower bound of $a$ is zero, so the lower bound of the area is
$\frac12(3(0^2)+25) = 12.5.$
If you want to restrict the solutions to just one possible solution for each arc, and choose the larger value of $a$ in the case of an arc less than a semicircle, then the minimum area occurs at $a = 5 - 2 \sqrt5,$ and the minimum area is
$10 (8 - 3 \sqrt5) \approx 12.91796.$
If you require the pink square to be no larger than the purple square,
that is, $b \geq 0,$ then the maximum value of $a$ is $\frac53$ and the maximum area is $\frac12\left(3\left(\frac53\right)^2+25\right) = \frac{50}{3} \approx 16.66667.$
If you allow the pink square to be larger than the blue square, then the upper bound of $a$ is $5$ and the upper bound of the area is
$\frac12(3(5^2)+25) = 50.$
This upper bound can be achieved only if you allow the purple square to be degenerate.
If you require the arc to pass through the leftmost point of intersection of the pink and purple squares (rather than the lower left vertex of the pink square), then the arcs that have solutions for $\frac53 < a < 5$ also have solutions for
$1 < a < \frac53,$ so again you have the option to set a rule that selects one of the two possible values. "Smallest value" has the same effect as requiring that the pink square be no larger than the purple square, but "largest value" results in areas between $\frac{50}{3}$ and $50$ being possible but areas between $14$ and $\frac{50}{3}$ not being possible.
If you also choose "largest value" for arcs less than a semicircle but disallow degenerate squares, the range of possible areas is then
$$ \left[10 (8 - 3 \sqrt5), 14\right] \cup \left[\frac{50}{3}, 50\right). $$
But if you choose "smallest value" for all arcs less than a semicircle but disallow degenerate squares, the range of possible areas is
$$ \left(12.5, 10 (8 - 3 \sqrt5)\right] \cup \left[14,\frac{50}{3}\right]. $$
"Largest value" for all arcs with the restriction that the pink square cannot be larger than the purple square results in the range of areas
$$ \left[10 (8 - 3 \sqrt5), \frac{50}{3}\right]. $$
"Largest value" but allowing the pink square to be larger than the purple square, requiring the arc to pass through the lower left vertex of the pink square, and disallowing degenerate squares gives the range of areas
$$ \left[10 (8 - 3 \sqrt5), 50\right). $$
Other reasonable conditions give a range of areas $\left(12.5, \frac{50}{3}\right]$
and yet another set of conditions give $\left(12.5, 50\right].$
In summary, you have several options for how to generalize the problem.
Choose how you think it should be generalized, and the range of possible areas follows.


text:
Q: How to find where the dependencies used in android studio I have a dependencies conflict shows I used com.google.android.gms to 9.0.0
, and I find the com.google.android.gms to 9.0.0 used in dependencies tree, but I haven't used it in my code, Where does the com.google.android.gms to 9.0.0 come from and how can I find where it used in the project? Thanks first.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
implementation 'io.reactivex:rxjava:1.2.0'
implementation 'io.reactivex:rxandroid:1.2.1'

implementation 'com.google.android.gms:play-services-auth:11.6.0'
}

dependencies tree:
releaseUnitTestCompileClasspath - Resolved configuration for compilation for variant: releaseUnitTest
+--- com.google.firebase:firebase-core:9.0.0
|    \--- com.google.firebase:firebase-analytics:9.0.0
|         +--- com.google.android.gms:play-services-basement:9.0.0 -> 11.6.0

releaseUnitTestRuntimeClasspath - Resolved configuration for runtime for variant: releaseUnitTest
+--- com.google.firebase:firebase-core:9.0.0
|    \--- com.google.firebase:firebase-analytics:9.0.0
|         +--- com.google.android.gms:play-services-basement:9.0.0 -> 11.6.0

A: To check project's entire dependency tree invoke gradle dependencies --configuration compile
You have to be using another module which is using this dependency.
you can force specific version with
configurations.all {
  resolutionStrategy {
    force 'com.google.android.gms:play-services-basement:11.6.0'
  }
}
or
compile('com.google.android.gms:play-services-basement:11.6.0') {
    force = true
}


text:
Q: Autowired not wiring bean by Type I have an interface(X) with a method which prints out a statement and the interface has 2 implementations of it X1 and X2 and there is this class Y which has 2 objects of X autowired by type for X1 and X2 with the interface. i.e, like private X x; and private X x2; and when I call x.statement() it prints the default profile statement but when x2.statement() is called it still prints the x.statement() print statement instead of x2.statement().
BTW I am using Spring boot.
public interface HelloWorldService {
    public String getGreeting();
}

@Component
@Profile({ "default", "english" })
public class HelloWorldServiceEnglishImpl implements HelloWorldService {
    @Override
    public String getGreeting() {
        return "Hello World";
    }
}

@Component
@Profile("spanish")
public class HelloWorldServiceSpanishImpl implements HelloWorldService {
    @Override
    public String getGreeting() {
        return "Hola Mundo";
    }
}

-
@Controller
public class GreetingController {

    @Autowired
    private HelloWorldService helloWorldService;

    @Autowired
    private HelloWorldService helloWorldServiceSpanish;

    public void setHelloWorldServiceSpanish(HelloWorldServiceSpanishImpl helloWorldServiceSpanish) {
        this.helloWorldServiceSpanish = helloWorldServiceSpanish;
    }

    public void setHelloWorldService(HelloWorldService helloWorldService) {
        this.helloWorldService = helloWorldService;
    }

    public String sayHello() {
        String greeting = helloWorldService.getGreeting();
        System.out.println(helloWorldServiceSpanish.getGreeting());
        System.out.println(greeting);
        return greeting;
    }
}

A: Firstly, what makes you think one of the Injected beans will be the 'English' bean and one will be the 'Spanish' bean. You inject two instances of the bean defined by the active profile: the 'English' bean. There is no Bean HelloWorldServiceKannadaImpl active for this profile. So both instances are instances of HelloWorldServiceEnglishImpl.
    //this code is not called. The instance variable is auto-wired by field
    //and the auto-wired bean is the only one available: the English one.
    public void setHelloWorldServiceSpanish(HelloWorldServiceSpanishImpl helloWorldServiceSpanish) {
        this.helloWorldServiceSpanish = helloWorldServiceSpanish;
    }

How it should be:
@Controller
public class GreetingController {

    //will be English or Spanish depending on Active profile.
    @Autowired
    private HelloWorldService helloWorldService;

    public void sayHello() {
        String greeting = helloWorldService.getGreeting();
        System.out.println(greeting);

    }
}

In your original code either remove the @Profile from the two beans, or change to spring.profiles.active=english,spanish and it might work as you expect. Although having both kinds of defeats the whole purpose which is to have dynamically injected bean based on the runtime environment.

A: At a time, only one Profile will be ACTIVE depending upon the set value, so you either can be able to print English or Spanish, but NOT both as per your config.
You can look at here for more details.

A: If you want to be able to inject the two beans of the same type at the same time you shouldn't bind them to profiles: you can assign them different names.
@Component("english")
public class HelloWorldServiceEnglishImpl implements HelloWorldService {
    @Override
    public String getGreeting() {
        return "Hello World";
    }
}

@Component("spanish")
public class HelloWorldServiceSpanishImpl implements HelloWorldService {
    @Override
    public String getGreeting() {
        return "Hola Mundo";
    }
}

then you can inject them with the @Named (java api) or @Qualifier (spring api) (if I remember it correctly) annotation
@Named("english") // @Qualifier("english")
@Autowired
private HelloWorldService helloWorldService;

@Named("spanish") // @Qualifier("spanish")
@Autowired
private HelloWorldService helloWorldServiceSpanish;


text:
Q: XPath: get value using relative path (PHP, Symfony, DOMCrawler) error I'm writing a test to test my understanding of XPath with Symfony's DomCrawler:
$crawler = new Crawler();
$crawler->add('<foo><foo>bar</foo></foo>');
$crawlerWithNodes = $crawler->filterXPath('/foo/foo');

$this->assertEquals('bar', $crawlerWithNodes->text());

But the above results in:

InvalidArgumentException: The current node list is empty.
On line:
$this->assertEquals('bar', $crawlerWithNodes->text());

What am I doing wrong?

A: You need to load the content as DOMDocument instead of simple string (is interpreted as HTML).
You also need to add the _root prefix in the xpath string if you want to find an absolute path in the structure. See the Symfony\Component\DomCrawler\Tests\CrawlerTest cass for further example (testFilterXpathComplexQueries method)
Consider the following test method:
    public function testCrawlerAsHtml()
    {
        $crawler = new Crawler();
        $crawler->add('<foo><foo>bar</foo></foo>');
        //die(var_dump($crawler->html()));
        $crawlerWithNodes = $crawler->filterXPath('/_root/html/body/foo/foo');

        $this->assertEquals('bar', $crawlerWithNodes->text());
    }

    public function testCrawlerAsDomElement()
    {
        $dom = new \DOMDocument();
        $dom->loadXML('<foo><foo>bar</foo></foo>');
        $crawler = new Crawler();
        $crawler->add($dom);
//        die(var_dump($crawler->html()));
        $crawlerWithNodes = $crawler->filterXPath('/_root/foo/foo');

        $this->assertEquals('bar', $crawlerWithNodes->text());
    }

Hope this help


text:
Q: How to pull a series of commits in git one at a time? I have a series of commits in a fork that I want to apply or reject one at a time to my fork.  Should I use git cherry-pick for this?

A: I'd use an interactive rebase for this:
git rebase -i master fork-branch

When git asks what you want to do with each of the commits, tell it edit for all of them (search and replace pick -> edit). Save and quit, and the interactive rebase will go through the commits, stopping at each to let you do your thing. Do your testing, decide if you want to keep it. If you do, just run git rebase --continue to move on to the next. If you don't, run git reset --hard HEAD^ to reset to the previous commit, throwing away the one you don't want, then move on to git rebase --continue.
If there are commits you know right away you don't want, you can just remove them from the list instead of changing pick to edit. And of course, if I've completely misunderstood, and you don't need to do any testing, then you can pretty much disregard the previous paragraph, and do it all by selectively removing lines.

A: Yes. git cherry-pick COMMIT_SHA will allow you to grab a specific commit. You don't need to reject commits, though; just don't cherry pick them.


text:
Q: asp.net After a Server.Transfer how do you get the path of the current page? To get the url of the current page, I usually do something like this:
string path = Request.Path;

If I do this after a Server.Transfer then I get the path of the page where the transfer was done. How can I get it for the current page?
For example:
On Page1.aspx  I do Server.Transfer ("Page2.aspx")
On Page2.aspx  Request.Path returns /Page1.aspx and not /Page2.aspx
I would like to get /Page2.aspx. How can I get it?

A: You're looking for the Request.CurrentExecutionFilePath property.

A: AppRelativeVirtualPath (http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.apprelativevirtualpath.aspx) seems to do the trick.

A: When you use Server.Transfer, despite the URL on browser doesn't change, the Request references URL does. So, you may use the UrlReferrer property's Request.
UrlReferrer gets information about the URL of the client's previous request that linked to the current URL.
For instance
string myContextBrowserPath = Context.Request.UrlReferrer.AbsolutePath


text:
Q: Nethack grinding for level 14 I decided to get into NetHack for the "junethack" competition. I'm loving it so far. I've finally made it safely through the early part of the dungeons. I've finished Sokoban and gone through Mine's End. I made it down to my quest. I'm level 12 and have been grinding forever to get my level up to 14 to go on the quest.
I've descended 10 dungeon levels past my quest and back up again. I've identified my potion of gain level, but searching for two of these will probably take longer than just killing stuff. I've run into no wraiths.
Are there any tips for making this part go faster? Do people usually skip the quest and come back later? I imagine this will take hours to just wander around killing enemies until I get up to 14. I'm a dwarvish valkyrie if that matters. I'm also playing the Nethack4 variant if that matters.

A: Levelling up through experience, as you're learning, gets ridiculously more difficult as you go past 10 or so. Your better options include: polypiling potions for gain level, alchemy (which takes a while), reverse-genociding wraiths (requires a cursed scroll of genocide and an Elbereth-marked square), and dancing with an incubus.
The incubus is probably safest and easiest. As long as you have a unicorn horn, you'll be able to repair most possible negative effects easily enough. You'll probably run out of June before you grind experience the slow way--you need to find a shortcut.


text:
Q: Multiple-level nested imports in Python I am currently working in the following project, and running into some difficulty with imports. I previously came from a Ruby background before Python, so I suspect I'm just missing something.
-src
--project
---actions
----some .py files
---config
----some .py files
---db
----some .py files
-tests
--some .py files
-run.py

Some of the actions I'd like to do are:

*

*import src/project/config/file.py from run.py

*import between second level folder in project (ie. file in actions imports something from config)

*import any file into a test

Would anyone have any advice on how to accomplish this?

A: So it's quite easy to reference something going deeper into the directory . For example, from run.py, you would be able to use something such as:
    from src.project.config.file import foo

It's easy to access something in the same directory as well, say you're in src/file1.py  trying to access src/file2.py, this would just be:
    from file2 import foo

This works too. However if you were trying to import upward say from file.py to run.py and tried running something like this:
    from ... import run.foo

You would get the following error:
    ValueError: attempted relative import beyond top-level package

The problem is that Python is assuming that your top-level package is wherever the file being run is located. That's why you can import everything on the same level and deeper but can't get at anything above.
An easy hack to get past this is to just append the path to your file to your sys.path so:
    import sys
    sys.append('path/to/run')
    from run import foo

So that's the answer to you question.
Based on the way your project is setup though it seems like you want to make a module and that's a bit more hands on, I suggest reading the documentation it's pretty good.


text:
Q: Missing Resource in EL implementation: ???propertyNotReadable? I'm using JSF2.1.  I don't have any jars in my WEF-INF folder.  My classpath is only referencing JSF2.1 and Java EE.  I'm using JDK1.7.
I'm getting "Missing Resource in EL implementation: ???propertyNotReadable???" when trying to test out processing GET parameters using f:event type="preRenderComponent".  Right now I'm just trying to do a simple test.  My page has a lot on it, so I'm only showing the important parts here.  The part I added is the <f:metadata> block.  When I remove that block, the error goes away.
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core">
<f:metadata>
   <f:viewParam name="team" value="#{appBean.team}" />
   <f:event type="preRenderComponent" listener="#{appBean.init}" />
</f:metadata>

In my backing bean, I have:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class AppBean implements Serializable{
    private static final long serialVersionUID = 1778234L;
    private Long team;

    public AppBean(){
    }

    public void init(){
        if (team != null) System.out.println(team);
        else System.out.println("team undefined");
    }

    public void setTeam(Long team){
       this.team = team;
    }
}

And the way I'm testing this out is to go to my url and add ?team=123 to the end.  I'm expecting System.out to print 123.  Any ideas on how to fix this error?

A: I figuered it out... I forgot to include:
  public Long getTeam(){
     return team;
  }


text:
Q: how to display other data from table when mouse over i need to fetch and display data using a table (shown on view below) from database when mouse-over and disappear when mouse is off.
here is the model
public function teacher_with_subject(){
    $this->db->select('*')
    ->from('teacher AS t')
    ->join('teacher_subject ts','t.computer_number=ts.computer_number', 'left')
    ->where('t.date_of_termination','0000-00-00')
    ->where('ts.date_of_end','0000-00-00');
    $query = $this->db->get();  return $query->result_array();
}

controller
$located=$this->select_model->teacher_with_subject();

view:-
if (count($located) > 0) {
    echo '
';

    foreach($located as $locate){
        echo "
".$locate['computer_number']."	".$locate['name']."	<"
";
    }
    echo '
';
}

i want to display postal address and email address when mouse is over name

A: Use the title attribute:
echo "
";
echo "".$locate['computer_number']."	";
echo "".$locate['name']."	";
echo "	";
echo "
";


text:
Q: Can the array's default pointer be changed in anyways? #include<stdio.h>

void change(int (*arr)[10]){
  // manipulate
}

int main(){
  int arrM[10]={1,2,3,4,5,6,7,8,9,0};
  change(&arrM)
}

I am aware that the arrM is a constant pointer and cannot be changed or assigned and also that it cannot be passed as a pointer to pointer like **argv since it degrades to a pointer from an array and not a pointer to pointer. But my question is "Is this the way the design goes so as to protect the array's initial memory from not getting overwritten(if yes the how?) or is there a mechanism that can get into the //manipulate region that can change the constant pointer arrM's value"

A:
I am aware that the arrM is a constant pointer

No, an array is not a constant pointer. An array is a different type. There are cases where an array decays or is implicitly converted to a pointer to its first element, e.g. when an array is passed to a function, but this does not mean an array is a constant pointer.

Is this the way the design goes so as to protect the array's initial
  memory from not getting overwritten(if yes the how?) or is there a
  mechanism that can get into the //manipulate region that can change
  the constant pointer arrM's value

A variable is a location in memory which can store a value and is referenced by an indentifier which is the variable's name. When a variable is defined, space is allocated for it (during run-time, of course) and the indentifier is made to refer to the location, i.e., the identifier is bound to that location. The identifier will always refer to that location throughout its lifetime.  You cannot rebind the indentifier to a different memory location. You can change the value of the variable, i.e., value stored in the location referenced by the variable's name but that's a different matter. This is true of any variable type, not just an array.
What this means is any variable is allocated space either on the stack (automatic storage allocation) or in text or data segment (static storage allocation) of the program's memory space. You cannot bind the variable to a different address later.

A:
I am aware that the arrM is a constant pointer and cannot be changed
  or assigned

An array name (arrM), should not be considered as a pointer, and thinking of it as a const type is going too far.
This post, pretty much answers your question.

Is this the way the design goes so as to protect the array's initial
  memory from not getting overwritten(if yes the how?) or is there a
  mechanism that can get into the //manipulate region that can change
  the constant pointer arrM's value

The array's initial memory is not being "protected". You can declare a pointer, to point to the array's first element, and use pointer arithmetic to "overwrite" the array.

A: Don't think of arrM as a pointer.  It helps instead to think of it as a constant integer-like thing whose value is the compiler-assigned address of the array.  It makes no more sense to take the address of arrM than to take the address of the constant 5.  Likewise, it makes no more sense to change the value of arrM than it would to change the value of 5.


text:
Q: Dagger 2: How to inject an object created within a @Provides method? I've got this:
Bike.java
public class Bike {
    String serial;

    @Inject
    Wheels wheels;

    public Bike(String serial) {
        this.serial = serial;
    }
}

BikeModule.java
@Module
public class BikeModule {
    @Provides
    public Bike provideBike() {
        return new Bike("BIK-001");
    }

    @Provides
    public Wheels provideWheels() {
        return new Wheels("WLS-027");
    }
}

BikeComponent.java
@Component(modules = BikeModule.class)
public interface BikeComponent {
    Bike bike();
}

Now here's the problem: when I call BikeComponent.bike(), I get a bike with the serial BIK-001, as intended, but the wheels are not injected. However, if I annotate the Bike constructor with @Inject and remove the BikeModule.provideBike() method, the wheels do get injected. So the problem seems to be about injecting an object created within a @Provides method, instead of created by Dagger itself.
Is there a way to tell Dagger to inject a provided object?

A: Rewrite like this:
public class Bike {

    private final String serial;
    private final Wheels wheels;

    @Inject
    public Bike(String serial, Wheels wheels) {
        this.serial = serial;
        this.wheels = wheels;
    }
}

@Module
public final class BikeModule {

    @Provides
    public static Bike provideBike(Wheels wheels) {
        return new Bike("BIK-001", wheels);
    }

    @Provides
    public static Wheels provideWheels() {
        return new Wheels("WLS-027");
    }
}


text:
Q: How can I distinguish between different BadRequest errors with Amazon S3? Amazon S3 has a large number of reasons why it will return an HTTP 400 Bad Request error.  Most relevant is the fact that some of these errors are from the unreliability of the internet, such as a request timeout. Another reason it might be returned is if the bucket or key name is invalid.
I am attempting to upload files to S3 with key names supplied by a customer-controlled key name.  I need to be able to distinguish between a transient 400 error such as a timeout and a bad key/bucket name error that will not be transient. A transient error will indicate we should retry that upload, while a non-transient error means we should cease trying to upload that file.
However, I do not know how to distinguish between these two errors! If it matters, I am attempting to use the JetS3t API to perfom these uploads. How can I distinguish between a bad key/bucket name error and anything else with a 400 error code?

A: Read the response body.
From the page you cited:

The body o[f] the response also contains information about the error.

Parse the response body that accompanies the http error code.  An explanation of the error is almost always spelled out in XML in the response body.
Example nonsense request (nothing edited here, this is exactly what I used for a GET request to generate this error):
http://example-bucket.s3.amazonaws.com/?AWSAccessKeyId=AKIAEXAMPLEEXAMPLE&Signature=bogus&Expires=1500000000

Response:
<Error>
 InvalidAccessKeyId
  <Message>
   The AWS Access Key Id you provided does not exist in our records.
  </Message>
 <AWSAccessKeyId>AKIAEXAMPLEEXAMPLE</AWSAccessKeyId>
 <RequestId>...</RequestId>
 <HostId>...</HostId>
</Error>

You'll find a pretty close correlation between this content and the list of possible errors.
Now, technically, that's a 403 not a 400, it's just the first idea I came up with for an easily handcrafted nonsense request to generate an error, but any S3 error should generate a comparable response.


text:
Q: How is the original num2 updated in this fibonacci instance? I've been given an instance of code and expected of to explain it.
    function fib(num1, num2, stop) {
      var num3 = num1 + num2;
      console.log(num3);
      if(stop === 0) {
          return;
      }
      fib(num2, num3, stop - 1);
    }

fib(0, 1, 6)

While It seems I get all of it, I cannot seem to fathom how does the parameter num2 keeps being updated to the next number.

*

*In this instance of code we're suppose to log the numbers according to the fibonacci sequence up until and including the 6th index.

Thanks!
P.S. This is my first time posting on stackoverflow, if anyone has any tips on how to better this post for example. I'd appreciate it.

A:
how does the parameter num2 keeps being updated to the next number.

Actually num2 is never updated. However, every recursive execution of fib introduces a new variable with that same name. And it gets its value from the caller. Once it has that value, it never changes. But you get as many variables with that name num2 as there are calls to fib.
Now note how the recursive call is made:
fib(num2, num3, stop - 1);

And then check how these arguments are received:
function fib(num1, num2, stop) {

Note that the num3 of the caller, becomes the initial value of num2 of the called. This gives the impression that num2 changes throughout this program, but it is actually a new variable each time a "change" occurs, and the initial value is always what num3 has in the calling execution context.
Visualisation
Each "box" in the below diagram represents a single execution context of fib. It is a container for a set of local variables. These remain untouched while yet a deeper call is made to a function, because that will result in yet another context (container) for a new set of variables:
fib(0, 1, 6)
+-------- new execution context ---------------------------------------------+
| // num1 = 0, num2 = 1, stop = 6                                            |
| var num3 = num1 + num2; // = 1                                             |
| fib(num2, num3, stop - 1);                                                 |
|     +------ new execution context ----------------------------------------+|
|     | // num1 = 1, num2 = 1, stop = 5                                     ||
|     | var num3 = num1 + num2; // = 2                                      ||
|     | fib(num2, num3, stop - 1);                                          ||
|     |     +------ new execution context ---------------------------------+||
|     |     | // num1 = 1, num2 = 2, stop = 4                              |||
|     |     | var num3 = num1 + num2; // = 3                               |||
|     |     | fib(num2, num3, stop - 1);                                   |||
|     |     |     +------ new execution context --------------------------+|||
|     |     |     | // num1 = 2, num2 = 3, stop = 3                       ||||
|     |     |     | var num3 = num1 + num2; // = 5                        ||||
|     |     |     | fib(num2, num3, stop - 1);                            ||||
|     |     |     |     +------ new execution context -------------------+||||
|     |     |     |     | // num1 = 3, num2 = 5, stop = 2                |||||
|     |     |     |     | var num3 = num1 + num2; // = 8                 |||||
|     |     |     |     | fib(num2, num3, stop - 1);                     |||||
|     |     |     |     |     +------ new execution context ------------+|||||
|     |     |     |     |     | // num1 = 5, num2 = 8, stop = 1         ||||||
|     |     |     |     |     | var num3 = num1 + num2; // = 13         ||||||
|     |     |     |     |     | fib(num2, num3, stop - 1);              ||||||
|     |     |     |     |     |     +------ new execution context -----+||||||
|     |     |     |     |     |     | // num1 = 8, num2 = 13, stop = 0 |||||||
|     |     |     |     |     |     +----------------------------------+||||||
|     |     |     |     |     +-----------------------------------------+|||||
|     |     |     |     +------------------------------------------------+||||
|     |     |     +-------------------------------------------------------+|||
|     |     +--------------------------------------------------------------+||
|     +---------------------------------------------------------------------+|
+----------------------------------------------------------------------------+


text:
Q: Is it possible to format a NumberField in a page layout? I'm developing a SharePoint publishing site and setting up its content types and page layouts. I need to display the value for a Year field with type Number. The markup currently is:
<SharePointWebControls:NumberField FieldName="Year" runat="server" id="Year" />

The problem with the default behaviour is that it shows each number with a comma, e.g. "2,009" instead of "2009". Is there a way I can set some sort of String.Format syntax on the field to make it display correctly?
I tried creating a new rendering template which looks like this:
<SharePoint:RenderingTemplate ID="YearNumberField" runat="server">
  <Template>
    <SharePoint:FormField ID="TextField" runat="server"/>
  </Template>
</SharePoint:RenderingTemplate>

... but there doesn't appear to be any 'Format' property on the FormField object.
Thanks for any help.
Update:
I tried wrapping the SharePoint:FormField tag inside SharePoint:FormattedString. Unfortunately the field was not formatted, same results as this question.

A: The issue is that the rendering template must use FormField. This always renders the value in the format: 1,989 . To resolve this the rendered text needs to be trapped and altered to get the desired output. Here are two approaches to resolving this:
1. Write a custom control inherited from NumberField
The RenderFieldForDisplay and RenderFieldForInput methods can be overridden to provide the desired output. Additional properties can be added to the control to describe additional behaviour.
Pros: No changes to rendering templates required.
2. Write a custom control for use in the rendering template
A control that (for example) uses regular expressions to alter text can wrap around the FormField control.
<SharePoint:RenderingTemplate ID="YearField" runat="server">
    <Template>
        <RX:RegexManipulatorControl runat="server"
                Mode="Replace"
                Expression=","
                Replacement="">
            <SharePoint:FormField runat="server"/>
        </RX:RegexManipulatorControl>
    </Template>
</SharePoint:RenderingTemplate>

Pros: Generic solution can be used for any type of field.

A: from Just Another SharePoint Blog

Open the list view in SharePoint
  Designer.
Right click on the data view web part.
  (the list)
Select Convert to XSLT Data View
Click on the number field you would
  like to format
A > will appear showing Data Field,
  Format As
Click on the link below Format As -
  Number formatting options
Under Options deselect Use 1000
  separator
Click OK
Save your changes and hit F12 to
  preview


text:
Q: Javascript change input value In my website I have a box that is not displayed. When the user types his username and password, if they are correct, the box must be displayed. Here you see the HTML code:

Test.

<input type="text" id="user"/>

<input type="text" id="password" value="a"/>

<input type="button" value="Log in" onclick="login();">

And here the javascript function:
function login() {
    var a = document.getElementById('password').value;
    var b = document.getElementById('user').value;
    if ((a == 'qwe') && (b == 'rty')) { //the problem is not here
     document.getElementById('password').style.display="none";
    }
    else
    {
     alert('You are not logged in.');
    }
}

When I click the button Log in looks like the function login(); is not called because anything happen. Do you know why?

A: if (a == 'qwe') && (b == 'rty') //Wrong

Enclose the condition like if( condition )
 if ((a == 'qwe') && (b == 'rty') ) //Corect

As @Frédéric Hamidi suggested, there is no need of inner parentheses.
Simple like this
if (a == 'qwe' && b == 'rty' )

Demo here

A: use proper if
if (a == 'qwe' && b == 'rty' )

fiddle


text:
Q: Stop command without pressing Ctrl+C (No luck using trap function) I am trying to make a script that runs 2 commands in a for loop as can be seen below:
#!/bin/bash
for ((i=0; i<2; i++)); do
    sudo ./bin/llc test-rx -c 184
    sleep 5
    trap ctrl_c INT
function ctrl_c()
{
  echo "Trap: CTRL+C received, exit"
  exit
}
    sudo ./bin/llc rxphylast
done

The 1st command (test-rx) continues to run as its is executed and it is stopped by pressing Ctrl+C. I want to stop this command in bash script so I used trap function as can be seen in the code. But when I execute the script, 1st command is running until I press Ctrl+C and then 2nd command (rxphylast) executes. So, in my case trap function is not working. Any advice on how to stop the 1st command in the script?

A: *

*Define the function and set the trap outside of the loop

*Define the function before you use it.

Try:
#!/bin/bash
function ctrl_c() (

{
  echo "Trap: CTRL+C received, exit"
  exit
}

trap ctrl_c INT

for ((i=0; i<2; i++)); do
    sudo ./bin/llc test-rx -c 184
    sleep 5

    sudo ./bin/llc rxphylast
done

Another example, not using ./bin/llc:
#!/bin/bash

function ctrl_c()
{
  echo "Trap: CTRL+C received, exit"
  exit
}

trap ctrl_c INT

for ((i=0; i<2; i++)); do
    echo first program
    sudo find / -type f > /dev/null
    sleep 5

    echo second program
    sudo find / -type f > /dev/null
done

Press Ctrl-C while the first find is running and it will print the "Trap: CTRL+C received, exit" message and exit immediately.  Press Ctrl-C while the second find is running and it will do the same.  This works the same whether sudo is used with the find commands or not - I only put that in there to make sure it wasn't sudo trapping and eating the Ctrl-C.
This is what happens when you run it and press Ctrl-C while the first find is running:
$ ./trap.sh
first program
^CTrap: CTRL+C received, exit
$


text:
Q: How to turn on the torch/flashlight with GooglePlay Services Vision API Xamarin Android I have been trying to implement the flashlight/torch feature of the camera using the GooglePlay Services Vision API (using Nuget from Visual Studio) for the past few days without success. I have noticed that there is a GitHub implementation of this API which has such functionality but that is only available to Java users.
I was wondering if there is anything related to C# Xamarin users.
The Camera object is not made available on this API therefore I am not able to alter the Camera parameters needed to activate the flashlight.
I would like to be sure if that functionality is not available so I don't waste more time over this. It just might be the case that the Xamarin developers have not attended to this functionality and they might in a near future.

UPDATE
https://github.com/googlesamples/android-vision/blob/master/visionSamples/barcode-reader/app/src/main/java/com/google/android/gms/samples/vision/barcodereader/BarcodeCaptureActivity.java
In there you can see that on line 214 we have such method call:
mCameraSource = builder.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null).build();

SetFlashMode is not a method of the CameraSource in Nuget, but it is on the GitHub (open source version).

A: Xamarin Vision Library Didn't expose the method to set Flash Mode.
WorkAround.
Using Reflection. You can get the Camera Object from CameraSouce and add the flash parameter then set the updated parameters to the camera.
This should be called after surfaceview has been created
Code
  public Camera getCameraObject (CameraSource _camSource)
        {
            Field [] cFields = _camSource.Class.GetDeclaredFields ();
            Camera _cam = null;
            try {
                foreach (Field item in cFields) {
                    if (item.Name.Equals ("zzbNN")) {
                        Console.WriteLine ("Camera");
                        item.Accessible = true;
                        try {
                            _cam = (Camera)item.Get (_camSource);
                        } catch (Exception e) {
                            Logger.LogException (this, e);
                        }
                    }
                }
            } catch (Exception e) {
                Logger.LogException (this, e);
            }
            return _cam;
        }

        public void setFlash (bool isEnable)
        {
            try {
                isTorch = !isEnable;
                var _cam = getCameraObject (mCameraSource);
                if (_cam == null) return;
                var _pareMeters = _cam.GetParameters ();
                var _listOfSuppo = _cam.GetParameters ().SupportedFlashModes;
                _pareMeters.FlashMode = isTorch ? _listOfSuppo [0] : _listOfSuppo [3];
                _cam.SetParameters (_pareMeters);
            } catch (Exception e) {
                Logger.LogException (this, e);
            }
        }

A: Basically, anything you can do with Android can be done with Xamarin.Android. All the underlying APIs area available.
Since you have existing Java code, you can create a binding project that enables you to call the code from your Xamarin.Android project. Here's a good article on how to get started: Binding a Java Library
On the other hand, I don't think you need a library to do what you want to. If you only want torch/flashlight functionality, you just need to adapt the Java code from this answer to work in Xamarin.Android with C#.


text:
Q: How do you print only the pages with figures on them? A friend of mine recently completed his doctoral thesis. In order to save on toner, he printed the pages with figures on a color printer, but printed everything else on a black and white printer. In order to do this, he went through the document and printed out each page with a figure, by hand.
While he was careful, it seems extremely error prone, and I'd like to know if there is a way to generate a document containing only the pages with figures on them while retaining the formatting and pagination of the full document?

A: It might be easiest to do this sort of thing with the pdfpages package. It's not automatic, but you wouldn't have to print each page individually, and you could generate the list of pages from the list of figures.
Here's an example:
\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf[pages={3-6, 17, 28, 29-31}]{yourdocument}
\end{document}

One thing to bear in mind when using this method is that the page numbers correspond to the number of the physical pages in yourdocument.pdf, not the page numbers in your document. This means that if you have n \frontmatter pages (which in a thesis, you would) then all of the relevant page numbers will be off by n. The easiest way around this is to simply delete all the frontmatter pages from the pdf document in order to generate the extracted page document, so that the first physical page corresponds to page 1 of the thesis.
Automating
Theoretically, it would be possible to automate the process slightly, although for something that is being done once or twice it is probably not worth it.  For those who like the challenge, here are some ideas (based on the discussion in the comments).

*

*Modify the \addtocontents code for figures to also write out a list of page numbers for subsequent use in the pdfpages document. This seems the most work for little gain in actual automation.

*Use your favourite scripting language to to extract the lof entries from the .aux file, and parse out the page numbers. The script could then generate the entire pdfpages document.  This would probably be the best route if you really needed to automate the process.

*You're only doing this once or twice; do 2 above by hand and spend the rest of your time enjoying a beer.

A: I gave a shot at this and came up with a solution. Probably not the best that can be made, but it works. The solution is based on @Alan Munn's answer.
It's a shell script that should work on all Unix systems with pdfLaTeX and pdfpages installed. You use it by giving it the file name of the TeX file (no .tex ending!) and the offset in pages (caused by front matter) as the second argument:
./only-figures.sh document 1

First we load the .aux and prepare to store it in a variable.
STR=$(cat $1.aux |\

We only care about the lines with figures.
 grep figure |\

And of these lines we only care about the number referring to unique pages.
 sed 's/.*}}{\([1-9]*\)}}/\1/' | uniq |\

We then add the offset to the page numbers.
 awk '{print $0+'$2'}' |\

And finally pack them all up in a comma-separated list.
 sed ':a;N;$!ba;s/\n/,/g')

A template file is used for the new temporary document.
cat template.tex | sed s/@@@/$STR/ > only-figures-tmp.tex

The template looks as following:
\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf[pages={@@@}]{document}
\end{document}

We call pdfLaTeX on the temporary file, move the new PDF and cleans up.
pdflatex only-figures-tmp
mv -f only-figures-tmp.pdf $1-only-figures.pdf
rm only-figures-tmp.*

The whole thing can also be found in this Gist


text:
Q: Keeping a route alive in Flutter I have a flutter app where can see several cards. These cards are clickable, and will show a InAppWebView with a custom made viewer, which exists on the website I link to.
The loading of this InAppWebView is pretty taxing on the app however, and I would like to pre-load this as much as possible.
It is kinda hard to give a lot of details, since this is job-related and thus private information, so I can't be too specific. I am also the only one working with Flutter here, so no advice can be expected from colleagues.
I am hoping to reduce the loading times of the InAppWebView by having it opened in the background already, and then just swapping to the correct route instead of initializing it from scratch. The problem here is that the URL will change, but that can be handled inside the view instead of creating an entirely new InAppWebView.
In short:
How do I create a widget/route in the background of my Flutter application, and swap to it when necessary?

A: Use IndexedStack for that.
Create a List of widgets you want to swap (and keep its state)
 final viewRoutes = const <Widget>[
    Screen1(),
    Screen2(),
    Screen3(),
 ];

Then use the IndexedStack to swap them
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
         index: 0, // <--- change this depending on the page
      ),
    );
  }

A: Maybe you can use a Stack and a Visibility widgets ? like this:
bool _isWebPageVisible = false;

Stack(
  children: <Widget>[
    MainWidget(),
    Visibility(
      visible: _isWebPageVisible,
      child: WebPageWidget()
  ]
)

And you could change _isWebPageVisible whenever needed. When visible, the WebPageWidget will appear above the MainWidget.


text:
Q: Exercise from Dixon's book on structure linear groups On page 99 of "Structure of linear groups" by John D Dixon there's an exercise right after
Theorem: Let $G$ be a finite non-modular linear group of degree $n$. Then $G$ has a normal abelian subgroup $A$ with index $[G:A]\leq (49n)^{n^2}$.
Exercise 1: Let $G$ be a finite non-modular linear group of degree $n$. Show that if $G$ has an abelian subgroup $B\supseteq Z(G)$ with $[B:Z(G)]>(4\pi)^n$, then $G$ has a normal abelian subgroup $A$ with $B\supseteq A\supsetneq Z(G)$. [Hint: We may suppose $G$ consists of unitary matrices, and the elements of $B$ are diagonal.]
I have absolutely no idea what to do here. Neither how to apply the theorem nor how to get to $(4\pi)^n$. I don't know how to make any use of the hint either. Any help would be appreciated.


text:
Q: ScheduledTimer selector. Objective-c or Swift? I am in Xcode 10.3. I try to use the provided Timer.scheduledTimer. When it comes to the selector, Xcode suggests that I should use @objc func. Is there a better way to do that? perhaps with Swift?
func startTimer() {
    countdownTimer = Timer.scheduledTimer( timeInterval: 1,
                                           target: self,
                                           selector: #selector(updateTime),
                                           userInfo: nil, repeats: true)
}

@objc func updateTime() {

    //do something

}

(Here explains very well what is a selector: Timer, #selector explanation
My question is if it is possible now (August 2019) to do that in a better way
Here it explains how to use Timer:
How can I use Timer (formerly NSTimer) in Swift? But this question is older than 5 years. If I understand, In that moment #selector(updateTime) was the best solution. My question is if now, August 2019, there is a new simpler way without @objc )