text:
Q: Linq To entities, Select from select I have tried for sum time now but I cant get the hold of doing this selection in LINQ to Entites? How can I do a Select on a Selection?
SELECT * FROM tProduct AS tpp, tProductGroupDetail AS tppg,
    (SELECT tpgd.ProductGroupID AS pgID
     FROM tProduct AS tp, tProductGroupDetail AS tpgd
     WHERE tp.ProductID = 428 AND tpgd.ProductID = tp.ProductID) AS JoinedTable
WHERE JoinedTable.pgID = tppg.ProductGroupID
      AND tpp.ProductID = tppg.ProductGroupID

A: Your SQL statement is very bizarre. Isn't it equivalent to the following statement?
SELECT *
FROM
    tProduct AS p
    INNER JOIN tProductGroupDetail AS pgd
        ON p.ProductID = pgd.ProductGroupID
WHERE
    pgd.ProductID = 428

The corresponding LINQ query would then be rather obvious.

Let's change your SQL step by step:
The nested SELECT looks like this:
(SELECT tpgd.ProductGroupID AS pgID
FROM tProduct AS tp, tProductGroupDetail AS tpgd
WHERE tp.ProductID = 428 AND tpgd.ProductID = tp.ProductID)

This is the same as
(SELECT tpgd.ProductGroupID AS pgID
FROM tProductGroupDetail AS tpgd
WHERE tpgd.ProductID = 428)

Since tpgd.ProductID = tp.ProductID you can directly directly test for tpgd.ProductID = 428 without having to join with tp. The simplyfied statement now looks like this:
SELECT * FROM tProduct AS tpp, tProductGroupDetail AS tppg,
    (SELECT ProductGroupID
     FROM tProductGroupDetail
     WHERE ProductID = 428) AS JoinedTable
WHERE JoinedTable.ProductGroupID = tppg.ProductGroupID
      AND tpp.ProductID = tppg.ProductGroupID

Basically, what it does, is to join tProduct with tProductGroupDetail. The purpose of the additional join with JoinedTable is to restrict the records to contain only product groups having a ProductID = 428. This condition can be applied directly:
SELECT *
FROM tProduct AS tpp, tProductGroupDetail AS tppg,
WHERE tppg.ProductID = 428 -- Note: ProductID of tggp, NOT tpp!
     AND tpp.ProductID = tppg.ProductGroupID

The last step is to replace the join with an INNER JOIN clause and to tweak the aliases. This yields my first SQL statement.

A: To obtain the list of ProductGroup containing the product #428, just write:
dataContext.Products.FirstOrDefault(p => p.ProductID == 428).ProductGroups

This solution assumes the existence in the entity Product of the navigation property ProductGroups. If this is not the case, thank you to specify the entity model.

A: I think this should do it (although it's off the top of my head, not tested):
var product = Products.Where(x => x.ProductGroup.Any(y => y.ProductID == 428));


text:
Q: java.lang.IllegalArgumentException: Invalid context argument error when logout I create a simple application that have login and logout using facebook. When login it's ok , but when logout the application was stopped. Is there any solution for this ? Here is my code
Activity
public class Login extends Activity implements OnClickListener {

    ImageView pic, button;
    Facebook fb;
    SharedPreferences sp;
    TextView welcome;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        String APP_ID = getString(R.string.app_id);
        fb = new Facebook(APP_ID);

        sp = getPreferences(MODE_PRIVATE);
        String access_token = sp.getString("access_token",null);
        long expires = sp.getLong("access_expires", 0);

        if(access_token != null){
            fb.setAccessToken(access_token);
        }
        if(expires != 0){
            fb.setAccessExpires(expires);
        }

        welcome = (TextView) findViewById(R.id.welcome);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        button = (ImageView)findViewById(R.id.login);
        pic = (ImageView)findViewById(R.id.picture_pic);
        button.setOnClickListener(this);

        updateButtonImage();

    }

    @SuppressWarnings("deprecation")
    private void updateButtonImage() {
        if (fb.isSessionValid()){
            button.setImageResource(R.drawable.logout_button);
            pic.setVisibility(ImageView.VISIBLE);

            JSONObject obj = null;
//          URL img_url = null;

            try {
                String jsonUser = fb.request("me");
                obj = Util.parseJson(jsonUser);

                String id = obj.optString("id");
                String name = obj.optString("name");

                welcome.setText("Welcome, " + name + " Your id is " + id);

            } catch (FacebookError e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }else{
            button.setImageResource(R.drawable.login_button);
            pic.setVisibility(ImageView.INVISIBLE);

        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onClick(View v) {
        // logout from facebook
                if(fb.isSessionValid()){

                    try {
                        fb.logout(Login.this);
                        updateButtonImage();
                        welcome.setText("Please Login !");

                    } catch (MalformedURLException e) {

                        e.printStackTrace();
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }else{
                    //login to facebook
                fb.authorize(Login.this, new String[] {"email"} ,new DialogListener(){

                    @Override
                    public void onComplete(Bundle values) {
                        Editor editor = sp.edit();
                        editor.putString("access_token", fb.getAccessToken());
                        editor.putLong("access_expires", fb.getAccessExpires());
                        editor.commit();

                        updateButtonImage();

                //      Intent intent = new Intent (Login.this,Home.class);
                //      startActivity(intent);
                //      finish();
                    }

                    @Override
                    public void onFacebookError(FacebookError e) {
                        Toast.makeText(Login.this, "onFBError", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(DialogError e) {
                        Toast.makeText(Login.this, "onError", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(Login.this, "onCancel", Toast.LENGTH_SHORT).show();
                    }

                });
                }
    }
    @SuppressWarnings("deprecation")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        fb.authorizeCallback(requestCode, resultCode, data);

    }

}

This is the error report from Logcat
> 03-28 07:27:37.379: W/dalvikvm(4094): threadid=1: thread exiting with
> uncaught exception (group=0xa62df288) 03-28 07:27:37.383:
> E/AndroidRuntime(4094): FATAL EXCEPTION: main 03-28 07:27:37.383:
> E/AndroidRuntime(4094): java.lang.IllegalArgumentException: Invalid
> context argument 03-28 07:27:37.383: E/AndroidRuntime(4094):  at
> android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:86)
> 03-28 07:27:37.383: E/AndroidRuntime(4094):   at
> com.facebook.internal.Utility.clearCookiesForDomain(Utility.java:255)
> 03-28 07:27:37.383: E/AndroidRuntime(4094):   at
> com.facebook.internal.Utility.clearFacebookCookies(Utility.java:279)
> 03-28 07:27:37.383: E/AndroidRuntime(4094):   at
> com.facebook.Session.closeAndClearTokenInformation(Session.java:593)
> 03-28 07:27:37.383: E/AndroidRuntime(4094):   at
> com.facebook.android.Facebook.logoutImpl(Facebook.java:667) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> com.facebook.android.Facebook.logout(Facebook.java:644) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> com.innoark.motivator.Login.onClick(Login.java:118) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> android.view.View.performClick(View.java:4084) 03-28 07:27:37.383:
> E/AndroidRuntime(4094):   at
> android.view.View$PerformClick.run(View.java:16966) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> android.os.Handler.handleCallback(Handler.java:615) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> android.os.Handler.dispatchMessage(Handler.java:92) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> android.os.Looper.loop(Looper.java:137) 03-28 07:27:37.383:
> E/AndroidRuntime(4094):   at
> android.app.ActivityThread.main(ActivityThread.java:4745) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> java.lang.reflect.Method.invokeNative(Native Method) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> java.lang.reflect.Method.invoke(Method.java:511) 03-28 07:27:37.383:
> E/AndroidRuntime(4094):   at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
> 03-28 07:27:37.383: E/AndroidRuntime(4094):   at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-28
> 07:27:37.383: E/AndroidRuntime(4094):     at
> dalvik.system.NativeStart.main(Native Method)

Thanks in advance.

A: I ran across this error in an old application that is still using the now deprecated logout method used in this question. I opted to patch the SDK for a quick fix instead of upgrading, for lack of time.
As the stack trace suggests, the problem is that at this line, the context argument passed to CookieSyncManager is null:
android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:86)
If you go further up the stack, you can see that the Context argument passed in is the staticContext member variable of the Session class in the Facebook SDK. For whatever reason, they are setting this variable to null, and thus when logout is called, the app crashes with this exception.
To fix this, I just edited the Session class to make initializeStaticContext a public method. Then, just call that before you call logout:
Session.initializeStaticContext(this.getApplicationContext());
fb.logout(Login.this);

Certainly, this is not the best solution, but it gets the job done.

A: A workaround for https://developers.facebook.com/bugs/547340878743830/ which causes this is to create a com.facebook.Door class to be able to call Session.initializeStaticContext(), and call its method before calling logout.
package com.facebook;

import android.content.Context;

public class Door {
  public static void initializeStaticContext(Context context) {
    Session.initializeStaticContext(context);
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ball Keeps Glitching On The Paddle Pong How To Fix? Pygame when ever my ball collides with my paddles the ball keeps glitching with the paddles Video

    if ball1.rect.colliderect(playerman.rect) or ball1.rect.colliderect(playerman2.rect):
        ball1.velx *= -1
        ball1.velx += 1

A: Why Are you saying += 1?
Does it have some specific purpose?
I've made more than 10 tiny and 2 big games with pygame but don't get this!
maybe try
if ball1.rect.colliderect(playerman.rect):
        ball1.velx *= -1
        ball1.velx += 1
        ball1.x = playerman.x + (playerman.rect.width / 2) + 5
elif ball1.rect.colliderect(playerman2.rect)
    ball1.velx *= -1
        ball1.velx -= 1
        ball1.x = playerman.x - (playerman2.rect.width / 2) - 5

if that doesn't work do this
if ball1.rect.colliderect(playerman.rect):
        ball1.velx *= -1
        ball1.velx -= 1
        ball1.x = playerman.x + (playerman.rect.width / 2) + 5
elif ball1.rect.colliderect(playerman2.rect)
    ball1.velx *= -1
        ball1.velx += 1
        ball1.x = playerman.x + (playerman2.rect.width / 2) + 5


text:
Q: Bootstrap: How to link to another page and then program that page This is a really stupid question, but I am having a brain fart. I want to go to one of the other pages on my webpage and then program that webpage. What happens now is that I will click on the link to the other page, but it will still show the main page. Thanks in advance!

A: A simple link like this you mean? You must have the physical
file in your project. In this example it'll have to be named FirstPage.html and SecondPage.html

First Page

Second Page

  ...


text:
Q: How can I reference a formula with an on going numbering? I work with LaTeX for long time and I used eqnarry. But that's obsolete so I gave equation and aligned a try. The problem is, that if I reference to my equation it shows the chapter numbering (?), but it shows the incorrect numbering at the equations right side.
...siehe Gleichung \ref{form:casteljau}.
\begin{equation}
    \begin{aligned}
    \mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k} + v\mathbf{p}^{l-1}_{i,j+1,k} + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \\
    l &= 1...n, i+j+k = n-l
    \end{aligned}
    \label{form:casteljau}
\end{equation}

That looks something like:
siehe Gleichung 2.6.2.
"equation" ____________________________(2.12)
"equation"

So I tried subequations and align. Now I get the correct numbering (2.13) in the text, but the equation doesn't have a number at the right side, as it usually does.
....siehe Gleichung \eqref{form:casteljau}.
\begin{subequations}
    \begin{align*}
        \mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k} + v\mathbf{p}^{l-1}_{i,j+1,k} + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \\
        l &= 1...n, i+j+k = n-l
    \end{align*}
    \label{form:casteljau}
\end{subequations}

That looks something like:
siehe Gleichung 2.13.
"equation" ____________________________
"equation"

btw the underscore is not really there, but it deletes my spaces, so i used ___s
Could anyone give me the correct combination? Because alot of blogs say that this should work, but it doesn't. Anything else I can post?
here the compile master document:
\documentclass[12pt,a4paper,oneside]{scrbook}
%\usepackage{showframe}

% German stuff
\usepackage[latin1]{inputenc}   % so can use Umlaut chars
\usepackage[ngerman]{babel} % load babel *before* natbi [english]
\usepackage[normal,small,bf]{caption} % normal, hang, center, nooneline, Large

% mathematical Symboles
\usepackage{amsmath,amssymb,amsfonts,amstext,chemarr}
%\numberwithin{equation}{chapter}

\usepackage[bf,sf]{subfigure}
\renewcommand{\subfigtopskip}{0mm}
\renewcommand{\subfigcapmargin}{0mm}
\renewcommand{\chaptername}{}

\linespread{1.3}            % 1.5facher Zeilenabstand

\usepackage{setspace}
\onehalfspacing

\usepackage{comment}
\usepackage{listings}
\usepackage{ulem} %dashuline

\usepackage[nolist]{acronym}%nolist printonlyused printonlyused,withpage

\usepackage{wrapfig}

% citations
\usepackage[numbers,square]{natbib}

\usepackage{url}

\usepackage{latexsym}

\usepackage{longtable}

\usepackage{ifpdf}      % detect outputstyle

% Free Header and Footer
\usepackage{fancyhdr}
%first[]-> even pages; second [] -> odd pages
\lfoot[\fancyplain{}{}]{\fancyplain{}{}}
\rfoot[\fancyplain{}{}]{\fancyplain{}{}}
\cfoot[\fancyplain{}{\footnotesize\thepage}]{\fancyplain{}{\footnotesize\thepage}}
\lhead[\fancyplain{}{\footnotesize\nouppercase\sc\leftmark}]{\fancyplain{}{}}
\chead{}
\rhead[\fancyplain{}{}]{\fancyplain{}{\footnotesize\nouppercase\sc\leftmark}}

% Color in Document
\usepackage{color}
\usepackage{colortbl}       %define colored backgrounds for tables
\definecolor{listinggray}{gray}{0.9}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\definecolor{orange}{rgb}{0.0,0.0,1.0}
\definecolor{yac}{rgb}{0.0,0.5,0.5}
\definecolor{middlegray}{rgb}{0.5,0.5,0.5}

\usepackage{array}

\ifpdf
  \usepackage[pdftex]{graphicx}
  \DeclareGraphicsExtensions{.pdf,.jpg,.png,.gif}
  \pdfcompresslevel=9
  \pdfpageheight=290mm
  \pdfpagewidth=210mm
  \usepackage[          % hyperref should be last package loaded
    pdftex,
    bookmarks,
    bookmarksnumbered,
    linktocpage,
    pagebackref,
    pdfview={Fit},
    pdfstartview={Fit},
    pdfpagemode=UseOutlines,    % open bookmarks in Acrobat
  ]{hyperref}           % for Querverweise
  \usepackage{bookmark}
\else                      % latex
  \usepackage{graphicx}
  \DeclareGraphicsExtensions{.ps}
\fi

\usepackage{epstopdf} %gordon: for displaying eps images

\lstset{
 backgroundcolor=\color{lbcolor},
 tabsize=4,
 rulecolor=,
 emph={a,b,c},
 language=c++,
 basicstyle=\scriptsize\ttfamily,
 upquote=true, %compile with pdflatex
 aboveskip={1.5\baselineskip},
 columns=fixed,
 showstringspaces=false,
 extendedchars=true,
 breaklines=true,
 prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
 frame=tlrb,
 numbers=left,
 numberstyle=\tiny,
 showtabs=false,
 showspaces=false,
 showstringspaces=false,
 identifierstyle=\ttfamily,
 keywordstyle=\bfseries\ttfamily\color{orange},
 stringstyle=\color{middlegray}\ttfamily,
 commentstyle=\color{yac}\ttfamily,
}

\setlength{\parskip}{3pt plus 1pt minus 0pt}       % vert. space before a paragraph

\setcounter{tocdepth}{2}        % lowest section level entered in ToC
\setcounter{secnumdepth}{3}     % lowest section level still numbered

% --- Start of Document ----------------------------------------
\begin{document}

\setcounter{page}{1}
\pagenumbering{roman}       %roemische ziffern
\pagestyle{plain}       % Initialize Header and Footer

\include{title}         % Title Page
\include{empty}         % Empty Page
\include{affidavit}     % affidavit
\include{abstracts}     % Englisch and German abstracts
\include{acknowl}       % Acknowledgements
\include{abbreviation}      % Abkuerzungen
\include{toc}           % Table of Contents

%--- Include your chapters here ----------
\setcounter{page}{1}
\pagenumbering{arabic}
\pagestyle{fancy}       % Initialize Header and Footer
\include{chapter1}      % Introduction
\include{chapter2}      % Background
\include{chapter4}      % Technische Umsetzung
\include{chapter6}

\pagenumbering{roman}       %roemische ziffern
\pagestyle{plain}       % Initialize Header and Footer
\appendix
\include{glossary}      % Glossary
\include{appendix}          % Appendix A

\end{document}

A: It's not clear to me if you want the equation number -- say, (2.13) -- to pertain to just the first line of the two-line equation structure or if it should pertain to both lines. At any rate, don't use an align* environment inside a subequations environment, as align* environments are designed not to show equation numbers.
If you want just the first line of the two-line system to be numbered, I suggest you use an align environment and use the command \notag to suppress equation numbering for the second line. If you want the equation number to pertain equally to both lines, I suggest you use a split environment inside an equation environment. Observe where the \label instructions are placed in the two cases.

\documentclass{book}
\usepackage{amsmath}
\numberwithin{equation}{chapter}
\begin{document}
\setcounter{chapter}{2}   % just for this example
\setcounter{equation}{12}

\dots\ siehe Gleichung \eqref{form:casteljau}.
\begin{align}
\mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k}
      + v\mathbf{p}^{l-1}_{i,j+1,k}
      + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \label{form:casteljau}\\
   l &= 1,\dots,n; \quad i+j+k = n-l \notag
\end{align}

\begin{equation}\label{form:casteljau_new}
\begin{split}
\mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k}
      + v\mathbf{p}^{l-1}_{i,j+1,k}
      + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \\
  l &= 1,\dots,n; \quad i+j+k = n-l
\end{split}
\end{equation}

\dots\ siehe Gleichung \eqref{form:casteljau_new}.
\end{document}

A separate suggestion: Since your formulas feature both 1 and l, you may want to provide a bit more visual distinction between the two symbols by using \ell instead of l. The first group of equations would then look like this:

A: I don't know if I understand your question. How about
\documentclass{book}
\usepackage{hyperref}

\usepackage{amsmath}
\numberwithin{equation}{chapter}  %numbering within chapter

\begin{document}
\chapter{a}

....siehe Gleichung~\ref{bbb}.
\begin{align}
    \mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k} + v\mathbf{p}^{l-1}_{i,j+1,k} + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \label{aaa} \\
    l &= 1...n, i+j+k = n-l \label{bbb}
\end{align}

\begin{align}
        \mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k} + v\mathbf{p}^{l-1}_{i,j+1,k} + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \nonumber \\  %without equation number
        l &= 1...n, i+j+k = n-l.
\end{align}

\end{document}

A: Okay I did some test, a combination with my code and your code, and the problem still occures. (sorry for my confusing way of writing...)
I;m using pdflatex btw.
\documentclass{scrbook}
\usepackage{amsmath}
\numberwithin{equation}{chapter}
\begin{document}
\setcounter{chapter}{2}   % just for this example
\setcounter{equation}{12}

See equation tangentSpace0 \ref{form:tangentSpace0}, form:tangentSpace1 \ref{form:tangentSpace1}, form:tangentSpace2 \ref{form:tangentSpace2}.
\begin{eqnarray}
E_{V2-V1} = V2.xyz - V1.xyz =
 \begin{pmatrix}
  18 - 0\\
  18 - 18\\
  0 - 0
 \end{pmatrix}
=
 \begin{pmatrix}
  18\\
  0\\
  0
  \label{form:tangentSpace0}
\end{pmatrix}
\end{eqnarray}
\nonumber\\
\begin{eqnarray}
E_{V2-V1} = V2.uv - V1.uv =
 \begin{pmatrix}
  1 - 0\\
  0 - 0
 \end{pmatrix}
=
 \begin{pmatrix}
  1\\
  0
  \label{form:tangentSpace1}
\end{pmatrix}
\end{eqnarray}
\\
\begin{eqnarray}
T_{unnormalisiert} = E_{V2-V1}.xyz / E_{V2-V1}.u =
 \begin{pmatrix}
  18 / 1\\
  0 / 1\\
  0 / 1
 \end{pmatrix}
=
 \begin{pmatrix}
  18\\
  0\\
  0
  \label{form:tangentSpace2}
 \end{pmatrix}
\end{eqnarray}

\dots\ your version: form:casteljau \eqref{form:casteljau}.
\begin{align}
\mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k}
      + v\mathbf{p}^{l-1}_{i,j+1,k}
      + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \label{form:casteljau}\\
   l &= 1,\dots,n; \quad i+j+k = n-l \notag
\end{align}

\dots\ your version: form:casteljau\_new \eqref{form:casteljau_new}.
\begin{equation}\label{form:casteljau_new}
\begin{split}
\mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k}
      + v\mathbf{p}^{l-1}_{i,j+1,k}
      + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \\
  l &= 1,\dots,n; \quad i+j+k = n-l
\end{split}
\end{equation}

...my old version with equation and aligned: form:casteljau1 \ref{form:casteljau1}.
\begin{equation}
    \begin{aligned}
    \mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k} + v\mathbf{p}^{l-1}_{i,j+1,k} + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \\
    l &= 1...n, i+j+k = n-l
    \end{aligned}
    \label{form:casteljau1}
\end{equation}

...my old version with subequations and align form:casteljau2 \eqref{form:casteljau2}.
\begin{subequations}
    \begin{align}
        \mathbf{p}^{l}_{i,j,k} &= u\mathbf{p}^{l-1}_{i+1,j,k} + v\mathbf{p}^{l-1}_{i,j+1,k} + (1-u-v)\mathbf{p}^{l-1}_{i,j,k+1} \\
        l &= 1...n, i+j+k = n-l
    \end{align}
    \label{form:casteljau2}
\end{subequations}

and eqnarry again: form:tangentSpace3 \ref{form:tangentSpace3}

\begin{eqnarray}
T_{unnormalisiert} = E_{V2-V1}.xyz / E_{V2-V1}.u =
 \begin{pmatrix}
  18 / 1\\
  0 / 1\\
  0 / 1
 \end{pmatrix}
=
 \begin{pmatrix}
  18\\
  0\\
  0
  \label{form:tangentSpace3}
 \end{pmatrix}
\end{eqnarray}

\end{document}

And this looks like the following image:

The numbering on the right hand side is so confusing. And I double checked the label names and reference names too.
It really look like you cant mix eqnarray with other packages... pls could someone just copie past that code and see if its the same result?!
Okay you can mix them, after compiling about 5 times it looks correct.

But If I try it in my work, after the 6th compiling it still look like that:

the lower equation doesent have a numbering and the reference shows 2.6.2 (thats the chapter...)


text:
Q: Inline editing in lightning data table in Aura Lightning not working? I am trying to inline edit the table record but they shows me error like this This page has an error.
You might just need to refresh it. First, would you give us some details? (We're reporting this as error ID: -1407392794)
my code look like this.
component:-
<aura:component controller='AccountToContactProvider' implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >

<aura:attribute name="contactList" type="List"/>
<aura:attribute name="conTableColList" type="List"/>
<aura:attribute name="selectedContactRecordList" type="List"/>
<aura:attribute name="totalRecords" type="Integer" default="0"/>
<aura:attribute name="selectedRecordCount" type="Integer" default="0"/>
<aura:attribute name="errors" type="Object" default="[]"/>
<aura:attribute name="draftValues" type="Object" default="[]"/>

<lightning:card title='Account Related Contact'>
    <lightning:button
                      variant="brand"
                      label="Show Current Contacts"
                      iconName="utility:search"
                      onclick="{!c.searchContactController}" />
    <lightning:button
                      variant="destructive"
                      label="delete Addressess"
                      iconName="utility:delete"
                      onclick="{!c.deleteSelectedContactController}"/>

    Number of Contacts = <ui:outputText value="{!v.totalRecords}" />
    Selected Records = <ui:outputText value="{!v.selectedRecordCount}" />

    <lightning:datatable
                         keyField="Id"
                         data="{!v.contactList }"
                         columns="{!v.conTableColList }"
                         hideCheckboxColumn="false"
                         onrowselection ="{!c.selectedContactsRows}"
                         errors="{! v.errors }"
                         draftValues="{! v.draftValues }"
                         onsave="{! c.handleSaveEdition }"
                         />
</lightning:card>

</aura:component>
JS Controller:-
 searchContactController : function(component, event, helper) {

    component.set('v.conTableColList', [

        {label: 'First Name', fieldName: 'linkName', type: 'url',editable: true,
         typeAttributes: {label: { fieldName: 'FirstName' }, target: '_blank'}},

        {label: 'Last Name', fieldName: 'LastName', type: 'text', editable: true},
        {label: 'Level', fieldName: 'Level__c', type: 'text', editable: true}
    ]);

    helper.searchContactHelper(component, event, helper);
    console.log('I am js Controller method.')
}

Helper:-
handleSaveContactsHelper : function(component, event, helper){
console.log('i am JS helper handleSave Method');
    var draftValues = event.getParam('draftValues');
    console.log(draftValues);
    var action = component.get("c.saveAccts");
    action.setParams({"conList" : draftValues});
    action.setCallback(this, function(response) {
        var state = response.getState();
        $A.get('e.force:refreshView').fire();

    });
    $A.enqueueAction(action);
}

Apex Class:-
@AuraEnabled
public static void saveAccts(List<Contact> conList){
    update conList;
}


text:
Q: Problem on error code ORA-12154 resolving Oracle database I am unable to resolve this error:
C:\Windows\system32>sqlplus dunya/tiger@ORADATA

SQL*Plus: Release 11.2.0.1.0 Production on Sun Feb 2 13:46:10 2018
Copyright (c) 1982, 2010, Oracle.  All rights reserved.

ERROR:
ORA-12154: TNS:could not resolve the connect identifier specified

In the database:
SQL> select database_name from v$database;

DATABASE_NAME
----------------------------------------------------
ORADATA

SQL> select instance_name from v$instance;

INSTANCE_NAME
----------------
oradata

tnsnames.ora:
ORADATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL=TCP)(HOST=himanshu-PC)(PORT=1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = oradata)
      (SERVER = DEDICATED)
    )
  )

listener.ora:
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = himanshu-PC)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = ORADATA)
      (ORACLE_HOME = G:\app\himanshu\product\11.2.0\dbhome_1)
      (SID_NAME = oradata)
    )
  )

sqlnet.ora:
SQLNET.AUTHENTICATION_SERVICES = (NTS)


text:
Q: How do I update props on a manually mounted vue component? Question:
Is there any way to update the props of a manually mounted vue component/instance that is created like this? I'm passing in an object called item as the component's data prop.
let ComponentClass = Vue.extend(MyComponent);

let instance = new ComponentClass({
    propsData: { data: item }
});

// mount it
instance.$mount();

Why
I have a non vue 3rd party library that renders content on a timeline (vis.js). Because the rest of my app is written in vue I'm attempting to use vue components for the content on the timeline itself.
I've managed to render components on the timeline by creating and mounting them manually in vis.js's template function like so.
template: function(item, element, data) {

    // create a class from the component that was passed in with the item
    let ComponentClass = Vue.extend(item.component);

    // create a new vue instance from that component and pass the item in as a prop
    let instance = new ComponentClass({
        propsData: { data: item },
        parent: vm
    });

    // mount it
    instance.$mount();

    return instance.$el;
}

item.component is a vue component that accepts a data prop.
I am able to create and mount the vue component this way, however when item changes I need to update the data prop on the component.

A: If you define an object outside of Vue and then use it in the data for a Vue instance, it will be made reactive. In the example below, I use dataObj that way. Although I follow the convention of using a data function, it returns a pre-defined object (and would work exactly the same way if I'd used data: dataObj).
After I mount the instance, I update dataObj.data, and you can see that the component updates to reflect the new value.

const ComponentClass = Vue.extend({
  template: '
Hi {{data}}
'
});

const dataObj = {
  data: 'something'
}

let instance = new ComponentClass({
  data() {
    return dataObj;
  }
});

// mount it
instance.$mount();
document.getElementById('target').appendChild(instance.$el);

setTimeout(() => {
  dataObj.data = 'another thing';
}, 1500);

A: In Vue 2.2+, you can use $props.
In fact, I have the exact same use case as yours, with a Vue project, vis-timeline, and items with manually mounted components.
In my case, assigning something to $props.data triggers watchers and the whole reactivity machine.
EDIT: And, as I should have noticed earlier, it is NOT what you should do. There is an error log in the console, telling that prop shouldn't be mutated directly like this. So, I'll try to find another solution.

A: This has changed in Vue 3, but it's still possible when using the new Application API.
You can achieve this by passing a reactive object to App.provide():

<template>

Count: {{ state.count }}

</template>

// script.js

import Counter from "./Counter.vue";

let counter;
let counterState;

function create() {
  counterState = reactive({ count: 0 });

  counter = createApp(Counter);
  counter.provide("state", counterState);
  counter.mount("#my-element");
}

function increment() {
  // This will cause the component to update
  counterState.count++;
}

A: Here's how I'm able to pass and update props programmatically:

const ComponentClass = Vue.extend({
  template: '
Hi {{data}}
',
  props: {
    data: String
  }
});

const propsObj = {
  data: 'something'
}

const instance = new ComponentClass()

const props = Vue.observable({
      ...instance._props,
      ...propsObj
})

instance._props = props

// mount it
instance.$mount();
document.getElementById('target').appendChild(instance.$el);

setTimeout(() => {
  props.data = 'another thing';  // or instance.data = ...
}, 1500);


text:
Q: How to wait an arbitrary amount of time in nightwatch.js without web browser interaction I'm migrating my tests from Intern.js to Nightwatch.js and I'm sure it's not the recommended way of writing tests, but my tests asynchronously make browser command calls (my tests use a class that has its own command queue). The Nightwatch command queue can be empty sometimes depending on what's executing, but will eventually be populated. I need a way to manually tell Nightwatch when it's done, and just wait until then, otherwise the browser will close too early.
I can do something like this:

finished() {
  let done = false;
  //will run at the end of my class's internal command queue
  this.command
    .then(() => {
      done = true;
    });

  //will cause nightwatch to wait until my command queue is done
  this.browser.perform(doneFn => {
    const check = () => {
      if (done) {
        return doneFn();
      }
      setTimeout(check, 10);
    }
    check();
  });
}

But in that case perform() will time out after waiting 10 seconds, and I don't seem to be able to configure that. I could otherwise run a sequence of ~9 second perform() calls but it just sounds too hacky. I could rewrite to depend on nightwatch command queue instead, but that'd also be a lot more work to rewrite everything.

A: In the end it was easier to just switch to depending on using nightwatch's command queue instead. Anything that was just a .then() with Intern.js got changed to a .perform() in its various forms.


text:
Q: Opencart 1.5.6 -> Opencart 2.1 Импортировал дамп базы данных таблиц (oc_category,oc_category_description,oc_category_path,oc_category_to_store) версии 1.5.6 в версию 2.1.0.2.1.
Импорт прошел успешно, но теперь вот незадача.
В администраторской панели, категории не отображаются. Подскажите пожалуйста, почему не отображаются категории в админке? Как устранить эту проблему?

A: Проверьте таблицу oc_category_to_store . Скорее всего у Вас не совпадает store_id для текущего магазина и импортированных категорий. Нужный id можете в oc_setting посмотреть. Если я прав, то надо будет просто обновить ID магазина для категорий.


text:
Q: What are the possible exceptions in connectionLost when using webclient.Agent? I've written an http downloader using webclient.Agent.
The connectionLost function of a body consumer object is called with a reason parameter.
def connectionLost(self, reason):
    if isinstance(reason.value, ResponseDone):
        self.df.callback(None)
    else:
        self.df.errback(reason.value)

I would really want to know what are the possible exception classes in 'reason'
because I need to catch them all and deal with them later in the calling
function which uses inlineCallbacks.
So far I identified:
ConnectError, BindError, ConnectionClosed, ResponseFailed
Is this documented somewhere?
Most of the documentation contains just vague
"...errback with a description of the error..." statements.

A: You don't need to catch them all specifically.  Exception handling respects inheritance: if you try to catch a base class and a subclass is raised, you'll catch that too.  Exception is the base class for just about all exceptions in Python, so if you catch that, you'll catch just about everything.
try:
    yield agent.request(...)
except Exception as e:
    print 'Oh no, some failure'
else:
    print 'Success'

There is no complete list of all the exceptions that Agent.request may fail with, because it is impossible to know this list in advance.  Failures may be due to connection setup - but is it a plain TCP connection or an SSL connection for an HTTPS URL?  Perhaps it's a connection over a SOCKS proxy due to an unfortunate user's network configuration.  These may all fail in different ways.  The same applies to the actual HTTP request itself - who knows how the server will behave?  Perhaps it will respond with an unexpected error code, or perhaps it will respond with something Agent isn't even capable of parsing and trigger an exception from the low-level HTTP client protocol implementation.  The parser is hand crafted, so there's probably a lot of different exceptions that could come from that kind of problem.  And then there's the variation on content and transfer encoding, which may invoke lots of different functionality (eg, a gzip decoder) which adds still more possible exceptions.
So, instead of trying to come up with the full list of all of these exceptions at every place you use Agent.request, only specifically handle the exception types you know about and have special code for and then handle everything else with an except Exception.


text:
Q: iOS 5 XCODE 4.3.2 Storyboard. How do I insert a new view before an existing table view? To start, I'm really new to iOS and Xcode. I've worked through several demos and read quite a bit on the dev site.
My current app started as a navigation controller > Table view controller (master view) > Detail view.  It's a basic menu in table view that can drill down to an items detail showing picture, price, description etc. I followed (mostly) the tutorial from the iOS dev library "your second iOS app" https://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/SecondiOSAppTutorial/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011318-CH1-SW1
in addition I did make some implementation changes as far as layout and properties, but in the end it functions perfectly.
Now, after the fact, I've decided I don't like the app's entry point to be the table view. Rather I would prefer to enter to a view controller with some other buttons, one of which will take you to the menu.
My problem is as follows;
 I delete the relationship "root view controller" between the navigation controller and the table view, and then I reconnect it from navigation controller to my new view. I think link a button with a push segue to the old table view.
Now the app still builds fine, however it crashes upon running with the following error
 "-[UIViewController setDataController:]: unrecognized selector sent to instance 0x6a6ed60
2012-05-09 16:51:28.618 [16513:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setDataController:]: unrecognized selector sent to instance 0x6a6ed60'
* First throw call stack: "
It appears that the setter is getting some bad data. so I'm going to guess it's somehow a problem with the old rootview not being valid, I really don't know enough to fix this. Please help.
sorry no rep to post a picture, if you need one let me know and I'll host it somewhere.

A: The error is telling you that the UIViewController that is your initial screen doesn't know what setDataController means. You can resolve this by subclassing UIViewController (call it FirstViewController or something) and then setting the class of your initial view controller to that subclass in storyboard. Then, in the header, give your FirstViewController a property @property (nonatomic, strong) DataController *dataController. There's probably more steps to getting it all up and running but the main thing is that you should be working with a subclass of UIViewController, not an instance of the class itself.

A: Go back to the last version in where your Table view was the root. And simply drag a new viecontroller on the story board anywhere. then you will see an arrow pointing to the table view, drag that arrow to the new viewcontroller.


text:
Q: module 'tensorflow.contrib.learn' has no attribute 'python' import tensorflow.contrib.learn.python.learn as learn

home/michael/miniconda3/lib/python3.6/importlib/_bootstrap.py:219:
RuntimeWarning: compiletime version 3.5 of module
'tensorflow.python.framework.fast_tensor_util' does not match runtime
version 3.6
return f(*args, **kwds)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-630a74eb6a34> in <module>()
----> 1 import tensorflow.contrib.learn.python.learn as learn

AttributeError: module 'tensorflow.contrib.learn' has no attribute 'python'

I am trying to import this library in jupyter in linux environment, and I could not find any answer on google.

A: Actually, the module tensorflow.contrib.learn reimports everything from tensorflow.contrib.learn.python.learn:
 91 # pylint: disable=wildcard-import
 92 from tensorflow.contrib.learn.python.learn import *
 93 # pylint: enable=wildcard-import
 94
 95 from tensorflow.contrib.learn.python.learn import learn_runner_lib as learn_runner

So you can just import it directly:
import tensorflow.contrib.learn as learn

or
from tensorflow.contrib import learn


text:
Q: Windows 8 Store app (Xaml) save settings I create setting page with this link. There are one TextBox. Value not saved in app. How save value on close settings?
    <StackPanel Style="{StaticResource SettingsFlyoutSectionStyle}">
        <TextBlock x:Uid="SiteUrl" Text="SiteUrl" Width="250"></TextBlock>
        <TextBox x:Name="SiteUrl" Width="250"></TextBox>
    </StackPanel>

A: Use Application.LocalSettings (or RoamingSettings):
// Save
ApplicationData.Current.LocalSettings.Values["SiteUrl"] = SiteUrl.Text;

// Load
SiteUrl.Text = (string)ApplicationData.Current.LocalSettings.Values["SiteUrl"];


text:
Q: How to pass all selected options to next selection on dynamic dropdown? I am trying to create a dropdown list that dynamically populates from my database. There are 9 dropdown lists, and the 10th should automatically print the product number based on the above selections.
The code currently functions, but only partially. It will only use the data from the immediate previous selection to populate the next list; instead of referencing all previous selections. All the data is on a single table in the database.
This is causing options to display further down in the lists that should no longer be available given previous selections, and the product number in the 10th position is spitting out a huge amount of product numbers because it is only referencing the selection just above it.
I need each option select to be referenced by every select after it.
I've tried adding '".$_POST['']."' to my select statement, to my where clause to try to reference the previous selections, but it either returns nothing or results in an internal server error.
I'm not sure if this is the right track, or what is missing from my code to make this work.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Product Builder Tool</title>

Product Builder Tool

Product Type:
<select distinct name="product_type" class="product_type">
<option selected="selected">--Select Product Type--</option>
<?php
 $stmt = $DB_con->prepare("SELECT DISTINCT product_type FROM surge_unit");
 $stmt->execute();
 while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
        <option value="<?php echo $row['product_type']; ?>"><?php echo $row['product_type']; ?></option>
        <?php
 }
?>
</select>

Voltage and Phase: <select name="voltage" class="voltage">
<option selected="selected">--Select Voltage and Phase--</option>
</select>

Capacity: <select name="capacity" class="capacity">
<option selected="selected">--Select Capacity--</option>
</select>
</select>

Modes: <select name="modes" class="modes">
<option selected="selected">--Select Modes Protected--</option>
</select>
</select>

Connection Type: <select name="connection" class="connection">
<option selected="selected">--Select Connection Type--</option>
</select>
</select>

Status Indication: <select name="status" class="status">
<option selected="selected">--Select Status Indication--</option>
</select>
</select>

Enclosure: <select name="enclosure" class="enclosure">
<option selected="selected">--Select Enclosure--</option>
</select>
</select>

UL 1449 Location Type: <select name="ul_type" class="ul_type">
<option selected="selected">--Select UL 1449 Type--</option>
</select>
</select>

Options: <select name="options" class="options">
<option selected="selected">--Select Options--</option>
</select>

Product Number:
<echo selected="selected" name="product_number" class="product_number">Product Number</echo>

And this is the get file for AJAX.

<?php
include('dbconfig.php');
if($_POST['product_type'])
{
 $voltage=$_POST['product_type'];

 $stmt = $DB_con->prepare("SELECT DISTINCT voltage FROM surge_unit WHERE product_type=:product_type");
 $stmt->execute(array('product_type' => $voltage));
 ?><option selected="selected">Select Voltage & Phase</option><?php
 while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
         <option value="<?php echo $row['voltage']; ?>"><?php echo $row['voltage']; ?></option>
        <?php
 }
}

if($_POST['voltage'])
{
 $capacity=$_POST['voltage'];
 $stmt = $DB_con->prepare("SELECT DISTINCT capacity
FROM surge_unit WHERE voltage =:voltage" );
 $stmt->execute(array('voltage' => $capacity));
 ?><option selected="selected">Select Capacity</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['capacity']; ?>"><?php echo $row['capacity']; ?></option>
  <?php
 }
}

if($_POST['capacity'])
{
 $modes=$_POST['capacity'];

 $stmt = $DB_con->prepare("SELECT DISTINCT modes FROM surge_unit WHERE capacity=:capacity");
 $stmt->execute(array(':capacity' => $modes));
 ?><option selected="selected">Select Modes Protected</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['modes']; ?>"><?php echo $row['modes']; ?></option>
  <?php
 }
}
if($_POST['modes'])
{
 $connection=$_POST['modes'];

 $stmt = $DB_con->prepare("SELECT DISTINCT connection FROM surge_unit WHERE modes=:modes");
 $stmt->execute(array(':modes' => $connection));
 ?><option selected="selected">Select Connection Type</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['connection']; ?>"><?php echo $row['connection']; ?></option>
  <?php
 }
}
if($_POST['connection'])
{
 $status=$_POST['connection'];

 $stmt = $DB_con->prepare("SELECT DISTINCT status FROM surge_unit WHERE connection=:connection");
 $stmt->execute(array(':connection' => $status));
 ?><option selected="selected">Select Status Indication</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['status']; ?>"><?php echo $row['status']; ?></option>
  <?php
 }
}
if($_POST['status'])
{
 $enclosure=$_POST['status'];

 $stmt = $DB_con->prepare("SELECT DISTINCT enclosure FROM surge_unit WHERE status=:status");
 $stmt->execute(array(':status' => $enclosure));
 ?><option selected="selected">Select Enclosure</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['enclosure']; ?>"><?php echo $row['enclosure']; ?></option>
  <?php
 }
}
if($_POST['enclosure'])
{
 $ul_type=$_POST['enclosure'];

 $stmt = $DB_con->prepare("SELECT DISTINCT ul_type FROM surge_unit WHERE enclosure=:enclosure");
 $stmt->execute(array(':enclosure' => $ul_type));
 ?><option selected="selected">Select UL 1449 Type</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['ul_type']; ?>"><?php echo $row['ul_type']; ?></option>
  <?php
 }
}
if($_POST['ul_type'])
{
 $options=$_POST['ul_type'];

 $stmt = $DB_con->prepare("SELECT DISTINCT options FROM surge_unit WHERE ul_type=:ul_type");
 $stmt->execute(array(':ul_type' => $options));
 ?><option selected="selected">Select Options</option>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['options']; ?>"><?php echo $row['options']; ?></option>
  <?php
 }
}
if($_POST['options'])
{
 $product_number=$_POST['options'];

 $stmt = $DB_con->prepare("SELECT DISTINCT product_number FROM surge_unit WHERE options=:options");
 $stmt->execute(array(':options' => $product_number));
 ?>
 <?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <?php echo $row['product_number']; ?><?php $row['SELECT product_number FROM surge_unit WHERE options=id9']; ?>
  <?php
 }
}
?>

What am I missing to make this work properly?
I'm pretty sure my select statements need to have a bunch of AND clauses in the WHERE clause, but I can't get it to function at all when I try. Is Ajax not sending the proper information in order for it to pick up earlier selections?


text:
Q: Overlaying an image with another non-rectangular image containing black pixels using OpenCV in Python I want to programmatically overlay an image, e.g. the blissfully familiar Windows XP wallpaper:

with another non-rectangular image that contains black pixels, e.g. a standard large cursor icon:

Copy-pastoring the codes from this and this tutorial which both use OpenCV bitwise masking magic I arrived at:
import cv2 as cv

# Load two images
img1 = cv.imread('bliss.png') # The image I want the overlay to be diplayed on.
img2 = cv.imread('cursor.png') # The image I want to overlay with, containing black pixels.

# I want to put logo on top-left corner, So I create a ROI.
rows, cols, channels = img2.shape
roi = img1[0:rows, 0:cols ]

# Now create a mask of logo and create its inverse mask also.
img2gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 20, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)

# Now black-out the area of logo in ROI.
img1_bg = cv.bitwise_and(roi, roi, mask = mask_inv)

# Take only region of logo from logo image.
img2_fg = cv.bitwise_and(img2, img2, mask = mask)

# Put logo in ROI and modify the main image
dst = cv.add(img1_bg, img2_fg)
img1[0:rows, 0:cols ] = dst
cv.imshow('res',img1)
cv.waitKey(0)
cv.destroyAllWindows()

During naive permutations of trying to find the right parameters for cv.threshold (including thres and maxval arguments as well as thresholding types), I always find that significant number of black pixels present in the original image are missing from the overlaid one. In the zoomed-in picture below on the left you can see the overlaid cursor and on the right is original copied one:

I reckon this loss of pixels is due to the grayscale conversion and/or the inverse (?) masking but could not figure out how or what to change in the code above. In the tutorials I linked above images not containing black pixels were used for the overlay and the results look fine. Is there a way to do the same with images containing black pixels?

A: The problem here is, that you lose the black pixels in cursor.png at cv.threshold(img2gray, 20, 255, cv.THRESH_BINARY). The remainder are the white pixels only, thus your mask is just too small. Since cursor.png has transparency information stored in it, you can use its alpha channel for your mask.
Here's your code, modified accordingly (I removed all of your comments; comments show my changes):
import cv2 as cv

img1 = cv.imread('bliss.png')
img2 = cv.imread('cursor.png', cv.IMREAD_UNCHANGED)         # Added cv.IMREAD_UNCHANGED parameter to maintain alpha channel information

alpha = img2[:, :, 3]                                       # Save alpha channel for later use
_, alpha = cv.threshold(alpha, 5, 255, cv.THRESH_BINARY)    # Threshold alpha channel to prevent gradual transparency
img2 = cv.cvtColor(img2, cv.COLOR_BGRA2BGR)                 # Remove alpha channel information, so that code below still works

rows, cols, channels = img2.shape
roi = img1[0:rows, 0:cols ]

                                                            # img2gray no longer needed
mask = alpha                                                # Mask is just the alpha channel saved above
mask_inv = cv.bitwise_not(mask)

img1_bg = cv.bitwise_and(roi, roi, mask = mask_inv)

img2_fg = cv.bitwise_and(img2, img2, mask = mask)

dst = cv.add(img1_bg, img2_fg)
img1[0:rows, 0:cols ] = dst
cv.imshow('res',img1)
cv.waitKey(0)
cv.destroyAllWindows()

Hopefully, the output image then looks like something you expected:


text:
Q: Ruby on Rails - How to do custom query? I have 2 tables with millions of records:
First table is Subscription and second table is Message.
In Subscription table, I have 3 indexes:

*

*subscription_id

*msisdn

*reporting_id
However, in Message table, I only have 2 indexes:

*

*message_id

*reporting_id
I have msisdn in Message table but it is not indexed.
So, I have a dashboard UI that let me search for Message.
I want to search Message using msisdn but since msisdn is not indexed, the query is taking forever!
but I want to put the idea of "Indexing msisdn in Message table" as plan B.
So my Plan A is(which is where I need help for):
Since both table has indexed reporting_id, I want to search for Message using subscription.msisdn in the dashboard, and then from there, I want to use the subscription.reporting_id and list all the Message with that subscription.reporting_id.
Something like subscription.reporting_id = message.reporting_id.
I have the view, controller and model for these 2 tables,
I tried doing this in both models
has_many :message, foreign_key: :reporting_id in Subscription.rb
and
belongs_to :subscription in Message.rb
but it didn't work.
In my view, the search_field for MSISDN is currently search for record from subscription.msisdn
Does anyone knows how can I achieve that?
PS: I want to prevent from editing the table structure.

A: If you want to establish a has_many :messages association in the Subscription class, you'll need to specify the primary_key.
class Subscription < ApplicationRecord
  has_many :messages, foreign_key: "reporting_id", primary_key: "reporting_id"
end

With this, the SQL generated will look like this:
SELECT "messages".* FROM "messages" WHERE "messages"."reporting_id" = $1  [["reporting_id", "#{reporting_id}"]]

The primary_key ensures the reporting_id value of the Subscription model is used, else it will default to the id column.
However, rather than establishing this association which doesn't seem exactly normalized(atleast 3NF), you can just have a query to find all messages using the msisdn and reporting_id. Something like this should still be effective:
Message.
 joins("INNER JOIN subscriptions ON subscriptions.reporting_id = messages.reporting_id").
 merge(Subscription.where(msisdn: "#{value}"))

A: have to add primary key as well
has_many :message, foreign_key: :reporting_id, primary_key: :reporting_id in Subscription.rb

A: Found the solution!
In my Message.rb, I did:
belongs_to :subscription, foreign_key: :reporting_id, primary_key: :reporting_id

and it generated this query
SELECT  `subscription`.* FROM `subscription` WHERE `subscription`.`reporting_id` = '1eaa7a61fe635005c81df347b1a7c401' LIMIT 1


text:
Q: Loop a sound file from a certain point? Suppose I have a sound file that I wish to play in this manner:

*

*Start from the 0:00 mark.

*When the sound file ends, replay from the 0:30.00 mark.

Essentially, I wish for the song to play from 0:00 to 0:30, then loop from 0:30 to the end.
How do you do this?
Usually, when playing Audio Files, I use AudioClip.
AudioClip audio = Applet.newAudioClip( this.getClass().getResource( "..." ) );
audio.loop();

It's because of bad experiences with loading the audio file when the project is packed into a .jar file. If the method you recommend uses another class, I would still be more than happy to listen. However, if you've encountered the same problem as I have and know how to fix it, please do tell me.

A: You might use a Clip for this, or if the clip is too large, feed the bytes directly to a SourceDataLine.


text:
Q: Pretty Permalinks not working - WordPress with Tomcat Thanks to someone's odd requirements, I've managed to serve WordPress with Tomcat 9. Everything works fine with the help of PHP/Java Bridge.
However, I'm unable to follow any links from home page when pretty permalinks enabled in WordPress (when clicked on links it shows "No input file specified", plain URLs work fine though). I think the problem is to rewrite the URL.
Following Tomcat documentation for rewriting URLs, I created context.xml and rewrite.config in the WEB-INF directory of my webapp, but still no luck. Here are the files:
ROOT/WEB-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
</Context>

ROOT/WEB-INF/rewrite.config
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Any help is much appreciated.

A: I ended up using Tuckey UrlRewriteFilter and removed ROOT/WEB-INF/context.xml and ROOT/WEB-INF/rewrite.config. Now the Tomcat is serving WordPress perfectly and everything is working fine.
Here are the steps to setup UrlRewriteFilter (taken from official website) for WordPress on Tomcat, which maybe useful to somebody:
Download UrlRewriteFilter.jar into      ROOT/WEB-INF/lib/ and follow all the instructions/steps on its       official website.
If you want to use .htaccess syntax to define rewrite rules, then you    can set a param modRewriteConf to true in ROOT/WEB-INF/web.xml as    below:
<!-- URLRewriteFilter -->
<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
        <param-name>modRewriteConf</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

Then create a .htaccess file in ROOT/WEB-INF/ directory (can be    placed elsewhere but then you've to specify path via a param in    web.xml).
Note: I had to comment out a RewriteRule in order to make it work successfully.
RewriteEngine On
RewriteBase /
# RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


text:
Q: Connecting Desktop to SQL Server 2012 SP1 via ArcGIS Server 10.1 very slow? We have just built and new ArcGIS/ArcSDE system with SQL Server 2012 SP1.  We are experiencing very long periods (up to 2 minutes) just to connect to the database in Desktop.  Desktop does connect and we can publish map services, but everything is painfully slow.  We have ruled out network issues, and wonder if we are missing something.  Has anyone experienced this?

A: Esri just released a patch addressing this exact problem. Identified as bug NIM082657 - When working with a SQL Server 2012 geodatabase and Geometry or Geography type data, ArcMap drawing performance is slower than it was using SQL Server 2008. This affects all rendering and editing operations.
Downloads and instructions here --
http://support.esri.com/en/downloads/patches-servicepacks/view/productid/160/metaid/1954

A: we had the same problem...and while not ideal the solution for us was to use SDE Binary storage type...super fast after that!


text:
Q: Wrapper for a method that accepts (EventArgs) I'm trying to implement EventArgs to pass a list of parameters to my messaging system: Question.
I subclassed EventArgs:
public class SingleParameterArgs<T> : EventArgs
{
    public T arg1;

    public SingleParameterArgs(T _arg1)
    {
        arg1 = _arg1;
    }
}

Here's the class and method that should accept the EventArgs:
static public class Messenger<TEventArgs> where TEventArgs : EventArgs {
    private static Dictionary< string, EventHandler<TEventArgs> > eventTable = new Dictionary< string, EventHandler<TEventArgs> >();

    static public void Invoke(string eventType, TEventArgs args) {
        EventHandler<TEventArgs> eventHandler;

        if (eventTable.TryGetValue(eventType, out eventHandler)) {
            if (eventHandler != null)
                eventHandler();
        }
    }

}

Before implementing EventArgs I would invoke a message in the following way:
Messenger<GameEndingType>.Invoke( "end game", GameEndingType.TimeEnded );

But now it looks much longer and much more complicated:
Messenger< SingleParameterArgs<GameEndingType> >.Invoke( "end game", new SingleParameterArgs<GameEndingType>(GameEndingType.TimeEnded) );

Is it possible to make it look shorter? I don't want to type such a long line every time I need to send a message. Maybe I could create a wrapper?
Something like this would be perfect:
    Messenger.Invoke("end game", GameEndingType.TimeEnded);
What is the best way to create a uniform wrapper for a random amount of parameters?

A: Are you happy for your Messenger class to be tied to SingleParameterArgs<T>? If so, you could use:
// Here TEventArgs represents the element type *within* SingleParameterArgs
public static class Messenger<TEventArgs> {
    private static
        Dictionary<string, EventHandler<SingleParameterArgs<TEventArgs>> eventTable =
            new Dictionary<string, EventHandler<SingleParameterArgs<TEventArgs>>();

    public static void Invoke(string eventType, TEventArgs args) {
        EventHandler<SingleParameterArgs<TEventArgs>> eventHandler;

        if (eventTable.TryGetValue(eventType, out eventHandler)) {
            if (eventHandler != null) {
                eventHandler();
            }
        }
    }
}

Of course you can have both, with a totally general Messenger class (as per your question), and then a SingleParameterMessenger class which delegates to it:
public static class SingleParameterMessenger<TEventArgs> {
    public static void Invoke(string eventType, TEventArgs args) {
        Messenger<SingleParameterArgs<TEventArgs>>.Invoke(eventType, args);
    }
}

Just as an aside, I'm not really sure this is all a good idea anyway - particularly in terms of static registration, which tends to make testing harder, and certainly needs more care in terms of concurrency. (Your code is currently not threadsafe.)


text:
Q: ASP.NET MVC Optimization: Bundling without minifying? Is it possible to bundle a set of scripts without minifying them? I just want to combine several third-party script files where I never need the non-minified versions. Some of these have warned against further minification.

A: Just use the Bundle class and don't specify any transforms.  The ScriptBundle/StyleBundles are automatically registering transforms that do minification.


text: Q: Connecting to server over WIFI reliably during bootup There is quite a bit of varience in how long it takes for WiFI connectivity to be established.  I would like some input on what is the best way to get connectivity established.  In particular I am considering how to make multiple attempts to connect to a server where one does not know ahead of time how long it will take for wifi to get established. For example is it better to make three tries spaced apart by 10 seconds. or to make on long continuous try for 30 seconds?  I am trying to make this connectivity as robust as possible. Getting connected to server over wifi in a reliable best effort manner is my goal, and I would welcome any suggestions on how to make this more reliable.  One environment I have is Sprint 3G and Sprint 4G/ Wireless Sierra.  Another is AT&T both 3G and 4G.  Thanks AM I the only one who deals with this? Really?


text:
Q: Insert into ElasticSearch using Hive/Qubole I am trying to insert data into elastic search from a hive table.
    CREATE EXTERNAL TABLE IF NOT EXISTS es_temp_table (
        dt    STRING,
        text  STRING
    )
    STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
    TBLPROPERTIES('es.resource'='aggr_2014-10-01/metric','es.index.auto.create'='true')
    ;

    INSERT OVERWRITE TABLE es_temp_table
    SELECT dt, description
    FROM other_table

However, the data is off. When I do a count(*) on my other table I am getting 6,000 rows. When I search the aggr_2014-10-01 index, I see 10,000 records! Somehow, the records are being duplicated (rows are being copied over multiple times). Maybe I can remove duplicate records inside of elastic search? Not sure how I would do that though.
I believe it might be a result of Hive/Qubole spawning two tasks for every mapping. If one mapper succeeds, it tries to kill the other. However, the other task already did damage (aka inserted into ElasticSearch). This is my best guess, but I would prefer to know the exact reason and if there is a way for me to fix it.
set mapred.map.tasks.speculative.execution=false;

One thing I found was to set speculative execution to false, so that only one task is spawned per mapper (see above setting). However, now I am seeing undercounting. I believe this may be due to records being skipped, but I am unable to diagnose why those records would be skipped in the first place.
In this version, it also means that if even one task/mapper fails, the entire job fails, and then I need to delete the index (partial data was uploaded) and rerun the entire job (which takes ~4hours).
[PROGRESS UPDATE]
I attempted to solve this by putting all of the work in the reducer (it's the only way to only spawn one task to ensure no duplicate record insertions).
INSERT OVERWRITE TABLE es_temp_table
SELECT dt, description
FROM other_table
DISTRIBUTE BY cast(rand()*250 as int);

However, I now see a huge underestimate! 2,000 records only now. Elastic search does estimate some things, but not to this extent. There are simply less records in ElasticSearch. This may be due to failed tasks (that are no longer retrying). It may be from when Qubole/Hive passes over malformed entries. But I set:
set mapreduce.map.skip.maxrecords=1000;

Here are some other settings for my query:
set es.nodes=node-names
set es.port=9200;
set es.bulk.size.bytes=1000mb;
set es.http.timeout=20m;
set mapred.tasktracker.expiry.interval=3600000;
set mapred.task.timeout=3600000;

A: I determined the problem. As I suspected, insertion was skipping over some records that were considered "bad." I was never able to find what records exactly were being skipped, but I tried replacing all non-alphanumeric characters with a space. This solved the problem! The records are no longer being skipped, and all data is uploaded to Elastic Search.
INSERT OVERWRITE TABLE es_temp_table
SELECT dt, REGEXP_REPLACE(description, '[^0-9a-zA-Z]+', ' ')
FROM other_table


text:
Q: Is it possible to use brunch with ampersand? I am trying to use ampersand with brunch instead of browserify but it causes some problems.
Here is the code :
"use strict";

var View = require("ampersand-view");

var HelloView = View.extend({
    autoRender: true,
    template: '
Hello
'
});

var app = new HelloView();

document.body.appendChild(app.el);

brunch-config file has :
npm:
    enabled: true

The brunch build command is OK but when I run the page in the browser I get :
View.extend is not a function

A console.log for the View object gives me a "function baseCopy()" object.
Is it not possible at all to use ampersand with brunch (without a browserify plugin) ?


text:
Q: emulate group_concat in MSSQL, ambiguous column name? I am currently trying to simulate the group_concat function in MySQL to MSSQL. I have followed code formats found in here and here. The problem is, when I try to execute the query, I get the message Ambiguous column name for my column RoleID. Here is my query:
select UserName, RoleID from tb_UserInRoles
cross apply(
    select RoleName from tb_Roles
    where tb_UserInRoles.RoleID = tb_Roles.RoleID
    for XML Path('')
) fxMerge (RoleID) group by UserName, RoleID

I'd like to know why this particular code format present the Ambiguous column name error message. I need to make this query work and understand it. Thanks in advance for the help.
I plan on using this in a many-to-many relationship table, wherein users of a system can have multiple roles, like this:
|  User  |   Role  |
|--------|---------|
| JamesP |  Maker  |
| JamesP | Approver|
| JamesP |  Admin  |

I want the result query to be like this:
|  User  |           Role           |
|--------|--------------------------|
| JamesP |  Maker, Approver, Admin  |

A: Try this:
SELECT UIR.UserName, MAX(STUFF(fxMerge.RoleID, 1, 1, ''))
FROM tb_UserInRoles UIR
CROSS APPLY(
    SELECT ',' + RoleName
    FROM tb_UserInRoles UIR1
    INNER JOIN tb_Roles RM ON UIR1.RoleID = RM.RoleID
    WHERE UIR.UserName = UIR1.UserName
    FOR XML PATH('')
) fxMerge (RoleID)
GROUP BY UIR.UserName


text:
Q: window.location not setting to new value correctly I am currently having issues with a bit of javascript I am running on a website. I am trying to redirect to a new page however instead of setting the redirect url to the page I pass in it seems to concatenate it to the end of the existing url.
For example if I am current on www.stackoverflow.com/questions and want to go to www.stackoverflow.com/questions/ask the url becomes www.stackoverflow.com/questions/www.stackoverflow.com/questions/ask
When I output the variable containing the URL to console it appears correctly
var nextPage = window.location.hostname + data.redirectUrl + "?confirmationtype=success";
console.log(nextPage);
window.location.href = nextPage;

the above output would be www.stackoverflow.com.au/questions/ask but would redirect to www.stackoverflow.com/questions/www.stackoverflow.com/questions/ask
I have done some searching and in many cases it seems to be related to onpost methods on the form, but I cant see how this would be an issue on my page and I am using a polling timer method to trigger these calls so page posts should not be a factor. Also if I try onpost="return false" other pages that use the same layout fail to post :S
Any help would be appreciated.

A: Url without protocol ("http:") becomes relative Url - so when you try to set window.location it will not perform navigation.
Something similar to:
var nextPage = window.location.hostname + data.redirectUrl + "?confirmationtype=success";
console.log(nextPage);
window.location = "http://" + nextPage;

You can use window.location.protocol instead "http://", you can use window.location or windows.location.href in code above.
Note that your sample shows some strange window.location.href(nextPage); which is function call, but href is not a function.


text:
Q: How do I hide properties of a model/object dynamically when retrieving it using Laravel My question is more theoretical, and I would like to know how do you handle this thing hiding property of an object dynamically. I know you can use
`protected $hidden`

as an array to hide the specific attributes, but this will not work for the case that based on different context of user show different attributes of the model.
An imaginary scenario would be: Let say we have three different users on platform, super admin, admin, normal users and each of the users can see all other users but let say super admin can see all attributes of user, admin, can see all not only password, and normal user can see only specific attributes.

A: To set the hidden attribute of a model dynamically you can use the setHidden() method on the eloquent model after querying for it from the database. This way you'll prevent it from outputting those fields by accident via lazy/eager loading.

A: Thinking difference, in other framework like Moodle, they define some arrays to handle the attributes that group of users could see.
Let see a small example I write bellow, you could apply if possible:
$attrSuperAdmin   = ['username', 'password', 'a1', 'a2', 'a3'];
$attrAdmin        = ['username', 'password', 'a1', 'a2'];
$attrNormal   = ['username', 'a1'];

if(isSuperAdmin($currentUser)){
    $userInfo = User::select($attrSuperAdmin)->get();
} else if(isSuperAdmin($currentUser)){
    $userInfo = User::select($attrAdmin)->get();
} else {
    $userInfo = User::select($attrNormal)->get();
}

It is pseudo code
You will not have to hiding anythings. Just select what you want. It is a safe way.


text:
Q: Simplifying a check for path's non-existence in a shell script Whenever I want to check if a path exists in a shell environment, be it interactive or a script, I use
[ -L "${PATH_TO_CHECK}" ] || ( [ ! -L "${PATH_TO_CHECK}" ] && [ -e "${PATH_TO_CHECK}" ]. A broken symbolic link is still an existing path to me. I'm trying to figure out how to check for the opposite, but I cannot figure anything simpler than ! ([ -L "${PATH_TO_CHECK}" ] || ( [ ! -L "${PATH_TO_CHECK}" ] && [ -e "${PATH_TO_CHECK}" ] ). Is that check not reducible?

A: boolean-logic answer:
!(a || (!a && b))
!a && !(!a && b)        # De Morgan's law
!a && (a || !b)         # De Morgan's law again
(!a && a) || (!a && !b) # Distributive law
!a && !b                # Complement law

(Bonus: apply De Morgan again to find that your original expression could be simplified to a || b)
shell answer:
Just check that it's not an existing file and also not a link:
[ ! -e "$path" ] && [ ! -L "$path" ]


text:
Q: Forced image reload after upload shows previously uploaded image I have the following markup:
The user can select a photo resource which will be uploaded to the server and displayed as a background image of a div container on top of the form.

<form id="photo_upload" enctype="multipart/form-data" action="/photo" method="post">

    <input type="file" id="select_photo" name="photo" />

</form>

I want the background image to be reloaded as soon as a new image has been uploaded. I add a timestamp to the image URL to force a reload.
$(document).ready(function() {

    function reloadBackground(tag) {
        // get background image source
        var source = tag.css('background-image').slice(4, -1);

        var index = source.lastIndexOf('?');

        if (index > -1) {
            // remove time stamp
            source = source.substring(0, index);
        }

        var image = new Image();

        image.onload = function() {
            // set new background image source
            tag.css('background-image', 'url(' + image.src + ')');
        }

        // add time stamp to force reload
        image.src = source + '?t=' + (new Date().getTime());
    }

    $('#select_photo').change(function() {
        $('#photo_upload').ajaxSubmit({
            error: function(response) {
                console.error(response.status);
            },

            success: function(response) {
                reloadBackground($('#self'));
            }
        });
    });

});

Here's the problem:
The first time I select and upload a new image, the background image does not change. After I select another photo, the background image changes to show the photo which was uploaded before, etc. However, if I reload the page manually, the correct (i.e. the last uploaded) image is displayed. It seems that reloadBackground() is called too early.
Do you have an idea what is going wrong?
Thank you!
EDIT:
For the sake of completeness, this is how the image is served by nodeJS:
app.get('/self.jpg', function (req, res, next) {
    res.sendFile(user.id + '.jpg', {
        root: uploadDir
    }, function (error) {
        if (error) {
            console.log(error);
            res.status(error.status).end();
        }
    });
});

A: function reloadBackground(tag) {
    // get background image source
    var source = tag.css('background-image').slice(4, -1);

    var index = source.lastIndexOf('?');

    if (index > -1) {
        // remove time stamp
        source = source.substring(0, index);
    }

    var image = new Image();

    image.onload = function() {
        // set new background image source
        tag.css('background-image', 'url(' + image.src + ')');
    }

    // add time stamp to force reload
    image.src = source + '?t=' + (new Date().getTime());
}

put this part out of the document ready function

A: Try to return only the file name from server and use an img tag to display it:

<form id="photo_upload" enctype="multipart/form-data" action="/photo" method="post">
    <input type="file" id="select_photo" name="photo"/>
</form>

and the js:
function reloadBackground(source) {
    var image = new Image();
    image.onload = function () {
        $('#self img').replaceWith(image);
    };

    image.src = source;
}

$('#select_photo').change(function() {
    $('#photo_upload').ajaxSubmit({
        error: function(response) {
            console.error(response.status);
        },

        success: function(response) {
            // Verify how to get image file name (Should be in the response)
            var source = response.data;
            reloadBackground(source);
        }
    });
});

});

A: D'oh. I found the problem:
After an image has been uploaded, I use the lwip library to scale the image and save it to its destination path. This can take up to two seconds but the success callback of ajaxSubmit() is, of course, called as soon as the image has been uploaded.
So I guess I can either keep a copy of the image in the upload folder under its original name or I find a way to tell the client to reload the image as soon as the image has been processed and written to its destination path.


text:
Q: Openquery statement in SQL Server I am fairly new to SQL, and I am hoping someone can help me with a problem I'm having.  I haven't been able to find any answers helping me figure out this exact problem.
I have two tables in two SQL Server databases on two different servers that I want to compare using the column ItemID. I want to find records from Table1 that have an ItemID that does not exist in Table2 and insert those into a table variable.  I have the following code:
--Create table variable to hold query results
DECLARE @ItemIDTable TABLE
  (
     [itemid][NVARCHAR](20) NULL
  );

--Query data and insert results into table variable
INSERT INTO @ItemIDTable
            ([itemid])
SELECT a.[itemid]
FROM   database1.dbo.table1 a
WHERE  NOT EXISTS (SELECT 1
                   FROM   [Database2].[dbo].[table2]
                   WHERE  a.itemid = [Database2].[dbo].[table2].[itemid])
ORDER  BY itemid

This works on a test server where the two databases are on the same server, but not in real life where they are on different servers.  I tried the following using OPENQUERY, but I know I haven't got it quite right.
--Create table variable to hold query results
DECLARE @ItemIDTable TABLE
    (
    [ItemID][nvarchar](20) NULL
    );

--Query data and insert results into table variable
INSERT INTO @ItemIDTable
    ([ItemID])
    SELECT a.[ItemID]
    FROM  Database1.dbo.Table1 a
    WHERE NOT EXISTS (SELECT 1
                      FROM OPENQUERY([Server2], SELECT * FROM [Database2].[dbo].[Table2]')
                      WHERE a.ItemID = [Database2].[dbo].[Table2].[ItemID])
    ORDER BY ItemID

I'm pretty sure I need to do something in the WHERE clause, where I have the two databases on two servers, I'm just not quite sure how to structure it.  Could anyone help?

A: Openquery works like this:
select *
from openquery
(LINKED_SERVER_NAME,
'select query goes here'
)

Note that the sql portion is single quoted.  That means you might have to quote the quotes if necessary.  For example:
select *
from openquery
(LINKED_SERVER_NAME,
'
select SomeTextField
from SomeTable
where SomeDateField = ''20141014''
'
)

A: You can't create an OPENQUERY that is correlated to an outer query.   You could populate a temp table with the results of an OPENQUERY and do your WHERE NOT EXISTS against the temp table, or you might want to look into Synonyms.


text:
Q: Docker error when pulling Java 8 image - "failed to register layer" I am trying to pull the latest official Java docker image (java:8), but I keep getting a failed to register layer error. The Java 7 and 9 docker images download successfully. I am running OS X El Capitan version 10.11.1.
> docker -v
Docker version 1.10.0, build 590d5108
> docker-machine -v
docker-machine version 0.6.0, build e27fb87
> docker pull java:8
8: Pulling from library/java
03e1855d4f31: Extracting [==================================================>] 51.36 MB/51.36 MB
a3ed95caeb02: Download complete
9269ba3950bb: Download complete
6ecee6444751: Download complete
5b865d39f77d: Download complete
e7e5c0273866: Download complete
6a4effbc4451: Download complete
4b6cb08bb4bc: Download complete
7b07ad270e2c: Download complete
failed to register layer: rename /mnt/sda1/var/lib/docker/image/aufs/layerdb/tmp/layer-273420626 /mnt/sda1/var/lib/docker/image/aufs/layerdb/sha256/78dbfa5b7cbc2bd94ccbdba52e71be39b359ed7eac43972891b136334f5ce181: directory not empty

Has anyone run across a similar error and successfully resolved it? Thanks

A: Sometimes docker messes up its workspace, probably that's the cause.
You can try these:

*

*stop all (java) containers, remove them, delete the java image (or all images),
then re-pull and run.

*if this doesn't help, then restart the docker engine too.

*if even this doesn't solve the problem, stop the docker engine, delete the docker working directory, then restart docker engine.

In my experience, this solves all similar issues like OP.


text:
Q: pandas Dataframe plot line : how to add directly label on lines? I put the following code :
ratio_result_selected_country.loc['3/17/20':].plot.line(figsize=(17,7), grid = True)

and the result is :

is it possible to add label  directly like this :

ax  = ratio_result_selected_country.loc['3/17/20':].plot(figsize=(17,7), grid = True)
for line , name in zip (ax.lines ,ratio_result_selected_country.columns ):
    y = line.get_ydata()[-1]
    ax.annotate(name,xy=(1,y),xytext=(6,0),color=line.get_color(),
               xycoords = ax.get_yaxis_transform(),textcoords ="offset points",
                size = 14, va="center"
               )

plt.show()


text:
Q: Wifi stops working "randomly" and only restarting the computer helps Often, but for no apparent reason, I cannot connect to the internet through the hotspot on my phone. The connection to the phone's network looks fine in the applet, but no pages will load and the phone now says no devices are connected. Disconnecting from the wi-fi connection only leads to error message "device not ready". rfkill shows no blocks. Power management is off. The phone itself connects to the internet just fine. Restarting the computer always fixes the problem, for a while.  Restarting Network Manager does not, nor does anything else I've come across on the forums. Updating the kernel did not help. Help would be appreciated!
Using Linux mint 20.3, Intel Wireless 3160
This is what iwconfig shows after disconnecting the hotspot that does not work:
iwconfig
lo        no wireless extensions.
eno1      no wireless extensions.
wlp2s0    IEEE 802.11  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated   Tx-Power=20 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:off
          lo        no wireless extensions.

Before I disconnect manually, the ESSID is shown by iwconfig, even if it does not work. But on the phone, the hotspot says it is not connected to any devices! One would think this could be a problem with the phone, but other presumably available hotspots also do not show in the applet.

A: Some thing or things in my network goes on and off for connections also.
Some devices are still working and others quit accessing sites. I have looked at status screens and settings and then would just restart IPFIRE, which is slow, then i started discovering some faster options below. This is for home use. I am running current 171. Do not know if this will help you or not. These are not approved by any body, but my self. So beware.
I have found squid (web proxy server) not running. So I restart it. I found a command that is easier than restarting the whole IPFIRE device. May not be the best way to fix things, but it is the fastest way I have found.
/etc/rc.d/init.d/squid status
/etc/rc.d/init.d/squid restart

That does not always fix the problems, squid is still running.  I also found another command. This one appears to restart the whole network, but leaves the rest of IPFIRE alone. This is much faster than restarting IPFIRE.
/etc/init.d/network restart

Some times I had what appeared to be DNS issuses, this command shows the SERVFAIL that was in the logs.
for f in $(ls /var/log/messages* | sort -rV | tail -12) ; do     fl=`ls -l $f`;     zg=`zgrep -ic "SERVFAIL" $f`;     printf "%s \t %s \n" "$fl" "$zg"; done

Bottom line, I have not made the problems stop or found/fixed all the problems. I have made it so it will recover faster, when something goes awry. I will keep investigating when I have time.


text:
Q: Adding only new list items to list I'm fairly new to JavaScript, so looking for the simplest solution possible (also, not looking for a jQuery solution).
I'm trying to add clicked list items to a new list, only if the clicked list item isn't already in the new list. I have managed to add the clicked list item to the new list, but I fail to create a functioning if statement that checks the new list for the current item.

window.onload = function () {
    var ul = document.getElementById('bulk');

    ul.addEventListener('click', function (e) {
        var target = e.target;
        while (target && target.parentNode !== ul) {
            target = target.parentNode;
            if(!target) { return; }
        }
        if (target.tagName === 'LI'){
            var node = document.createElement("LI");
            var textnode = document.createTextNode(target.id);
            var textarea = document.getElementById("test1");
            if (!textarea.querySelector(target.id)) {
                node.appendChild(textnode);
                document.getElementById("test1").appendChild(node);
            }
        }
    });
}
<!DOCTYPE html>

banana

apple

A: Since you're not supposed to have multiple elements with the same ID in a single document, I changed things so the unique ID of each element is in a dataset attribute data-id.
Beyond that, it's just a question of using querySelector() to figure out whether such a node already is in the destination list.

var ul = document.getElementById('bulk');
var destination = document.getElementById("test1");

ul.addEventListener('click', function(e) {
  var target = e.target;
  while (target && target.parentNode !== ul) {
    target = target.parentNode;
    if (!target) {
      return;
    }
  }
  if (target.tagName === 'LI') {
    var id = target.dataset.id;
    var node = document.createElement("LI");
    node.dataset.id = id;
    var textnode = document.createTextNode("element with id " + id);
    if (destination.querySelector("[data-id=" + id + "]")) {
      return;
    }
    node.appendChild(textnode);
    destination.appendChild(node);
  }
});

banana

apple


text:
Q: How to make Neon Line have thin and bold strokes on a single CAShapeLayer? I have an issue with drawing Line by CAShapeLayer + UIBezierPath in Swift iOS.
My expected results (Image 1):
A Neon line has thin stroke from the start (or end) to the end (or start) to bold increasing point by point.
=> https://i.stack.imgur.com/JgWA0.png
My result (Image 2 , 3):
I use many layers (1 layer has 1 path), and link all of them to a LINE (so lagging, the line not smoothy)
=> https://i.stack.imgur.com/pLFWc.png
I just set only one time for CAShapeLayer, lineWidth cannot change after that.
=> https://i.stack.imgur.com/mztgs.jpg
Hope you help me resolve this issue. Thank you!


text:
Q: Access: Complex sum with count and union I have to problem to sum two calculated values from different tables:
Tables:

*

*T_AACDB_Daily_Status (contains STATUS_ID, COMPLETION_DATE, DATE and APP_ID)

*T_AACDB_Service_Costs (contains SERVICE_COSTS_ID and COSTS)

*T_AACDB_Services (contains SERVICE_ID, DATE and QTY)

There is a Join on T_AACDB_Daily_Status.STATUS_ID = T_AACDB_Service_Costs.SERVICE_COSTS_ID = T_AACDB_Services.SERVICE_ID
Calculations needed:

*

*Count STATUS_ID from T_AACDB_Daily_Status As CountFromDailyStatus

*Multiply CountFromDailyStatus with Costs from T_AACDB_Service_Costs As SUM1

*Multiply Costs from T_AACDB_Service_Costs with T_AACDB_Services.QTY As SUM2
and finally sum SUM2+SUM2

Query:

*

*The first query part counts a specific staus whithin a certain time period

*The second query part multiplies costs with the associated service_id

This is my Query so far:
SELECT
      SUM(t1.[CountFromDailyStatus]* tC.[COSTS]) AS SUM1
FROM
    (
    T_AACDB_Service_Costs AS tC LEFT JOIN
          (
          SELECT
          T_AACDB_Daily_Status.[APP_ID],
          T_AACDB_Daily_Status.[COMPLETION_DATE],
          T_AACDB_Daily_Status.[STATUS_ID],
           COUNT(T_AACDB_Daily_Status.[STATUS_ID]) AS CountFromDailyStatus
          FROM T_AACDB_Daily_Status
          GROUP BY T_AACDB_Daily_Status.[APP_ID], T_AACDB_Daily_Status.[COMPLETION_DATE], T_AACDB_Daily_Status.[STATUS_ID]
          )  AS t1
          ON tC.[SERVICE_COSTS_ID]=t1.[STATUS_ID]
    )

LEFT JOIN T_AACDB_Services AS tS
ON tC.[SERVICE_COSTS_ID]=tS.[SERVICE_ID]

WHERE
    (NOT(t1.COMPLETION_DATE) Is Null)
    AND (t1.[COMPLETION_DATE]>=DATEVALUE([Startdatum]))
    AND (t1.[COMPLETION_DATE]<=DATEVALUE([Enddatum]))
    AND t1.[STATUS_ID]  = 'Code-Review'
    AND NOT EXISTS
        (
        SELECT *
        FROM T_AACDB_Daily_Status t2
        WHERE t1.[APP_ID] = t2.[APP_ID]
        AND (Not(t2.COMPLETION_DATE) Is Null)
        AND (t2.[COMPLETION_DATE]>=DATEVALUE([Startdatum]))
        AND (t2.[COMPLETION_DATE]<=DATEVALUE([Enddatum]))
        AND t2.[STATUS_ID] = 'Deployment'
        );

UNION
SELECT
SUM(tC.[COSTS]*tS.[QTY]) AS SUM2
FROM T_AACDB_Services AS tS INNER JOIN T_AACDB_Service_Costs AS tC ON tC.[SERVICE_COSTS_ID]=tS.[SERVICE_ID]
WHERE
          tS.[SERVICE_ID]="PSEUDO" AND (tS.[Date]>=DATEVALUE([Startdatum])) And (tS.[Date]<=DATEVALUE([Enddatum]));

A: I was able to solve it myself:
SELECT
SUM(Summe+gesamt2) AS gesamtTotal,
SUM(anzahlNeu+anzahlNeu2) AS anzahlTotal

FROM (
SELECT
    sum(t1.[AnzahlAusDailyStatus]* tC.[COSTS]) AS Summe,
    sum(tC.[COSTS]*tS.[QTY]) AS gesamt2,
    COUNT(t1.[STATUS_ID]) AS anzahlNeu,
    SUM( tS.[QTY]+0)  AS anzahlNeu2

    FROM ((
           T_AACDB_Service_Costs tC
             LEFT JOIN  (
                     SELECT
                     T_AACDB_Daily_Status.[APP_ID] ,
                     T_AACDB_Daily_Status.[STATUS_ID] ,
                     T_AACDB_Daily_Status.[COMPLETION_DATE] ,
                     COUNT(T_AACDB_Daily_Status.[STATUS_ID]) AS AnzahlAusDailyStatus
                     FROM T_AACDB_Daily_Status
                     GROUP BY
                     T_AACDB_Daily_Status.[APP_ID] ,
                     T_AACDB_Daily_Status.[STATUS_ID] ,
                      T_AACDB_Daily_Status.[COMPLETION_DATE]
                     )  AS t1
          ON tC.[SERVICE_COSTS_ID]=t1.[STATUS_ID]
    )
    LEFT JOIN T_AACDB_Services tS ON tC.[SERVICE_COSTS_ID]= tS.[SERVICE_ID])

    WHERE
    (NOT(t1.COMPLETION_DATE) Is Null)
    AND (t1.[COMPLETION_DATE]>=DATEVALUE([Startdatum]))
    AND (t1.[COMPLETION_DATE]<=DATEVALUE([Enddatum]))
    AND t1.[STATUS_ID]  = 'Code-Review'
    AND NOT EXISTS
        (
        SELECT *
        FROM T_AACDB_Daily_Status t2
        WHERE t1.[APP_ID] = t2.[APP_ID]
        AND (Not(t2.COMPLETION_DATE) Is Null)
        AND (t2.[COMPLETION_DATE]>=DATEVALUE([Startdatum]))
        AND (t2.[COMPLETION_DATE]<=DATEVALUE([Enddatum]))
        AND t2.[STATUS_ID] = 'Deployment'
        )
    OR (((tS.SERVICE_ID)="PSEUDO-CR") AND ((tS.Date)>=DateValue([Startdatum]) And (tS.Date)
    <=DateValue([Enddatum])))
)
;


text:
Q: php SOAP request gives internal server error with specific method im trying to build a soap request for the following wsdl method= "GetData"
note that not all the values are required, i've been struggling with this for a week, any help would be very appreciated
Host: xxxxxxxxxxxxxxxx
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "xxxxxxxxxxx"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetData xmlns="xxxxxx">
      <key>string</key>
      <transferDef>
        <Where />
        <OrderBy>
          <OrderByItems>
            <BinaryArithmetic xsi:nil="true" />
            <Categorization xsi:nil="true" />
            <Function xsi:nil="true" />
            <QueryField xsi:nil="true" />
            <QueryForm xsi:nil="true" />
          </OrderByItems>
        </OrderBy>
        <ProjectId>string</ProjectId>
        <DbType>Production or Test</DbType>
      </transferDef>
      <token>
        <Id>guid</Id>
        <LastResponseIdReturned>long</LastResponseIdReturned>
        <FirstResponseIdReturned>long</FirstResponseIdReturned>
        <NumberOfResponsesReturned>long</NumberOfResponsesReturned>
        <DatasetsReturned>long</DatasetsReturned>
        <LastDataSet>boolean</LastDataSet>
        <ProjectId>string</ProjectId>
        <ChangeTrackingVersion>long</ChangeTrackingVersion>
      </token>
    </GetData>
  </soap:Body>
</soap:Envelope>

A: Nowadays, the best way to consume SOAP WS in PHP is to use a WSDL to PHP such as the PackageGenerator project which will generate the classes to construct the request, then to send the request then to handle the response all that using PHP objects. The generated classes are sufficiently intuitive to construct the request. In addition, it uses composer as the autoloader.

A: kind of resolved the issue, the problem was with the <token></token> part.
Since it needs a value of type:guid <Id>guid</Id> that as mentioned in the wsdl and xml request, is a dataset created by a .Net library, and it's used to iterate over the samples, it's quite a complicated request, since it needs previous steps to be fulfilled, so i did the request, by omitting the <token> section


text:
Q: Meaning of "| =" operator? I have encountered code like
if (flagsDef)
flagsTainted |= flagsUsed;

please assist in knowing the meaning of the operator used.

A: a op= b is a = a op b, and | is the bitwise or operator (bitwise meaning it's applied for each binary digit).
Here is the truth table for or:
    0 1
    ___
 0| 0 1
 1| 1 1

A: The statement:
flagsTainted |= flagsUsed

is shorthand for:
flagsTainted = flagsTainted | flagsUsed

which uses the binary/bitwise OR operator |.
The code is manipulating a flag variable, which is keeping state information by setting bits in the variable flagsTainted.
For more information about bitwise manipulation, the wikipedia article is pretty good.

A: | is a bitwise OR.  This means that it compares the bits using an or operator.
For example:
101
001

If you | the two, you get 101. The | =  assigns the result back to the left hand side of the operation.

A: It can be read in English as "or equals".
It's similar to += except instead of adding the left value to the right, it instead performs a bitwise or of the two values and then assigns the result into the left variable as you would expect.
For more information on bitwise operations, see this link:
Wikipedia


text:
Q: Change process name when launched as batch file I'm working on a monitoring system called "Nagios" which monitors services for UNIX and WINDOWS servers. Problem is WINDOWS services that are launched by batch files are named in task manager as "cmd.exe", so system can't distinguish between these services when monitoring.
How can I change a process name on task manager when launching it so each one has a unique name rather than "cmd.exe"?
Thank you in advance.

A: You can run batch file as windows service to make a process name. You can set what to happen on start and on stop. You can kill the service using its PID.
C# Tutorial to create batch file as windows service.

A: You can't change the name of the process. If you need to distinguish between the processes then I would suggest you use their process ID rather than their name.

A: DOS has a wonderful command called title - would seem to fit
@echo off
title MyBatchTitle
...


text:
Q: Append Text Insert to ListBox or ComboBox1 I have a richTextBox1 with this line:
my test
my test2

and tried to use this code to insert the lines in to a listbox or combox:
richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString();
listBox1.Items.Add(richTextBox1.Text);

but the listbox displays

mytestmytest2

How do I insert (append) each item as a new line?

A: You should split the text coming from richTextBox1 based on line feeds. If you want multiple items in your listbox, you should call Items.Add for each item.
Example:
richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString();

foreach (string line in richTextBox.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
{
    listBox1.Items.Add(line);
}

A: richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString();
listBox1.Items.AddRange(richTextBox1.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None));

You dont need a loop in insert all the items. this can be done by using Items.AddRange

A: To add a string one after one, use File.ReadAllLines() method.
string []lines=System.IO.File.ReadAllLines("file.txt");

    foreach(string str in lines)
     {
      listBox1.Items.Add(str);
     }

Another way to draw text is to set DrawMode=OwnerDrawVariable and handle the DrawItem event to draw the text.


text:
Q: Using NSURLSession with special characters being returned So I have this data being returned as nil with NSURLSession that had one field with an accented e. When the accented e was removed the data return works just fine.
Is there any way to have this work with the possibility of non-standard english characters being returned?
I am using the task format:
    let url = NSURL(string: "www.test.com")
    var session = NSURLSession.sharedSession()
    let loadDataTask = session.dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
        let string1 = NSString(data: data, encoding: NSUTF8StringEncoding)
        println(string1)
    }

A: You're probably not getting the data back in UTF-8 encoding.  I'm not sure how this translates into Swift, but here's what you'd do in Objective-C:
NSString *encodingName = response.textEncodingName;
CFStringEncoding cfsenc = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)encodingName);
NSStringEncoding nssenc = CFStringConvertEncodingToNSStringEncoding(cfsenc);

Then pass that value instead of NSUTF8StringEncoding when you create the NSString.
Hope that helps.