text:
Q: Excel: Column comparison with dates and values I currently have 4 columns that contain data on Bitcoin Prices and S&P 500 closing day values, as well as their respective dates:

Since the S&P 500 is closed on non-trading days and the Bitcoin market is open 24/7, the amount of data I have for each is unequal; I have way more days for Bitcoin than for the S&P 500.
I want to compare the two columns containing their dates, extract the dates that are matching in both columns, and then output the matches and their corresponding values into a separate column.
Please let me know if any of this is unclear.

A: Assuming that all original values are on Sheet1 and new values will be placed on a new sheet.
Set the values as follows:

*

*C1 = =Sheet1!C1, "fill" that formula down to as many rows as you want.

*D1 = =Sheet1!D1, "fill" that formula down to as many rows as you want.

*A1 = =Sheet1!A1

*A2 onwards = =VLOOKUP(C2,Sheet1!$A$2:$B$6,1,FALSE), "fill" that formula down to as many rows as you want. Technically you don't need this, you could just set it to the value in the same row, in column C. However, this will give you a blank string in both columns A and B if there isn't a matching value in the original data.

*B1 = =Sheet1!B1

*B2 onwards = =VLOOKUP(C2,Sheet1!$A$2:$B$6,2,FALSE), "fill" that formula down to as many rows as you want.

Here's what that looks like given the first few rows of data:
Original data:

Sheet 2 without non-trading days:

EDIT 1: Lock the references on Sheet 1

A: A simple combination of INDEX & MATCH solves the issue:

I would like to suggest two search patterns, since you have not specified that what would be it!

*

*Formula in cell E67:
 =IFERROR(INDEX(D$67:D$74,MATCH(C67,A$67:A$74,0)),"")

N.B. Matches dates from Column C into A.

*

*Formula in cell F67:
 =IFERROR(INDEX(D$67:D$74,MATCH(A67,C$67:C$74,0)),"")

N.B. Formula matches dates from Column A into C.

*

*You may use either of the formulas as is suitable.

*Adjust cell references, Dates & related values as needed.


text:
Q: TIdTCPServer - On unexpected disconnect wait for reconnect I have several programs made using Delphi 6 with Indy components and am trying to figure out a way to put a TCP connection on hold in case of an unforeseen disconnect.
We connect via TCP  to PLC's on our factory floor and for whatever reason (operator messing with things they shouldn't be, switches going down temporarily, faulty wire, or whatever the case may be) the connection is ended.
This causes our programs to lock up hard. As soon as a disconnect happens between PLC and PC, the program will linger for a short amount of time and finally lock up.
Is there a way to put the connection on hold when a disconnect between PLC and PC happens, and reestablish connection without locking the program up?
Perhaps also is there a way to do this with TIdTCPClient as well?
If I need to be more descriptive please say so and I will try to be.
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
  i : Integer;
begin

begin
if NOT  IdTCPServer1.Active   then exit;
try

   Comm_Status  :=  True;

 {************************************************
    Clear PC Buffer before Read
  ************************************************}
 for i := 0 to giBufferSize -1 do  begin
     gabToPCBuffer[i] := 0;
 end;

 {************************************************
            Recieve the buffer from PLC
  ************************************************}
    // WE READ
     AThread.Connection.ReadBuffer(gabToPCBuffer, giBufferSize);

     StateMachineLogic;      //Sort Through buffer and copy to server buffer

     // WE SEND back to PLC
     AThread.Connection.WriteBuffer(gabToPLCBuffer, giBufferToPLC );

except
    //;
end;
end;
end;

A: If a client connection to a TCP server is gracefully disconnected from the client, the OnDisconnect event will be triggered. Your thread will also be marked terminated, so you should check for this in your loop.
However, for non-graceful disconnections, the TCP server will immediately error on the next read or write. You have wrapped your read and write in an empty try...except block. Instead, you should handle the error and break out of the loop.
For Delphi 6, you should update your Indy components to the latest Indy v9 release.

redpajama_set_name: RedPajamaStackExchange


text: Q: Are results of "quantum eraser experiment" same both for particles moving at the speed of light and slower ones? Recently I've encountered a video about the quantum eraser experiment. I was curious, if results of this experiment are the same for entangled particles moving with the speed of light and slower ones?


text:
Q: Rails number_to_currency delete trailing zeroes right of decimal I have a dynamically generated table that multiplies price * qty.  Some of the prices are in partial cents. For example
if the price of an item is 0.0375 I can display that in my table as
number_to_currency(0.0375,:precision => 4)
=> $0.0375

but on quantities where the price is a standard 2 decimal number I get
number_to_currency(33.95,:precision => 4)
  => $39.9500

I need a way to trim the trailing zeroes of a decimal value.  Keep in mind that the output is in a Model.each block so I'm uncertain I can modify the precision parameter conditionally.

A: Try to specify strip_insignificant_zeros option:
number_to_currency(33.95, precision: 4, strip_insignificant_zeros: true)

It should remove zeros after decimal separator. Here is description of this option.

A: The default for this method is 2. So you simply need
number_to_currency(33.95)
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency

A: number_to_currency(33.95,:precision => 2)

A: Since number_to_currency returns a String, you can use .remove(/0+$/) to remove any trailing zeros:
number_to_currency(33.95,:precision => 4).remove(/0+$/)

A: Try using round before number_to_currency:
number_to_currency(33.95.round(4)) # $33.95
number_to_currency(0.0375.round(4)) # $0.0375


text:
Q: Relative paths in twig or absolute in PhpStorm I'm new to twig. I'm using it in PhpStorm and have problem with paths.
Here is my folder structure:
- template /folder/
    - main.twig
    - common /folder/
        - bootstrap.twig
        - nav.twig

In  main.twig I have code:
{% extends "common/bootstrap.twig" %}

When I Ctrl + Click on link PhpStorm opens correct file.
But in bootstrap.twig I have to write:
{% include "common/nav.twig" %}

and then Ctrl + Click is not working.
I cannot use relative paths like nav.twig or ./nav.twig - twig throws error.
How can I make twig to use relative paths so go to source would work in PhpStorm?

A: Mark your template root folder (template in your case) as Resource Root (either via right click in Project View or via Settings/Preferences | Directories).
https://www.jetbrains.com/help/phpstorm/2016.2/configuring-folders-within-a-content-root.html?search=directories

Files under a folder marked as Resource Root can be referenced relative to this folder.


text:
Q: In Ruby, why is Hash[:a, 1] and Hash[[[:a, 1]]] giving the same result {:a => 1}, while Hash[[:a,1]] gives an empty hash?  > Hash[:a,2,:b,4]
 => {:a=>2, :b=>4}

 > Hash[:a,1]
 => {:a=>1}

 > Hash[[:a,1]]
 => {}

 > Hash[[[:a,1]]]
 => {:a=>1}

A: You can pass the key-value pairs two ways:

*

*Directly as arguments to Hash::[], with the keys and values alternating

*As an array of pairs, each represented by an array containing a key and a value

The first form fits 1, the second form fits 1, the fourth form fits 2, but the third form doesn't fit either (it consists of a single array, but neither :a nor 1 is a key-value pair).
The reason the second form is useful is because that's what you tend to get from Hash's Enumerable methods — an array of key-value pairs in arrays. So you can write Hash[some_hash.map {|k, v| [k, v+1]}] and you'll end up with a Hash transformed the way you want.


text:
Q: clearing a output result and reusing the result I am working on creating a Calculator i want to be able to ask the user if he wants to clear the result or reuse the result with a second number to create a new result. any tips or help is appreciated
def cally():
    op = input('''Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')

    n1 = float(input('Please enter the first number: '))
    n2 = float(input('Please enter the second number: '))

    if op == '+':
        print(n1 + n2)

    elif op == '-':
        print(n1 - n2)

    elif op == '*':
        print(n1 * n2)
    elif op == '/':
        print(n1 / n2)

    else:
        print('You have not typed a valid operator')
cally()

def again():

    calc_again = input("Do you want to calculate again?Please type Y for YES or N for NO.")

    if calc_again == 'Y':
        cally()

    elif calc_again == 'N':
        print('See you later.')

    else:
        again()
cally()

A: Modify cally() to add an optional argument which is the previous result.  If this argument is present, use it as n1 instead of prompting.  Also return the current result after printing it.
Then, after you call cally(), save its result in a variable, and if the user says they want to reuse the last result, pass that same variable back in to the next call to cally().

A: you can combine them into the same function and feed the previous result into the next operation as follows:
def cally(last_result=None):
    op = input('''Please type operator''')

    if last_result:
        n1=float(last_result)
    else:
        n1 = float(input('Please enter the first number: '))

    n2 = float(input('Please enter the second number: '))

    if op == '+':
        res = (n1 + n2)

    elif op == '-':
        res = (n1 - n2)

    elif op == '*':
        res = (n1 * n2)
    elif op == '/':
        res = (n1 / n2)

    else:
        print('You have not typed a valid operator')
        return

    print(res)

    calc_again = input("Do you want to calculate again? Please type Y for YES or N for NO.")

    if calc_again == 'Y':
        cally(res)

    elif calc_again == 'N':
        print('See you later.')

cally()

EDIT - just saw John Gordon's answer, this is basically an implementation of it


text:
Q: Javascript switch statement within a function that is called when the onclick event fires My HTML is this:

Please enter your discount code

    <input type="text" name="discountCode" id="discountCode">

    <button id="myButton"  onclick="myFunction()">Click Me</button>

When I click the button, I want the call to myFunction() fire on the event.
My JavaScript is this:
 function myFunction(){
    var discount;
    var discount = document.getElementById("discountCode").innerHTML;
    switch(discount){
        case "SAVE10":
        document.getElementById("message").innerHTML = "you are saving 10% on this order.";
        break;

        case "SAVE15":
        document.getElementById("message").innerHTML = "you are saving 15% on this order.";
        break;

        default:
        document.getElementById("message").innerHTML = "please enter a valid discount code.";
        break;
    }
}

I want to output the messages to the div element of "message". When I run this code and enter a discount code, the only line that outputs to the message div is the default line:

please enter a valid discount code.

Can anyone steer me in the right direction.
Thanks!

A: Use .value instead of .innerHTML to get value from input tag.
Check below:

function myFunction() {
  var discount = document.getElementById("discountCode").value;
  switch (discount) {
    case "SAVE10":
      document.getElementById("message").innerHTML = "you are saving 10% on this order.";
      break;

    case "SAVE15":
      document.getElementById("message").innerHTML = "you are saving 15% on this order.";
      break;

    default:
      document.getElementById("message").innerHTML = "please enter a valid discount code.";
      break;
  }
}

Please enter your discount code

<input type="text" name="discountCode" id="discountCode">

<button id="myButton" onclick="myFunction()">Click Me</button>

Also removed var discount you declared twice. That was not required.
Read this for more information : https://www.w3schools.com/jsref/prop_text_value.asp


text:
Q: Write-S3Object : A parameter cannot be found that matches parameter name 'Credentials' I'm trying to set up AWS deployment via the AWS Tools for Powershell on a new machine using write-s3object -credentials $aws_creds ..., and I'm running into the following error:
Write-S3Object : A parameter cannot be found that matches parameter name 'Credentials'.

This has definitely worked for me previously, and the AWS docs still say you should be able to pass through credentials with -Credentials. Does anyone know if this behaviour has changed?

A: Found it - it appears to now be just -Credential without the 's'. AWS docs still say -Credentials, and unfortunately Get-Help doesn't show the AWS common parameters.


text:
Q: How to create virtual paths to files on web server? I have two files:  file1.php and file2.php in a directory that contains more files.
I want to change the path of these two files to be newdir/fileX.php .
I would like to do it without actually changing their physical position, because of images and stuff that appear on these pages.
Running Apache on Linux
Can I do it?
Thank you.

A: You can do it using symbolic links. In the terminal go to the newdir directory and type:
ln -s path/to/phpfiles/file1.php


text:
Q: Is the multiplicative group of non-zero elements of a finite field cyclic? How to decide if the multiplicative group of non-zero elements of a finite field is cyclic or not?
Based on our experience with $\left(\mathbb{Z}_7 \setminus \{0\}, \cdot \right)$, which is generated by $3$ or $5$, and with $\left(\mathbb{Z}_{11} \setminus \{0\}, \cdot\right)$, which is generated by $2$, $6$, $7$, or $8$,
can we conclude that $\left(\mathbb{Z}_p \setminus \{0\}, \cdot\right)$, where $p$ is any prime, is cyclic? And if so, then which elements can generate this group?


text:
Q: Add option to point to code file in \tcblisting environment This question is building off the code and solution found here.  I would like to add the option to point the actual code file (either a Matlab or Python code file) and put that into my options.  I have the current command
\begin{mcode}{Some Matlab Code}{matcode1.m} that specifies that this is a Matlab environment mcode, the name of the script (in this case "Some Matlab Code") and finally the path to the file.
For some reason, the filecontents contents do not show up in their respective environments and I just output these "empty" cells:

Can you tell me what I need to do, to have the contents of the file show up in their respective environments?  Thanks!
\documentclass[a4paper, 10pt, oneside, fleqn, openright]{report}
\usepackage[no-math]{fontspec}

\usepackage{calc}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{pdfpages,graphicx}
\usepackage{mdframed}
\usepackage{listings}
\usepackage{filecontents}

\begin{filecontents*}{matcode1.m}
V = diag([0.02, 0.5*pi/180].^2);
P0 = diag([0.005, 0.005, 0.001].^2);
W = diag([0.1, 1*pi/180].^2);
map = LandmarkMap(20);
veh = Bicycle('covar', V);
veh.add_driver( RandomPath(map.dim) );
\end{filecontents*}

\begin{filecontents*}{pycode1.py}
"""
===============
Many plot types can be combined in one figure to create
powerful and flexible representations of data.
"""

import matplotlib.pyplot as plt
import numpy as np

# np.random.seed(19680801)
# data = np.random.randn(2, 100)
#
# fig, axs = plt.subplots(2, 2, figsize=(5, 5))
# axs[0, 0].hist(data[0])
# axs[1, 0].scatter(data[0], data[1])
# axs[0, 1].plot(data[0], data[1])
# axs[1, 1].hist2d(data[0], data[1])

fig, ax = plt.subplots()
plt.plot(x, y, label='Loaded from file!')
plt.fill_between(x, y, color='#539ecd')
\end{filecontents*}

\definecolor{light-gray}{gray}{0.92}

\definecolor{mainColor}{RGB}{211, 47, 47} % some dark red

\usepackage[numbered,framed]{matlab-prettifier}

\renewcommand\lstlistingname{Python Code}
\lstdefinestyle{pycode}{
    language=Python,
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Black},
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    basicstyle=\color{Black}\ttfamily,
    commentstyle=\color{LimeGreen},
    keywordstyle=\color{BurntOrange}\bfseries,
    stringstyle=\color{WildStrawberry},
    keywords={var, func, extends, import},
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    basicstyle=\ttfamily\scriptsize,
}

\lstdefinestyle{mcode}{
    style = {Matlab-editor},
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Gray!80}\scriptsize,
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    %backgroundcolor=\color{cyan!20},
    basicstyle=\ttfamily\scriptsize,
}

%\lstnewenvironment{myPyCode}
%{\lstset{style=pycode}}
%{}
%
%\lstnewenvironment{myMatCode}
%{\lstset{style=mcode}}
%{}

\usepackage{tcolorbox}
\tcbuselibrary{skins,breakable,listings}

\newcounter{pylst}
\newtcblisting[use counter=pylst]{pycode}[3][]{%
        enhanced,noparskip,breakable,colback=light-gray,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-a}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=pycode, xleftmargin=-1mm},after upper={\centering\strut Python Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm]([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\newcounter{mlst}
\newtcblisting[use counter=mlst]{mcode}[3][]{%
        enhanced,noparskip,breakable,colback=cyan!20,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-b}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=mcode, xleftmargin=-1mm},after upper={\centering\strut Matlab Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm] ([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\begin{document}

\begin{mcode}{Some Matlab Code}{matcode1.m}
\end{mcode}

\begin{pycode}{Some Python Code}{pycode1.py}
\end{pycode}

\end{document}

A: Basically, you need to use \newtcbinputlisting instead of \newtcblisting. The latter expects the listing contents to be provided as the body of the environment you are defining (in your case: empty). On the other hand, \newtcbinputlisting uses the file named by /tcb/listing file as input.
Before running the following code, make sure matcode1.m and pycode1.py don't already exist in the directory in which LaTeX is run, because previous runs of \newtcblisting would have truncated them to size zero, and filecontents or filecontents* without the overwrite option wouldn't rewrite them. Alternatively, you can use \begin{filecontents}[overwrite,noheader]{〈file name〉} ... \end{filecontents} if your LaTeX kernel is from October 2019 or later (which supersedes the filecontents package, see the LaTeX News Issue number 30).
(just prepend \RequirePackage{filecontents} at the very top of the file in case your LaTeX kernel is too old)
\begin{filecontents*}{matcode1.m}
V = diag([0.02, 0.5*pi/180].^2);
P0 = diag([0.005, 0.005, 0.001].^2);
W = diag([0.1, 1*pi/180].^2);
map = LandmarkMap(20);
veh = Bicycle('covar', V);
veh.add_driver( RandomPath(map.dim) );
\end{filecontents*}

\begin{filecontents*}{pycode1.py}
"""
===============
Many plot types can be combined in one figure to create
powerful and flexible representations of data.
"""

import matplotlib.pyplot as plt
import numpy as np

# np.random.seed(19680801)
# data = np.random.randn(2, 100)
#
# fig, axs = plt.subplots(2, 2, figsize=(5, 5))
# axs[0, 0].hist(data[0])
# axs[1, 0].scatter(data[0], data[1])
# axs[0, 1].plot(data[0], data[1])
# axs[1, 1].hist2d(data[0], data[1])

fig, ax = plt.subplots()
plt.plot(x, y, label='Loaded from file!')
plt.fill_between(x, y, color='#539ecd')
\end{filecontents*}

\documentclass{article}
\usepackage[dvipsnames,svgnames]{xcolor}
\usepackage{listings}
\usepackage[numbered,framed]{matlab-prettifier}
\usepackage{tcolorbox}
\tcbuselibrary{skins,breakable,listings}

\definecolor{light-gray}{gray}{0.92}
\definecolor{mainColor}{RGB}{211, 47, 47} % some dark red

\renewcommand\lstlistingname{Python Code}
\lstdefinestyle{pycode}{
    language=Python,
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Black},
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    basicstyle=\color{Black}\ttfamily,
    commentstyle=\color{LimeGreen},
    keywordstyle=\color{BurntOrange}\bfseries,
    stringstyle=\color{WildStrawberry},
    keywords={var, func, extends, import},
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    basicstyle=\ttfamily\scriptsize,
}

\lstdefinestyle{mcode}{
    style = {Matlab-editor},
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Gray!80}\scriptsize,
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    basicstyle=\ttfamily\scriptsize,
}

\newcounter{pylst}
\newtcbinputlisting[use counter=pylst]{\pycode}[3][]{%
        enhanced,noparskip,breakable,colback=light-gray,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-a}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=pycode, xleftmargin=-1mm},after upper={\centering\strut Python Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm]([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\newcounter{mlst}
\newtcbinputlisting[use counter=mlst]{\mcode}[3][]{%
        enhanced,noparskip,breakable,colback=cyan!20,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-b}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=mcode, xleftmargin=-1mm},after upper={\centering\strut Matlab Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm] ([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\begin{document}

\mcode{Some Matlab Code}{matcode1.m}

\pycode{Some Python Code}{pycode1.py}

\end{document}


text:
Q: Components to record ultrasonic sound? Up to 200kHz For a personal project, I'm trying to record ultrasonic sound. I would like to find the best way to record from 20kHz to 200kHz.
As I found from Wikipedia, animals can hear up to 200kHz.
As I prefer to design my own board, the best component I have found is this Knowles SPH0641LU4H-1.
But the range is from 50Hz to 80kHz...
What is the best configurations/components to record ultrasonic sound?


text:
Q: PixiJS - Sprite not being rendered on screen This is my first time using PixiJS and I'm following the tutorial
https://pixijs.io/guides/basics/getting-started.html
To try and get an image rendered onto the screen.
<!doctype html>
<html>
  <head>
    <script src="https://pixijs.download/release/pixi.min.js"></script>
  </head>
  <body>
    <script>
      // Create the application helper and add its render target to the page
      let app = new PIXI.Application({ width: 640, height: 360 });
      document.body.appendChild(app.view);

      // Create the sprite and add it to the stage
      let sprite = PIXI.Sprite.from('sample.png');
      app.stage.addChild(sprite);

      // Add a ticker callback to move the sprite back and forth
      let elapsed = 0.0;
      app.ticker.add((delta) => {
        elapsed += delta;
        sprite.x = 100.0 + Math.cos(elapsed/50.0) * 100.0;
      });
    </script>
  </body>
</html>

I'm using the exact code provided inside the tutorial, but I can't get anything to appear.

The path of sample.png is in the same directory as my html file.

What am I doing incorrectly here?

A: Your app seems to work, since the black frame is appearing. The sprite is the only thing not appearing. I tried copying the code and it works for me with my own image:

Running your project by opening the index.html file won't work because it can't reach the sample.png file. You need a development build to do that. I recommend using the Live Server VSCode extension to test your project.


text:
Q: Exponential of infinite dimensional matrix Asked this on MathOverflow with some more details

I have a matrix originating from Master Equation for birth death process on semi infinite lattice. It is tridiagonal. It is not symmetric.
I wanted to know if there is any way to compute the elements of $e^{(H-\lambda_1 I)t}$ where $\lambda_1$ is the first eigenvalue of $H$ and $I$ is the identity matrix.
(analytically. I know perhaps I could try to numerically approximate but I am hoping to use that as last resort)
Any help is appreciated! I can provide more details if needed.
Edit: Additional details
The matrix I have looks like this:
\begin{pmatrix} 0&d&0&0&.&.&.\\ 0&-(b+d)&2d&0&.&.&.\\ 0&b&-(2b+2d)&3d&0&.&.\\0&0&2b&-(3b+3d)&4d&0&.\\ .&.&0&3b&-(4b+4d)&5d&.\\.&.&.\end{pmatrix}
$b$ and $d$ are birth and death rates and both are positive. This is an infinite matrix since it is over all possible lattice sites. I don't know of any approximate methods either. That would be helpful too. This is a sparse tridiagonal matrix. But I don't know if I can apply the approximate methods that exist for finite matrices.
PS: From writing the generating function for the probability distribution and calculating it at long times, I know the first eigenvalue and the first eigenstate. But it is too complicated to write an expansion of the generating function for all times. Hence, I do not know how the other eigenstates look like. I also know that the zeroth eigenvalue is 0 and the corresponding eigenstate. Maybe that would help somehow?


text:
Q: Is there mechanical strain on a wire along the direction of current flow? The (attractive) magnetic force on two parallel wires can be seen by the two wires bending towards each other. This can be explained by the Lorentz force acting on the charges and the charges "pulling" transversally on the wires, because they cannot leave the wire because of the work needed to leave the wire.
Now the charges inside of a wire connected to the ends of a voltage source also experience a (generally much stronger) electric force along the main axis of the wire. As they collide with the atoms of the wire, shouldn't they "push" the wire in the direction of the positive cathode? Can this strain be measured?

A: When the current is constant, the net force on the free electrons is zero, as they are not accelerating, the average speed of the free electrons is constant.
That zero force can be decomposed to two parts: The force caused by the collisions and the force caused by the electric field.
How about positive charges?
They feel a force caused by the collisions with the electrons and a force caused by the electric field. Net force is zero also here. (for simplicity's sake, let's say N electrons are colliding with N protons)
When the current is changing, the force caused by the collisions is either larger or smaller than the force caused by the electric field. Also in this case there is a symmetry between negative and positive charges.
What happens if there is a superconducting ring on a frictionless surface, and we induce a current to the ring? Some electrons start to revolve to one direction, while rest of the ring starts to revolve to the opposite direction.


text:
Q: Android Handler reset I use the following code and a handler to produce a beep sound after 5 seconds from when my device is totally flat (accelerometer x,y values). Then the sound reproduces every 5 seconds if the device is still flat. The problem is that the code works fine for the first time that I will have the device flat but if it is not flat and try to put it flat again, the handler does not work and the sound produces immediately and follows the "lastBip" statement. I think I must try to reset the handler each time the device is not flat but I do not know how. What I want is that when my device is flat the sound should work after 5 seconds all the time that my application is running and not only the first time when I opened it. Does someone know what I must change to my code to work properly? Thank you in advance..
 handler.postDelayed(new Runnable() {
   @Override
   public void run() {

    if (x > -0.1 && x < 0.1 && y > -0.1 && y < 0.1 && System.currentTimeMillis() - lastBip > bipRate) {

        AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_RING);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_RING);
        float volume = streamVolumeCurrent / streamVolumeMax;
        lastBip = System.currentTimeMillis();
        soundPool.play(bipSoundID, volume, volume, 1, 0, 1);

    }

   }

 }, 5000);


text:
Q: Jquery - Enable an editorFor text field on button click I have an editorFor that starts off disabled that looks like this
 @Html.EditorFor(job => j.serialNumber, new { htmlAttributes = new { @class = "form-control", disabled = true} })

Then below that I have an edit button that looks like this
<input id="edit@(j.serialNumber)" type="button" class="noprint btn btn-primary" value="Edit" onclick="enableEdit('@(j.serialNumber)')" />

This calls my enableEdit method that currently looks like this
 function enableEdit(serialNumber) {

  }

What do I have to add to the method in order to enable the 'EditorFor' textbox?

A: You can set the id of the EditorFor element this way:
@Html.EditorFor(job => j.serialNumber, new { htmlAttributes = new { @class = "form-control", @id = "my-editor", disabled = true} })

Then, in your method you can select it by jquery and set the disabled prop.
$("#my-editor").prop("disabled", false);

https://learn.jquery.com/using-jquery-core/faq/how-do-i-disable-enable-a-form-element/


text:
Q: Integral part of sum of huge powers
Question: What is the integral part of the following expression?$$(a+\sqrt{b})^{2n}+(a-\sqrt{b})^{2n}$$

The question has specific values of $a=2,b=5$ and $2n=2016$.
I was able to simplify (or complexify) it to:$$\sum_{i=0}^n\binom{2n}{2i}a^{2i}b^{n-i}.$$
I think I need to use $$\binom{2n}{2i}=\binom{2n-1}{2i-1}+\binom{2n-1}{2i},$$
but because the powers of $a$ and $\sqrt{b}$ dont change I cant make a closed form.
Please help.

A: It is the Lucas number $L_{6048}$.
Explicitly:
$$\eqalign{&9062504429942830612498674723940636856073005180754102851103202470654400480862004\cr&470945569990318549786600962729358391458409742980121786528345516555311724482526\cr&469267214426875327939356480512886766136191123865898185909060509390911530211575\cr&250068296151787836515687295491384367878337029779507202772473247457611189758829\cr&765936634113604899116555301784760851901747848131875756210602568727367710580171\cr&895805654908212158642925592215357660076677734346857341254456623431865984405026\cr&892929174068925635521071005404413310101081812578653451740631688019712993398028\cr&457721524261115727978848468969621355164549034177997064126859568812631509397511\cr&016984199127347171026602653375690100545552519714738487571315942718492813756706\cr&082204335257998697204024192225222110769079285160314467805807823101456293333013\cr&846744313345219198803135032572074342248040447170428652954313635095193406457345\cr&312384800612815239265977428989281668436611671607920070840254359108721833323841\cr&188078628899091481176464496313126989415994801739336416785720301217234956031027\cr&978552035253675749937689863092976010498341281125560768668240052298434396165671\cr&537289666399741274176671027424411077085703975089732293442712775771653296648523\cr&231441100434648095729915791965725056427249879681535562607728243485574370058117\cr&109750914437122}$$

A: Define $c_0 = 2$, $c_1 = 4$, and $c_{n + 2} = 4c_{n + 1} + c_n$ for $n \geqslant 0$, then$$
c_n = (2 + \sqrt{5})^n + (2 - \sqrt{5})^n. \quad \forall n \in \mathbb{N}
$$
Note that$$
\begin{pmatrix}c_{n + 2}\\c_{n + 1}\end{pmatrix} = \begin{pmatrix}4 & 1\\ 1 & 0\end{pmatrix} \begin{pmatrix}c_{n + 1}\\c_n\end{pmatrix}.
$$
Denote $\displaystyle A = \begin{pmatrix}4 & 1 \\ 1 & 0\end{pmatrix}$, then$$
\begin{pmatrix}c_n\\c_{n - 1}\end{pmatrix} = A^{n - 1} \begin{pmatrix}c_1\\c_0\end{pmatrix}.
$$
(Tedious computation starts.) Because$$
2016 = 2^{10} + 2^9 + 2^8 + 2^7 + 2^6 + 2^5,
$$
and$$
A^2 = \begin{pmatrix}17 & 4 \\ 4 & 1\end{pmatrix}, A^{2^2} = \begin{pmatrix}305 & 72 \\ 72 & 17\end{pmatrix}, A^{2^3} = \begin{pmatrix}98209 & 23184 \\ 23184 & 5473\end{pmatrix}, \cdots
$$
then the explicit answer can be computed, but it is too hard to continue computing manually.

A: Note that $\displaystyle 2-\sqrt{5}=\frac{-1}{2+\sqrt{5}}$.
So, $\displaystyle (2-\sqrt{5})^{2n}=\frac{1}{(2+\sqrt{5})^{2n}}\in(0,1)$.
Let $K=(2+\sqrt{5})^{2n}+(2-\sqrt{5})^{2n}$ which is an integer.
$$ (2+\sqrt{5})^{2n}+(2-\sqrt{5})^{2n}= (2+\sqrt{5})^{2n}+\frac{1}{(2+\sqrt{5})^{2n}}$$
$$ K=\lfloor(2+\sqrt{5})^{2n}\rfloor+1$$


text:
Q: I don't want magento Frontend Customers Session to log out Automatically except they logout it manually If My Website Frontend Customers once login (Not Backend Admin Users), they should not be logged out Automatically. If they manually logout Then only it should be logged out.
I want this because if any registered customer comes to my site and view any product or add to cart then I can send them emails.
Please suggest if it is Possible.
This is my Current setting
In Magento Admin

In php.ini file

magento version : 1.9.2.0

A: Go to System -> Configuration -> Web -> Session Cookie management and set it to the value you need in the correct store view or if you have only one, in the default config.
Also keep in mind this has to be the same or lower than session.gc_maxlifetime in your PHP config. 0 should give you an endless session.


text:
Q: D3 Bubble View Getting Slower for bulk of records Could anyone suggest or help me

*

*I am using the D3 bubble js library for showing the data bulk of data

*I am facing the loading issue while using the bulk of data like 3K+ data is there any way to optimized or get load faster way.

Thanks in advance for the help.


text:
Q: Inconsistent console logs for NodeJS worker threads in AWS Lambda I have an lambda function which spins up a worker thread.
hello-world.js:
const { Worker } = require('node:worker_threads')

export const hello = async (event, context) => {
  console.log('Hello World')
  const w = new Worker('./build/other-file.js')
  return new Promise(resolve => {
    w.on('exit', () => {
      console.log('Goodbye')
      resolve()
    })
  })
}

other-file.js:
console.log('Blah Blah')

Defined in serverless.yml as:
functions:
  helloWorld:
    handler: build/hello-world.hello
    maximumRetryAttempts: 0

If I invoke this locally with serverless, I get what I'd expect:
15:40:59 $ sls invoke local --function helloWorld
Using serverless-localstack
Hello World
Blah Blah
Goodbye

If I invoke it on AWS each message from the function itself is also prefixed with a timestamp and an execution ID. This is very nice. However, it doesn't do this for messages from the worker thread.
15:44:00 $ aws lambda invoke --function-name sheetbuilder-dev-helloWorld out --log-type Tail --query 'LogResult' --output text | base64 -d
START RequestId: ebf33295-c59e-4182-a5b0-d436210f5e6f Version: $LATEST
2022-09-05T14:51:48.833Z    ebf33295-c59e-4182-a5b0-d436210f5e6f    INFO    Hello World
Blah Blah
2022-09-05T14:51:48.973Z    ebf33295-c59e-4182-a5b0-d436210f5e6f    INFO    Goodbye
END RequestId: ebf33295-c59e-4182-a5b0-d436210f5e6f
REPORT RequestId: ebf33295-c59e-4182-a5b0-d436210f5e6f  Duration: 154.59 ms Billed Duration: 155 ms Memory Size: 1024 MB    Max Memory Used: 73 MB  Init Duration: 192.28 ms
15:51:49 $

This also matches what I get if I look at the logs in Cloudwatch
Hence my questions are:

*

*Why's there a difference between the default output and the worker thread output?

*Is it possible / easy to make the worker thread output match the main output? (or at the very least include timestamp/execution ID)

*Is it possible to also make the serverless local output consistent?


text:
Q: Python drop rows containing ending characters from any column Is there a way other than specifying each column, i.e. df.drop(df[Col1]...,
where rows can be deleted based on a condition?
For example, can I iterate through Col1, Col2, ...through Col15 and delete all rows ending with the letter "A"?
I was able to delete columns using
df.loc[:,~ df.columns.str.startswith('A')]

A: IIUC, you have a pandas DataFrame and want to drop all rows that contain at least one string that ends with the letter 'A'. One fast way to accomplish this is by creating a mask via numpy:
import pandas as pd
import numpy as np

Suppose our df looks like this:
      0     1     2     3     4  5
0  ADFC  FDGA  HECH  AFAB  BHDH  0
1  AHBD  BABG  CBCA  AHDF  BCAG  1
2  HEFH  GEHH  CBEF  DGEC  DGFE  2
3  HEDE  BBHE  CCCB  DDGB  DCAG  3
4  BGEC  HACB  ACHH  GEBC  GEEG  4
5  HFCC  CHCD  FCBC  DEDF  AECB  5
6  DEFE  AHCH  CHFB  BBAA  BAGC  6
7  HFEC  DACC  FEDA  CBAG  GEDD  7

Goal: we want to get rid of rows with index 0, 1, 6, 7.
Try:
mask = np.char.endswith(df.to_numpy(dtype=str),'A') # create ndarray with booleans
indices_true = df[mask].index.unique() # Int64Index([0, 1, 6, 7], dtype='int64')
df.drop(indices_true, inplace=True) # drop indices_true
print(df)

out:
      0     1     2     3     4  5
2  HEFH  GEHH  CBEF  DGEC  DGFE  2
3  HEDE  BBHE  CCCB  DDGB  DCAG  3
4  BGEC  HACB  ACHH  GEBC  GEEG  4
5  HFCC  CHCD  FCBC  DEDF  AECB  5

A: A bit unclear on your requirements but maybe this fits.  Generate some words in columns for which end in 'A'.  If any string in the designated columns ends with 'A' then delete the row.
nb_cols = 9
nb_vals = 6

def wgen():
    return ''.join(random.choices(string.ascii_lowercase, k=5)) + random.choice('ABCDEFGH')

df = pd.DataFrame({'Col'+str(c): [wgen() for c in range(1,nb_vals)] for c in range(1,nb_cols+1)})
print(df)

     Col1    Col2    Col3    Col4    Col5    Col6    Col7    Col8    Col9
0  aawivA  qorjeA  qfjuoD  nkwgzF  auablC  aehnqE  cwuvzF  diqwaF  qlnpzG
1  aidjuH  ljalaB  ldhgsC  zaangH  mdtgkF  lypfnB  kynrxG  qlnygH  zzqyrC
2  pzqibD  jdumcF  ddufmG  xstdcH  vqpbkG  rjnqxD  ugscrA  kmvyaE  cykutE
3  gqpycH  ynaeeA  onirjE  mnbtyH  swjuzF  dyvmvC  tpxgsH  ssnhbD  spsojD
4  isptdF  qzpitH  akzwgE  klgqpH  pqpcqH  psryiD  tjaurC  daaieC  piduzE

Say that we are looking for the "ending A" in Col4-Col7.  Then row with index 2 needs to be deleted:
df[~df[['Col'+str(c) for c in range(4,7+1)]]
   .apply(lambda x: x.str.match('.*A$').any(), axis=1)]

     Col1    Col2    Col3    Col4    Col5    Col6    Col7    Col8    Col9
0  aawivA  qorjeA  qfjuoD  nkwgzF  auablC  aehnqE  cwuvzF  diqwaF  qlnpzG
1  aidjuH  ljalaB  ldhgsC  zaangH  mdtgkF  lypfnB  kynrxG  qlnygH  zzqyrC
3  gqpycH  ynaeeA  onirjE  mnbtyH  swjuzF  dyvmvC  tpxgsH  ssnhbD  spsojD
4  isptdF  qzpitH  akzwgE  klgqpH  pqpcqH  psryiD  tjaurC  daaieC  piduzE


text:
Q: Find the number of appointments booked for each treatment type Given these tables:

*

*DOCTOR (Doctor_ID, Surname, Specialization, Supervisor_ID, Address, Tel_No)

*APPOINTMENT (Doctor_ID, Dog_ID, Date, Time, Type_of_Treatment, Appointment_Length)

*PATIENT (Dog_ID, Breed, Sex, Name, Owner, Address)

Find the number of appointments booked for each treatment type.

A: I don't know what you are actually looking for. The simple query will be
Select Type_of_Treatment, count(Type_of_Treatment)
from APPOINTMENT
group by Type_of_Treatment;


text:
Q: Is there any option to create multiple dict from array elements in python I want to create multiple dict at one go :
I have a list: a=[a,b,c,d]
Now want to create multiple dict from the above list as a={},b={},c={},d={}

A: using dict
a=["a","b","c","d"]
print( dict((i,{}) for i in a) )

Output:
{'a': {}, 'c': {}, 'b': {}, 'd': {}}


text:
Q: How to call a stored procedure without passing parameter? I've created a SP in mysql, where I will be passing one IN parameter 'val'. In the body part of the procedure I'm using if else condition with select statements having 'val' in where condition of the query. In one of the select query, I don't want to use 'val'. So how to call procedure for the condition which doesn't use 'val' parameter. Thanks in advance, Krishna

A: Pass in a null value into your stored procedure and have your stored procedure detect a null and behave accordingly.
To call the stored proc with a null:
call my_proc(null);

Then inside the proc, here's how you "ignore" the parameter if it's null:
select ...
from ...
where ...
and (val is null or some_column = val)


text:
Q: Primary servers in capistrano I have a task in capistrano wherein I want just a single line to run only if the server is a marked as primary.  Is there a variable or method that I can reference inside a task?  'primary?' or 'primary' doesn't seem to work.
I've also tried something akin to the following:
after "deploy", "task1"
after "deploy", "task2"
after "deploy", "task3"

task :task1, :roles => :app do
  *code*
end

task :task2, :roles => :app, :only => {:primary => true} do
  *code for just primary server*
end

task :task3, :roles => :app do
  *more code*
end

But even this doesn't seem to work (all three tasks get run on every server).
I've been working on this on and off for a few days and I'm having no luck with my searches.  Thoughts?

A: I've solved the issue, but it wasn't pretty.  The thing that I've found is that you need to use the 'primary => true' on a per-task basis.  Looking at the code, it appears that capistrano generates a list of the servers that the task will be run on before the task is run.


text:
Q: How can I compute $\int\frac1{e^{ct}} dt $ $$ \displaystyle \int \dfrac{1}{e^{ct}} dt $$
How do I do this, I've tried substitution. Rewrite the above integral as $\displaystyle \int e^{-ct} dt $, then we have $u=-ct$, but at this point derivatives and integrals are confusing me. If we want $[e^u]'$, we just have $[e^u]u'$, but for integrals I've forgotten how to tackle this.

A: No need for the u-sub. The anti derivative is the e-power again. You just need to "account for" the derivative of your exponent, which is $-c$. So divide by that and you are done

A: Let $u=-ct$ then $du = -c\,dt$ or alternatively: $\,\,-\frac{1}{c}du = dt\,\,$ thus your integral becomes
$$\int e^{-ct} dt = -\int e^{u}\frac{1}{c}du = -\frac{1}{c}\int e^{u}du.$$
Can you take it from here?

A: Please change "numerator" to "denominator" in the title of your post, because the way you have written the integral the $e$ is in the denominator. In a fraction like $\frac35$ the $3$ is the numerator and the $5$ is the denominator; the numerator tells us how many of them there are (there are three of them), the denominator tells us what they are (they are fifths).
Now about that confusing integral $\int e^{-ct}dt$. I want a function whose derivative is $e^{-ct}$. I know how to differentiate exponential functions, but integration confuses me. What I do is use the "guess and correct" method. I know that the integral of $e^t$ is $e^t$; $e^{-ct}$ is sort of like $e^t$; my first guess is$$\int e^{-ct}dt=e^{-ct}.$$I check by differentiating:$$\frac d{dt}e^{-ct}=-ce^{-ct}.$$*Oops*, I got an unwanted factor of $-c$. I correct for that by dividing my first guess by $-c$:$$\frac d{dt}\frac1{-c}e^{-ct}=\frac1{-c}\cdot-ce^{-ct}=e^{-ct}.$$That worked!! So the correct answer is$$\int e^{-ct}dt=\frac{e^{-ct}}{-c}.$$


text:
Q: Core Plot - Creating a graph of increasing size based on realtime data Ive done some searching and haven't found anyone attempting anything similar so I figured id ask around here. What I'm trying to do is basically create a graph that will get data every say 5 seconds and plot it. So far the best I've done is allow the user to pan around a static graph of a static plot.
I'm currently trying to get to the point where I can press one button and it will create a new point on the graph based on a steady time interval for the X axis, and a random number from 1 to 100 on the Y axis. How I'm trying to do this is below:
@synthesize scatterPlot = _scatterPlot;
@synthesize statusLabel, data, isPlotting;

CGFloat xCoord;

- (void)startPlot:(id)sender {

    if (isPlotting == FALSE) {
        xCoord = 0;
    }

    if (isPlotting == TRUE)
    {
        statusLabel.text = @"Starting Plot";

        xCoord += 5;
        [data addObject:[NSValue valueWithCGPoint:CGPointMake(xCoord, (arc4random() % 100 + 1))]];

        self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:data];
        [self.scatterPlot initialisePlot];

        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(startPlot:) userInfo:nil repeats:NO];
    }
}

- (void)endPlot:(id)sender {
    statusLabel.text = @"Plotting Stopped";
    isPlotting = FALSE;
}

This is basically the core of how I'm trying to do the described task. The idea is that I press my 'start' button which calls startPlot and sets the isPlotting value to true, then i increment my xCoord value which will be the time by an arbitrary 5, for 5 seconds, then I generate and add my new point to my NSMutableArray array called data. After that I reinitialize my scatter plot and start a timer to sleep for 5 seconds and call the startPlot function again.
The problems I've been running into is that it either just doesnt update and I get a blank X and Y axis with no points. In any case there is something that I'm missing that I'm hoping someone knows and can help me out!
Thank You!
-Karoly

A: What you are describing is a real-time plot, almost like an oscilloscope right? Have you looked at the example app; specifically the Plot Gallery project in the Real Time Plot? That should be it, it's in the examples folder.
Look the RealTimePlot class (in the project tree, under the Plots group), basically what is being done is setting up a timer that calls the method -(void)newData:(NSTimer *)theTimer add a new point to the data array, redraw and move the CPTPlotRanges.
What version of CorePlot are you using?


text:
Q: Tomcat Maven plugin throwing exception at webapp deployment I am attempting to deploy my webapp using maven to an embedded tomcat server.  I am running into issues.
My project is a multi-module maven project.  I have a number of "jar" modules, and then a web-app that uses these jars. When I deploy to a locally installed tomcat server, it works properly.  When I have already built and installed the other jars, then separately build and deploy the webapp to the embedded server, it also works properly.  When I attempt to build the entire project, jars and the webapp, the embedded tomcat server deployment fails.  Whatever I try, it always comes down to one of my jars seems to not be deployed.  Tomcat complains that it cannot find some class that is located within this one jar.  When I remove that class, then Spring complains that it cannot find a applicationContext.xml file which is located within this same jar.  It comes down to one of my jars is not being found.
I have been trying to investigate why this jar is not being found.  I ran maven with the -X to get more data.  I did find this:
[DEBUG] add dependency to webapploader com.myproject:security-lib:1.0-SNAPSHOT:compile
[DEBUG] skip adding artifact security-lib as it's in reactors
But, I also noticed that all of my own jars get this same message. They seem tobe found by tomcat.
Does anyone have any suggestions why my embedded tomcat server is not getting this jar file?  And why the embedded tomcat server works when I deploy it by itself, but does not work when I deploy it while building the entire project?  Any tips on debugging this would be appreciated.

A: I found the issue.  I was using the "run" goal.  I intended to use the "run-war" execution goal for the tomcat-maven-plugin.


text:
Q: how to replace a word in string in php? <?php
        $querysb=mysql_query("SELECT  * FROM services WHERE cid='".$_GET[id]."'");
        $rowsb=mysql_fetch_assoc($querysb);
        ?>

           <?php $str=$rowsb['cname'];
            $str = mb_convert_case($str, MB_CASE_TITLE);
            echo $str;?>

the output of this code is Hello/hi World but i want this to be Hello/Hi World.

A: In that case you can use ucwords() function

string ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] )

PHP ucwords

A: have a look on ucwords function
<?php

$str = 'Hello/hi World';

echo ucwords($str, '/');

output
Hello/Hi World

seet result at: https://3v4l.org/XhORd


text:
Q: When to return a jQuery function as opposed to just calling it? I've been doing some reading about queueing JS callbacks without stacking them over here,
How do I animate in jQuery without stacking callbacks?
I've tried playing around Julian Aubourg's answer, and I noticed that after removing the "return" statements from the functions, everything happens at once.
I'm just wondering what the behavior of these return statements are, and what role they play in making this code synchronous.
    $('div1').fadeOut('slow').promise().pipe(function() {
        return $('div2').fadeOut('slow');
    }).pipe(function() {
        return $('div3').animate({ top: 500 }, 1000 );
    });

A: All jQuery animations now return their own promise, so basically you're returning a promise that is resolved when the animation completes when you do :
return $('div2').fadeOut('slow');

It would be equivalent to
var def = new $.Deferred();
$('div2').fadeOut('slow', function() {
    def.resolve();
});
return def.promise();


text:
Q: NativeBase - ReactNative - Dropdown Do you have any ideas to how to do that?
A dropdown list opened by clicked on the button and this dropdown list contain a other list of items. And dynamically if it's possible!
For example:
Categories: Fruits, Foods (the first dropdown list)
And in this categories there is a list for each categories :
Fruits : ["Banana", "Apple", "Strawberry"]
Foods: ["1", "2", "3"].
Looks like this :

A: I have an idea for you, hope this could solve your problem. For now there is no way to add nested Picker component. So I came up with this idea:
first is restructure the data
const data = [
    {'title' : 'Fruits',
    'items' : ["Banana", "Apple", "Strawberry"]
    },
    {'title' : 'Foods',
    'items' : ["1", "2", "3"]}
]

next create state toggle for show component while we click the button
 constructor() {
  super();
  this.state = {
      toggleDropdown: false
  }
}

next is create function to trigger the state
onClickButton = () => {
  this.setState({
      toggleDropdown: !this.state.toggleDropdown
  })
}

make button for showing the dropdown
<Button primary onPress={this.onClickButton}>
   <Text>Click Me!</Text>
</Button>

and show the dropdown
{this.state.toggleDropdown &&  //cek if toggle is true or false
            data.map((item, index) => { //loop the first dropdown
                return (
                    <Content key={index}>
                        <Text style={{backgroundColor: '#CCC'}} >{item.title}</Text>
                        <Picker mode="dropdown" >
                            {item.items.map((value, idx) => { //loop the second dropdown
                                return(
                                    <Item key={idx} label={value} value={idx} />
                                )
                            })}
                        </Picker>
                     </Content>
                )
            })
        }

this is the full source code :
import React, { Component } from 'react';
import { Container, Content, Text, Button, Picker, Item } from 'native-base';

const data = [
        {'title' : 'Fruits',
        'items' : ["Banana", "Apple", "Strawberry"]
        },
        {'title' : 'Foods',
        'items' : ["1", "2", "3"]}
]

class Example extends Component {
  constructor() {
      super();
      this.state = {
          toggleDropdown: false
      }
  }
  onClickButton = () => {
      this.setState({
          toggleDropdown: !this.state.toggleDropdown
      })
  }
  render() {
    return (
        <Container>
          <Content>
            <Button primary onPress={this.onClickButton}>
                <Text>Click Me! </Text>
            </Button>
            {this.state.toggleDropdown &&  //cek if toggle is true or false
                data.map((item, index) => { //loop the first dropdown
                    return (
                        <Content key={index}>
                            <Text style={{backgroundColor: '#CCC'}} >{item.title}</Text>
                            <Picker mode="dropdown" >
                                {item.items.map((value, idx) => { //loop the second dropdown
                                    return(
                                        <Item key={idx} label={value} value={idx} />
                                    )
                                })}
                            </Picker>
                         </Content>
                    )
                })
            }
           </Content>
        </Container>
    );
  }
}

export default Example

and this is the screenshot :
Screenshot
i hope it can help you :)


text:
Q: Issue while updating @OneToMany collection I am stuck at a point where i am trying to update a @OneToMany mapping.
Problem:
I have 2 entities: Criteria and Tasks. A criteria can contain multiple tasks.
class Criteria {
    @OneToMany(mappedBy = "criteria", cascade = { CascadeType.PERSIST,
    CascadeType.MERGE, CascadeType.REFRESH }, fetch = FetchType.LAZY)
    @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE,
               org.hibernate.annotations.CascadeType.ALL,
               org.hibernate.annotations.CascadeType.MERGE,
               org.hibernate.annotations.CascadeType.PERSIST })
     private Set<Task> tasks;
}

class Task {
    @ManyToOne
    @JoinColumn(name = "CRITERIA_ID", nullable=false)
    private Criteria criteria;
}

I am trying to update an existing Criteria with new set of tasks. This requires removing all existing tasks and adding new tasks.
Here is how i am doing:
criteriaDao.persist(criteria);
Set<Task> existingTasks=criteria.getTasks();
if(existingTasks != null) {
    for (Task task : existingTasks) {
        task.setCriteria(null);
    }
    criteria.setTasks(tasks);
    //more code which sets criteria for each task - this works if i try to save new criteria with new tasks
}

Hibernate is throwing an exception:
Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (CCA_DEV_5.TASK__UN) violated

This exception is thrown because it didn't remove the existing tasks.
If i only delete all the tasks, it works perfectly and removed all the tasks for the given criteria with below code:
criteriaDao.persist(criteria);
Set<Task> existingTasks=criteria.getTasks();
if(existingTasks != null) {
    for (Task task : existingTasks) {
    task.setCriteria(null);
}
}

I tried all options of using merge after adding new tasks and more stuff but nothing seems to work for me. I am badly stuck here and definately missing something very basic in Hibernate.
Thanks in advance.!

A: In your Task class you should have no reference to Criteria at all. Just remove it along with its annotations.
Then, instead of setting the Criteria referenced by the Task, as this reference no longer exists, just use criteria.setTasks(newTasks) and save criteria.

Let me explain a bit. The relation between Criteria and Task is obvoiusly Criteria 1 --- n Tasks - 1 to n. Now, you can call one-to-many relation and you can call it many-to-one, depends on your point of view. Looking from Criteria oint of view, it's one-to-many, while looking from Task point of view - it's many-to-one. Generally, it's advisable and more intuitive to choose one of these point of views and stick to it. Choosing a point of view, defines the entity that "controls" the relation thorugh which any modification should be applied.
In your case, if you regard a Criteria as containing or owning a set of Tasks - you'd treat the relation as one-to-many. After deciding that, no need for Criteria reference in the java class of Task. You control the relation solely with Criteria API (the table created for Task in the DB, however, does have a column that refers its containing Criteria).


text:
Q: How can I get the JButton to run a class dependent on what is selected by the user in the JComboBox I have created a user interface in Eclipse whereby the I require the user to select an option in the JComboBox and click the JButton to start the event. Depending on which option they select, a different class will be run and output its results. Everything is set up fine and the JButtons work on their own but I cannot get them to respond to changes in the JComboBox.
This is a sample of the code and the class which starts the interface (The full code is longer and contains more buttons etc. hence the extra columns and rows):
package projectFinal;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class test extends JFrame {

  public test() {

    setTitle("BIM Representative GUI");

    JPanel pane = new JPanel(new BorderLayout());

    int numberOfRows = 8;
    int numberOfColumns = 4;
    pane.setLayout(new GridLayout(numberOfRows, numberOfColumns));

    JLabel metric1label = new JLabel(" Greenhouse Gas Emissions: ");
    pane.add(metric1label);
    JLabel metric1alabel = new JLabel("  ");
    pane.add(metric1alabel);
    String[] pollutants = { "Total","CO2", "CH4","N2O"};
    final JComboBox<String> cb1 = new JComboBox<String>(pollutants);
    cb1.setVisible(true);
    getContentPane().add(cb1);
    JButton button1 = new JButton("Check");
    pane.add(button1);

    getContentPane().add(pane);

    pack();

    button1.setToolTipText("This button will show the Greenhouse Gas Emissions");

    button1.addActionListener(new MyActionListener1());

  }
  public class MyActionListener1 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String choice = (String)cb1.getSelectedItem();
            if(choice.equals("Total"))
        {
            GHGEmissions.UI();
        }
        if(choice.equals("CO2"))
        {
            CO2Emissions.UI();
        }
        if(choice.equals("CH4"))
         {
             CH4Emissions.UI();
         }
        if(choice.equals("N2O"))
             {
             N2OEmissions.UI();
        }
             }
}}

And the code for running the interface:
package projectFinal;

import projectFinal.test;

public class testRun {
      public static void main(String[] args) {
          test view = new test();
        view.setVisible(true);
      }
    }

The JComboBox does not appear on the interface at all (it does when the String choice and if statements are removed). Does anybody know how I can fix this so that it will run the different classes depending on the JComboBox.
The only part that is showing a problem is cb1 in the line:
            String choice = (String)cb1.getSelectedItem();

Thanks

A: cb1 is a local variable in you constructor, so you need to declare your ActionListener as annoynimus class in order to access cb1 variable,
button1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // you code.

        }
    });

Also tou need to compare String using .equals() method not ==.
So try to change your code to something like:
if(choice.equals("Total"))
{
    GHGEmissions.UI();
}

Refer to this for more details.


text:
Q: Exercise in algebra with modulo I'm studying Cassels' book Elliptic Curves for a week now, and I'm at the local global principle. I'm trying to prove the first exercise of this chapter, which says

Let $p > 2$ be prime and let $b, c \in \Bbb Z$ and $ p $ does not divide $b$. Show that $bx^2 + c$ takes
  precisely $\frac {p + 1}{2}$ distinct values $p$ for $x \in \Bbb Z$.

The problem here is that i don't understand what "values $p$" means. At first i thought that it means $\mod(p)$ values, but if that was the case, then for $x=0\in \Bbb Z$,we have that the $b\cdot 0^2+c=c$ can take $p-1$  values $\mod(p)$, $\{0,1,...,p-1\}$, and then we should have that $p-1=\frac {p + 1}{2}=>p=3$ which restricts the exercise.
So what  does "values $p$" mean?
Thank you!

A: Since $b$ is not divisible by $p$ it has an inverse under multiplication, call it $b'$ for now, such that $b'b=1$ mod $p$. Then the equation $bx^2=c$ may be multiplied on both sides by $b'$ to get $b'bx^2=b'c,$ which since $b'b=1$ is the same as the equation
$$x^2=b'c \tag{1}$$
Thus since $b,c$ are fixed we may as well define $d=b'c$ and we're looking at the equation $x^2=d$. Now note that $x^2=(-x)^2$ for any $x$, and note that if $d \neq 0$ the values $x,-x$ are distinct, otherwise $2x=0$ and then $x=0$ since $p$ is odd. The solution to $x^2=0$ is only $x=0$, so that counts as one, and the other solutions can be paired up as $x,-x$ as indicated above. The "values taken on" are then the various possible $b$ which can appear on the right side of $x^2=b$, so by the 2-to-1 ness of the solutions for nonzero $b$ there are $(p-1)/2$ with nonzero $b$, and one more solution when $b=0$, for a total of $(p-1)/2+1=(p+1)/2.$
Once you've arrived at $x^2=b$ you are looking for values of $b$ which are either $0$ or else are what is called "quadratic residues". If you google the latter you can likely find sites where this count of the quadratic residues is done more carefully than outlined above.


text:
Q: Exception setting (example) iBeacon parser layout with Android Beacon Library I have integrated the 2.0-beta6 version of https://github.com/AltBeacon/android-beacon-library into my Android app. With debug turned on I see my Roximity iBeacons being seen, but being rejected by the beacon parser as the bytes are unexpected.
In the reference application there is the following note:
    // By default the AndroidBeaconLibrary will only find AltBeacons.  If you wish to make it
    // find a different type of beacon, you must specify the byte layout for that beacon's
    // advertisement with a line like below.  The example shows how to find a beacon with the
    // same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb
    //
    // beaconManager.getBeaconParsers().add(new BeaconParser().
    //        setBeaconLayout("m:2-3=aabb,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
    //
    // In order to find out the proper BeaconLayout definition for other kinds of beacons, do
    // a Google search for "setBeaconLayout" (including the quotes in your search.)

I created what I thought is the right formatted string (at leas good enough for my test application) and attempted to set it with the following very defensive code:
        List<BeaconParser> beaconParsers = beaconManager.getBeaconParsers();
        if (beaconParsers  != null) {
            // We can add a new parser
            String roximityBeaconParser = this.getRoximityBeaconParserString();
            BeaconParser beaconParser = new BeaconParser();
            Log.e("iBeacon", "About to set BeaconLayout with " + roximityBeaconParser);
            try {
                beaconParser.setBeaconLayout(roximityBeaconParser);
                beaconParsers.add(beaconParser);
            } catch (BeaconLayoutException e) {
                e.printStackTrace();
            }
        }

My own string caused an error, so I changed my function to get parser string to simply copy the example from the note:
private String getRoximityBeaconParserString() {
    String result = "m:2-3:beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25";

    return result;
}

The line of code that attempts to set the parser string causes a BeaconLayoutException:
beaconParser.setBeaconLayout(roximityBeaconParser);

The exception stack trace has no useful information to say what is wrong with the string.
What am I doing wrong?

A: Okay figured it out. I copied the example from the parser function's comment and that has a colon and not an equal character - ironically the parser function's comment is wrong. Thus
m:2-3:beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25

is wrong, whereas
m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25

is right. The difference is the "=" character after the "m:2-3" characters.
For reference, the parsing code is found at The Parsing Source Code has the following patterns:
private static final Pattern I_PATTERN = Pattern.compile("i\\:(\\d+)\\-(\\d+)(l?)");
private static final Pattern M_PATTERN = Pattern.compile("m\\:(\\d+)-(\\d+)\\=([0-9A-F-a-f]+)");
private static final Pattern D_PATTERN = Pattern.compile("d\\:(\\d+)\\-(\\d+)([bl]?)");
private static final Pattern P_PATTERN = Pattern.compile("p\\:(\\d+)\\-(\\d+)");

This is what the string is parsed against.
What is not clear from the documentation is that the parsing function requires a (single) power ("p") element, requires a (single) matching ("m") element, and at least one identifier ("i") element to be valid. Otherwise an exception is thrown.
As we can't see/debug into the parser method, I ended up copying the top level method into my class (along with the initialized variables it relies on) and then called the local copy of the function to figure out why it was complaining. The big issue is that if there is a term (one of the comma separated values) that does not perfectly match against the patterns then a general purpose "can't parse this term" exception is thrown and that is not easy to debug. Hence I copied the function and called it to see what was thrown and why.


text:
Q: LINK : fatal error LNK1104: cannot open file 'C:\Users\hp\.pyxbld\lib.win32-2.7\gensim\models\word2vec_inner.pyd' I run the sourcecode of TWE model. I need to compile the C extension of python. I have installed the Microsoft Visual C++ Compiler for Python 2.7 and Cython.
First, I need to run the TWE/train.py:
import gensim
sentence_word = gensim.models.word2vec.LineSentence("tmp/word.file")
print "Training the word vector..."
w = gensim.models.Word2Vec(sentence_word,size=400, workers=20)
sentence = gensim.models.word2vec.CombinedSentence("tmp/word.file","tmp/topic.file")
print "Training the topic vector..."
w.train_topic(topic_number, sentence)
print "Saving the topic vectors..."
w.save_topic("output/topic_vector.txt")
print "Saving the word vectors..."
w.save_wordvector("output/word_vector.txt")`

Second, TWE/gensim/models/wor2vec.py:
try:
    raise ImportError  # ignore for now
    from gensim_addons.models.word2vec_inner import train_sentence_sg,train_sentence_cbow, FAST_VERSION, train_sentence_topic
except ImportError:
    try:
        import pyximport
        print 'import pyximport'
        models_dir = os.path.dirname(__file__) or os.getcwd()
        print 'models_dir'
        pyximport.install(setup_args={"include_dirs": [models_dir, get_include()]})
        print 'pyximport'   # is the follow code's problem
        from word2vec_inner import train_sentence_sg, train_sentence_cbow,
        FAST_VERSION, train_sentence_topic
        print 'from word2vec'
    except:
        FAST_VERSION = -1
        def train_sentence_sg(model, sentence, alpha, work=None):
                   ...
        def train_sentence_cbow(model, sentence, alpha, work=None, neu1=None):
                   ...
class Word2Vec(utils.SaveLoad):
                   ...
    def train(self, sentences, total_words=None, word_count=0, chunksize=100):
        if FAST_VERSION < 0:
        import warnings
        warnings.warn("Cython compilation failed, training will be slow. Do you have Cython installed? `pip install cython`")
        logger.info("training model with %i workers on %i vocabulary and %i features, "
        "using 'skipgram'=%s 'hierarchical softmax'=%s 'subsample'=%s and 'negative sampling'=%s" %
        (self.workers, len(self.vocab), self.layer1_size, self.sg, self.hs, self.sample, self.negative))
         def worker_train():
              ...
             if self.sg:
                 job_words = sum(train_sentence_topic(self, sentence, alpha, work) for sentence in job)
             else:
                 ob_words = sum(train_sentence_cbow(self, sentence, alpha, work, neu1) for sentence in job)`
              ...

Thrid, I haved compiled the TWE/gensim/models/word2vec_inner.pyx with a setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
extensions = [
    Extension("word2vec_inner", ["word2vec_inner.pyx"],
              include_dirs=[numpy.get_include()])
]
setup(
    name="word2vec_inner",
    ext_modules=cythonize(extensions),
)

by using the command 'python setup.py install', I have complied the word2vec_inner.pyx. But it appears the follow errors:
E:\Python27\python.exe D:/pycharm/TWE/TWE1/train.py wordmap.txt model-final.tassign 100
import pyximport
models_dir
pyximport
word2vec_inner.c
e:\python27\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12) : Warning Msg : Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
C:\Users\hp\.pyxbld\temp.win32-2.7\Release\pyrex\gensim\models\word2vec_inner.c(15079) : warning C4244:
'initializing' : conversion from 'double' to 'float', possible loss of data
C:\Users\hp\.pyxbld\temp.win32-2.7\Release\pyrex\gensim\models\word2vec_inner.c(15085) : warning C4244 : 'initializing' : conversion from 'double' to 'float', possible loss of data
LINK : fatal error LNK1104: cannot open file 'C:\Users\hp\.pyxbld\lib.win32-2.7\gensim\models\word2vec_inner.pyd'
Training the word vector...
D:\pycharm\TWE\TWE1\gensim\models\word2vec.py:410: UserWarning: Cython compilation failed, training will be slow. Do you have Cython installed? `pip install cython`
warnings.warn("Cython compilation failed, training will be slow. Do you have Cython installed? `pip install cython`")
PROGRESS: at 100.00% words, alpha 0.02500, 2556 words/s
Training the topic vector...
D:\pycharm\TWE\TWE1\gensim\models\word2vec.py:882: UserWarning: Cython compilation failed, training will be slow. Do you have Cython installed? `pip install cython`
warnings.warn("Cython compilation failed, training will be slow. Do you have Cython installed? `pip install cython`")
Exception in thread Thread-23:
Traceback (most recent call last):
  File "E:\Python27\lib\threading.py", line 801, in __bootstrap_inner
      self.run()
  File "E:\Python27\lib\threading.py", line 754, in run
      self.__target(*self.__args, **self.__kwargs)
  File "D:\pycharm\TWE\TWE1\gensim\models\word2vec.py", line 909, in worker_train
     job_words = sum(train_sentence_topic(self, sentence, alpha, work) for sentence in job)
  File "D:\pycharm\TWE\TWE1\gensim\models\word2vec.py", line 909, in <genexpr>
     job_words = sum(train_sentence_topic(self, sentence, alpha, work) for sentence in job)
NameError: global name 'train_sentence_topic' is not defined

Saving the topic vectors...
Saving the word vectors...

Process finished with exit code 0

I have checked that the .pyx file was compiled correctly and also installed the cython. in conclusion, it can't import train_sentence_sg,train_sentence_cbow, FAST_VERSION, train_sentence_topic from gensim/models/word2vec_inner or gensim_addons/models/word2vec_inner. So it appears these problems. But why? I have compiled the .pyx file correctly in both two directionarys. Anyone can help me? This problem haved troubled me several days. Please help me, thank you!

A: I ran into the same problem with PyCharm 2018.1 + Python 3.6.2.
This line is the key:
LINK : fatal error LNK1104: cannot open file 'C:\Users\hp\.pyxbld\lib.win32-2.7\gensim\models\word2vec_inner.pyd'

This error message is misleading. With Python, this error actually means:

*

*cannot open file to write to it.

The file is probably locked for writing by some process, so the linker cannot complete its job.
Solution 1
A previous Python line import word2vec_inner locked writing to the file. Reset the Python console to remove the lock:

Solution 2
Use Process Explorer to find out which program is locking the file. Use Ctrl-F, then type the name of the locked file in question, and it will give you the process that locked the file.
Solution 3
Exit Pycharm, then precompile the Cython file into a package on the command line. In case this link changes, here is a mirror:

Imagine a simple "hello world" script in a file hello.pyx:
def say_hello_to(name):
    print("Hello %s!" % name)

The following could be a corresponding setup.py script:
from distutils.core import setup
from Cython.Build import cythonize

setup(
  name = 'Hello world app',
  ext_modules = cythonize("hello.pyx"),
)

To build, run python setup.py build_ext --inplace. Then simply start
  a Python session and do from hello import say_hello_to and use the
  imported function as you see fit.
One caveat if you use setuptools instead of distutils, the default
  action when running python setup.py install is to create a zipped egg
  file which will not work with cimport for pxd files when you try to
  use them from a dependent package. To prevent this, include
  zip_safe=False in the arguments to setup().


text:
Q: Android auto GPS on/off code not working with Samsung Galaxy Y I am using code to Auto GPS on/off this code is working fine with Karbonn handset but not on Samsung Galaxy Y.
public void turnGPSOn() {
    Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    sendBroadcast(intent);

    String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (!provider.contains("gps")) {
        // if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3"));
        sendBroadcast(poke);

    }
}

public void turnGPSOff() {

    String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider.contains("gps")) {
        // if gps is enabled
        final Intent gps = new Intent();
        gps.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        gps.addCategory(Intent.CATEGORY_ALTERNATIVE);
        gps.setData(Uri.parse("3"));
        sendBroadcast(gps);

    }
}

By using turnGPSOff method Samsung device does not make any change. turnGPSOn methods works well. But turnGPSOn method have a problem, by using this method after getting the fix GPS receiver does not go on sleep mode, it always blink on mobile screen. When i do not use this method then after getting fix GPS receiver go on sleep mode till next frequency value.
Any idea? Please help.


text:
Q: Sending notification message to android device curl error I'am trying to send notification message to android device using the code below the out put form the result is
Curl failed: Failed to connect to android.googleapis.com port 443:
Connection timed out

my server is amazon ec2.
my code :
public function send_notification($registatoin_ids, $message) {
    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';
    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,
    );
    $headers[] = 'Content-Type:application/json';
    $headers[] = 'Authorization:key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    // Open connection
    $ch = curl_init();
    // Set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_HEADER, true);
    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    // Execute post
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    // Close connection
    curl_close($ch);
    echo $result;
}

I just tried the code on another server it's working
{"multicast_id":5322863685330856855,"success":1,"failure":0,"canonical_ids":0,
"results":[{"message_id":"0:1401820119301203%a5dcde78f9fd7ecd"}]}

so i think there is something wrong with amazon ec2 settings

A: I figured out the problem my code was correct, port 443 was not open on the sever


text:
Q: mainDiv.innerHTML = external file I have a code.js file which contains the following:
DivDialogHTML = function(){
  var mainDiv = document.createElement("div");
  mainDiv.id = "optin_settings_dialog";
  mainDiv.className = "OptinDialog";
  mainDiv.innerHTML = "
Text
";
}

The code to load the popup (dont know if it's all code, but to get the idea):
DivDialogOverlayHTML = function(){
  var mainDiv = document.createElement("div");
  mainDiv.id = "optin_settings_overlay_dialog";
  mainDiv.className = "OptinDialog";
  return mainDiv;
}

renderOptinWindow = function(){
  var pageHead = document.getElementsByTagName("head")[0];
  var pageBody = document.getElementsByTagName("body")[0];
  if( pageHead && pageBody ){
    pageBody.appendChild( this.getDivDialogHTML() );
  }
}

Instead of using the mainDiv.innerHTML = '
Text
' I'd like the mainDiv.innerHTML to open another file (Dialog.html).
How do I do that?

A: with Ajax. But why not using jQuery?
$('.selector').load(url);

In your case you have to insert jQuery first like this in your

And than take your existing function and change it like this
DivDialogHTML = function(){
    var $mainDiv = jQuery("div");
    $mainDiv.attr('id', "optin_settings_dialog");
    $mainDiv.addClass("OptinDialog");
    /* $mainDiv.html("
Text
"); */
    $mainDiv.load('Dialog.html');
}

A: Do you mean another window? If so, please take a look at window.open
window.open
After you create new window, you put its contents and display

A: if you don't want to use jQuery you can use an iframe
HTML

Javascript
document.getElementById("optin_settings_dialog").src="Dialog.html";


text:
Q: Font size increases button volume. What is the correct behaviour? I have a button , well .. actually a <li> acting as one. I shape it with the padding without giving it any height. For a click effect, I set font increase +1 on active. Now, on Firefox it expands the button, which is not what I want. On Chromium it does it right and keeps the button size constant while increasing the font size. I can fix this with setting the buttons height - no problem. Although it is not ideal.
But I am just wondering what is the correct behaviour? Should the font size expand the button or should it not?
I assumed that with IE out of the way, two compliant browsers should agree on how to render stuff in common scenarios.
Thanks.
UPDATE
I do apologise for not including the CSS. I thought the wording is simple enough. Here is the sample ...
<!DOCTYPE html>

<html>
  <head>
    <title>Basal</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="base2.css">
  </head>
  <body>
    <nav>
      <ul>
        <li> Create </li>
        <li> Read </li>
        <li> Update </li>
        <li> Delete </li>
      </ul>
    </nav>
  </body>
</html>

And the CSS ...
html, body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

nav ul {
  display: flex;
  border: 2px solid #232B2B;
  border-radius: 5px;
}

nav ul li {
  flex: 1;
  display: inline-block;
  border-right: 2px solid #232B2B;
  text-align: center;
  padding: 5px 0;
  cursor: pointer;
  background: #685642;
  font-size: 16px;
}

nav ul li:last-child {
  border-right: 0;
}

nav ul li:hover {
  background: #74695C;
}

nav ul li:active {
  font-size: 18px;
}

In Firefox, It expands the <li> container every time I click it. In Chromium - it does not. In Chromium it just increases the font size keeping the container size constant.
Firefox - 28.0
Chromium -  34.0.1847.116 (260972)

A: If you're increasing the font size, it would make sense that when the font gets large enough, the "li" container will also have to increase its size to keep it contained.

A: I test your question in chrome, and it does the same as it in Firefox.When you set font increase +1 on active, you must set the active button's attribute "padding-top" or "padding-bottom" decrease the same size.
Browser calculate button's height as follows:
height=margin-top+border-top+padding-top+height+padding-bottom+border-bottom+margin-bottom
You can search CSS box model to see more detail.

A: The height of an element generally depends on the height requirements of its content. The details have intentionally been left browser-dependent in CSS specifications. Increasing font size may or may not increase the height requirements; typically, an increase of 1px does not, an increase of 2px does.
For the given code, both Firefox and Chrome (34.0.1847.131, Win 7) increase the height of the li element when it is activated. The difference is that on Chrome, the increased height remains even when the element returns from active state to normal state. This is probably unintentional and might be classified as a bug. (The effect can perhaps be seen better if you add :active { background: red }.)
In general, you should not expect different browsers to assign the same height to an element unless you explicitly set the height.


text:
Q: How can I make a certain part of my form scrollable? I'm making a program in vb6 that requires me to be able to scroll a certain area of the screen to the right. It consists solely of lines and picture boxes, is there a way to only scroll that area? Thanks!

A: You can take advantage from the fact that some visual controls can act as container of other visual controls.
Just an example:
In the VBIDE, place a Frame over a VB Form. Then - inside this Frame place a PictureBox. Pay attention that the PictureBox shall be fully contained inside this Frame.
Now, if you drag the Frame around the Form, you will see that the PictureBox inside is moving together, while keeping the position inside the container Frame, i.e. it will keep the original top & left coordinates relative to the container control.
To find out which visual controls have this capability, simply retry the test. You will see, for example, that a Label can't act as a container.
That said, you need following:

*

*one visual control (preferably a PictureBox) which act as container (the viewport)

*one visual control (preferably a PictureBox) which act as scrollable area

*a HScrollBar (and, optionally, a VScrollBar) to scroll the
view-able area

Now, inside the second PictureBox (the scrollable area) you can place your controls, the Lines and PictureBoxes you mentioned in your question.
Why is a PictureBox preferable? Because you can profit from the ScaleMode property, set it to 3-Pixeland use pixel-exact scrolling. With Frames you can't do that, you are limited to just Twips.
By using a contained control you have two advantages:

*

*you can visually place and reposition the controls ypu need inside the IDE

*you need to scroll just only one control - all other hosted controls will
move together

The boring thing you must code is the synchronization of the container with the ScrollBars.
But luckily, as VB6 has been going a long way, you will find enough cut-and-paste code examples of such a task, one of which is on VBForums: Scroll bar in picturebox
Some final notes:
PictureBoxes in VB6 are constrained to a maximum size of 16,383 x 16,383 pixels. If your scrollable area should be bigger, you may implement a kind of custom "infinite scroller", and manage the position of your controls by grouping them, and you will need some additional coding.
ScrollBars in VB6 can range from a minimum value of -32,768 to a maximum value of 32,767. If you need more, you will end up with some other additional coding tasks.
If you stick to Twips, you can have a bigger logical area available - for example: until 245,745 with the typical 15 TwipsPerPixel - but you can't use such a big value with ScrollBars.

A: Here is a simple example illustrating what you requested.  The key is that the scrollable area must be a container control hosting the controls you wish to scroll.
Option Explicit

Private oldPos As Integer

Private Sub Form_Load()
   HScroll1.Min = 0
   HScroll1.Max = 1000
   HScroll1.SmallChange = Screen.TwipsPerPixelX * 10
   HScroll1.LargeChange = HScroll1.SmallChange
End Sub

Private Sub HScroll1_Change()
   ScrollPictureBox
End Sub

Private Sub HScroll1_Scroll()
   ScrollPictureBox
End Sub

Private Sub ScrollPictureBox()
   Dim c As Control

   For Each c In Me.Controls
      If c.Container.Name = "Picture1" And Not TypeOf c Is HScrollBar Then
         c.Left = c.Left - (oldPos - HScroll1.Value)
      End If
   Next

   oldPos = HScroll1.Value
End Sub

In this code, Picture1 is a PictureBox (the scrollable area) containing HScroll1 (a horizontal scrollbar) and the other controls you wish to scroll.


text:
Q: Bundling the Windows Mono runtime with an application Regarding my earlier question about the Point of Mono on Windows, let's say that I develop an app against the windows mono runtime so that it will also run on Linux, OSX, etc.. and to make it more complicated, I use GTK# so that I don't have to deal with WinForms.  Is there then an easy way to bundle the Windows Mono runtimes with my Windows version of the application so that it can all be installed at once?  Or, is there no point to this?  Once I develop against the Windows Mono runtime, would it still run fine against the MS .NET runtime?  (I assume I would still need GTK# installed though).

A: The short answer is Yes.
The things you should take care about while programming are

*

*Not to use platform API

*Don't hardcode directory & file name separators, i.e. don't hardcode file paths, but use appropraite class to obtain path separator then concat the names.

*Keep in mind that file names on *nx are case sensitve and on Windows are not. While programming don't refer to the same file as log.txt and Log.txt but keep it all small.

Other then that, if you created GTK# application on *nx system, you will be able to run it on Windows if you installed GTK# assembly, and vice-versa.
I did this myself, and it worked like expected. I had a problem to find specific assembly dll version of GTK# on Windows and that took me few hours.

A: In general, you probably would just use the .Net runtime on Windows.  The installer for GTK# for .Net is available from Mono's download page.  Your users would need this installed, and then could run you app using the regular .Net runtime.


text:
Q: Generic function to return list of objects using ISession's CreateCritieria function in nHibernate I could able to create a list of objects by doing like this:
using (var session = sessionFactory.OpenSession()) {
    ICriteria criteria = session.CreateCriteria<Foo>();
    IList<Foo> Foo = criteria.List<Foo>();
}

where Foo is my class.
I wish to write a generic function to return list of object depending on the input Type as shown below:
public IList<T> GetObjList <T> (T obj)
{
    IList<T> list;
    try {
        var sessionFactory = CreateSessionFactory();
        if (sessionFactory == null)
            return null;
        using (var session = sessionFactory.OpenSession()) {
            ICriteria criteria = session.CreateCriteria<T>(); //Error
            list = criteria.List<T>();
        }
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message);
        return null;
    }
    return list;
}

I'm getting the following compiler error in the line ICriteria criteria = session.CreateCriteria()
The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NHibernate.ISession.CreateCriteria<T>()'

Please help me to solve this.

A: Generic type parameters can be further constrained to limit what can be provided as such parameter. What your error message says, is that NHibernate.ISession.CreateCriteria<T>() requires its type parameter to be constrained to reference type. Since your method doesn't define any constraint at all, C# compiler has no clue whether T is a valid type parameter for CreateCriteria<T>.
If we take a closer look at NHibernate source code, we indeed can notice that ISession.CreateCriteria<T> is declared as follows:
public ICriteria CreateCriteria<T>() where T : class

As a result, you need the same constraint on your method in order for type parameter passed to it to play nicely with CreateCriteria call. Simply change it to:
public IList<T> GetObjList<T>(T obj)
    where T : class
{
    /* ... */
}

A: try
public IList<T> GetObjList <T> (T obj) where T : class
{
    // body doesn't change
}

This restricts the type parameter 'T' to be a 'class' - this means that this method will not accept a value type as 'T'.


text:
Q: Google Cloud Platform VPN Is there a way to change the lifetime in seconds for Phase 1 and Phase 2 of Ipsec?  I am trying to connect to a Cisco ASA 5550 at a customer site and their lifetime in seconds setting is 86,400(Phase 1) and 28,800(Phase 2).  These need to match and I cannot adjust it on the Cisco side as their IT department will not alter it.  From what I can find on the GCP the default settings are 36,000 and 10,800 and I cannot find any way to change this... Any help is appreciated.

A: As you know, with IKEv1 the configuration must match at both ends, and this is not configurable on the Google side. As a result, if you're not able to change the configuration of the peer, unfortunately you won't be able to configure Cloud VPN for use.


text:
Q: React Native - Add Background Color/Opacity To Entire Screen But to Child Component? Is there a way to achieve something like below where a child component will have no background color/opacity that is applied from the parent?
Unfortunately the solution right now is to use an image. But that only works as long as I plan to create an app only for the iPhone X. Not good.


text:
Q: How to obtain the private key for getting a signed apk file in android? I want to know the information of publishing an android apk in google play store.i read the developer website.But i struggled to get the private key for apk file.how to get the signed apk file with release mode.so i need some step by step process.

A: Here a few steps to help you create a release private signing key:

*

*Select File -> Export

*In the pop-up, expand Android and select Export Android Application

*In the next pop-up, select the Browse button and select the Project you need to publish the APK of.

*Click the Next button. The next set of options, is for selecting an existing Keystore or creating a new one. Choose Create new keystore, set a location where you want to save the keystore file, choose your own password and confirm the same.

*Next page is the Key Creation set of options. In this, create an alias for the keystore. Again, choose a password and confirm the same. Set a validity in number of years for your keystore. It has to be a minimum 25 years. Enter the rest of the details on this page.

*On the final page of this wizard, choose the location where you want the APK to be saved on your computer.

That's all there is to it.
NOTE: The release signing key is to be created by the developer and not by Google for the dev. It is a self signed certificate. Keep this key safe and secure, and possibly in multiple locations. If you are to loose access to the signing key file created in Step 4 above, you will not be able to publish updates to your application. There are no known ways of recovering a lost key. The same applies to the passwords you select in the process above. Do not loose either the key file or it's passwords.
Read more about signing your applications here: http://developer.android.com/tools/publishing/app-signing.html

A: If you are using eclipse right click on your project >tools>export signed apk
then follow the steps. You will be asked to either use existing or generate a new key there select option to generate new key and a new key will be generated

A: There's a guide to signing Android applications on the developer website:
http://developer.android.com/guide/publishing/app-signing.html

A: Check this out : Compile the application in the release mode

Android Tools > Export Signed Application Package

Support for a true debug build. Developers no longer need to add the android:debuggable attribute to the tag in the manifest — the build tools add the attribute automatically. In Eclipse/ADT, all incremental builds are assumed to be debug builds, so the tools insert android:debuggable="true". When exporting a signed release build, the tools do not add the attribute. In Ant, a ant debug command automatically inserts the android:debuggable="true" attribute, while ant release does not. If android:debuggable="true" is manually set, then ant release will actually do a debug build, rather than a release build.


text:
Q: Transfer all settings and files to new AD user We have a domain enviroment with 100 user. We have 300 colleague in the company. We have many officies and we used one user account / officies.
We bought a new sever, and we bought 300 user CAL because we would like to dedicate a uniqe profile to every colleague.
So we bought the CAL, and generated the new user profile. We did everyting on back-and. Now we have to enroll each user with the new/unique account.
The problem is how to transfer the files under the "site1@company.local" profile folder to the new enrolled folder via remotely! (And i mean not remote desktop. I need a solution which automatically made this changes when user log in)
We have to migrate:

*

*files from documents, desktop

*printers

*explorer settings /certificates, history, favorites..etc.../

Is there any way to do this?
We use Windows XP and Windows 7
Thank you for any suggestion

A: How To:
Files: I would have everyone run a script that basically looks in common file places and copies to a share with their new username.
copy %userprofile%\Desktop \\ServerBackup\%newUserName%\Desktop
copy %userprofile%\Downloads\\ServerBackup\%newUserName%\Downloads

Just find what directories you are going to support, and write the script, fairly easy here.
For printers, you can add to your script WMI queries to get basic printer information easily. look at:
wmic printer get /?

To decide which atttributes give you the information you need. If the printers are already on a file server, then you can remap the drives on the new profile easily with:
\\printServer\PrinterName

For explorer settings, I would not mess with these. Favorites can be backed up from %userprofile%\favorites
I would not dig much deeper, some things will not transfer correctly, and there would be a lot of registry digging. It would probably be easier to find the most important / common settings and apply them to the new profiles on the restore / login script.
Once the user logs in, have them run a restore script, that copies everything you backed up to the local profile.
As long as you use the environment variables, like %userprofile% you should not need different scripts for XP and 7.
Do thorough testing, domain changes are always a good time. You want to be sure you have it right before you roll it out and find that GP broke something simple, or that you missed some key directories.
This is a short and simple way to do it at least, although perhaps not the most robust.

A: Deploy Roaming User Profiles; Windows 8, Windows Server 2012
Configuring Roaming User Profiles; Windows Server 2003, Windows Server 2003 R2, Windows Server 2003 with SP1, Windows Server 2003 with SP2
VideO:
How to Set Up Roaming Profiles, User Files, and Connect to a Domain  18 min 50 sec.