text:
Q: Extract String Beetwen 2 Character in Excel I want the string in column A to be extracted to each column, where the position of the string taken between "d /" and "/ search".
Based on the formula I made, it only extracts it in one column.

A: In Cell B2, you already have the formula as:
=MID(A2,FIND("d/",A2)+2,FIND("/search",A2)-FIND("d/",A2)-2)

You are really close, you only needed to add the starting position as an argument for the following formulas, so it will start searching after the previously found string as below.
In C2 add the following:
=MID(A2,FIND("d/",A2,FIND(B2,A2))+2,FIND("/search",A2)-FIND("d/",A2)-2)

And in D2 the following:
=MID(A2,FIND("d/",A2,FIND(C2,A2))+2,FIND("/search",A2)-FIND("d/",A2)-2)

A: If you have Office 365 Excel it can be done with one formula:
=CONCAT(IF(TRIM(MID(SUBSTITUTE(SUBSTITUTE($A2,"d/","|/",COLUMN(A:A)),"/",REPT(" ",99)),ROW($1:$100)*99,99))="|",TRIM(MID(SUBSTITUTE($A2,"/",REPT(" ",99)),ROW($2:$101)*99,99)),""))

this is an array formula, it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

A: Well, I'm certainly not going to retype all the sample data you left in an image for everyone to retype but try this in B2 then drag right and down,

A: Another way, Try this.
Apply the below formula in Cell B2
=TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," ")," ",REPT(" ",LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," ")))), (2-1)*LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," "))+1, LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," "))))&", "&TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," ")," ",REPT(" ",LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," ")))), (4-1)*LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," "))+1, LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," "))))&", "&TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," ")," ",REPT(" ",LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," ")))), (6-1)*LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," "))+1, LEN(SUBSTITUTE(SUBSTITUTE(A2,"d/"," "),"/search?"," "))))


text:
Q: Using preferences in Firefox How do I access user preferences in Firefox? I have the following code:
var control = document.getElementById(control_id);
if (control) {
    control.setAttribute('color', nsPreferences.copyUnicharPref(prefstr, default_val));
}

But when I run this, I get the following:
Error: nsPreferences is not defined
Source file: chrome://backgroundtoggle/content/options.xul
Line: 9

I'm having trouble wading through the Mozilla documentation. How do I make this do what I want?

A: It looks like you need to include nsUserSettings.js in your .xul file:
<script type="application/x-javascript" src="chrome://global/content/nsUserSettings.js" />

This is where nsUserPreferences is defined.
See here for an example options.xul file. The script tag should be the first child element of prefwindow to ensure it gets loaded before your own code does.

Additional Information
This looks like a decent tutorial on how to write Firefox extensions. It seems to do a good job of consolidating all the relevant information on mozilla.org in one place, and contains links to mozilla.org when you need more details on a topic being covered. I do wish the navigation was a little better, but what can you do? Use the navigation pane on the left-hand side and click Tutorial to get started. You have to move through each section using the navigation pane, which took me few seconds to figure out, as I was looking for 'Next' and 'Previous' links on the page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is the max. number of intersections of k lines in $\mathbb{R}^2$ = $\binom{k}{2}$? Why is the maximum number of intersections of k lines in $\mathbb{R}^2$ = $\binom{k}{2}$?

A: Each pair of line can intersect each other once (as far as they aren't the same line) and there is $\binom{k}{2}$ pairs among k lines.

A: Consider two lines : the max number of intersections is 1.
Then the third line will intersect at max the two others lines so the max number of intersection is 1+2=3.
Then the fourth line will intersect at max the three others lines so the max number of intersection is 1+2+3=6.
By induction, it is therefore easy to show that the maximum number of intersections is $$\sum_{i=1}^{k-1} i = \frac{(k-1)k}{2} = \binom{k}{2}$$


text:
Q: How to check if a string matches with regex in Thymeleaf? I'm writing a training application to collect books on the following stack: Java/Spring/Thymeleaf.
I should input some values about books such as a book title and a book size (a number of pages).
Validation fields in dto class Book:
@NotEmpty
private String title;
@NotNull
@Digits(integer = 4, fraction = 0)
private Integer size;

The view file contains:

    <input type="text" placeholder="book_title" th:field="*{title}">

field title must not be empty

    <input type="text" placeholder="size (page)" th:field="*{size}">

field value must be digit and less than 4 signs

It works properly: if the title field is not filled we can see the message.
However, for the size field we expect 4 digits, but how to configure this regex correctly? !${#size.matches('[0-9]{1,4}')} in this way there is no warning message.
I have foung the simillar question
Check if a string contains number or is numeric - Thymeleaf
But I need to invert boolean condition and it dooes not work for my case

A: You can check which field has errors in the Thymeleaf template when calling hasErrors() function.
Something like this:

field value must be digit and less than 4 signs

This way the error is shown only when the size field has errors and you don't need to use the regex to check its value.


text:
Q: Finding pole order and calculating residue of: $\frac1{z-\tan z} - \frac1{z}$ Part of the the problem I'm trying to do involves finding the residue of
$\frac{1}{z-\tan z} - \frac{1}{z}$ at z=0
I am not sure of the order of the pole
Here's what I did to find the order of the pole
f(z) = $\frac{1}{z-\tan z} - \frac{1}{z}$
      = $\frac{\tan z}{z(z - \tan z)}$
Now $z - \tan z = \frac{1}{3}z^3 + \frac{2}{15}z^5 + ...\quad$
and $\quad z(z - \tan z) =  \frac{1}{3}z^4 + \frac{2}{15}z^6 + ... $
So f has pole of order 4 at z=0.
Is this correct and to find the residue I use the formula
$\frac{1}{n!}\lim_{z\to 0} \frac{d^3}{dz^3}(z^4f(z))$ right?

A: You may write
$$
\begin{align}
\frac{1}{z-\tan z} - \frac{1}{z}&=\frac{1}{z-\left(z+\frac{1}{3}z^3 + \frac{2}{15}z^5 + \mathcal{O}(z^7)\right)} - \frac{1}{z}\\\\
&=\frac{1}{-\frac{1}{3}z^3 - \frac{2}{15}z^5 + \mathcal{O}(z^7)} - \frac{1}{z}\\\\
& =-\frac{3}{z^3}\frac{1}{1 + \frac{2}{5}z^2 +\mathcal{O}(z^4)} - \frac{1}{z}\\\\
& =-\frac{3}{z^3}\left(1- \frac{2}{5}z^2 + \mathcal{O}(z^4)\right) - \frac{1}{z}\\\\
& =-\frac{3}{z^3}+ \frac{6}{5z} - \frac{1}{z}+  \mathcal{O}(z)\\\\
& =-\frac{3}{z^3}+ \frac{1}{5z} +  \mathcal{O}(z)
\end{align}
$$  giving the value $\dfrac15$ for the desired residue.


text:
Q: How to create possible image urls and check if they exist with jQuery I am working on a website that uses its own language, similar to Smarty. It has a very rough set of functions built into a template "created" for me. This template does not offer a function to display images of cart items. So, I have to "guess" what the images' URLs are.
Since I cannot create any PHP-like functions in the template, I have to use JavaScript/jQuery.
What I need to do:
Create a few possible URLs, check to see if I guessed the URL correctly. If so, then I need to replace a
's background image with the valid image URL.
HTML

            Shopping Cart

                        Intel 4770K
                        Quantity: 1
                        Price: $275

JS
var dirs = '/product_images/18/4301/';
var ext = '.jpg';
var element = $('#session-menu .cart li');

$('#session-menu .cart li').each(function(){
    var data = $(this).data();
    for (var i in data){
        console.log(data[i]);
        checkUrl(createUrl(data[i]));
    }
});

function createUrl(val) {
    var imgStr = dirs + val.replace(/ |\.|\//g, '-').replace(/"|'/g, '').toLowerCase().toString() + ext;

    console.log(imgStr + ' has been made');

    return imgStr;
}

function checkUrl(img) {
    $.ajax({
        url: img,
        type: "HEAD",
        success: function() { console.log(img + ' exists'); changeBgImg(img); },
        error: function () { console.log(img + ' does not exist'); }
    });
}

function changeBgImg(img) {
    $('#session-menu .cart li .image').children('a').css('background-image', img);
}

The images (if they exist) are in the form of '/product_images/18/4301/intel-i7-4770k', '/product_images/18/4301/intel-4770k', or '/product_images/18/4301/large-intel-4770k'.
I really would prefer to do this in a jQuery plugin, if possible.
I had a different script doing essentially the same thing earlier, but all of the $.ajax checks came back successful? Even though the image did not exist. Even with variations of the above, the checks always came back successful.

A: Maybe try using a get request?
function checkUrl(img) {
    $.ajax({
        url: img,
        type: "GET",
        success: function() { console.log(img + ' exists'); changeBgImg(img); },
        error: function () { console.log(img + ' does not exist'); }
    });
}

I just tested it on my own site. When linking to an existing image, it came back successful. When linking to a non-existing image, it came back with an error.

A: So I had to remove the data-qty attribute because the script through an error with it in there... I also had to pass the element's "$(this)" through the functions so I could eventually change the BG on that specific element when I found a valid image... It seems like I could structure this script differently to avoid having to pass that through multiple functions... Maybe just set a variable outside of the functions... Yeah :)
HTML

            Shopping Cart

                        Intel 4770K
                        Quantity: 1
                        Price: $275

The JS is still very unpleasant to me. Seems like it could be composed much better. Like I said, I will need to do this set of functions on some other things around our site. Would be nice to have as a plugin, but tidier...
ALSO, It seems like I am guessing multiple valid URLs (I checked- and it is finding multiple images for each item). So how can I adjust the below to quit guessing URLs when it finds a valid one. And should there be some kind of priority system in place? Like "IF data-name URL AND data-code is valid THEN use data-name URL"?
JS
var dirs = '/product_images/18/4301/';
var ext = '.jpg';
var element = $('#session-menu .cart li');

element.each(function(){
    var data = $(this).data();
    for (var i in data){
        checkUrl(createUrl(data[i]), $(this));
    }
});

function createUrl(val) {
    var imgStr = dirs + val.replace(/ |\.|\//g, '-').replace(/"|'/g, '').toLowerCase().toString() + ext;

    return imgStr;
}

function checkUrl(img, el) {
    $.ajax({
        url: img,
        type: "HEAD",
        success: function() { console.log(img + ' exists, changing background image...'); changeBgImg(img, el); },
        error: function () { console.log(img + ' does not exist'); }
    });
}

function changeBgImg(img, el) {
    el.find('.image a').css('background-image', 'url(' + img + ')');
}


text:
Q: Can I use an API function for a directive's template URL? I want to load an svg file dynamically from its path in the database I used RestApi to retrieve the path and the Svg file id and display the SVG in an  widget - "Id_Leaf"file id svg:
 // Get All information for LeafPlan

$scope.LoadLeaf = function (Id_Leaf) {
    RESTSummoner.DoGet(PATH_LEAF, "/" + Id_Leaf).succes(function (data) {
        $scope.Leaf = data;
        console.log(data);
    }).error(function () {

    });
}

module.directive('svgPlan', ['$compile', 'RESTSummoner', function ($compile, RESTSummoner) {

    return {
        restrict: "A",
        replace: true,
        controller: function ($scope) {
            $scope.PATH_LEAF = 'SV_MAP_LEAF';
            alert($scope.PATH_LEAF);
        },
        templateUrl:'',
        link: function (scope, element, attrs) {
            scope.PATH_LEAF = 'SV_MAP_LEAF';
            alert("coucou");
            RESTSummoner.DoGET(1).then(function (res) {
                alert("coucou");
                element.replaceWith(res.data)
                console.log(res.data);
                console.log(res.data);
            });
    }
    }
}])

A: You could make the request yourself and manually replace the directive element yourself using angular.element replaceWith()
Something like:
module.directive('Plan', ['$compile','API', function ($compile, API) {
    return {
        restrict: "A",
        templateUrl:  'Api.DoGet(PATH)',
        link: function (scope, element, attrs) {
            Api.DoGet(PATH).then(function(res){
               element.replaceWith(res.data)
            });
        }
    }
}]);


text:
Q: How do I get the font color from a piece of HTML source code? I have a piece of HTML source like this:
Beverly Mitchell Shawnee Smith Glenn Plummer <NOBR>more >></NOBR>

I tried to retrieve the "color" value, like this:
MSHTML::IHTMLDocument2Ptr htmDoc1 = NULL;
SAFEARRAY *psaStrings1 = SafeArrayCreateVector(VT_VARIANT, 0, 1);
CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2, (void**) &htmDoc1);

VARIANT *param1 = NULL;
HRESULT hr = SafeArrayAccessData(psaStrings1, (LPVOID*)&param1);
param1->vt = VT_BSTR;
param1->bstrVal = SysAllocString(varSrc1.bstrVal);

hr = SafeArrayUnaccessData(psaStrings1);
hr = htmDoc1->write(psaStrings1);

MSHTML::IHTMLElementPtr pElemBody1 = NULL;
MSHTML::IHTMLDOMNodePtr pHTMLBodyDOMNode1 =NULL;

hr = htmDoc1->get_body(&pElemBody1);
if(SUCCEEDED(hr))
{
    hr = pElemBody1->QueryInterface(IID_IHTMLDOMNode,(void**)&pHTMLBodyDOMNode1);
    if(SUCCEEDED(hr))
    {
        ProcessDomNodeSmartWrapper(pHTMLBodyDOMNode1, ProcTgtTagStrVec);
    }
}

long lLength = 0;
MSHTML::IHTMLElementCollectionPtr pElemColl1 = NULL;
MSHTML::IHTMLElementPtr pChElem1 = NULL;
MSHTML::IHTMLStylePtr pStyle1 = NULL;
IDispatchPtr ppvdisp1 = NULL;

hr = htmDoc1->get_all(&pElemColl1);
hr = pElemColl1->get_length(&lLength);
for(long i = 0; i < lLength; i++)
{
    _variant_t name(i);
    _variant_t index(i);

    ppvdisp1 = pElemColl1->item(name, index);
    if(ppvdisp1 && SUCCEEDED(hr))
    {
        hr = ppvdisp1->QueryInterface(IID_IHTMLElement, (void **)&pChElem1);

        if(pChElem1 && SUCCEEDED(hr))
        {
            BSTR bstrTagName = NULL;

            pChElem1->get_tagName(&bstrTagName);
            hr = pChElem1->get_style(&pStyle1);
            if(pStyle1 && SUCCEEDED(hr))
            {
                _variant_t varFtCol;

                hr = pStyle1->get_color(&varFtCol);
                if(hr = S_OK && varFtCol)
                {
                    hmStyles1[wstring(varFtCol.bstrVal)] = L"FontColor";
                }
            }
            if(bstrTagName)
               SysFreeString(bstrTagName);
        } // if pStyle && SUCCEEDED(hr)
    }//if ppvdisp && SUCCEEDED(hr)
}//for

But I can never get the "color" value - varFtCol.bstrVal is a bad pointer when I debug the program. This is what varFtCol showed when I debug the program:

-       varFtCol    {???}   _variant_t
-       tagVARIANT  BSTR = 0x00000000  tagVARIANT
        vt  8   unsigned short
-       BSTR    0x00000000     wchar_t *
            CXX0030: Error: expression cannot be evaluated

#5a6571 is a hex color represents for RGB value of (90,101,113).
How can I get this color info?

A: According to the MSDN documentation, IHTMLStyle::get_color may return either a BSTR or an integer value in the variant. Have you tried assigning varFtCol into an integer value and examining that result?
const int colorValue = static_cast<int>(varFtCol);

As a recommendation, when working with _variant_t, it is usually best to use the built-in casting operators than to direct access the members of the union itself.

A: You shouldn't be getting style on pChElem1 because the color is not part of style in your case. Color is part of Font element.
Instead you must call pChElem1->getAttribute("color" . . .)
This will return #5a6571
The following code is in MFC. But you can easily convert to regular Win32 if you are not using MFC.
COLORREF GetColorFromHexString( CString szColor )
{
    TCHAR *szScan;
    CString strTemp;
    CString strColor = szColor;
    long lRR = 0,lGG = 0,lBB = 0;

    //first we will remove # characters which come from XML document
    strColor.TrimLeft(_T('#'));
    strColor.TrimRight(_T('#'));

    //it should be of the form RRGGBB
    if (strColor.GetLength() == 6) {
        //get red color, from the hexadecimal string
        strTemp = strColor.Left(2);
        lRR = _tcstol(LPCTSTR(strTemp),&szScan,16);

        //get green color
        strTemp = strColor.Mid(2,2);
        lGG = _tcstol(LPCTSTR(strTemp),&szScan,16);

        //get blue color
        strTemp = strColor.Right(2);
        lBB = _tcstol(LPCTSTR(strTemp),&szScan,16);
    }

    return RGB(lRR,lGG,lBB);
}


text:
Q: C# Passing double array to constructor overload method I am learning c# from one book and  I have to write a code on my own as a part of exercise. One of the things to be done is to pass double array to one of the constructor overload method who will handle it further. Problem is that I don't know how to do it.
Here comes the full code (till now):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace assignment01v01
{

    public class Matrix
    {
        int row_matrix; //number of rows for matrix
        int column_matrix; //number of colums for matrix
        int[,] matrix;

        public Matrix() //set matrix size to 0*0
        {
            matrix = new int[0, 0];
            Console.WriteLine("Contructor which sets matrix size to 0*0 executed.\n");
        }

        public Matrix(int quadratic_size) //create quadratic matrix according to parameters passed to this constructor
        {
            row_matrix = column_matrix = quadratic_size;
            matrix = new int[row_matrix, column_matrix];
            Console.WriteLine("Contructor which sets matrix size to quadratic size {0}*{1} executed.\n", row_matrix, column_matrix);
        }

        public Matrix(int row, int column) //create n*m matrix according to parameters passed to this constructor
        {
            row_matrix = row;
            column_matrix = column;
            matrix = new int[row_matrix, column_matrix];
            Console.WriteLine("Contructor which sets matrix size {0}*{1} executed.\n", row_matrix, column_matrix);
        }

        public Matrix(int [,] double_array) //create n*m matrix and fill it with data passed to this constructor
        {
            matrix = double_array;
            row_matrix = matrix.GetLength(0);
            column_matrix = matrix.GetLength(1);
        }

        public int countRows()
        {
            return row_matrix;
        }

        public int countColumns()
        {
            return column_matrix;
        }

        public float readElement(int row, int colummn)
        {
            return matrix[row, colummn];
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Matrix mat01 = new Matrix();

            Matrix mat02 = new Matrix(3);

            Matrix mat03 = new Matrix(2,3);

            //Here comes the problem, how should I do this?
            Matrix mat04 = new Matrix ( [2,3] {{ 1, 2 }, { 3, 4 }, { 5, 6 }});

            //int [,] test = new int [2,3] { { 1, 2, 3 }, { 4, 5, 6 } };

        }
    }
}

Part of the code that bothers me is marked with "//Here comes the problem, how should I do this?".
Any suggestions are welcome.

A: It looks like you're struggling with how to create a multi-dimensional array with a set of initial values.  The syntax for that is the following
new [,] {{ 1, 2 }, { 3, 4 }, { 5, 6 }}

Because you are initializing the array in this case you don't need to specify a size or a type.  The compiler will infer it from the elements provided

A: A multi dimensional array can be created as follows.
 new Matrix(new int[,] {{1, 2, 3,}, {1, 2, 3}});

The int is even redundant so you can make it even easier (or, at least, it should be easier to read :))
 new Matrix(new [,] {{1, 2, 3,}, {1, 2, 3}});

A: You just have the indices switched, and are missing a new keyword. This should work:
Matrix mat04 = new Matrix ( new [3,2] {{ 1, 2 }, { 3, 4 }, { 5, 6 }});

Or, as @JaredPar noted, you can omit the array size completely and have the compiler infer it for you:
Matrix mat04 = new Matrix ( new [,] {{ 1, 2 }, { 3, 4 }, { 5, 6 }});


text:
Q: The "Open Other" option is absent in Cocos Creator version 2.3.2 all!
The Cocos Creator version 2.3.2 doesn't have the "Open Other" option as shown in the image below...

I wonder what might be the counterpart option for Cocos Creator v2.3.2. Where can we see it? I was trying to follow the steps on the video I'm watching today.

Thank you!


text:
Q: In a random experiment, what is the probability of choosing a white but not black token? So I and my friend had a argument on the following question:
A box contains 7 black colored, 14 white coloured and 9 yellow colored tokens. Now, if a random experiment is done, then what is the probability of choosing a white token but not black token?
Here is how I did:-
So i want to choose a (W)hite but(I can say 'and' here WLG, Right?) not (B)lack token. It can symbolically be expressed as:
$W \cap \neg B $
$ \implies W \cap ( W \cup Y)$
$\implies (W \cap W) \cup (W \cap Y)$
$ \implies W $  ( because $ (W \cap Y) \subset W $ )
Which means n(Outcomes in favour) = 14.
$\therefore P(W \cap \neg B) = \frac{14}{30}$
But My friend did like this:
$P(W)=\frac{14}{30} , P(\neg B)=\frac{23}{30} $
$\implies P(W \cap \neg B)= \frac{14×23}{30×30} =\frac{161}{450}$
And now, after seeing him doing like this, I've become confused a little bit. So, I want to know which is correct. Help me be learned.
Thanks in advance

A: We can use the events $W$ and $\neg B$ and calculate the intersection rigrously:

*

*$P(W \wedge \neg B)=P(W  )+P( \neg B)-P(W \vee \neg B)$
$P(W \wedge \neg B)=\frac{14}{30}+\frac{23}{30}-\frac{23}{30}=\frac{14}{30}$

*$P(W \wedge \neg B)=P(W)\cdot P(\neg B|W)=\frac{14}{30}\cdot 1$

$P(W)=\frac{14}{30} , P(\neg B)=\frac{23}{30} $
$\implies P(W \wedge \neg B)=\frac{161}{450}$

Here your friend assumes independence of $W$ and $\neg B$. But this is not true.
$P(W)\cdot P(\neg B)\neq P(W \wedge \neg B)$

A: Any white token you choose is not black. You are indeed correct.
If your friend is being confused by you counting yellows, try to explain your reasoning to him. If he still doesn't understand, use a Venn diagram. Remember you are interested in the value of $$|W \cap (S-B)|\over|S|$$
See the following (black region represents set $B$, white does $W$, blue does $Y$)

Obviously the coins only have one color each so the areas are disjoint.


text:
Q: AWS Python Lambda with Oracle I am trying to connect to an Oracle db from AWS Lambda using python. I managed to package cx_Oracle but the environment does not find the dependencies.
I had zipped the content, which contained cx_Oracle.so and cx_Oracle-5.2.1-py2.7.egg-info (created on 64bit AWX Linux). I also added the files from instantclient-basic-linux.x64-12.1.0.2.0.zip into local/lib in that zip file.
The error I get is
import cx_Oracle

ImportError: libaio.so.1: cannot open shared object file: No such file or directory

I dynamically change environment variables in python like so:
oracledir = os.path.join(os.getcwd(), 'local', 'lib')
libdir = os.environ['LD_LIBRARY_PATH'] + ":" + os.path.join(os.getcwd(), 'local', 'lib')

command = 'LD_LIBRARY_PATH={} ORACLE_HOME={} python OracleWorker.py "{}"'.format(libdir, oracledir, args)
subprocess.call(command, shell=True)

OracleWorker.py starts with import cx_Oracle

A: Resolved. Added all dependencies by running
    ldd cx_Oracle.so| grep "=> /" | awk '{print $3}' | xargs -I '{}' cp -v '{}' /destination
Added all those files in destination to lib folder in lambda zip


text:
Q: TypeError: cannot concatenate 'str' and 'int' objects with randint Doing the following code
import easygui
from random import randint

Minimum = easygui.enterbox(msg = "Choose your minimum number")
Maximum = easygui.enterbox(msg = "Choose your maximum number")
operator = easygui.enterbox(  msg="which operator would you like to use? X,/,+ or - ?",title="operator")

rn1 = randint(Minimum,Maximum)
rn2 = randint(Minimum, Maximum)

print "%s %s %s =?" %(rn1, operator, rn2)

Gives me this error
TypeError: cannot concatenate 'str' and 'int' objects

I know it is a confliction between the string and interger, but how do i fix it?

A: enterbox returns a string. Convert the values to integers before storing them.
import easygui
from random import randint

Minimum = int(easygui.enterbox(msg = "Choose your minimum number"))
Maximum = int(easygui.enterbox(msg = "Choose your maximum number"))
operator = easygui.enterbox(  msg="which operator would you like to use? X,/,+ or - ?",title="operator")

rn1 = randint(Minimum,Maximum)
rn2 = randint(Minimum, Maximum)

print "%s %s %s =?" %(rn1, operator, rn2)

A: Minimum and Maximum are strings, not ints, so you can't pass them to randint as such.
Though you should probably watch out for exceptions if they enter something that's not an int you can do randint(int(Minimum), int(Maximum)) and as long as they entered good numbers you'll be all set.


text:
Q: Match to the end of the string in PHP Given a string and regex, how can I make sure it matches the entire string? That is, I don't want a newline to trigger the end of the match - I want it to match to the very end of the string.
Example:
<?php
// simplified date pattern
$pattern = "/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/";
$d = "2014-01-05\n"; // OOPS - this will match
if(preg_match($pattern, $d)) {
    echo "This is a date string.";
}

A: Use the D modifier:

D (PCRE_DOLLAR_ENDONLY)
  If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines).

$pattern = "/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/D";

A: You would need to use the multi-line pattern modifier m like this:
$pattern = "/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/m"; // note m at end after pattern


text:
Q: Create new table concatenating fields from many records I have a large table that hold all our customer purchase.
Each record contains the purchased item, the date of purchase and a lot of other fields that are uselessly replicated for each purchase.
I wish to create a stored procedure to periodically export a new table with only one record per client with all the dates and the purchased items concatenated into one text field separated by a conventional character or crlf.
So now my table "Purchases"  is something like this:
ID  |Name|PurDate |PurItem |etc
0001|Jack|20100101|Art. 115|.......
0002|Jack|20100105|Art. 230|.......
0003|Jack|20120408|Art. 098|.......
0004|John|20150808|Art. 021|.......
0005|John|20160203|Art. 432|.......

The new table should look like:
ID  |Name|Purchase|etc
0001|Jack|20100101 Art. 115;20100105 Art. 230;20120408 Art. 098|.......
0002|John|20150808 Art. 021;20160203 Art. 432|.......

Have you any suggestion?

A: try this code and customize to your requirement,
    CREATE PROCEDURE UPDATERECORDS
BEGIN

-- Create temp table to get distinct names
CREATE TABLE #TEMP (NAME NVARCHAR(100))
-- insert names
INSERT INTO #TEMP
SELECT DISTINCT NAME FROM PURCHASES
-- insert to your table
INSERT INTO [YOUR NEW TABLE]
SELECT
ROW_NUMBER()OVER (ORDER BY NAME) ID,
NAME =
STUFF((SELECT ', ' + NAME
FROM PURCHASE A
WHERE A.NAME = B.NAME
FOR XML PATH('')), 1, 2, ''),
PURCHASE =
STUFF((SELECT ', ' + PURCHASE
FROM PURCHASE A
WHERE A.NAME = B.NAME
FOR XML PATH('')), 1, 2, ''), ETC.....
FROM #TEMP B

END


text:
Q: Из xml передать данные в формулу xml выглядит вот так:
<item id="31025805">
        <genre>статья в сборнике трудов конференции</genre>
        <type>статья в сборнике трудов конференции</type>
        <source id="31025548">
            <titles>
                <title lang="EN">CEUR Workshop Proceedings</title>
            </titles>
            <titleaddinfo>3</titleaddinfo>
            <volumenumber>1825</volumenumber>
            <volumename>MMIT 2016 - Proceedings of 3rd Russian Conference "Mathematical Modeling and Information Technologies"</volumename>
            <seriesname>MMIT 2016 - Proceedings of 3rd Russian Conference "Mathematical Modeling and Information Technologies"</seriesname>
            <yearpubl>2016</yearpubl>
            <confname>3rd Russian Conference "Mathematical Modeling and Information Technologies", MMIT 2016</confname>
            <confplace>Yekaterinburg</confplace>
            <confdatebegin>16.11.2016</confdatebegin>
        </source>
        <pages>111-117</pages>
        <language>IT</language>
        <yearpubl>2016</yearpubl>
        <cited>0</cited>
        <titles>
            <title lang="EN">Modelling of cash flows by means of Markov processes</title>
        </titles>
        <grnti>270100</grnti>
        <risc>yes</risc>
        <corerisc>yes</corerisc>
        <authors>
            <author num="1" lang="EN">
                <lastname>Timofeeva</lastname>
                <initials>G.A.</initials>
                <authorid>15676</authorid>
                <spin>2292-7833</spin>
                <email>Gtimofeeva@usurt.ru</email>
                <affiliations>
                    <affiliation num="1" lang="EN">
                        <orgname>Ural State University of Railway Transport</orgname>
                        <orgid>6766</orgid>
                        <country>rus</country>
                        <town>Yekaterinburg</town>
                    </affiliation>
                    <affiliation num="2" lang="EN">
                        <orgname>Ural Federal University</orgname>
                        <orgid>290</orgid>
                        <country>rus</country>
                        <town>Yekaterinburg</town>
                    </affiliation>
                </affiliations>
            </author>
            <author num="2" lang="EN">
                <lastname>Bozhalkina</lastname>
                <initials>Y.A.</initials>
                <authorid>779136</authorid>
                <spin>6791-5486</spin>
                <email>Bozhalkina@mail.ru</email>
                <affiliations>
                    <affiliation num="1" lang="EN">
                        <orgname>Ural State University of Railway Transport</orgname>
                        <orgid>6766</orgid>
                        <country>rus</country>
                        <town>Yekaterinburg</town>
                    </affiliation>
                </affiliations>
            </author>
        </authors>
    </item>
    <item id="29099767">
        <genre>статья в сборнике трудов конференции</genre>
        <type>статья в сборнике трудов конференции</type>
        <source id="29091999">
            <titles>
                <title lang="EN">Mathematical Modeling and Information Technologies</title>
                <title lang="RU">Математическое моделирование и информационные технологии</title>
            </titles>
            <titleaddinfo>Proceedings</titleaddinfo>
            <yearpubl>2016</yearpubl>
            <pagesnumber>275</pagesnumber>
            <publisher>CEUR-WS.org</publisher>
            <confname>3rd Russian Conference "Mathematical Modeling and Information Technologies"</confname>
            <confplace>Екатеринбург</confplace>
            <confdatebegin>16.11.2016</confdatebegin>
            <confdateend>16.11.2016</confdateend>
        </source>
        <pages>111-117</pages>
        <language>RU</language>
        <yearpubl>2016</yearpubl>
        <cited>0</cited>
        <titles>
            <title lang="RU">Моделирование потоков платежей с помощью марковских случайных процессов</title>
        </titles>
        <grnti>270100</grnti>
        <risc>yes</risc>
        <corerisc>no</corerisc>
        <authors>
            <author num="1" lang="EN">
                <lastname>Timofeeva</lastname>
                <initials>G.A.</initials>
                <authorid>15676</authorid>
                <spin>2292-7833</spin>
                <email>Gtimofeeva@mail.ru</email>
                <affiliations>
                    <affiliation num="1" lang="EN">
                        <orgname>Public Educational Institution of Higher Professional Education The Ural State University of Railway Transport</orgname>
                        <orgid>6766</orgid>
                        <country>RUS</country>
                        <town>Ekaterinburg</town>
                        <address>Kolmogorov Street 66, Ekaterinburg, Russia, 620034</address>
                    </affiliation>
                </affiliations>
            </author>
            <author num="1" lang="RU">
                <lastname>Тимофеева</lastname>
                <initials>Галина Адольфовна</initials>
                <authorid>15676</authorid>
                <spin>2292-7833</spin>
                <email>Gtimofeeva@mail.ru</email>
                <affiliations>
                    <affiliation num="1" lang="RU">
                        <orgname>Уральский государственный университет путей сообщения</orgname>
                        <orgid>6766</orgid>
                        <country>RUS</country>
                        <town>Екатеринбург</town>
                        <address>620034  г.Екатеринбург, ул. Колмогорова,66</address>
                    </affiliation>
                </affiliations>
            </author>
            <author num="2" lang="EN">
                <lastname>Bozhalkina</lastname>
                <initials>Ya.A.</initials>
                <authorid>779136</authorid>
                <spin>6791-5486</spin>
                <email>bozhalkina@mail.ru</email>
                <affiliations>
                    <affiliation num="1" lang="EN">
                        <orgname>Public Educational Institution of Higher Professional Education The Ural State University of Railway Transport</orgname>
                        <orgid>6766</orgid>
                        <country>RUS</country>
                        <town>Ekaterinburg</town>
                        <address>Kolmogorov Street 66, Ekaterinburg, Russia, 620034</address>
                    </affiliation>
                </affiliations>
            </author>
            <author num="2" lang="RU">
                <lastname>Божалкина</lastname>
                <initials>Яна Андреевна</initials>
                <authorid>779136</authorid>
                <spin>6791-5486</spin>
                <email>bozhalkina@mail.ru</email>
                <affiliations>
                    <affiliation num="1" lang="RU">
                        <orgname>Уральский государственный университет путей сообщения</orgname>
                        <orgid>6766</orgid>
                        <country>RUS</country>
                        <town>Екатеринбург</town>
                        <address>620034  г.Екатеринбург, ул. Колмогорова,66</address>
                    </affiliation>
                </affiliations>
            </author>
        </authors>
    </item>

Из xml получаю ФИО авторов в таком виде:
['<lastname>Овчинников</lastname> <initials>Игорь Георгиевич</initials>', '<lastname>Овчинников</lastname> <initials>Илья Игоревич</initials>', '<lastname>Телегин</lastname> <initials>Максим Александрович</initials>', '<lastname>Хохлов</lastname> <initials>Сергей Викторович</initials>']

Или вот в таком:
['<lastname>Овчинников</lastname> <initials>И.Г.</initials>', '<lastname>Овчинников</lastname> <initials>И.И.</initials>', '<lastname>Караханян</lastname> <initials>А.Б.</initials>']

За каждым автором закреплен индивидуальный код. Я оформила его в виде двух словарей(с инициалами, с полным именем). Например, полное имя:
full_name_auth = {'Овчинников Игорь Георгиевич': '10002712', 'Алексеева Людмила Модестовна': '10000006', 'Анненкова Капитолина Ивановна': '10000007'}

Или ФИО с инициалами:
ini_name = {'Овчинников И. Г.': '10002712', 'Алексеева Л. М.': '10000006', 'Анненкова К. И.': '10000007'}

Индивидуальный код у авторов и в том, и в другом словаре абсолютно одинаковый.
Если у статьи автор один, то он должен попасть в формулу со своим кодом в таком виде:
#700: ^310002712^AОвчинников^BИ. Г.

Если авторов 2, то первый встает в 700 поле, а второй в 701. Выглядит вот так:
#700: ^310002712^AОвчинников^BИ. Г.
#701: ^AШепелева^BИ. О.

Если авторов нет в словарях, то он будет без кода. Если авторов 3, то:
#700: ^310002712^AОвчинников^BИ. Г.
#701: ^310000006^AАлексеева^BЛ. М.
#701: ^AГузенкова^BЕ. А.

Если 4 и больше, то авторы все попадают в 701:
#701: ^310002712^AОвчинников^BИ. Г.
#701: ^AСтаценко^BК. А.
#701: ^AГузенкова^BЕ. А.
#701: ^AПахомов^BА. П.

Я решила авторов посчитать и коды подставляла в ручную. Мой вариант непрактичный и, мало того, длиннющий получился и работает только для одного автора. Подскажите, пожалуйста, как мне автоматизировать этот процесс. Заранее благодарна за ответ.
P.S. Вчера я уже задавала подобный вопрос и мне понравилось решение, но теперь я не могу сообразить как решить вопрос с количеством авторов. Благодарю за понимание


text:
Q: Router TP-Link WR841ND rapidly decreased the speed - How to fix it? I bought a new router because:

*

*my old one (Tenda W311R+) started to behave strangely -> just haven't shown the WiFi  .. times to times, it appeared, but disappeared in a second .. it started with occasional disappearing, but now it's like missing all the time ... and it appears for a few seconds only :(

*wired connection on the old one works great (full speed provided by provider 50/50)
and, because the old one was a quite old (~10 years) so I decided to buy a new one, the TP-LINK WR841ND.
According to the reviews - it seemed great, BUT !!!
After I turn on the router, set it up the weirdest thing started to happen... the router is rapidly decreasing the speed of download and upload as well ... instead of 50/50 it's just about 0.8/20-30 which is ridiculous :) I do not mind the upload, but download is big headache for me.
I've tried almost everything - settings, default settings, factory reset, firmware is the newest one, .... I've tried to disable/enable everything, try almost all possible combinations in setup ...  nothing worked
Strange is, that wired connection is the same as WiFi connection ... both are cut to 0.8/20-30 ..
Do you have any idea what is going on here? Is there any way how to setup the router ?? Or do you have any idea how to fix the old one to show WiFi without dealing with the dropping ? Or have I bought just a crummy piece? And do I need to buy another one (I mean a different brand) ??
If you need more information, please let me know .. I will provide it
PS: speed was measured on speedtest[dot]net
Thank you guys

A: From everything you have described, the problem is interference - ie someone else has set up an access point which is trying to use all the available bandwidth or another device (baby monitor, cordless phone, microwave are prime candidates) is spewing noise and killing the spectrum.
Unfortunately there is no simple answer to the problem.   You either need to track down the source of Interference and eliminate it - which can be quite hard, block the interference (again, quite hard) avoid using WIFI, or get a newer router which handles 802.11ac connections - and make sure your equipment also handles it.  (802.11ac works in the 5 gig rather then 2.4 gig band, which means that it is less prone to interference because its less used, has more spectrum and signals don't travel as far).   It also has an idea of using multiple antennas to cancel out interference and create "corridores" which increase performance.
I do note that there is a small possibility that another WIFI device is transmitting on the same / overlapping frequency with your router, in which case you can log into it and change the channel you are using.    If you have an android tablet/smartphone you can download a free App WIFI Analyser which can show you what channels quietest and you may be able to use those.

A: SOLUTION:
I have found a solution ... the question was "incompatibility" between provider's modem and NEW router... so I've used old router (with disabled wifi) as a bridge between the modem and new router (wifi works great and wired connection as well) ... now, it works great :)


text:
Q: AngularJs set a global I'm trying to set a global for my entire app. But it's not working. Here I declare my globals:
(function() {
    angular.module('employeeApp')
        .controller('authenticationController', authenticationController)
        .constant('GLOBALS', {
            url:'http://skindustries.dev/api/v1/',
            role:'',
            companyid:'',
            name:''
        });

Then when a employee signs in I want to set globals.
function authenticationController(requestFactory,authenticationFactory,GLOBALS,$location,$cookieStore)
    {
    var vm = this;

        vm.login = function() {
            data = {"email": vm.email, "password": vm.password};
            requestFactory.post(GLOBALS.url + 'login', data)
                .then(function (response) {
                    console.log(response);
                    GLOBALS.role = response.data.result.Employee.Role;
                    GLOBALS.companyid = response.data.result.Employee.CompanyId;
                    authenticationFactory.setToken(response.data.result.Employee.api_token);
                    $cookieStore.put('employeeid', response.data.result.Employee.EmployeeId);
                    $location.path('/home');

                }, function () {
                    console.log('Niet ingelogd!');
                });
            }
        }

If I console.log(GLOBALS.role) in authenticationController result is superadministrator. Then the user is redirected to home. If I console.log(GLOBALS.role)  in my homeController.
(function()
{
    angular.module('employeeApp').controller('homeController', homeController);

    function homeController(employeeFactory,GLOBALS) {
        console.log(GLOBALS.role);

Result is null?
What am I doing wrong here!?
--EDIT--
constant (service)
(function() {
    angular.module('employeeApp')
        .service('constants',constants);

    function constants() {
        this.url = 'http://skindustries.dev/api/v1/';
            this.role =  'oldRole',
            this.companyid = '',
            this.name = ''
    }
})();

login (factory)
factory.login = function(email,password)
        {
            console.log('login');
            data = {"email": email, "password": password};
            requestFactory.post(GLOBALS.url + 'login', data)
                .then(function (response) {
                    constants.role = response.data.result.Employee.Role;
                    constants.companyid = response.data.result.Employee.CompanyId;
                    factory.setToken(response.data.result.Employee.api_token);
                    $cookieStore.put('employeeid', response.data.result.Employee.EmployeeId);
                    $location.path('/home');

                }, function () {
                    console.log('Niet ingelogd!');
                });
        }

homeController
(function()
{
    angular.module('employeeApp').controller('homeController', homeController);

    function homeController(constants) {
  console.log(constants.role);
}

A: Basically value (or a constant) initializes every time when it is injected in a controller. So it never retain your new value and hence initializes its old value.
For your need you could use a service as a global object in your application so that it retains your new saved value in the GLOBAL object
Demo Fiddle
.service('GLOBALS', function() {
      this.url = 'http://skindustries.dev/api/v1/';
      this.role =  'oldRole',
      this.companyid = '',
      this.name = ''
  })

.controller('MyController', function(GLOBALS, $scope) {
  console.log(GLOBALS.role);
  $scope.role = GLOBALS.role;
  GLOBALS.role = "new role";
  console.log(GLOBALS.role);
})

.controller('MyController2', function(GLOBALS, $scope) {
  console.log(GLOBALS.role);
  $scope.role = GLOBALS.role;
});

For a better understanding of constants and values refer this question
Hope this helps.

A: A constant can not be intercepted by a decorator, that means that the value of a constant should never be changed.
Use Value :
angular.module('app', []);

.value('GLOBALS', 'The Matrix');

.controller('MyController', function (GLOBALS) {
  GLOBALS = "hello";
})


text:
Q: Changing ID to something more friendly When creating a record the URL generated to view that record ends with its id
/record/21

I would like to be able to change that to something easier to read, such as my name and reference attributes from the model. I have looked at friendly_id but has trouble implementing a custom method to generate the URL
class Animal < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name_and_ref

  def name_and_ref
   "#{name}-#{reference}"
  end
end

I ended up getting an error
PG::UndefinedColumn: ERROR: column animals.name_and_ref does not exist LINE 1: SELECT "animals".* FROM "animals" WHERE "animals"."name_an... ^ : SELECT "animals".* FROM "animals" WHERE "animals"."name_and_ref" = 'Clawd-A123456' ORDER BY "animals"."id" ASC LIMIT 1

def show
  @animal = Animal.friendly.find(params[:id])
end

I then come across the to_param method which Rails has available, in my model I have
def to_param
  "#{self.id}-#{self.name}"
end

which will generate a URL for me of
/19-clawd

This works, but when I do the following it throws an error
def to_param
  "#{self.name}-#{self.reference}"
end

My question though is how can I generate the URL to be name and reference without it throwing
Couldn't find Animal with 'id'=Clawd-A123456

A: If you would like to use your own "friendly id" then you'll need to adjust the find statement in your controller to something like
id = params[:id].split(/-/, 2).first
@animal = Animal.find(id)

Similarly, for the name/reference combination
name, reference = params[:id].split(/-/, 2)
@animal = Animal.find_by(name: name, reference: reference)

The second choice is a little more difficult because you'll have to do some work in the model to guarantee that the name/reference pair is unique.

A: The easiest way, is to go with friendly_id and simply add the missing database column. Keep in mind that you will need to ensure this new column is unique for every record. It basically acts as primary key.


text:
Q: Incorrect number of html elements being returned I'm scraping from the following page: https://www.pro-football-reference.com/boxscores/201809060phi.htm
I have this code:
import requests
from bs4 import BeautifulSoup

url = 'https://www.pro-football-reference.com/boxscores/201809060phi.htm'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')

tables = soup.findAll("div",{"class":"table_outer_container"})
print (len(tables))

Each table on the page has the element "div",{"class":"table_outer_container"}. But my print statement only returns 1. Am I wrong in believing that my findAll statement will assign all of those elements to the variable, "tables"?

A: It's because most of the tables are within comments and your script wont grab them unless you kick out those vicious signs -->,<!-- from response. Try the following. It should give you 20 tables from that page.
import requests
from bs4 import BeautifulSoup

url = 'https://www.pro-football-reference.com/boxscores/201809060phi.htm'

r = requests.get(url).text
res = r.replace("<!--","").replace("-->","")
soup = BeautifulSoup(res, 'lxml')

tables = soup.findAll("div",{"class":"table_outer_container"})
print (len(tables))


text:
Q: Perform calculation in Excel with 2 table comparison I have 2 tables: SheetA!D5:F15, with Column D containing date and time, and Column F containing values. Table 2: SheetB!C5:D100, with Column C containing Date and Time and Column D contain values.
I want to perform some calculation (for example, add values together) on SheetA column G with values of Column F in SheetA and values in column D of SheetB if corresponding date and time of sheetB is equal or less than date and time of sheetA.
In the example I attached below, G5 should return 39+30+30+30+30+30+30+30=219 as there are 6 date and time in SheetB that are equal or less than 10/26/16 13:30
I'm thinking vlookup or index match, but not sure the exact details. Greatly appreciate if anyone can provide some details.
SheetA:

SheetB:


text:
Q: How do i split an input string into a smaller string and compare them I just started picking up Java and ran into a problem with this practice question. I am supposed to print the number of duplicated lines in an input. Any help would be appreciated!
Sample input:
test
test
TesT
Sample output:
2
Here is my attempt that did not work:

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int count=0;
        while(scan.hasNext()) {
            String s = scan.nextLine()+"\n";
            String first=s.split("\n")[0];
            for (int i=0;i<s.length();i++){
                if(first==s.split("\n")[i])
                    count++;
            }
        }
        System.out.println(count);
    }
}

A: Please try this - if you are using Java8, and the intent is to count duplicate lines(not words) and see if it helps. This is using input from the file "error.txt" in your local anywhere.
public static void main(String args[]) throws IOException {
            Map<String, Long> dupes = Files.lines(Paths.get("/Users/hdalmia/Documents/error.txt"))
                    .collect(Collectors.groupingBy(Function.identity(),
                            Collectors.counting()));

            dupes.forEach((k, v)-> System.out.printf("(%d) times : %s ....%n",
                    v, k.substring(0,  Math.min(50, k.length()))));
        }

My File had input as
hello
hello
hi
Output was :
(1) times : hi ....
(2) times : hello ....

A: You'll need to add a Java Map to memorize what input lines you've already encountered, something like
public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Map map=new HashMap();
    int count=0;
    while(scan.hasNext()) {
        String s = scan.nextLine()+"\n";
        if(map.hasKey(s)) count++;
        else map.put(s, true);
    }
    System.out.println(count);
  }
}

You can read more about this topic here dynamic-programming


text:
Q: How can I dynamically unload a javascript file? I am including pages using Ajax but I also need to include their respective javascript files, which requires removing the previous javascript files from memory at the same time.
How can I unload the currently-loaded javascript files (as well as their code in memory) so that I can load the new page's files? They will more than likely conflict, so having multiple independent files' javascript files loaded.

A: you can just namespace your code.. that way you prevent collisions

var MyJavaScriptCode = {};
MyJavaScriptCode.bla = function () {};

A: It is possible to unload a javaScript file clearing the entire code from the browser. The steps are:

*

*Give an ID to the target "script" element (e.g. "mainJs", pointing to "main.js")

*Create another JS file (e.g "flush.js"), with the same functions and variables in "main.js", and make sure the functions and variables contents are empty.

*After "main.js" has been used up, we flush it by deleting the "script#mainJs" element and loading the "flush.js" dynamically into the DOM tree.

Example
mainJs    = document.getElementById("mainJs");
document.head.removeChild(mainJS);//Remooves main.js from the DOM tree

flushFile = document.createElement("script");
flushFile.setAttribute("src", "flush.js");
document.head.appendChild(flushFile);//Loads flush.js into the DOM tree, overwriting all functions and variables of main.js in browser memory to null

That's it

A: Actually that's quite possible. You can replace an script or link element.
function createjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
}

else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
}
  return fileref
}

function replacejscssfile(oldfilename, newfilename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
    if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
        var newelement=createjscssfile(newfilename, filetype)
        allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
    }
  }
}

you must fill filename parameters as src attribute and filetype as "js" or "css"
I think there's no need to explain the code. Also you've posted in 2009 but hey. Maybe someone will need it right? :)
All credit goes to: http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
You can learn some tricks there btw.

A: This really sounds like you need to reevaluate your design.  Either you need to drop ajax, or you need to not have collisions in you method names.
You can review this link: http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
Which gives information on how to remove the javascript from the DOM.  However, modern browsers will leave the code in memory on the browser.

A: No, you can't do that. Once a block of JavaScript gets loaded in the browser and executed, it gets stored in browser memory under the scope of the respective window. There is absolutely no way to unload it (without page refresh/window close).

A: Exactly the similar requirement I've and I've tried in following way but it requires a small coding part from developer side even.
I've a js file with 20+ functions as below and file name is profile.js
function myprofile(){
//code block A
}
function updateprofile(){
//code block B
}....
var functionsInJs=["myprofile","updateprofile",...]

Now I've written a method to clear the memory of this file as follows
function unloadJs(array){
    array.forEach(function(eachJsFn){
         window[eachJsFn]=undefined;//Clearing the functionality of js function in browsers window
    }
}

So, while to unload js functions i'll pass the array of function names in it.


text:
Q: supee 7405 Hunk #2 FAILED at 472. Magento 1.8.1 I know how to install patches via shell, but this supee 7405 is giving me a problem.
The only error I get is
checking file app/code/core/Mage/Checkout/controllers/CartController.php
Hunk #2 FAILED at 472.
1 out of 2 hunks FAILED
I tried uploading the patched file, and then running the patch to update the rest of the files, but it still does not work..
No one else seems to have this issue with this file.
All previous patches are applied

A: You have to apply your patch manually for this file.
1- Copy and save the lines refering to the lines refering to the file app/code/core/Mage/Checkout/controllers/CartController.php
2- Inside the patch file, remove the lines refering to the file app/code/core/Mage/Checkout/controllers/CartController.php
3- Apply your patch
4- Open file the file app/code/core/Mage/Checkout/controllers/CartController.php and modify the lines you saved at the first step


text:
Q: Retain focus on a pop up window I have a button on a "home page" that opens a pop up which contains several onward links.
When someone clicks on one of the onward links, the linked page opens in a new, separate window, leaving "home page" still open, and the pop up "blurs" (I think that is the correct word to mean the pop up does not close, but disappears behind "home page").
I would like the pop up to remain in "focus" (on top of "home page") until a user clicks on "Close this window" that appears at the bottom of the pop up.
This is the JavaScript that generates the popup:
function OpenPop()
{
    var windowcontents = "https://example.com/link.html";
    var win = window.open(windowcontents,"remote",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=450,height=425');
    win.creator=self;
    myWindow.focus();
}

This is the HTML on "home page" that displays the button that opens the pop up

Here is the "close this window" code at the bottom of the pop up

Is there a way to keep the pop up in "focus"?
Thank you.


text:
Q: Reasonable design of using socket.io for RPC I am building a web app that uses socket.io to trigger remote procedure calls that passes sessions specific data back go the client. As my app is getting bigger and getting more users, I wanted to check to see if my design is reasonable.
The server that receives websocket communications and triggers RPCs looks something like this:
s.on('run', function(input) {
  client.invoke(input.method, input.params, s.id, function(error, res, more) {
    s.emit('output', {
      method: input.method,
      error: error,
      response: res,
      more: more,
      id: s.id
    });
  });
});

However, this means that the client has to first emit the method invocation, and then listen to all method returns and pluck out its correct return value:
socket.on('output', function(res) {
  if (res.id === socket.sessionid) {
    if (!res.error) {
      if(res.method === 'myMethod') {
        var myResponse = res.response;
        // Do more stuff with my response
      });
    }
  }
});

It is starting to seem like a messy design as I add more and more functions... is there a better way to do this?
The traditional AJAX way of attaching a callback to each function would be a lot nicer, but I want to take advantage of the benefits of websockets (e.g. less overhead for rapid communications).


text:
Q: Java Project Environment Preparation I am new to project environment setup. Below is my project structure in eclipse
Project Name
    --> .settings
    --> .bin
    --> lib
    --> resources
    --> src
    --> .classpath
    --> .project

I am attempting to export src folder as jar.
When i export to jar, all the above folders & files are created in jar. But i need to convert only src folder as.
Also when i export to executable jar, all the third party libraries are exported as class files in jar. is it right.
What is the best practice to export project. Only src folder or everything.
Which i need to use jar/runnable jar. My requirement is to write start/stop bat file to call jar and execute java program.
Please advice me. Thanks in advance.

A: First it's important to know what these folders actually do. Following are the workings of several of these files.
.settings -> This file records project specific settings and workspace preferences.

.bin      -> folder is usually where the compiled files are copied to.

lib       -> contains external libraries that are used in your project (like Apache Commons)

resources -> the resources like images, text, pdf, audio, video are usually copied here

src       -> the folder where the project's source files are located.

.classpath -> It contains information that the JDT feature needs in order to properly compile the project: the project's source folders, the output folders , and classpath entries.

.project  -> This file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view.

So you can see that if you exclude some of the files like lib, resources, bin etc... Your jar file will probably stop working. Your jar file needs compiled files and their dependencies.
For example: All your compiled .class files are in bin folder. And your jar works because of these .class files and NOT .java files that are in src. If you delete this bin folder then your jar will probably stop working.
Also, your project may be using some external library supplied by someone else. Like Apache Commons or google/guava and these are usually in lib folder. So you can't delete this folder as well.
However, if you no longer expect to use .java code, then you can exclude files that were created by eclipse to manage this project. See this post.
see also:
1. What's in an Eclipse .classpath/.project file?
2. exclude files from jar or war in eclipse


text:
Q: Expected value depending on $k$ identically independent exponential distributions Suppose a computer has $s$ processors with identical independent exponential processing times with rate $\mu$. Instructions are processed on a first-come first-serve basis as soon as a processor becomes free. Instructions arrive with independent exponentially distributed inter-arrival times with rate $\lambda$.
Suppose that an instruction finds itself first in line with all processors busy. Denote $W$ the waiting time of the instruction and $T_P$ its processing time once
accepted by a processor. Let $T = W + T_P$ be the total time elapsed between
the arrival of the instruction and the completion of its processing.
I need to find the distribution of $W$ and calculate $\mathbb{E}[T]$.
My Thoughts
I've found several documents that state that the expected value of the waiting time of a customer in the queue is
$$W_q = \left[ \frac{1}{(s-1)!}\left(\frac{\lambda}{\mu}\right)^s\frac{\lambda \mu}{(s\mu-\lambda)^2}\right]p_0,$$ where $p_0$ is the probability of $0$ customers in the queueing system. Now how can this expected value help me to find the distribution of $W$?

A: This is much easier since you know the exact state on arrival of this particular instruction. Since it's first in line and all the processors are full, the waiting time $W$ is the time until the first of the $s$ instructions being processed is done. Since all is exponential/memoryless, the wait time till the first finishes is exponential with rate $\mu s.$ (This is from the superposition principle for Poisson processes, or more simply from the fact that the minimum of $s$ independent exponentials with rate $\mu$ is an exponential with rate $\mu s$.)
Thus we have $E(T) = \frac{1}{\mu s}+ \frac{1}{\mu}$


text:
Q: Sortable  using only image I have a page that looks like this:

    A
    B

    A
    B

Which works great. But I would like to sort the 's only using the image for each row. Now its possible to drag etc
How is that done?

A: You can use the jquery sortable attribute handle
$('table tbody').sortable({
    handle: ".handle"
});

You'd give your image the class "handle"

And here is a Fiddle: http://jsfiddle.net/qGGhK/16/


text:
Q: onClick button to another activity crashes emulator I am completely new to Android studio. I have been trying to create a list of buttons which take the user to the different activities ("movieShowings" in this instance).
When I click on the button however the app crashes on the emulator.
Main Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void MovieShowings(View view) {

    Intent intent = new Intent(this, MovieShowings.class);
    startActivity(intent);
}

}
layout Button
<Button
        android:id="@+id/showingTimes"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginTop="124dp"
        android:text="Movie Showings"
        android:textColor="#0000ff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="MovieShowings"/>

activity_Main
public class MovieShowings extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String[] foods = {"Bad Boys", "Purge", "Interstellar", "7 Pounds"};
    ListAdapter Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foods);
    ListView movieList = (ListView) findViewById(R.id.movieList);
    movieList.setAdapter(Adapter);

    movieList.setOnItemClickListener(
            new AdapterView.OnItemClickListener(){
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String food = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(MovieShowings.this, food, Toast.LENGTH_LONG).show();
                }
            }
    );
}

}
Error message
FATAL EXCEPTION: main
                                                                                Process: com.example.niallgrace.cinemaapp, PID: 6200
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.niallgrace.cinemaapp/com.example.niallgrace.cinemaapp.MovieShowings}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                                at com.example.niallgrace.cinemaapp.MovieShowings.onCreate(MovieShowings.java:22)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)

A: Remove View view from the bracket of your method MovieShowings.
Also replace this in your method with YourActivityName.this
Edit 1:
As per your error logs, it looks like that something is wrong with listView in your activity in which you are switching too

A: Check your layout file here setContentView(R.layout.activity_main); and make sure that the ListView matches the id specified here (ListView) findViewById(R.id.movieList);. That would throw the exception if it fails to find the layout element.


text:
Q: What are the names of everyone in the four houses in Harry's year? I'm currently making a mind map of the Harry Potter universe, but when I got to filling in the houses of Hogwarts, I realised that I barely know any names.
What are the names of everyone from Harry's year?

A: If it's just Harry's year you want, JKR had a list of forty students ready when she started writing the books, called "The Original Forty".
Also see this answer that tells you what happened to those original forty.
Wizarding World also has lists of characters, organised by house. For instance, the Ravenclaws. If you set out and explore Wizarding World, I think most of your question will be answered there.


text:
Q: how to insert value for bit column of postgresql with jdbc If the preparedStatement sql is fixed, how can I do the insert?
table schema
create table if not exists ttqs_a (b bit(1));

code
try(PreparedStatement ps = conn.prepareStatement("insert into ttqs_a values(?)")){
  ps.setObject(1,1, Types.BIT);
  ps.execute();
}

exception
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: column "b" is of type bit but expression is of type boolean

A: I don't think you can tell the JDBC driver to use the data type bit on the database side, you you will have to add a type cast:
INSERT INTO ttqs_a VALUES (CAST(? AS bit))

Then use any of the types that can be cast to bit, such as text
stmt.setString(1, "0");

or integer
stmt.setInt(1, 0);

A: With MySQL you can use PreparedStatement#setByte to insert into BIT(M) fields, but I'm not sure whether this is also true for PostgreSQL.
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO ttqs_a VALUES (?);")) {
    ps.setByte(1, (byte) 1);
    ps.executeUpdate();
}

But if it's just BIT(1), why not use BOOLEAN?


text:
Q: Proof of convergence I have the following problem I want to solve with induction method. Would be great if someone helped me with it.
I have $a_0=0$, $a_1=$$1\over 2$ and $|a_{n+1}-a_n|\le|a_n-a_{n-1}|^2$
I need to show $a_n$ is convergent.
I need to show that the sequence is increasing and bounded. I use induction method:
$a_1\lt 1,$ I assume $a_n\lt 1$ and prove that $a_{n+1}\lt1$
$|a_{n+1}-a_n|=|a_n-a_{n-1}|^2\lt1\to|a_{n+1}-a_n|\lt1$ and since $a_n\lt1,a_{n+1}\lt1$
Is this true? How do I use induction to prove increasingness?
Help would be appreciated!
Thanks in advance!

A: The sequence $(a_n)$ need not be increasing. For example, $a_2$ could be as high as $\frac{3}{4}$, but it also could as low as $\frac{1}{4}$. There is a similar available choice at every $n+1$.
I would suggest that you try to prove that our sequence is a Cauchy sequence.

A: Define $b_n =|a_{n+1} -a_n | $ then $b_0 =\frac{1}{2} ,$  $b_{n+1} \leq b_n^2 $ thus $b_n \leq\left(\frac{1}{2}\right)^{2^n}$ and this implies convergence of $(a_n )$ because $$|a_{m} -a_n|\leq\sum_{j=0}^{m-n-1} |a_{m-j} -a_{m-j-1}|= \sum_{j=0}^{m-n-1} b_{m-j-1}\leq \sum_{j=0}^{m-n-1}\left(\frac{1}{2}\right)^{2^{m-j-1}}\to 0$$ as $m,n\to \infty.$


text:
Q: Hacking Google AJAX Search Result page I am a novice developer, and have created a simple greasemonkey script to modify content at Google Search result page. Scripts loads fine at first page. but as user goes to second page (or searches for new query) - the modifications are not reflected.
I guess this is because of ajax, as Google now loads results using ajax. I read other answers here, suggesting use of DOMNodeInserted and other tricks, but nothing works.
Can someone please suggest a solution?

A: Listening to events like DOMNodeInserted will work if used correctly. Other useful events can be found here.


text:
Q: drawing characters on the canvas using string declared object names I'm trying to create an ecology game and am working on the spawning aspect of it. One of my attempts includes creating multiple independent objects to control different squares or "wolves" as the simulation goes on. The reason I am using strings as names for objects is so each newly created wolf has their own seperate values from the rest (which helps keep things moving on their own instead of in unison). When the object is created it calls the setupWolf function to be drawn. When the object is printed to the console it shows up with no x, y, w, or h values. Heres my code

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var body = document.getElementById("body");

var wolfPop = 2;
var bornWolves = 0;

var wolves = {

};

function setupWolf(x, y, w, h){
    context.fillStyle = "blue";
    context.fillRect(this.x, this.y, this.w, this.h);
    context.fill();
}

body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";

setInterval(function(){
    if(wolfPop != bornWolves){
        spawnWolf();
        bornWolves++;
    }
}, 1);

function spawnWolf(x, y, w, h){
    name = "w" + bornWolves;
    this.x = 10;
    this.y = 10;
    this.h = 10;
    this.w = 10;
    wolves[name] = Object.create({}, {x: {value: this.x}, y: {value: this.y}, h: {value: this.h}, w: {value: this.w}});
    wolves[name] = new setupWolf(name.x, name.y, name.w, name.h);
    console.log(wolves);
}
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
</body>
</html>

Firstly, I had declared my object then reassigned it as a function, and upon calling it giving the wrong output value to the console. Heres what I should have done

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var body = document.getElementById("body");

var wolfPop = 2;
var bornWolves = 0;

var wolves = {

};

var name;

function setupWolf(x, y, w, h){
    context.fillStyle = "blue";
    context.fillRect(wolves[name].x, wolves[name].y, wolves[name].w, wolves[name].h);
    context.fill();
    console.log(wolves[name].x);
}

body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";

setInterval(function(){
    if(wolfPop != bornWolves){
        spawnWolf();
        bornWolves++;
    }
}, 1);

function spawnWolf(){
    name = "w" + bornWolves;
    rand = Math.floor(Math.random() * 100) + 1;
    wolves[name] = Object.create({}, {x: {value: Math.floor(Math.random() * 100) + 1}, y: {value: Math.floor(Math.random() * 100) + 1}, h: {value: 10}, w: {value: 10}});
    setupWolf();
    console.log(wolves[name]);
}
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
</body>
</html>

Now all I need help with is the independent movement of the objects. Thank you for the help


text:
Q: Why does this loop always return false, when you enter the correct value? import java.util.Scanner;
public class Password {
    public static void main(String[] args) {
         Scanner reader = new Scanner(System.in);

        System.out.println("Please create a password");
        String pw = reader.nextLine();

        while (true) {
            System.out.println("Enter the password");
            String pwt = reader.nextLine();
            if (pwt == pw) {
            System.out.println("The password is correct!");
                break;
            } else {
                System.out.println("The password is incorrect, please try again");

            }
        }
    }
}

I'm new to this, so the answer is probably obvious, but I just don't understand why it reads false when I type the right password


text:
Q: How to interpret hazard ratios in Cox model in Stata? I am estimating the survival of trade relationships from South Africa to various importing countries. These are the hazard ratios using robust standard errors. I just want to know how to interpret the results.
Is this correct?

*

*Value > 1 indicates higher hazard ratios (poor survival)

*Value between 0 – 1 indicates lower hazard ratios (good survival)

*Value = 1 indicates that the variable has no effect on the hazard rate (constant hazard).

For example: If SA has a common language with importing country =1 if not = 0
How to interpret 0.745 hazard ratio for this variable?
Thanks in advance.

A: Your interpretation is correct.
For the "common language" variable, having a common language reduces the hazard to where it is 0.745 times the hazard that it would be given everything else was the same but there was no common language. The hazard measures the probability of the trade relationship ending in the near future after time t given there is a relationship up to time t. There is a lower risk of it ending if they have a common language (about 3/4 the risk compared to if they do not have a common language).


text:
Q: using css3 scale blurs the view in metro app I am trying to scale a DIV to 0.8 times and it is causing the DIV to get blurred.
It seems to working fine in Chrome and Safari but gets blurred in a metro app.
I tried using some Jquery transform2d plugins thinking that may be CSS rendering is slower,but the blur effect was there in that also.
Can someone suggest a solution to this problem.

A: You could try making the original div a scale down and then just scaling it up the actual size therefore making it appear to scale up!


text:
Q: Why are the top two containers different sizes? The top two containers, containing the picture of beds are of unequal heights but I have set the width and height to be the same.
http://justbedroomdesigns.com/
Sorry to ask but I have no clue why they aren't the same height?
Edit: confusion in my questions seems apparent. I mean the top two that are side by side, not the two that are in the first column.
Thanks

A: You have a typo in your CSS file
#title {
float: left;
idth: 410px;
}

should be
#title {
float: left;
width: 410px;
}

A: First things first, you are using IDs on your page more than once. DON'T DO THAT. ID's are meant to be used once per page. Switch them to classes.
Second, ASSIGN A WIDTH / HEIGHT TO YOUR IMAGES WITH PIXELS. Otherwise you will have problems like this. I can see you are using Wordpress, and you can do so in the WYSIWYG on the back end. Percentages are going to be a bad idea if you aren't sure on the exact widths / heights of where the images are being placed.
Next, check how it looks across browsers, Firefox looks good, Chrome not so much. IE7 doesn't like much at all.
Ok. So besides that, a quick fix might be.
.post-block img {
width:338px;
height:248px}

Hope this helps.

A: They are the same height. The box on the left is partially obscured by the box below it.


text:
Q: Is there a word that describes this gesture of interlocking hands on the lower stomach? Specifically, I am referring to the traditional gesture some female service staff members seem to do, when demonstrating their work or their readiness to receive orders.
Also, this is the gesture Alice Cullen performs in Twilight movies on several occasions (if I remember correctly).
I could not find a photo with this exact gesture.
It is similar to the one shown in the first photo, but the hands are held higher with demonstrativeness, tension, sharpness of movement and gesture itself (possibly with emotion and a smile), and military-like demeanor. The main difference with with the second photo is that in the gesture I refer to, the hands are held in the front and not in the back; also, the way the hands are interlocked is different (more like in the first picture).

A:
I'm posting images, so if anyone knows the correct terminology for these different hand gestures, because I've become curious myself, please post your answers.
For image No. 1, the person on the right is clasping or clenching her hands. In Image No. 2, I'd say she is holding her own hands. The caption for Image No. 3 reads: hands clenched in lower position.

Hand and Arm Gestures:
  Research by Nierenberg and Calero on the hands-clenched position
  brought them to the conclusion that this was a frustration gesture,
  signalling that the person was holding back a negative attitude. The
  gesture has three main positions; hands clenched in front of the face,
  (Figure 39), hands resting on the desk (Figure 40) or on the lap when
  seated and placed in front of the crotch when standing (Figure 41).

Source: BODY LANGUAGE How to read others' thoughts by their gestures by
Allan Pease

A: I don't think there's a single word that conveys the whole pose. Hands clasped covers the positioning of the hands relative to each other, either with fingers intertwined, or with one hand covering the other. But hands can also be clasped behind the back, or in prayer, and two people can clasp hands. So "hands clasped in front" is probably as good a phrase as there is.

A: My first posting here. This piqued my interest, to the point of actual Google hunting. :)
I thought perhaps the style of hand clasp is similar to how singers hold their hands. Not sure if I've helped, hindered or befuddled.
http://tvtropes.org/pmwiki/pmwiki.php/Main/RecitationHandclasp

A: If you search for victorian maids in images, they don't seem to all be doing that gesture. On paintings of (hand)maidens, most of the time their hands are handling objects. Is that a specific pose or is that behavior? So I wondered specifically if maids - or women of a certain era - were taught to act in such a way or would they be generally so familiar with singing techniques as to spontaneously do a recitation handsclap in a - tenseful - way in different contexts. Consider these images:

Coronation of the Queen of England, Elizabeth II, 1953
I don't think there's any randomness here; this is an incredible show of power. Were the hand placement random it wouldn't be so twice on the same occasion. And the right hand overtaking the left comes as no surprise. This is I think a display of classic (British) etiquette. It also showcases an intuitive yet thorough understanding of the lexical, symbolic and cultural underpinnings associated with the (word) hand.
The hand
The NED provides insight: 3. In reference to action performed with the hand and hence (fig.) to action generally; thus often=agency, instrumentality[...]. - 5. As used in various ways of making a promise or oath; (spec.)[...] marriage. - 6. Hence, In oaths[...]. - 8. A person employed by any other in manual work. - 10. [...]a person[...] as the source from which something is obtained[...]+references to trust and best price. - 12. Horsemanship. - 20. A lineal measure. Usage of clean hands: freedom from wrongdoing, innocence and uprightedness of life. Of course there's come to hand, give one's hand etc. to no end. Considering the hand/arm are also heraldic symbols, and looking briefly at the countless religious references associated with cross, it's unlikely such a gesture is an attempt at crossing hands or fingers, especially not while mixing random colors.
The right hand
I think it's also easy to identify that historically in the Western world the left hand was always considered suspicious or "sinister" and treated very differently from the "right" hand(see right-handed, i.e. of the right kind). Within that frame of thought if one had to be shown it should be the right hand.
The grace of repose
And the end of the 19th "Victorian" sort of etiquette. Such as holding a fork with the right hand and having the Routledge tell you how to carve(lobster would have been useful) or that [w]ashing your hands in milk and water, for 2-3 days, will make them white. There is great care for "the unity of the hands". In a document I found the following:

The nervous toying with ear-rings or brooches, or dress buttons, is
  another mannerism to be guarded against.  The hands should learn the
  grace of repose.  It is a great triumph of nervous control[...]

It's about acting in a composed manner, showing composure. Surely the hands take part in a graceful composition.

A. Therefore I think this is about a display of honest, serving, dextrous hands, and what composed/mannered used to mean in the Victorian era, which may seem like mannerism today.


text:
Q: How to create a Receiver for creating a new Event I have created an application that successively adds appointments to a calendar. However i wish now to be able to click the "New Event" button in a calendar program eg. aCalendar and have my program popup. and i think i am a little lost.
in my AndroidManifest.xml
    <receiver
        android:name="com.johnny.CalendarAdd"
        android:enabled="true"
        >
        <intent-filter>
            <data android:pathPrefix="vnd.android.cursor.item/event" />
            <action android:name="android.intent.action.EDIT" />
        </intent-filter>
    </receiver>

tryed to change it to.
    <activity android:name="CalendarAdd">
      <intent-filter>
        <data android:pathPrefix="vnd.android.cursor.item/event" />
        <action android:name="android.intent.action.EDIT" />
      </intent-filter>
    </activity>

In class file
package com.johnny;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class CalendarTest extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
     Log.i("CalendarAdd", "CalendarAdd.onReceive called!");

 }
}

when i click the "New Event" button i don't get my app in the list.
I have had a look-around and think i have missed something simple or i am Totally on the wrong path.
Thanks for any Help in advance.

A: You can't achieve it using Broadcast Receiver, Broadcast intent-filter will work only when some app broadcast that particular intent, e.g connectivity state got changed, screen got turned off, battery low etc are correct example of system broadcasts. While create calendar event can't be a broadcast & thats why you can't receive it.
From android documentation regarding Broadcast Receivers:

A broadcast receiver is a component that responds to system-wide
  broadcast announcements. Many broadcasts originate from the system—for
  example, a broadcast announcing that the screen has turned off, the
  battery is low, or a picture was captured. Applications can also
  initiate broadcasts—for example, to let other applications know that
  some data has been downloaded to the device and is available for them
  to use. Although broadcast receivers don't display a user interface,
  they may create a status bar notification to alert the user when a
  broadcast event occurs. More commonly, though, a broadcast receiver is
  just a "gateway" to other components and is intended to do a very
  minimal amount of work. For instance, it might initiate a service to
  perform some work based on the event.

For achieving desired functionality, you need to register intent-filter for your activity.
Also your manifest should contain read/write calendar permission and event edit/insert intent-filter, e.g.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.CalanderTest"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8"/>

    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />

    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.EDIT" />
                <action android:name="android.intent.action.INSERT" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.item/event" />
            </intent-filter>
        </activity>
    </application>
</manifest>

for testing it out do below in onclick of some test button:-
@Override
public void onClick(View view) {
    super.onClick(view);
    if (view.getId()==R.id.create_event)
    {
       Intent i = new Intent(Intent.ACTION_INSERT);
        i.setType("vnd.android.cursor.item/event");
        startActivity(i);
    }
}

On clicking of my test button i got menu like in below image, so above code works fine to show your app in App chooser dialog for adding/editing calendar events.

Now in your activity you can handle this intent using getIntent() and perform action accordingly.
You can have a look here for extras supported by Calendar event.
Like Events.TITLE,Events.EVENT_LOCATION etc. If you are going to create your own calendar event creator, then you need to handle all such extras Gracefully, for awesome user experience.

A: Place the <intent-filter> you defined inside your <activity> instead. The user should be given a list of apps (including yours) that can handle that action, so they can select yours if they want to.
<receiver>s are for receiving BroadcastIntents, which are a bit different.

A: Use <receiver> as you originally did, and android:name should be com.johnny.CalendarTest if you wish to register your receiver, since your receiver class name is CalendarTest.
See here
android:name
Required name of the class implementing the receiver, deriving from BroadcastReceiver.

A:
However i wish now to be able to click the "New Event" button in a
  calendar program eg. aCalendar and have my program popup.

Have you tried the various action and category filter declarations in your <intent-filter>.
For instance:
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.EDIT" />
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.OPENABLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="application/myapp" />
    </intent-filter>

See if any of those help you.
See also: http://developer.android.com/reference/android/content/Intent.html

A: From CalendarController, I can almost be sure that these intent are explicit intent with specific component set. For example, in launchEditEvent method.
private void launchEditEvent(long eventId, long startMillis, long endMillis, boolean edit) {
    Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
    Intent intent = new Intent(Intent.ACTION_EDIT, uri);
    intent.putExtra(EXTRA_EVENT_BEGIN_TIME, startMillis);
    intent.putExtra(EXTRA_EVENT_END_TIME, endMillis);
    intent.setClass(mContext, EditEventActivity.class);
    intent.putExtra(EVENT_EDIT_ON_LAUNCH, edit);
    mEventId = eventId;
    mContext.startActivity(intent);
}

The intent is set to be handled by EditEventActivity. So it is impossible to receive such intents in your application. I think the Calendar App make it as an explicit intent because it regard this as an in-app event. If this is not an explicit intent, your code should work, because the component in Calendar App is almost same with what you did.
    <intent-filter>
        <action android:name="android.intent.action.EDIT" />
        <action android:name="android.intent.action.INSERT" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="vnd.android.cursor.item/event" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.EDIT" />
        <action android:name="android.intent.action.INSERT" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="vnd.android.cursor.dir/event" />
    </intent-filter>

A: The aCalendar New Event Intent is as this.
{act=android.intent.action.EDIT typ=vnd.android.cursor.item/event flg=0x20000000 cmp=org.withouthat.acalendar/.edit.EditActivity (has extras)}
And Google Calendar App New Event Intent is as this.
{act=android.intent.action.VIEW cmp=com.android.calendar/.event.EditEventActivity
They are explicit intent.
Your can not receive this intent in your app.
More about intent click here

A:             <activity android:name="com.johny.CalendarTest"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.EDIT" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.ALTERNATIVE" />

            <data android:host="com.android.calendar" />
            <data android:host="calendar" />
            <data android:scheme="content" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.EDIT" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.ALTERNATIVE" />

            <data android:mimeType="vnd.android.cursor.item/event" />
        </intent-filter>
    </activity>

This was the exact code i used and got to work.
Most of The Answers helped in getting the response.
The reward went to the person who put most effort into it and achieved what was a result.

A: The old answers show me the direction, but I had to do a small modification to make it work:
<activity
        android:name=".YourActivity"
        android:exported="true">
    <intent-filter>
            <action android:name="android.intent.action.INSERT" />
            <action android:name="android.intent.action.EDIT" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="vnd.android.cursor.dir/event" />
     </intent-filter>
</activity>


text:
Q: Insert values into same regist/row using more than one activity I will give a example of what i want to achieve:
Lets say i have a table called "5Fruits" with 6 camps:
ID - Fruit1 - Fruit2 - Fruit3 - Fruit4 - Fruit5
Using 3 different activities (or more) i want to insert on first activity the fruit1, then i have a button "next" that opens another activity where i insert fruit2 and fruit 3 and then again, a button "next" that opens the last activity where i insert the fruit4 and fruit5.
And save the five fruits on the same row, regist, whatever.
How can i achieve this? It must be simple but im not figuring it out.
Thanks.

A: You can transfer some data between activities with putExtra method. Like that.

Define a stringArray in your mainActivity. And put Fruit1 in.

       String[] myFruits= new String[6];
       myFruits[0] = "apple";

       //Start your second activity.
       Intent intent = new Intent(this, secondActivity.class);
       intent.putExtra("myExtras", myFruits);
       startActivity(intent);

For your other activities.

String[] myFruits;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bla_bla_bla);

              //gets oldFruits.
    Intent intent = getIntent();
    myFruits = intent.getStringArrayExtra("myExtras");
}
private void sendFruits()
{
    myFurits[i] = "banana";  // "i" is your fruit number;
    Intent intent = new Intent(this, otherActivities.class);
    intent.putExtra("myExtras", myFruits);    //sends new fruits
    startActivity(intent);
}

Your Last Activity

private SQLiteDatabase sqw;
String[] myFruits;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bla_bla_bla);

              //gets oldFruits.
    Intent intent = getIntent();
    myFruits = intent.getStringArrayExtra("myExtras");
}

//if your id column is not AUTOINCREMENT, you can add query in.

String query = "INSERT INTO YOURTABLE (Fruit1,Fruit2,Fruit3,Fruit4,Fruit5)
        VALUES("'+myFruits[0]+'","'+myFruits[1]+'","'+myFruits[2]+'","'+myFruits[3]+'","'+myFruits[4]+'");";
sqw = new YOURDB().getWritableDatabas();   //get your db openhelper instance
sqw.execSQL(query);    //your fruits inserted

It's not good way. Because using multiple activities for a just process that decreases your application performance.
  You can use with Fragments or dynamically creation Buttons and EditTexts and your process in a one Activity.