text:
Q: Fill Between in Group plots Using the solution present in Groupplot to generate group plots and Fill Between-under curve to shade area under the curve generated by a scatter plot, I am having issues with the output. It is always filling the chart area with white.
Here is a sample code
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{filecontents}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.10}
\usetikzlibrary{pgfplots.groupplots}
%\pgfplotsset{plot coordinates/math parser=false}

\makeatletter
\pgfplotsset{
    groupplot xlabel/.initial={},
    every groupplot x label/.style={
        at={($({group c1r\pgfplots@group@rows.west}|-{group c1r\pgfplots@group@rows.outer south})!0.5!({group c\pgfplots@group@columns r\pgfplots@group@rows.east}|-{group c\pgfplots@group@columns r\pgfplots@group@rows.outer south})$)},
        anchor=north,
    },
    groupplot ylabel/.initial={},
    every groupplot y label/.style={
            rotate=0,
        at={($({group c1r1.north}-|{group c1r1.outer
west})!0.5!({group c1r\pgfplots@group@rows.south}-|{group c1r\pgfplots@group@rows.outer west})$)},
        anchor=east
    },
    execute at end groupplot/.code={%
      \node [/pgfplots/every groupplot x label]
{\pgfkeysvalueof{/pgfplots/groupplot xlabel}};
      \node [/pgfplots/every groupplot y label]
{\pgfkeysvalueof{/pgfplots/groupplot ylabel}};
    },
    group/only outer labels/.style =
{
group/every plot/.code = {%
    \ifnum\pgfplots@group@current@row=\pgfplots@group@rows\else%
        \pgfkeys{xticklabels = {}, xlabel = {}}\fi%
    \ifnum\pgfplots@group@current@column=1\else%
        \pgfkeys{yticklabels = {}, ylabel = {}}\fi%
}
}
}

\def\endpgfplots@environment@groupplot{%
    \endpgfplots@environment@opt%
    \pgfkeys{/pgfplots/execute at end groupplot}%
    \endgroup%
}
\makeatother
\begin{filecontents}{data.dat}
    sat1    etc1    sat2    etc2    sat3    etc3    sat4    etc4
    0   0.06    0   0.10    0   0.17    0   0.25
    10  0.09    10  0.15    10  0.23    10  0.31
    20  0.13    20  0.22    20  0.30    20  0.37
    30  0.15    30  0.27    30  0.36    30  0.43
    40  0.17    40  0.31    40  0.42    40  0.49
    50  0.19    50  0.31    50  0.46    50  0.53
    60  0.20    60  0.32    60  0.47    60  0.54
    70  0.22    70  0.33    70  0.48    70  0.55
    80  0.24    80  0.34    80  0.49    80  0.56
    90  0.25    90  0.35    90  0.50    90  0.57
    100 0.27    100 0.35    100 0.51    100 0.58
\end{filecontents}

\begin{document}
\pgfplotstableread{data.dat}{\1}

\begin{tikzpicture}
\pgfplotsset{%
    label style={font=\scriptsize},
    tick label style={font=\scriptsize},
    axis line style={<->},
      width=4cm,
      height=4cm,
      scale only axis
    }
\begin{groupplot}[%
          group style={group size=2 by 1,
          horizontal sep=5pt,
          vertical sep=5pt},
        xtick={0,10,20,30,40,50,60,70,80,90},
        xticklabels={0,10,20,30,40,50,60,70,80,90},
        yticklabels={0,0.1,0.2,0.3,0.4,0.5,0.6},
        ytick={0,0.1,0.2,0.3,0.4,0.5,0.6},
        groupplot ylabel={Y label},
        groupplot xlabel={X label},
        group/only outer labels
%       legend style={legend cell align=right,legend plot pos=right}
]

% ROW 1
\nextgroupplot[
  xmin=0,
  xmax=100,
  ymin=0,
  ymax=0.6,
 title=\textbf{$\phi=25\%$},every axis title/.style={below right,at={(0,1)},draw=black,fill=white}
]
\addplot+ [smooth,blue,name path=A] table[x={sat4}, y={etc4}] {\1};
\addplot+[draw=none,name path=B, domain=1:50, mark=none] {1};
\addplot+[gray, fill opacity=0.4] fill between[of=A and B,soft clip={domain=1:50}];
\nextgroupplot[
%  ylabel={E=10 GPa},
  xmin=0,
  xmax=100,
  ymin=0,
  ymax=0.6,
  title=\textbf{$\phi=30\%$},every axis title/.style={below right,at={(0,1)},draw=black,fill=white}
]
\addplot+ [smooth,blue,name path=A] table[x={sat3}, y={etc3}] {\1};
\addplot+[draw=none,name path=B, domain=1:50, mark=none] {1};
\addplot+[gray, fill opacity=0.4] fill between[of=A and B,soft clip={domain=1:50}];
\makeatletter
\end{groupplot}
\end{tikzpicture}
\end{document}

I think there seems to be a layering issue which I can't figure out. Alternate suggestions which don't use Fill Between are also welcome.

A: I think this is not the solution you are hoping for, but at least you get a working result. For more details please have a look at the comments in the code.
% used PGFPlots v1.15
    \begin{filecontents}{data.dat}
        sat1    etc1    sat2    etc2    sat3    etc3    sat4    etc4
        0   0.06    0   0.10    0   0.17    0   0.25
        10  0.09    10  0.15    10  0.23    10  0.31
        20  0.13    20  0.22    20  0.30    20  0.37
        30  0.15    30  0.27    30  0.36    30  0.43
        40  0.17    40  0.31    40  0.42    40  0.49
        50  0.19    50  0.31    50  0.46    50  0.53
        60  0.20    60  0.32    60  0.47    60  0.54
        70  0.22    70  0.33    70  0.48    70  0.55
        80  0.24    80  0.34    80  0.49    80  0.56
        90  0.25    90  0.35    90  0.50    90  0.57
        100 0.27    100 0.35    100 0.51    100 0.58
    \end{filecontents}
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepackage{filecontents}
    \usetikzlibrary{
        pgfplots.fillbetween,
        pgfplots.groupplots,
    }
    \pgfplotsset{
        % use this `compat' level or higher so TikZ coordinates don't have to be
        % prefixed by `axis cs:'
        compat=1.11,
%        plot coordinates/math parser=false,
    }
    \makeatletter
        \pgfplotsset{
            groupplot xlabel/.initial={},
            every groupplot x label/.style={
                at={
                    ($ ({group c1r\pgfplots@group@rows.west}
                    |-{group c1r\pgfplots@group@rows.outer south})%
                    !0.5!%
                    ({group c\pgfplots@group@columns r\pgfplots@group@rows.east}%
                    |-{group c\pgfplots@group@columns r\pgfplots@group@rows.outer south}) $)
                },
                anchor=north,
            },
            groupplot ylabel/.initial={},
            every groupplot y label/.style={
                rotate=0,
                at={
                    ($ ({group c1r1.north}-|{group c1r1.outer west})%
                    !0.5!%
                    ({group c1r\pgfplots@group@rows.south}%
                    -|{group c1r\pgfplots@group@rows.outer west}) $)
                },
                anchor=east,
            },
            execute at end groupplot/.code={%
                \node [/pgfplots/every groupplot x label]
                    {\pgfkeysvalueof{/pgfplots/groupplot xlabel}};
                \node [/pgfplots/every groupplot y label]
                    {\pgfkeysvalueof{/pgfplots/groupplot ylabel}};
            },
            group/only outer labels/.style={
                group/every plot/.code = {%
                    \ifnum\pgfplots@group@current@row=\pgfplots@group@rows\else%
                        \pgfkeys{xticklabels = {}, xlabel = {}}\fi%
                    \ifnum\pgfplots@group@current@column=1\else%
                        \pgfkeys{yticklabels = {}, ylabel = {}}\fi%
                },
            },
        }
%        % ---------------------------------------------------------------------
%        % is it intended that these lines cause the axis lines to not be drawn?
%        % This is also one of the causes why the `fill between' stuff isn't drawn.
%        \def\endpgfplots@environment@groupplot{%
%            \endpgfplots@environment@opt%
%            \pgfkeys{/pgfplots/execute at end groupplot}%
%            \endgroup%
%        }
%        % ---------------------------------------------------------------------

    \makeatother
    \pgfplotstableread{data.dat}{\1}
    \pgfplotsset{
        label style={font=\scriptsize},
        tick label style={font=\scriptsize},
        axis line style={<->},
        width=4cm,
        height=4cm,
        scale only axis,
    }
\begin{document}
\begin{tikzpicture}
    \begin{groupplot}[
        group style={
            group size=2 by 1,
            horizontal sep=5pt,
            vertical sep=5pt,
        },
        xtick={0,10,20,30,40,50,60,70,80,90},
        ytick={0,0.1,0.2,0.3,0.4,0.5,0.6},
        % (moved here)
        every axis title/.style={
            below right,
            at={(0,1)},
            draw=black,
            fill=white,
        },
        % ---------------------------------------------------------------------
        groupplot ylabel={Y label},
        groupplot xlabel={X label},
        group/only outer labels,
        %
        % instead of using the above custom keys you can also force the
        % ticklabels to be drawn only on the left and bottom with
        group/xticklabels at=edge bottom,
        group/yticklabels at=edge left,
        % ---------------------------------------------------------------------
    ]

    % ROW 1
    \nextgroupplot[
        xmin=0,
        xmax=100,
        ymin=0,
        ymax=0.6,
        title=\textbf{$\phi=25\%$},
    ]
        \addplot+ [smooth,blue,name path=A] table [x={sat4}, y={etc4}] {\1};
        % you didn't follow the solution given at
        %     <https://tex.stackexchange.com/a/283533>
        % so changing the constant from 1 to 0.6 in the following `\addplot'
        % command would work, but then you have to keep this in sync with the
        % `ymax' value ...
%        \addplot+[draw=none,name path=B, domain=1:50, mark=none] {0.6};
        % ... so I suggest doing this
        \path [name path=B]
            (\pgfkeysvalueof{/pgfplots/xmin},\pgfkeysvalueof{/pgfplots/ymax}) --
            (\pgfkeysvalueof{/pgfplots/xmax},\pgfkeysvalueof{/pgfplots/ymax});
        \addplot+ [gray, fill opacity=0.4] fill between [of=A and B,soft clip={domain=1:50}];

    \nextgroupplot[
        xmin=0,
        xmax=100,
        ymin=0,
        ymax=0.6,
        title=\textbf{$\phi=30\%$},
    ]
        \addplot+ [smooth,blue,name path=A] table [x={sat3}, y={etc3}] {\1};
        \path [name path=B]
            (\pgfkeysvalueof{/pgfplots/xmin},\pgfkeysvalueof{/pgfplots/ymax}) --
            (\pgfkeysvalueof{/pgfplots/xmax},\pgfkeysvalueof{/pgfplots/ymax});
        \addplot+ [gray, fill opacity=0.4] fill between [of=A and B,soft clip={domain=1:50}];
    \end{groupplot}

    % add axis labels
    \node [
%        red,
        anchor=north,
    ]
        at ($ (group c1r1.below south west)!0.5!(group c2r1.below south east) $)
            {X label};
    \node [
%        red,
        anchor=east,
    ]
        at ($ (group c1r1.left of north west)!0.5!(group c1r1.left of south west) $)
            {Y label};

\end{tikzpicture}
\end{document}


text:
Q: Usar string.format para aliniamiento resulta que me preguntaba como puedo alinear con el string.format el result hacia la derecha 15 carácteres. Lo he hecho de la siguiente manera y no ha funcionado (se queda en el mismo lugar).
Adjunto el código:
using System;

    namespace Exercisi_random
    {
        class Program
        {
            static void Main(string[] args)
            {
                int a, b, result;
                Console.WriteLine("Insert first number:");
                a = int.Parse(Console.ReadLine());
                Console.WriteLine("Insert second number:");
                b = int.Parse(Console.ReadLine());
                result = (a + b) * (a - b);
                Console.WriteLine(String.Format("{0,15}\n", "The result of the operation is: {0:f5}", result));
            }
        }

}

Este es el resultado que espero:
Insert first number: 2
Insert second number: 3
The result of the operation is:        -5.00000
Press any key.

Esto es lo que me da:
Insert first number: 2
Insert second number: 3
The result of the operation is:-5.00000
Press any key.

A: Es muy sencillo. Solo necesitas especificar en la propia string los formatos que vas a aplicar:
Console.WriteLine("The result of the operation is: {0, 15:f5}", result);
// "The result of the operation is:        -5.00000"

Como ves, solo basta con indicar que el valor en índice 0 tomará todo ese espacio (, 15) y que además lo escribirá con determinado formato (:f5). También observa que WriteLine te permite formatear el texto igual que la función string.Format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compress each file while uploading many files to a server(HTML5) I have a form where user can upload multiple file. For e.g several xml files
But the requirement is to compress(gzip) each xml file, and then send it to the web server in a single multipart/mixed request. How do i specify this in html forms, so that the browser will do the same for me.
The post request should somewhat look like this;
POST /localhost:3000/abc HTTP/1.1
HOST: localhost:3000
Content-Type: multipart/mixed; boundary=1cb9ud_4afcystp-opazlj
Transfer-encoding: chunked
--1cb9ud_4afcystp-opazlj
Content-Disposition: attachment; name="XYZ"
Content-Type: text/xml
Content-Encoding: gzip
 ...
--1cb9ud_4afcystp-opazlj
Content-Disposition: attachment; name="ABC"
Content-Type: text/xml
Content-Encoding: gzip
 ...
--1cb9ud_4afcystp-opazlj


text:
Q: Convert timestamps from temporal series to the same index I have a data frame containing a timestamp every 5 minutes with a value for each ID. Now, I need to perform some analysis and I would like to plot all the time series on the same temporal time window.
My data frame is similar to this one:
ID      timestamp                           value
 12345    2017-02-09 14:35:00               60.0
 12345    2017-02-09 14:40:00               62.0
 12345    2017-02-09 14:45:00               58.0
 12345    2017-02-09 14:50:00               60.0
 54321    2017-03-09 13:35:00               50.0
 54321    2017-03-09 13:40:00               58.0
 54321    2017-03-09 13:45:00               59.0
 54321    2017-03-09 13:50:00               61.0

For instance, in the xy axis, I need to use the x=0 value as the first timestamp for each ID, and the x=1 the second after 5 minutes, and so on.
Until now, I correctly resampled every 5 minutes with this code:
df = df.set_index('Date').resample('5T').mean().reset_index()

But, given the fact the every ID starts at different timestamps, I don't know how to modify the timestamps in order to use the first measured date of each ID as timestamp 0, and each next timestamp every 5 minutes as timestamp 1, timestamp 2, timestamp 3, ecc, in order to plot the series of each ID to confront them graphically. A sample final df may be:
 ID      timestamp       value
 12345    0               60.0
 12345    1               62.0
 12345    2               58.0
 12345    3               60.0
 54321    0               50.0
 54321    1               58.0
 54321    2               59.0
 54321    3               61.0

Using this data frame, is is possible to plot all the series starting and finishing at the same point? Start at 0 and finish after 3 days.
How do I create such different timestamps and plot every series for each ID on the same figure?
Thankl you very much

A: First create a new column with the timestamp number in 5 minutes intervals.
df['ts_number'] = df.groupby(['ID']).timestamp.apply(lambda x: (x - x.min())/pd.Timedelta(minutes=5))

If you know in advance that all your timestamps are in 5 minute intervalls and they are sorted, then you can also use
df['ts_number'] = df.groupby(['ID']).cumcount()

Then plot the pivoted data:
df.pivot('ts_number', 'ID', 'value').plot()


text:
Q: private static final vs private final This question has been asked here. As per the answer :
private final int NUMBER = 10;

If it cannot change, there is no point having one copy per instance.

My doubt is what if instance of the class is created, say once a day and it lasts around a few seconds. Is it good idea to keep the int(in some case object) in memory?
Assuming, there can be many (20-30) such objects.

A: How you store the information depends very much on what it is intended to be used for.
There are a few approaches you might take:
private static final
This is a good choice if the value will never be modified during the lifetime of the application. It means, when you're creating your multiple instances, you are only actually storing this particular variable ONCE.
private final
This is meant for those times when the value might take on different values for different instances of your object, but any specific instance will not have it's value modified throughout the object's life time.
If you're looking at something which might take on different values over a range of time, then this might be of interest to you.
public static int GetNumber(){...}
Another approach you might consider is to have a static method return the value you are after. This makes it easy to deal with changes in the value, but you also need to consider the effect of such a change throughout the lifetime of any given instance.
Hope that helps...

A: Regarding private final int number, your claim that

If it cannot change, there is no point having one copy per instance

is absolutely wrong. Consider this code, typical of an immutable class:
private final int number;

public MyClass(int number) {
    this.number = number;
}

There are many instances of this pattern in the JDK, and in production code classes around the globe.

To answer your question about performance, I doubt you could measure the difference between using static vs instance constants.


text:
Q: Is there an expression for getting number of times to divide an even number by 2 to get an odd number? I found a function $f$ to basically say, given any two integers $i\geq 0$ and $j\geq 0$, then $f(i,j)=x$ where $x>0$, will tell you that if you divide $x$ by $2$, $i$ times, then you will get an odd number $\leq x$ (like the first odd number in the sequence of dividing by 2). And every integer $x>0$ can be represented by some $i\geq0$ and $j\geq0$. I have also proved this to be true.
Does there exist something like this that someone discovered already or am I the first?

Edit:
f(3,4)=72
f(0,5)=11
f(17,6)=1703936
f(6,2)=320

A: Appears
$$  f(i,j) = 2^i \cdot (2j+1)   $$

A: Wouldn't the description be a lot simpler as "Given non-negative integers $i, j$ with $j$ odd, let $f(i, j) = 2^i * j?$ I don't quite understand why you make $j$ into $2j+1$.


text:
Q: Sorry too many clients are already logged there's someone who knows this error " Sorry too many clients are already logged" ,even if i increase number of connection pool size in my persistence like that.i still have it
Any help please this error blocks my progress !!!

A: That error points at a connection leak.  If you create new connections without releasing all of them, you'll eventually run out!
Have a look at pg_activity.  It's a "top" for Postgres and can often quickly identify the source of the leak.  Another option is to set Postgres to more verbose logging and analyse the log file.


text:
Q: Error after selecting data from database I am currently working on a forum website with an upvote-system. However, there are some annoying, probably syntactic errors that are bugging me. I am talking about this piece of code.
<?php
session_start();

include_once 'dbh_discussion.inc.php';
$conn = db_discussion_connect();

$thread_id = $_POST['upvote'];

$sql1 = $conn->prepare("SELECT * FROM users WHERE user_id = '$_SESSION['u_id']' AND thread_id = '$thread_id'");

The things that aren't clear in this piece of code are as follows:

*

*db_discussion_connect() A function declared in dbh_discussion_connect.inc.php. This funtion returns a new PDO that connects to my database.

*the index 'upvote' is the name of a button in another php file that will call the code above.

*$_SESSION['u_id'] is a session variable that will be assigned when the user logs onto the website.

The error that I'm getting when debugging on the server:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE),
  expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or
  number (T_NUM_STRING) in /var/www/html/includes/thread_upvotes.inc.php
  on line 9

I feel like I'm missing out on something syntactical. Anyhow, I'd really appreciate someone telling me whats going wrong here.
Thanks

A: I get triggered so hard by this people who provide answers that are still wide open to Injections. Is it that difficult to change his prepared statement to something safe?!!!
Here a solution with a correct prepared statement. As if it takes that long to rewrite it. That should be against the rules here.
<?php
session_start();

include_once 'dbh_discussion.inc.php';
$conn = db_discussion_connect();

$sql1 = $conn->prepare("SELECT * FROM users WHERE user_id = :uid AND thread_id = :tid");
$sql1->bindParam(':uid', $_SESSION["u_id"]);
$sql1->bindParam(':tid', $_POST['upvote']);
$sql1->execute();

A: Your code has an error, specifically the code user_id = '$_SESSION['u_id']', try this:
 $sql1 = $conn->prepare("SELECT * FROM users
 WHERE user_id = '{$_SESSION['u_id']}' AND thread_id = '$thread_id'");

To insert array keys inside a string, you must enclose it in { } if you specify the key inside ' '
WARNING inserting directly $_SESSION contenst in the query you'll be eligible for SQL Injection!!!
The correct and better way to insert them is by binding each one like this:
$sql1 = $conn->prepare("SELECT * FROM tableName WHERE fieldID = :id");
$sql1->bindParam(':id', $_SESSION["id"]);

A: seems like quotes making problem, try like below,
$uid = $_SESSION['u_id'];
$sql1 = $conn->prepare("SELECT * FROM users WHERE user_id = '$uid' AND thread_id = '$thread_id'");


text:
Q: Does a maven plugin exist to gracefully check elevated privilege? Does anyone know of a maven plugin which can gracefully check that the maven process is running with elevated privileges on Windows.
I searched using Google, the Maven Users mailing list archive, Commons Exec mailing list archives, stackoverflow but I've only found people saying Run As Administrator.  The search terms I used included

*

*elevated

*maven

*exec-maven-plugin

*administrator

*privileged

*commons-exec

I'd just like a way to check for elevated privileges and end the maven build early with a user friendly error message before time is wasted executing a bunch of maven plugins only to fail at the end when trying to execute exec-maven-plugin with an error like
Downloaded: http://somehost:8082/artifactory/repo/org/apache/commons/commons-exec/1.3/commons-exec-1.3.jar (54 kB at 85 kB/s)
[ERROR] Command execution failed.
java.io.IOException: Cannot run program "C:\Program Files (x86)\InstallAnywhere 2017\build.exe" (in directory "C:\Downloads\New Builds\Artifactory Downloads\Maven Implementation\InstallerSharedDownloa
d\WindowsDownload"): CreateProcess error=740, The requested operation requires elevation
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at java.lang.Runtime.exec(Runtime.java:620)
        at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:61)
        at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:279)
        at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:336)
        at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:166)
        at org.codehaus.mojo.exec.ExecMojo.executeCommandLine(ExecMojo.java:804)
        at org.codehaus.mojo.exec.ExecMojo.executeCommandLine(ExecMojo.java:751)
        at org.codehaus.mojo.exec.ExecMojo.execute(ExecMojo.java:313)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.io.IOException: CreateProcess error=740, The requested operation requires elevation
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
        at java.lang.ProcessImpl.start(ProcessImpl.java:137)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 30 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:13 min
[INFO] Finished at: 2017-07-31T14:27:38-04:00
[INFO] Final Memory: 21M/298M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:exec (My Command Runner) on project WindowsDownload: Command execution failed.: Cannot run program "C:\Program Files (x86)\Inst
allAnywhere 2017\build.exe" (in directory "C:\Downloads\New Builds\Artifactory Downloads\Maven Implementation\InstallerSharedDownload\WindowsDownload"): CreateProcess error=740, The requested operatio
n requires elevation -> [Help 1]
[ERROR]


text:
Q: Undo-Redo functionality using Command-Pattern in Qt for FitInView feature I have QGraphicsView which contains some QGraphicsItem. This view has some feature like zoom-in, zoom-out, fitIn, Undo-Redo.
My fitIn feature is not working in Undo-Redo functionality.
( To implement Undo-Redo I have used Command-Pattern in Qt. )
myCommand.h
class myCommand: public QUndoCommand
{
public:
    myCommand();
    myCommand(QTransform t, int hr, int vr, QGraphicsView* v);
    void undo();
    void redo();
    QTransform t;
    int hScrollBar;
    int  vScrollBar;
    QGraphicsView* mView;
};

myCommand.cpp
myCommand::myCommand(QTransform t, int hr, int vr, QGraphicsView *v)
{
    this->t = t;
    this->hScrollBar= hr;
    this->vScrollBar= vr;
    this->mView = v;
}

void myCommand::undo()
{
    mView->setTransform(t);
    mView->horizontalScrollBar()->setValue(hScrollBar);
    mView->verticalScrollBar()->setValue(vScrollBar);
}

void myCommand::redo()
{
   myView mv;
   mv.FitInView();
}

myView.cpp
 void myView::FitIn()
    {
        FitInView();
        QTransform t = view->transform();
        int hrValue = view->horizontalScrollBar()->value();
        int vrValue = view->verticalScrollBar()->value();
        myCommand* Command1 = new myCommand(t,hrValue,vrValue,view);
        undoStack->push(Command1);
    }

void myView::DrawDesign()
{
   // Logic for inserting all the Rectangles and polylines.
   QTimer::singleShot(100, this, [&]() {
        FitInView();
    });
}

void myView::FitInView()
{
    QRectF bounds = scene->sceneRect();
    QRectF rect  {0,0,200,200};
    if (bounds.width() < 200)
    {
        rect .setWidth(bounds.width());
        bounds.setWidth(200);
    }
    if (bounds.height() < 200)
    {
        rect.setWidth(bounds.height());
        bounds.setHeight(200);
    }
    view->fitInView(bounds, Qt::KeepAspectRatio);
    view->updateGeometry();
}

myView.h
public:
      QUndoStack* undoStack;

FitInView fits my design perfectly but it does not work in Undo-Redo feature.
I think I am making a mistake in myCommand::undo() and myCommand::redo() function.

A: Based on the many question you posted on the Qt's Undo Framework, it seems to me you are missing an essential part of the Command pattern:

The Command pattern is based on the idea that all editing in an
application is done by creating instances of command objects. Command
objects apply changes to the document and are stored on a command
stack. Furthermore, each command knows how to undo its changes to bring the document back to its previous state. [1]

So all changes, should be implemented inside the QUndoCommand (follow the link to discover a basic usage example), i.e. inside QUndoCommand::redo. Once the command is pushed on the QUndoStack, using QUndoStack::push, the change (i.e. QCommand::redo) is automatically performed:

Pushes cmd on the stack or merges it with the most recently executed command. In either case, executes cmd by calling its redo() function. [4]

Steps to create a new QUndoCommand

*

*Implement the desired changes inside QUndoCommand::redo (and not somewhere else).

*Write the inverse of this command inside QUndoCommand::undo. If needed, capture the initial state inside the QUndoCommand constructor, to easily revert QUndoCommand::redo.

Applied to your example
So, the only action that myView::FitIn should perform, is pushing the command on the undo stack:
void myView::FitIn()
{
    undoStack->push(new fitCommand(view));
}

Implement your changes inside the redo command:
void fitCommand::redo()
{
    mView->FitInView(); // Can be implemented using QGraphicsView::fitInView
}

As the inverse operation of fitting is not uniquely defined, we store the initial state inside the QUndoCommand constructor (to be able to restore the initial state inside QUndoCommand::undo):
fitCommand::fitCommand(myView *view)
{
    this->t = view->transform();
    this->hScrollBar= view->horizontalScrollBar()->value();
    this->vScrollBar= view->verticalScrollBar()->value();
    this->mView = view;
}

Now we can implement the undo command to revert the redo command:
void fitCommand::undo()
{
    mView->setTransform(t);
    mView->horizontalScrollBar()->setValue(hScrollBar);
    mView->verticalScrollBar()->setValue(vScrollBar);
}

Usefull reading material:

*

*Overview of Qt's Undo Framework

*Detailed description of QUndoCommand, including basic code example


text:
Q: ImageComboBox for VBA Excel Is it possible to use images inside a ComboBox instead of strings? I've seen post regarding the ImageComboBox control but it seems that I couldn't find any resource how and where to download the said control so I could use it in my project that I'm working on.
Thanks all.

A: To be able to use the Image Combo Box, you have to do the following:
Insert the control from the Insert menu on the developer tools tab:

If you press the highlighted button, a new menu appears.
Search for "Microsoft ImageComboBox Control, version XX"
Then you are able to insert the desired combobox.


text:
Q: Ionic 2 change input component style md to windows My client likes to use windows platform input field style to android platform. How can use windows input component style to android platform in ionic 2.

A: You can try to set a specific target behavior in Config object.
ionicBootstrap(AppRoot, customProviders, {
  iconMode: 'md',
  pageTransition: 'md',
});

http://ionicframework.com/docs/v2/api/config/Config/
Here http://ionicframework.com/docs/v2/theming/platform-specific-styles/ you have a configuration for specific modes


text:
Q: Handling large file downloads with javascript I have a server hosting very large files: > 50GB. Until now, these files were just downloaded via the browser normally. (<a href="...">)
The problem is, many times these are downloaded over slow/unreliable connections, and if the download fails, they have to start over from scratch.
As a solution to this, I want to make an alternative downloader in the browser, where each downloaded chunk is saved to some temporary storage with javascript, allowing the download to be resumed if it fails.
A good example of where something similar is being used, is mega.nz. Downloads are handled with javascript, and when the entire file is downloaded to a temporary location, the browser shows the classical file download dialog, which is actually referencing a blob url.
I've come up with some solutions, but the difficult part is I need to support FF, Chrome, and IE 11+.
Solution #1) fetch + Filesystem API + HTTP Range header
I use fetch() and stream the result into a FileWriter. If at any time the download fails, I can check how many bytes were written into the file, and use the Range header on the next fetch(). When the download completes, I can get a url like filesystem:http://some-url/file, which I can assign as the a attribute of an href tag, with the download option set. I send a click() event, and the file is downloaded almost instantaneously. The entire file is not loaded into memory, so it can work with very large files, but this method only works on Chrome. I know there is a polyfill for the FileSystem API which uses indexedDB, but when I need to generate the url, it will give me a blob, which is loaded into memory. Also the writes load the entire value into memory, append to it, and then write it back. (Hardly efficient, and won't work with large files)
Solution #2) Service workers + IndexedDB
With a service worker, I can hijack the fetch event, and send back any data I want. I can use this to implement saving files to IndexedDB, and serving them from there chunk by chunk, without loading the entire thing into memory if I make a ReadableStream with the correct logic.
Solution #3) Flash (Actionscript)
Mega seems to use some Flash based downloader as a fallback for old browsers, haven't looked into it yet, but maybe this is a viable solution for IE.
Solution #4) ActiveX
Again a possible solution for IE. Can ActiveX be used to stream data straight to the filesystem without loading it in memory?
So far I'm missing support for IE, and for versions of FF where service workers are not enabled, like Firefox ESR. IE has IndexedDB, but in order to download the data, I have to make one blob which contains the entire file, and this gets loaded into memory
Is there anything else I'm missing? Any other way to implement this?
Note: browser extensions are unfortunately off limits.

A: I'd recommend using the Background Fetch API, with the caveat that it's only supported in Chrome 74+ (and the corresponding Edge preview releases) at this time. It's designed for your use case.
I could imagine using that when supported, and falling back to an alternative on browsers that don't support it.


text:
Q: for every row in one data frame find the most similar row in another I have two data frames with Boolean values and numeric values. If needed the numeric values could be put into categories.
var1 <- c(400,234,199,45,77,19)
var2 <- c(0,0,1,1,0,1)
var3 <- c(1,0,1,0,0,1)
df1 <- data.frame(var1,var2,var3)
var.1 <- c(78,147,670,200,75,17)
var.2 <- c(0,0,0,1,1,1)
var.3 <- c(0,1,1,0,1,1)
df2 <- data.frame(var.1,var.2,var.3)

I want to find in df1 the most similar row in df2.
I am aware of cluster analysis, which I could do for one data frame by itself, but once I have clusters for one data frame, how would I extract and apply the same clustering algorithm to the other data frame, so that both data frames are clustered in the same way? I also need as many "clusters" as rows in the data frame, which makes me think cluster analysis is not for this task.
Additionally, every row in df1 must be matched with only one row in df2 so that at the end of the process every row in df1 matches to a different row in df2. This is tricky, because if taking each row in isolation in df1, the same row in df2 might get matched multiple times, which is not desired.

A: You don'T have to do clustering, just search for the smallest distance. Take the first row of df1 and cbind it with df2. This is easiest, if column names are identical
var1 <- c(400,234,199,45,77,19)
var2 <- c(0,0,1,1,0,1)
var3 <- c(1,0,1,0,0,1)
df1 <- data.frame(var.1,var.2,var.3)
var.1 <- c(78,147,670,200,75,17)
var.2 <- c(0,0,0,1,1,1)
var.3 <- c(0,1,1,0,1,1)
df2 <- data.frame(var.1,var.2,var.3)

rbind(df1[1,], df2)

the result of this can be examinated with dist. We are only interested in the first column of the result, i. e. the first nrow(df2) results.
dist(rbind(df1[1,], df2))[1:nrow(df2)]

evaluates to
> dist(rbind(df1[1,], df2))[1:nrow(df2)]
[1]   0.000000  69.007246 592.000845 122.004098   3.316625
[6]  61.016391

and which.min tells us, which of the rows has the smallest distance:
> which.min(dist(rbind(df1[1,], df2))[1:nrow(df2)])
[1] 1

So the first line in df2 has the smallest distance to the first line of df1. You can put that into an apply or a for loop to do the calculation for each row in df1.
You have to answer the question though, how the distance of a mixture of Boolean and numeric values should be computed. There is no universal answer for that.


text:
Q: Query to select: who two employee works for the same company Suppose that we have following tables:
company             company_has_employee        employee
-------------------------------------------------------------
id                  company_id                  id
companzy_name       employee_id                 emplyee_name

How to create SQL Query, which retrieves any two employees, who works for the same company and what is this company?

A: select company_name,
       min(e.employee_name) as emp1,
       max(e.employee_name) as emp2
from compyny c
join company_has_employee ce on ce.company_id = c.id
join employee e on e.id = cs.employee_id
group by company_name
having count(e.id) > 1

A: Assuming juergen d's joins of the table are correct, I will modify the query to
select top 2 company_name, e.employee_name
   from compyny c
   join company_has_employee ce on ce.company_id = c.id
   join employee e on e.id = cs.employee_id
   group by company_name
   having count(e.id) > 1

This will always return the top 2 employees
juergen d's original query will always return the first and last employees based on their ID.
If you want two employees chosen randomly, then you can try this:
select top 2 company_name, e.employee_name
   from compyny c
   join company_has_employee ce on ce.company_id = c.id
   join employee e on e.id = cs.employee_id
   group by company_name
   having count(e.id) > 1
   order by RAND((e.ID)*DATEPART(millisecond, GETDATE()))

The last order by clause will change the order of records randomly and you will always get the top 2 of a random order...which means 2 random employees will be selected each time the query is run.


text:
Q: Is there a practical advantage to returning a pending promise? For the most part, I think I understand how async functions work in JavaScript / Node.js, and I am familiar with the syntax of async/await. But this question is about a very specific case, which I can't seem to find anywhere, and I think it involves the inner workings of await, which is beyond my understanding.
First I'll start off with a simple example, and then I'll extend it to real working code. (Note: I'm actually using Typescript, so you'll see void instead of undefined, but that's not important to the problem.)
async function subtask() {
    // doSomeStuff();
    return; // returns a `Promise<void>`
}
// async function run() {
//  see options below
// }
function app() {
    run().catch((e) => console.error(e));
}

Option 1
async function run() {
    await subtask(); // resolves to `void`
    return; // returns a new `Promise<void>`
}

Option 2
async function run() {
    return subtask(); // returns a new Promise, resolving to the `Promise<void>` of `subtask()`
}

In the simple example above, I have an async function run that calls a smaller async function subtask. Both functions must return a Promise<void>. I have two options: (1) to await the smaller function and return a new Promise<void>, or (2) to return a wrapped promise, given by the smaller function, which will later resolve to void.
My lack of understanding is about how this works. In Option 1, is execution is paused before subtask() returns? What does that actually mean? Does that mean that the async subtask executes synchronously? Does that mean that app, which calls run(), will also pause execution? What if app was async, would that make a difference?
Is it "better" (more performant) to let the promise bubble up and resolve later, or to resolve it directly within the run function?
The reason this is important is that in my real code I have a bunch of smaller subtasks, which all return void, and then the big function must also return void—it cannot return an array. (Note that the subtasks need not run in any particular order.)
Option 1
async function run() {
    await Promise.all([
        subtask0(),
        subtask1(),
        subtask2(),
    ]);
    return;
}

Option 2
async function run() {
    return Promise.all([
        subtask0(),
        subtask1(),
        subtask2(),
    ]).then((_all) => {});
}

function app() {
    // do some stuff
    run(); // if `run` contains `await`, does execution pause here?
           // what if `app` was async?
    // do some more stuff
}

A: It is always better to let the Promise bubble up. This avoids the creation of an extra Promise object that will also be awaited on (whether this is optimized away behind the scenes in whichever JavaScript engine you're using is up to debate, though).
async function run() {
    await subtask();
    return;
}

This creates an extra Promise (and subsequently an extra callback in the chain that will be executed).
async function run() {
    return subtask();
}

This isn't actually doing what you think it is. This is also creating an extra Promise (since you're using the async keyword) and is almost functionally the same as the previous example. By using the async  keyword, you're creating and returning a new Promise that will resolve/reject to the same value as the Promise created from the call to subtask(). If you remove the async keyword, then this will avoid the creation of the extra unnecessary Promise .
Now with your Promise.all() examples, I think they're both optimal (assuming you remove the unnecessary async keyword from the 2nd one, like noted above). The first would create 2 Promise s (the Promise.all() one, and the one created from returning from an async function), and the 2nd would as well (the Promise.all() one, and the one created from calling then()). Whichever you'd want to use is basically up to personal choice. Personally, I like the 2nd example since it's not mixing the use of async functions and Promises, which I think makes it a little easier to understand.
And for the last part of your question, execution will be paused wherever the await keyword exists (so within the run() call).
You can also essentially think of the await keyword transforming your code from this:
// Do some stuff
let result = await run();
// Do some other stuff

to this:
// Do some stuff
run().then(result => {
    // Do some other stuff
};

(the whole point of await is to reduce confusion/complexity caused by nesting)


text:
Q: Codeigniter : Adding array indexes in loop I am fetching news items from posts table in foreach loop  and attachments related to any this item are being fetched from attachments table .
i want to structure array like this
Array
(
    [news] => stdClass Object
        (
            [id] => 95
            [date] => 2016-07-29
            [title] => This is first news
            [content] => This is first news details
            [type] => news
            ['attachment'] =>  stdClass Object
             (
              [id] => 25
              [attachment_id] => 95
              [type] => news
              [path] => Jellyfish23.jpg
           )

        )

this is how i am doing my loop
$posts=$this->db->get_where('posts',array('type'=>$type));
        if($posts->num_rows()>0){
            foreach ($posts->result() as $key=> $value) {
                echo $value->id;
                $res['news']=$posts->row();
                $result = $this->db->get_where('attachments', array('attachment_id'=>$value->id));
                $res['attachment']= $result->row();

            }

        }

this is what i get
Array
(
    [news] => stdClass Object
        (
            [id] => 95
            [date] => 2016-07-29
            [title] => This is first news
            [content] => This is first news details
            [type] => news
        )

    [attachment] => stdClass Object
        (
            [id] => 25
            [attachment_id] => 97
            [type] => news
            [path] => Jellyfish23.jpg
        )

)

Now how do i modify my code in a way that each news item and attachment related to that news are formatted properly as i mentioned above

A: Use $data = array(); to store your data after process
Just modify the line
$res['attachment']= $result->row();
to
$res['news']['attachment']= $result->row();
And use Array push $res to $total;
Because after each loop your $res has been overided but you don't store it
Full of code
$posts=$this->db->get_where('posts',array('type'=>$type));
$data = array();

if($posts->num_rows()>0){
    foreach ($posts->result() as $key=> $value) {
        echo $value->id;
        $res['news']=$posts->row();
        $result = $this->db->get_where('attachments', array('attachment_id'=>$value->id));
        $res['news']['attachment']= $result->row();
        array_push($data, $res);
    }
}

echo "<pre>";
var_dump($data);
echo "</pre>";


text:
Q: awk and sed tab seperation. How to add third tab? In a previous question I asked about the syntax for awk and sed in Windows. This now works, but I have another question (which you hopefully will and can answer).
PS: Sorry for all these questions, but I am still very inexperienced with using awk and sed.
The following script will output 2 tabs, one showing the time in seconds and the second showing the bytes per second.
Wireshark\tshark -r WireShark\dumps\combinedOutput2.pcapng -T fields -e  frame.time_relative -e frame.len
        | sed -e "s/\...*\t/,\t/"
        | awk -F"\t" "$1==last {sum += $2; next}
{
printf(\"%s  %8d bytes/s \n\",last,sum,sum*8/1024/1024);
last=$1;sum=$2
}" > test.csv

Output:
10993,       135 bytes/s
10994,        54 bytes/s
10995,       135 bytes/s
10996,        54 bytes/s
10997,       135 bytes/s
10998,        54 bytes/s
10999,       135 bytes/s
11000,       199 bytes/s

Now I would like another tab on the right with the destination IP address (ip.dst), comma delimited. When I try to put another tab in the script it gives me errors.
Can anyone help me in the right direction?
Thanks in advance! :)


text:
Q: Javascript: list.indexOf(elm+"") returns index, but list.indexOf(elm) returns -1 I was writing a function to remove given elements from an array and then i came to this particular situation:
function removeStudent(elm, list){
var elmToDelete = list.indexOf(elm);
console.log(elm + " element");

the console shows -1, so the given element couldn't be found in the list. However, if a search it as a concatenated stirng, it will return the index of given element:
function removeStudent(elm, list){
var elmToDelete = list.indexOf(elm+"");
console.log(elm + " element");

For the record, I'm currently using Chrome version 57.0.2987.133 (64-bit) in Mac OS.


text:
Q: CSS Positioning Issue: When I stretch out my browser, the position of my picture will change So when I fully reduce the browser size, I have my website looking like this, which is how I want it to look:
http://oi66.tinypic.com/10x7zw4.jpg
But when I start stretching out the browser, the position of my picture in the center will begin to change and move all the way to the left. I want the picture to stay on the center regardless of whether I stretch out the browser or reduce it. Is there a way I can fix this issue? Been trying to find out how to solve the issue but cannot find any clue. Please help, thank you.
My HTML:

    <title>Jason H Kang</title>
  <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css">

Home

About

Portfolio

Contact

Jason H Kang

23 Years Old | Junior Web Developer | NJ

          Hello I am Jason Kang. Welcome to my personal website!
Please feel free to contact me if you have further inquiries.

Copyright: Jason Kang 2015

My CSS:
body {
    background-color: #F8F8FF;
    color: #000000;
}

.navbar {
    background: rgba(114, 180, 39, 1)
}

.navbar .brand, .navbar .nav > li > a {
    color: #FFFFFF;
    margin-left: 14em;
    padding-right: 0em;
    font-family: Gill Sans;
    font-size: 1.0em;
}
.navbar .brand, .navbar .nav > li > a:hover {
    color: #000000;
}

#footer {
    background:#000000;
    width:100%;
    height:47px;
    position:fixed;
    bottom:0px;
    left: 0px;
}

.copyright {
    padding-top: 19px;
    padding-left: 1.3%;
    font-family: Arial;
    font-size: 0.9em;
    color: white;
}

.intro {
    padding-left: 0.35%;
    font-family: 'Source Sans Pro', sans-serif;
    position: relative;
}

.hello {
    padding-top: 1.5%;
    padding-left: 5%;
    font-family: 'Source Sans Pro', sans-serif;
    position: relative;
}

.img-circle {
   width: 11.0em;
   height: 11.0em;
   border: 1px solid black;
   margin-left: 10em;
   margin-top: 1em;
   position: relative;
  }

A: To center a block level element, you use margin:auto:
.img-circle {
   width: 11.0em;
   height: 11.0em;
   border: 1px solid black;
   margin: auto;
   margin-top: 1em;
   position: relative;
   display:block;
  }

JSFiddle Demo
Or, alternatively, you can set the parent to text-align:center;:
.image {
  text-align: center;
}

JSFiddle Demo

A: Change your css for the img-circle class as follows
.img-circle {
    width: 11.0em;
    height: 11.0em;
    margin: 0 auto;
    border: 1px solid black;
    display: flex;
 }


text:
Q: Python guessing game, my win condition prints win and loss Im learning python and having a go at the guessing game. my game works but my win condition prints both "you win" and "you loss", I think my "if" statements are incorrect but i could be wrong.
Also, there's an issue with my printing of the win loss, I can only get it to print the loss..
Thanks in advance!
import random

print("Number guessing game")

name = input("Hello, please input your name: ")
win = 0
loss = 0

diceRoll = random.randint(1, 6)

if diceRoll == 1:
    print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
    print("You have 3 guesses.")
if diceRoll == 4:
    print("You have 4 guesses.")
if diceRoll == 5:
    print("You have 5 guesses.")
if diceRoll == 6:
    print("You have 6 guesses.")

number = random.randint(1, 5)

chances = 0

print("Guess a number between 1 and 5:")

while chances < diceRoll:

    guess = int(input())

    if guess == number:

        print("Congratulation YOU WON!!!")
        break
        win += 1
    elif guess < number:
        print("Your guess was too low")

    else:
        print("Your guess was too high")

    chances += 1

if not chances == 0:
    print("YOU LOSE!!! The number is", number)
    loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))

A: Try changing your loop. Since you're breaking if it's correct, you can use a while: else. Otherwise you can win on your last chance and still get the lose message.
while chances < diceRoll:

    guess = int(input())

    if guess == number:

        print("Congratulation YOU WON!!!")
        break
        win += 1
    elif guess < number:
        print("Your guess was too low")

    else:
        print("Your guess was too high")
    chances += 1
else:
    print("YOU LOSE!!! The number is", number)
    loss += 1

A: In your while loop the if statement should be...
if guess == number:
    print("Something)
    win += 1
    break

and the last if statement should be...
if win != 0:
    print("You lose")
else:
    print("You win")

A: The problem lies within the final if statement. The player loses if their chances are greater than the diceRoll, whereas the if condition is true if the player's chances are not 0 i.e. the player failed once.
The code for the final if statement should look something like this:
if chances >= diceRoll:
    print("YOU LOSE!!! The number is", number)
    loss += 1

As for the problems printing the win, the problem here is in the first if statement inside the while loop. If the player wins the break statement is encountered first, so the code breaks out of the while loop without incrementing the win counter.
Just swap the break statement with the win += 1 and it'll work wonders:
if guess == number:
    print("Congratulation YOU WON!!!")
    win += 1
    break

A: To start look at

*

*the position of your break

*the loss condition


text:
Q: Setting showing Me.ComBox.Value and Me.ComboBox.RowSource properties in VBA I am trying to create a search form in Microsoft Access. The search form is going to lookup values from a client table.
I have the following code in OnUpdate event of a ComboBox and it is set to automatically update Form Data AfterUpdate.
Private Sub firstname_combo_Change()
Dim stringSQL As String
Dim RecordSt As Recordset
Dim dBase As Database
Dim strWhere As String
Dim varLname As Variant
Dim varClientID As Database
If Not IsNull(Me.firstname_combo.Column(1)) Then
    strWhere = "WHERE [Client_Data].[firstname]='" & Me.firstname_combo.Column(1) & "'"
    Me.lastname_cmbo.RowSource = "SELECT [Client_Data].[clientid], [Client_Data].[lastname] FROM Client_Data " & strWhere & ";"
    stringSQL = "SELECT TOP 1 [Client_Data].[lastname] FROM Client_Data " & varWhere & " ORDER BY [Client_Data].[lastname];"
    Set RecordSt = CurrentDb.OpenRecordset(stringSQL)
    RecordSt.MoveFirst
        'PLease note there would be multiple rows in the recordset but I need to select only the first row. However, varLname is populated correctly
    varClientID  = RecordSt.Fields("cleintid").Value
    varLname  = RecordSt.Fields("lastname").Value
    Me.lastname_cmbo.Value = varLname
         'MsgBox (varLname)
End If
End Sub

What I am trying to do here is this:

*

*OnChange of firstname, VBA will look for all lastnames matching the firstname and show that as available options in the lastname fields.

*Take the first row from the RecordSet and populate the lastname_combo.value to it.
Access currently sets the RowSource property correctly but refuses to populate the control's .Value property. So I get a blank lastname in ComboBox (with the correct RowSource).
Do note that each ComboBox has been set to "Find a record on my From based on the value selected in my combo box".

A: Looks like I found the problem.
My RowSource lines goes like this

Me.lastname_cmbo.RowSource = "SELECT [Client_Data].[clientid], [Client_Data].[lastname] FROM Client_Data " & strWhere & ";"

Now that means access is using the [Client_Data].[clientid] field as the value for each element in the ComboBox
ReplacedMe.lastname_cmbo.Value = varLname
with

Me.lastname_cmbo.Value = varClientID
Now it works as expected.


text:
Q: FragmentManager on a null object reference Null object reference exception coming on this line  mFragmentTransaction.replace(R.id.containerView,new SentFragment()).commit();
The below code is trying to add TabActivity in Mainactivity. But in TabFragment its throwing null exception. I know that, issue is will my TabFragment. Below is my MainActivty.java and after that, there will be TabFragment.java
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;

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

    /**
     *Setup the DrawerLayout and NavigationView
     */

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mNavigationView = (NavigationView) findViewById(R.id.shitstuff);

    /**
     * Lets inflate the very first fragment
     * Here , we are inflating the TabFragment as the first Fragment
     */

    mFragmentManager = getSupportFragmentManager();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerView,new SentFragment()).commit();
    /**
     * Setup click events on the Navigation View Items.
     */

    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawerLayout.closeDrawers();

            if (menuItem.getItemId() == R.id.nav_item_sent) {
                FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.containerView,new SentFragment()).commit();

            }

            if (menuItem.getItemId() == R.id.nav_item_inbox) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
               // xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
            }

            return false;
        }

    });

    /**
     * Setup Drawer Toggle of the Toolbar
     */

    android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
            R.string.app_name);

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerToggle.syncState();

}

}
TabFragment.java
public class TabFragment extends Fragment {

public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    /**
     *Inflate tab_layout and setup Views.
     */
    View x =  inflater.inflate(R.layout.tab_layout,null);
    tabLayout = (TabLayout) x.findViewById(R.id.tabs);
    viewPager = (ViewPager) x.findViewById(R.id.viewpager);

    /**
     *Set an Apater for the View Pager
     */
    viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

    /**
     * Now , this is a workaround ,
     * The setupWithViewPager dose't works without the runnable .
     * Maybe a Support Library Bug .
     */

   tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });

    return x;

}

class MyAdapter extends FragmentPagerAdapter {

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    /**
     * Return fragment with respect to Position .
     */

    @Override
    public Fragment getItem(int position)
    {
        switch (position){
            case 0 : return new PrimaryFragment();
           // case 1 : return new SocialFragment();
           // case 2 : return new UpdatesFragment();
        }
        return null;
    }

    @Override
    public int getCount() {

        return int_items;

    }

    /**
     * This method returns the title of the tab according to the position.
     */

    @Override
    public CharSequence getPageTitle(int position) {

        switch (position){
            case 0 :
                return "Primary";
            case 1 :
                return "Social";
            case 2 :
                return "Updates";
        }
        return null;
    }
}

}
Please help me to correct this code.
error which i am getting is this.
tabproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kpgames.tabproject, PID: 7410
java.lang.NullPointerException: Attempt to write to field 'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager' on a null object reference
    at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:418)
    at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:413)
    at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:943)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1157)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18788)
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.refl

A: I was passing 2 fragment to my 3 configured Tabhost. thats why i was getting null issue. its working fine now.


text:
Q: Django-CMS unsuccessful while removing plugin from page I can add successfuly plugin to page with created by django cms. But, when I try to remove plugin from page  plug in don't disappears and I got this execption error:
DatabaseError at /admin/cms/page/3/remove-plugin/

relation "cmsplugin_latestentriesplugin" does not exist
LINE 1: ...latestentriesplugin"."current_language_only" FROM "cmsplugin...
                                                             ^

Request Method:     POST
Request URL:    http://example.com/admin/cms/page/3/remove-plugin/
Django Version:     1.3.1
Exception Type:     DatabaseError
Exception Value:

relation "cmsplugin_latestentriesplugin" does not exist
LINE 1: ...latestentriesplugin"."current_language_only" FROM "cmsplugin...

                                                         ^

How can I correct this error?

A: Just figure out that, I missed to remove cmsplugin_blog.middleware.MultilingualBlogEntriesMiddleware from settings.
It's now works fine.


text:
Q: Phonegap for android store user credentials locally and pass in json for notifications I've built some pretty straight forward apps earlier using phonegap for android.
Now i'm building one that will need statusbar notifications from a background service per user.
Using phonegaps backgroundservice plugin, im able to get notifications through the example twitter feed.

getMethod = new
  HttpGet("http://search.twitter.com/search.json?q=phonegap&rpp=1&page1");

It works as expected, but i'm having big troubles with it.

1 - im not good with json
2 - ive yet to figure out how to store user credentials( user id f.example) on phone.
So lets say i want to build my own json file, myjson.php. in my java class, i cant pass a userid since this is not stored locally, and im unable to fetch it. my httpget would be:

getMethod = new
  HttpGet("http://domain.com/myjson.php");

Myjson.php would serve me any new messages, so i have to have a way of specifying which user is requesting the file. Concidering it is all through sql, it has to be the same values.
php sessions wont cut it as phones often clears caches and forgets user credentials.
How can i do this? local sql? xml?
And if i manage to store the user credentials locally, how can i add these to my httpget request?
Any help and pointers are greatly appreciated as ive read and read and read and now = stuck.

A: You can store data locally using LocalStorage. It's very simple. (Link: https://developer.mozilla.org/en-US/docs/DOM/Storage)

A: Your first problem is you dont really do json. You just ask for a content encoded in Jason. Look at the native code contained here.


text:
Q: Comparing overlap within sequences of dates within a data frame I have a data frame with 2 columns of starting dates and 2 columns of ending dates. I want to count the number of overlapping dates between the two sets of series (ie., how many days in the start2/end2 series fall within start1/end1 (as seen in the "output" column here)).
      start1       end1     start2       end2 output
 2011-02-10 2011-02-11 2011-02-10 2011-02-10      1
 2009-07-25 2009-07-27 2009-07-26 2009-07-27      2
 2007-12-02 2007-12-07 2007-12-08 2007-12-10      0

start1 <- as.Date(c("2011-02-10", "2009-07-25", "2007-12-02"))
end1 <- as.Date(c("2011-02-11", "2009-07-27", "2007-12-07"))
start2 <- as.Date(c("2011-02-10", "2009-07-26", "2007-12-08"))
end2 <- as.Date(c("2011-02-10", "2009-07-27", "2007-12-10"))

my.dat <- data.frame(start1,end1,start2,end2)

I should probably be using a list of sorts here in order to supply vectors of starting and ending values to seq.Date, but I can't quite seem to get that to work. Instead, my non-list approach yields the error that the "from" argument should equal 1 (because it can't handle the vector of starting dates).
my.dat$output <- length(seq(my.dat$start1,my.dat$end1,by=1) %in% seq(my.dat$start2,my.dat$end2,by=1))

There are plenty of discussions about matching dates on SO, but I can't seem to translate any of that to multiple columns of dates.
Thanks!!

A: Using data.table:
library(data.table)
setDT(my.dat)[,output:=pmin(end2,end1)-pmax(start2,start1)+1]

       start1       end1     start2       end2 output
1: 2011-02-10 2011-02-11 2011-02-10 2011-02-10 1 days
2: 2009-07-25 2009-07-27 2009-07-26 2009-07-27 2 days
3: 2007-12-02 2007-12-07 2007-12-08 2007-12-10 0 days
4: 2007-12-02 2007-12-07 2007-11-01 2007-12-01 0 days

Can be converted to integers by wrapping RHS of := in as.integer.

A: Of course, I figured it out right after posting. But I'm curious if others have more elegant solutions. Here was mine:
apply(my.dat[,c("start1","end1","start2","end2")],1,function(x)length((seq.Date(as.Date(x[1]),as.Date(x[2]),by=1) %in% (seq.Date(as.Date(x[3]),as.Date(x[4]),by=1)))))


text:
Q: Filter SQL query condition for purchase with refund id I have a data table which has two transaction types 'purchase' and 'refund' which has unique transaction id.
refund has another column named 'Refund ID' which is actually a transaction id for particular purchase. (let say there is a purchase with transaction id 100, so for refund the transaction id will be 101 and Refund ID will be 100).
Now in my query I want to show only the transaction type purchase but I want to add one field that if the particular purchase has been refunded it should show as refunded, if not refunded yet, the column should be null.
The query I have written is to display the data is:
SELECT Transaction_ID, Amount, Transaction_Type, Transaction_Date, Refund_ID
FROM Transaction
WHERE Transaction_Status = 'OK'
ORDER BY Transaction_Date desc

A: You can use CASE WHEN to check this.
SELECT Transaction_ID, Amount, Transaction_Type, Transaction_Date, Refund_ID,
       CASE WHEN IFNULL(Refund_ID, '') <> ''
       THEN 'Refunded'
       ELSE NULL
       END AS RefundStatus
FROM Transaction
WHERE Transaction_Status = 'OK'
ORDER BY Transaction_Date desc

A: From what I understood your table have these 4 main columns -
t_id, t_type, amount, r_id.
According to me you need to add another column - 'refund status'(r_status). It can only have three values - "N.A" for transaction type purchase. "Refunded" and "null" for transaction type refund.

Now, you want to display only details of transactions where transaction type is purchase along with refund status. The query for that is -
SELECT (@a:=t_id) as tr_id,(select if(t_id=(SELECT @b:=r_id from transaction where t_id>@a LIMIT 1),(select r_status from transaction where r_id=@b),'N.A')) as refund_status from transaction WHERE t_type="purchase"
If might be a little confusing. Let me explain, it will first select transaction id and also store it in 'a', then it will select refund status by checking if transaction id of current row is equal to the refund id of next row,if yes it will display the refund status of the refund id and if not it will show N.A .


text:
Q: How are value assigned to moves in minimax or other strategy in Chess? I am trying to understand how values are assigned to different moves in AI chess strategy. For example user has 3 options moves pawn, queen or knight, then for each move the opponent has 3 moves. Those moves have values: move rook + 3, move Queen +2, move Pawn -3 and so on.
So, what represent these numbers, the number of moves opponent has or the item opponent can beat(if beat a rook is +2 if beat a pawn is 0)?
Sorry if my question is confusing.

A: I could also add that actually you evaluate the positions, not moves.
The value of the position can be calculated as the sum of pieces (pawn = 1, knight = 3, bishop = 3.2, rook = 5, queen = 9), negative values for black.
Also complicated algorithms consider pawn structure, control of open files/diagonals, control of central squares etc.
Anyway, the position gets some value. And the move value is therefore the value of the position being reached when this move is made on the board.
I hope this helps :-)

A: Imaging you could play every position to the end. In that case, every final position would either be a win for white, a win for black, or a draw. Using the Minimax algorithm, you could compute for every move in your starting position whether it is won, lost or drawn.
For instance, if white is to move next, and one of its move is winning, the previous position must be lost for black (here we assume that both players are perfect and will only play the best moves). If white has no winning moves, but some moves that draw and some that will loose, it will not play the loosing moves, so the previous position must be drawn for black. And so on, until you finally arrive at the starting position.
However, that is not feasible as the number of possible moves explodes too fast, even if you use more advanced algorithms. That is why chess engines stop after a few moves and call an evaluation function. This function assign each position a score. These scores are the numbers that you describe in your question.
Every engine has a unique evaluation function, but all share the most fundamental chess knowledge:

*

*Material (one pawn is +100, knight/bishop +300, rook +500, and queen +900)

*Mobility (encourages the engine to moves its pieces toward the center)

*King safety (a weak king can be easily mated unless it is the endgame)

*Passed pawns

*Pawn structure (double pawns or isolated pawns should be avoided)

*etc

Often, the scores that you see in the output are rounded to pawns. For instance, +1.09 is an advantage of roughly one pawn. That could be because one side has one pawn more in an equal position, or it could be that the material is equal but one side has some positional advantages.

A: To assign a number to a chess position, we use

*

*Count the pieces on the board for White and Black

*Count the positions of the pieces, for example, rook on the seventh rank is strong

*Count number of squares the pieces can attack, in particular squares that are undefended

*Count number of squares the pieces attack near the enemy king


text:
Q: C# run same MessageBox 2 time in Timer Tick I read time from php with C#. I have to show MessageBox before Logoff windows when the time is equal. But when I run program it show same MessageBox 2 time. I want to show MessageBox 1 time only before Logoff. I set Interval is 30,000. How to do it? This is my code
        private void timer1_Tick(object sender, EventArgs e)
        {
            bool showingBox = false;
            timer1.Start();
            WebClient client = new WebClient();
            Stream stream = client.OpenRead("http://172.22.22.20/time.php");
            StreamReader reader = new StreamReader(stream);
            String content = reader.ReadToEnd();
            //textBox1.Text = content;

            if (showingBox) return;
            showingBox = true;
            try
            {

                if (content == "08:00")
                {

                    MessageBox.Show(new Form() { TopMost = true }, "11111");  // This will show 2 Message Box when time = 08.00

                }
            }
            finally
            {
                showingBox = false;
            }

            if (content == "08:05")
            {

                ExitWindowsEx(4, 0);

            }

            timer1.Enabled = false;
        }

        }

    }

A: I don't know if i understand your question right, but could it be that you start the timer twice ?
As far as i can see you do start the timer again in your timer_tick method
   private void timer1_Tick(object sender, EventArgs e)
        {
            bool showingBox = false;
            timer1.Start(); // <-- second time startet.

A: Why you using timer1.Start(); in timer1_Tick Event?

A: I remove timer1.Start() but it also show twice messagebox . I change the code like this flag = true; have to run before show message box . Now it work!!.
      if (content == "10:09")
      {
          if (!flag)
          {
              flag = true;
              MessageBox.Show(new Form() { TopMost = true }, "11111" +flag);

          }
      }


text:
Q: Import statements taking time on spark executors (Pyspark Executors) I am developing a python prediction script using Spark (PySpark) streaming and Keras. The prediction is happening on the executor where I am calling model.predict().
Modules that I have imported are
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential

I have checked and these imports are taking 2.5 seconds on Spark driver(2 cor + 2gb) to load. What is surprising for me is that each time executor gets the job, it automatically do these imports again. The reason I am sure that these imports are happening each time a job is submitted to the executor is because I see below statements in executor logs per job which are only comes when I do imports of above said modules.
/opt/conda/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype fromfloattonp.floatingis deprecated. In future, it will be treated asnp.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters Using TensorFlow backend.

My target is to make the prediction in 1 sec but imports itself are taking 2.5 seconds (each time imports happens on the spark executor). Is this is the intended behavior? Is their anything I can do to minimize this time say in milliseconds ?
Update 1
For the past few days I was analyzing it and found out that there are 2 main issues.

*

*I found a way to wrap keras model and pickle it on driver and unpickle on executor. So that improves time by 1 sec.

*But on driver when mapPartition() occur for each batch the whole keras and tensorflow initialization happens each time on executor (for every job) which is taking 2.5 secs. Is there a way to initialize these imports once on each executor and not per job. May be some file in pyspark where can I put these imports(assuming that these files executed once when executor comes up)


text:
Q: Javascript equation with negative and positive numbers I have four text input fields, after the user enters relevant values, I have to make a JavaScript calculation to add all of them
I use:
 var total = Number(value1) + Number(value2) + Number(value3) + Number(value4);

then I display the total:
document.getElementById("value5").innerHTML = total;

If one of the values is negative, it gets added as a positive number. How do I get the equation to treat it as a negative one (so it gets subtracted)?

A: I dont know what the problem is but it works well
     <script type="text/javascript">
 function fnc(){
 val1=Number(document.getElementById("t1").value);
  val2=Number(document.getElementById("t2").value);

 var total = val1+val2;
 document.getElementById("t3").value=total;
 }
 </script>
 input1: <input type="text" id="t1" />
  input2: <input type="text" id="t2" />
  <br />
<input type="text" id="t3" />
<input type="button" id="btn" onclick="fnc()" value="click me" />


text:
Q: Synch Clock Per Request I am using CentOS 7.4, and NTP is replaced by Chrony.
I just wonder whether Chrony has something similar to ntpdate, which can be used to synch clock per request (from command line, etc)?
Thanks in advance.

A: First, understand what software running would be seriously affected by jumps from stepping the time. It may be safer to wait until you can bring databases down.
Start chronyd, wait a few seconds for the first measurement, and make it step the remaining correction with the makestep commmand.  Usually chrony.conf will contain a makestep directive to step the first updates anyway, but the makestep command can be at any time.
systemctl start chronyd
sleep 10
chronyc makestep

There is an option to set clock once and exit. Similar to ntpd -q, even is the same -q option. However, it only works while chronyd is not running, which it should be. So I prefer makestep, although the -Q option is nice to get the offset of something not in the configuration.

Does chronyd have an ntpdate mode?
Yes. With the -q option chronyd
  will set the system clock once and exit. With the -Q option it will
  print the measured offset without setting the clock. If you don't want
  to use a configuration file, NTP servers can be specified on the
  command line. For example:
chronyd -q 'pool pool.ntp.org iburst'

These are not your only options. You can trigger a burst of measurements, or wait on slew instead of stepping the time, or some combination of the above.  See this chrony-users thread comparing burst and waitsync.


text:
Q: parents remove doesn't work on appended elements I'm trying to remove a div after it the remove link on that div is clicked.
The divs are generated using append after the website is loaded.
Appended HTML:

Test Test

            <time class="timeago" datetime="2013-09-19 22:49:59" title="Thursday, Sep 19, 2013 - 10:49 PM">5 minutes ago</time>,
            remove

My JQuery Code:
            $(".reviews").on('click', '.removereview', function() {
            var review_id = $(this).parents('.row-fluid').attr('id');
            console.log(review_id);

            $.ajax({
                type: "POST",
                url: "event_send.php",
                data: "func=remove_review&post_id=" + review_id + "&event_name=" + getUrlVars()["event_name"],
                success: function(response){
                    $(".review-count").html(parseInt($(".review-count").html()) - 1);
                    $(this).closest('.row-fluid').remove();
                }
            });

            return false;
        });

The problem is that the div doesn't get removed although the right ID is chosen by the code.
Any ideas on how to fix the problem?
Thank you

A: this inside the success handler does not refers the clicked element so your selector $(this).closest('.row-fluid') fails to find the element.
One solution is to use a closure variable self which then will be used inside the success handler
$(".reviews").on('click', '.removereview', function() {
    var review_id = $(this).parents('.row-fluid').attr('id');
    console.log(review_id);

    var self = this;
    $.ajax({
        type: "POST",
        url: "event_send.php",
        data: "func=remove_review&post_id=" + review_id + "&event_name=" + getUrlVars()["event_name"],
        success: function(response){
            $(".review-count").html(parseInt($(".review-count").html()) - 1);
            $(self).closest('.row-fluid').remove();
        }
    });

    return false;
});

Another is to use $.proxy() to pass a custom context to the success callback
$(".reviews").on('click', '.removereview', function() {
    var review_id = $(this).parents('.row-fluid').attr('id');
    console.log(review_id);

    $.ajax({
        type: "POST",
        url: "event_send.php",
        data: "func=remove_review&post_id=" + review_id + "&event_name=" + getUrlVars()["event_name"],
        success: $.proxy(function(response){
            $(".review-count").html(parseInt($(".review-count").html()) - 1);
            $(this).closest('.row-fluid').remove();
        }, this)
    });

    return false;
});

A: I believe you are trying to remove the element you got in review_id; Why not remove it directly?
$('#'+review_id).remove();

correct me if I misunderstood your question.


text:
Q: python3: How to get logical complement (negation) of a binary number, eg. '010' => '101'? Maybe I'm missing something but I can't find a straightforward way to accomplish this simple task. When I go to negate a binary number through the "~" operator it returns a negative number due to the two's complement:
>>> bin(~0b100010) # this won't return '0b011101'
'-0b100011'

What about if I just want to switch 0s into 1s and vice-versa, like in classic logical complement?

A: >>> bin(0b111111 ^ 0b100010)
'0b11101'
>>>

A: YOU's answer as a function:
def complement(n):
    size = len(format(n, 'b'))
    comp = n ^ ((1 << size) - 1)
    return '0b{0:0{1}b}'.format(comp, size)

>>> complement(0b100010)
'0b011101'

I made it preserve the bit length of the original. The int constructor doesn't care about the leading zeros:
>>> complement(0b1111111100000000)
'0b0000000011111111'

>> int(complement(0b1111111100000000), 2)
255

A: Ultra nasty:
>>> '0b' + ''.join('10'[int(x)] for x in format(0b100010,'b')).lstrip('0')
'0b11101'

A: Here's another couple of functions that returns the complement of a number I came out with.
A one-liner:
def complement(c):
    return c ^ int('1'*len(format(c, 'b')), 2)

A more mathematical way:
def complement(c):
    n=0
    for b in format(c, 'b'): n=n<<1|int(b)^1
    return n

Moreover, one-linerizing this last one with functools (such baroque):
def complement(c):
    return functools.reduce( lambda x,y: x<<1|y, [ int(b)^1 for b in format(c, 'b') ])

Finally, a uselessly nerdish variant of the first one that uses math.log to count the binary digits:
def complement(c):
    c ^ int('1' * math.floor(math.log((c|1)<<1, 2)), 2)

A: Another function more a 'Hack' for complementing a Integer. You can use the same logic for complementing binary. Wonder why I did not come across python external libs that can do same. The next ver of Python should take care of this in built-ins

def complement(x):
b = bin(x)[2:]
c= []
for num in b:
    if num == '1': c.append('0')
    elif num == '0': c.append('1')

cat = ''.join(c)
res = int(cat, 2)
return print(res)


text:
Q: Formatting column name in dual table How to add spaces or special characters to column name when using SELECT * FROM dual;
For example, if I want to print "Hello World" as the column name, how should I use this with dual table as the following is not working.
SELECT 'HELLO WORLD' FROM dual;

This displays result as:
'HELLOWORLD'
------------
HELLO WORLD

A: Try this
SELECT 'HELLO WORLD' as HELLOWORLD FROM dual;

or
SELECT 'HELLO WORLD' as "HELLO WORLD" FROM dual;

See SQL Fiddle

A: You may also try brackets:
SELECT 'HELLO WORLD' as [HELLO WORLD] FROM dual;


text:
Q: Could it be possible to define an array with a variable? I am writing a code that uses arrays whose dimension depends of values that the user gives. This value depends on the number of cells that he/she is using and I use this number to do a for-loop structure.
Here it´s an example:
Sub Test()
    Dim Row As Integer
    Dim Myarray(1 To Row) As String

    For 1 To Row
        'Do whatever I need
    Next linha
End Sub

When I tried this, an error appears. Is there any way to use that? I was looking for any clues on google and I found dynamic array. But it dosen´t seem to fit in my problem.
Thanks!

A: Change the syntax to (obviously `LengthOfArray' should hold a number with the size of the array):
Sub Test()
    Dim Row As Integer
    Dim Myarray() As String

    n = LengthOfArray

    Redim MyArray(1 to LengthOfArray)

    For linha = 1 To n
        'Do whatever I need
    Next linha
End Sub

A: I would use a collection instead of an array and you may want to look into doing redim preserve. (https://msdn.microsoft.com/en-us/library/w8k3cys2.aspx)
sub Test(row as range)
Dim my myCollection as new collection

myCollection.add row
For each Item in myCollection
    'Do some stuff here...
Next 'Item
end Sub


text:
Q: CA certificate directory on Windows I make a network client in C and normaly I work with linux and I don't know how work CA certificate on windows. And the windows manual is not very good.
A CA certificate directory (root) exist by default on windows?
Like the directory /etc/ssl/certs/ under linux, which is a list of CA certificate.
I need this for adapted a programme which work with openSSL.
can you help me? Thank you in advance.

A: I don't believe Windows stores your Certificates in a default file location, but rather in a registry entry.  Check out this link - it's for Windows Server 2003, but I believe most of the information is still relevant.
The basic tools typically used to manage certificates are Certreq.exe and Certutil.exe.
Here is a basic C++ program example for how to insert/create a certificate for Windows.  It does not address the network portion of your question, but I think you might find it useful.
Good luck.

A:
A CA certificate directory (root) exist by default on windows? Like
  the directory /etc/ssl/certs/ under linux, which is a list of CA
  certificate.

No. You must provide a file with root and intermediate certificates with your app on Windows. It can be from Linux or you can export nessecity certificates from Windows Store manually through certmgr. Or you can create a list of trusted root and intermediate certificates programmatically with help's of WinAPI like Qt does, for example.

A: you can acces to the Windows certificate store (which contain CA cert) and manipulate certificate whith this functions:
CertOpenSystemStore()
CertEnumCertificatesInStore()
CertCloseStore()

and convert DER certificate to OpenSSL X509 structure with:
d2i_X509()

for exemple, see in this link:
TLS client:
.


text:
Q: Posting JavaScript objects with Ajax and ASP.NET MVC How can I post a list from view to controller using ajax? I have this code in client side:
    $(".js-save").click(function (e) {
        e.preventDefault();
        var button = $(this);
        var lstERegistroVenta = [];
        var ERegistroVenta = new Object();
        ERegistroVenta.IdProducto = 1;
        ERegistroVenta.IdInventario = 2;
        ERegistroVenta.MontoProducto = 12.5;
        ERegistroVenta.CantidadProducto = 1;
        ERegistroVenta.MontoTotalSinIGV = 20.5
        ERegistroVenta.MontoTotal = 23.5
        lstERegistroVenta.push(ERegistroVenta);
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: "/API/Inventario/Venta/1",
            data: JSON.stringify({ lstERegistroVenta: lstERegistroVenta }),
            success: function () {
                toastr.success("Correcto");
            },
            error: function () {
                toastr.error("Error");
            }
        });
    });

When I try to pass the data I receive only empty list. In server side I have this API
[HttpPost]
    [Route("API/Inventario/{Venta}/{IdProducto}")]
    public IHttpActionResult AsignarProducto(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
    {
        return Ok();
    }

public class ERegistroVenta
{
    public int IdProducto { get; set; }
    public int IdInventario { get; set; }
    public double MontoProducto { get; set; }
    public int CantidadProducto { get; set; }
    public double MontoTotalSinIGV { get; set; }
    public double MontoTotal { get; set; }
}

A: First of all, I wouldn't suggest calling an API method directly from a View. Instead, call a controller method which should internally call the API method. The code for this would look something like below.
$.ajax({
        dataType: 'json',
        type: 'POST',
        url: "/TestController/TestMethod",
        data: { "IdProducto" : "1", "lstERegistroVenta": lstERegistroVenta },
        success: function () {
            toastr.success("Correcto");
        },
        error: function () {
            toastr.error("Error");
        }
});

   [HttpPost]
   public void TestMethod(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
   {
        // Your Logic Here
   }

A: I found a solution. Maybe my mistake was that I didn't send an anonymous list of objects.
Take a look to this:https://kwilson.io/blog/post-an-array-of-objects-to-webapi-using-jquery/
My solution below:
    $(".js-save").click(function (e) {
        e.preventDefault();
        var button = $(this);
        var lstERegistroVenta = [];
        var ERegistroVenta = new Object();
        ERegistroVenta.IdProducto = 1;
        ERegistroVenta.IdInventario = 2;
        ERegistroVenta.MontoProducto = 12.5;
        ERegistroVenta.CantidadProducto = 1;
        ERegistroVenta.MontoTotalSinIGV = 20.5
        ERegistroVenta.MontoTotal = 23.5
        lstERegistroVenta.push(ERegistroVenta);
        $.ajax({
            dataType: 'json',
            method: 'POST',
            url: "/API/Inventario/Venta/1",
            data: { '': lstERegistroVenta },
            success: function () {
                toastr.success("Correcto");
            },
            error: function () {
                toastr.error("Error");
            }
        });
    });

And in server side:
[HttpPost]
[Route("API/Inventario/{Venta}/{IdProducto}")]
public IHttpActionResult AsignarProducto(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
    // Logic Here
}

Hope this helps to another user.