text:
Q: Question Answer and Problem Answer document In the code below, there are two parts in the document.  The first part contains a Question then Answer, and the second part contains a Problem then Answer.
For Part 1, I wanted to format the document such that it will appear like:
Question 1
Q1 Question 1
...
AQ1 Answer 1
...
Question 2
Q2 Question 2
...
AQ2 Answer 2
...
Then for Part 2, the format should appear like:
Problem 1
P1 Problem 1
...
AP1 Answer 1
...
Problem 2
P2 Problem 2
...
AP2 Answer 2
...
Here is the code that is written thus far:
\documentclass{book}
\usepackage[top=3cm,bottom=3cm,left=3.2cm,right=3.2cm,headsep=10pt,letterpaper]{geometry}
\usepackage{rotating, ltablex, dcolumn}
\usepackage{lipsum}
\usepackage[english]{babel}
\usepackage{booktabs}
\usepackage{tikz}
\usepackage{pgfplots,pgfplotstable}

\usepackage{titletoc}

\begin{document}

\mainmatter

\part{Questions}
\chapter{Question 1}
\section{Question 1 }
\section{Answer 1 }
\chapter{Question 2}
\section{Question 2 }
\section{Answer 2 }
\chapter{Question 3}
\section{Question 3}
\section{Answer 3}
\chapter{Question 4}
\section{Question 4}
\section{Answer 4}
\chapter{Question 5}
\section{Question 5}
\section{Answer 5}
\chapter{Question 6}
\section{Question 6}
\section{Answer 6}
\chapter{Question 7}
\section{Question 7}
\section{Answer 7}

\part{Problems}
\chapter{Problem 1}
\section{Problem 1}
\section{Answer 1}
\chapter{Problem 2}
\section{Problem 2}
\section{Answer 2}
\chapter{Problem 3}
\section{Problem 3}
\section{Answer 3}
\chapter{Problem 4}
\section{Problem 4}
\section{Answer 4}

\end{document}

A: This uses a switch for the individual styles, \questionanswer for the first part and \problemanswer for the 2nd part.
The \if@questionmode checks whether the current section is the question or the answer -- no gaps between questions are assumed!
\documentclass{book}
\usepackage[top=3cm,bottom=3cm,left=3.2cm,right=3.2cm,headsep=10pt,letterpaper]{geometry}
\usepackage{rotating, ltablex, dcolumn}
\usepackage{lipsum}
\usepackage[english]{babel}
\usepackage{booktabs}
\usepackage{tikz}
\usepackage{pgfplots,pgfplotstable}

\usepackage{titletoc}%

\usepackage{xparse}
\usepackage{chngcntr}
\counterwithout{section}{chapter}
\counterwithin{section}{part}

\makeatletter
\let\latex@@thesection\thesection
\newif\if@questionmode

\newif\if@problemanswermode

\newcommand{\problemprefix}{P}
\newcommand{\problemanswerprefix}{A\problemprefix}
\newcommand{\questionprefix}{Q}
\newcommand{\questionanswerprefix}{A\questionprefix}

\DeclareRobustCommand{\questionanswerformat}{%
    \if@questionmode%
    \questionprefix\arabic{section}%
    \global\@questionmodefalse
    \else
    \addtocounter{section}{-1}%
    \questionanswerprefix\arabic{section}%
    \global\@questionmodetrue
    \fi
}

\DeclareRobustCommand{\problemanswerformat}{%
    \if@questionmode%
    \problemprefix\arabic{section}%
    \global\@questionmodefalse
    \else
    \addtocounter{section}{-1}%
    \problemanswerprefix\arabic{section}%
    \global\@questionmodetrue
    \fi
}

\newcommand{\questionanswer}{%
  \@questionmodetrue
  \renewcommand{\thesection}{%
    \questionanswerformat%
  }%
}

\newcommand{\problemanswer}{%
  \@questionmodetrue
  \renewcommand{\thesection}{%
    \problemanswerformat%
  }%
}

\makeatother

\usepackage{hyperref}

\begin{document}
\tableofcontents

\mainmatter

\part{Questions}
\questionanswer
\chapter{Question 1}
\section{Question 1 }
\section{Answer 1 }
\chapter{Question 2}
\section{Question 2 }
\section{Answer 2 }
\chapter{Question 3}
\section{Question 3}
\section{Answer 3}
\chapter{Question 4}
\section{Question 4}
\section{Answer 4}
\chapter{Question 5}
\section{Question 5}
\section{Answer 5}
\chapter{Question 6}
\section{Question 6}
\section{Answer 6}
\chapter{Question 7}
\section{Question 7}
\section{Answer 7}

\part{Problems}
\problemanswer
\chapter{Problem 1}
\section{Problem 1}
\section{Answer 1}
\chapter{Problem 2}
\section{Problem 2}
\section{Answer 2}
\chapter{Problem 3}
\section{Problem 3}
\section{Answer 3}
\chapter{Problem 4}
\section{Problem 4}
\section{Answer 4}

\end{document}


text:
Q: updating a dictionary leaves out over 600 key value pairs I'm trying to collect the results of a cosine similarity calculation within a dictionary.
I've compared 95x249 items, which should result in 23655 results. I've checked that via generating  a list of results, which is in deed of length 23655. When I try to do that within a dictionary, I get a length of 22979, hence 676 results are missing. I wonder why that is, has it something to do with how update() works?
Here, I've tried to give a minimal working example:
for wordvector1 in words1:
 for wordvector2 in words2:
         dot = numpy.dot(wordvector1, wordvector2)
         norm_o = numpy.linalg.norm(wordvector1)
         norm_r = numpy.linalg.norm(wordvector2)
         cosine = dot / (norm_o * norm_r)
         cosine_sim.append(cosine)
         dict_of_sims.update({cosine:[o_key,r_key]})

when I print the results, I get the values added as comments:
print(len(dict_of_sims)) #22979
print(len(cosine_sim)) #23655
print(len(words1)) #95
print(len(words2)) #249

Any hint or explanation is highly appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are these C++ Macros doing? I'm new to C++ and trying to understand what these two macros are doing in this FileMaker Plugin Example.
#define FMX_PROC(retType)           retType __stdcall
#define FMX_PROCPTR(retType, name)  typedef retType (__stdcall *name)

So far I understand that they are both macros, and that the FMX_PROCPTR is a pointer to a function that takes those two arguments, and that __stdcall is some sort of calling convention (decided to not dig to much into what that means).
What I don't understand are the ends of each lines, the parts that come after FMX_PROC(retType) and FMX_PROCPT(retType, name).
It's possible that it is the spacing that is confusing me, but is retType __stdcall the return type for FMX_PROC(retType) ? Or is it giving the argument a type?
Somewhere else in the code FMX_PROC(retType) is used like this
static FMX_PROC(fmx::errcode) Do_FMmp_ConvertToBase( short /* funcId */, const fmx::ExprEnv& /* environment */, const fmx::DataVect& dataVect, fmx::Data& results )

A: Macros dont have return types. They aren't functions. To express that difference, such macros are called "Function-like macros", ie they look like functions but they aren't functions. The preprocessor replaces FMX_PROC(fmx::errcode) with fmx::errcode __stdcall. That is, this:
static FMX_PROC(fmx::errcode) Do_FMmp_ConvertToBase( short /* funcId */, const fmx::ExprEnv& /* environment */, const fmx::DataVect& dataVect, fmx::Data& results )

Gets expanded to this
static fmx::errcode __stdcall Do_FMmp_ConvertToBase( short /* funcId */, const fmx::ExprEnv& /* environment */, const fmx::DataVect& dataVect, fmx::Data& results )

Its a function declaration and fmx::errcode is its return type.

A: These macros are just to provide the calling-convention __stdcall into the function being defined, or a function pointer alias.
__stdcall is a non-standard compiler-intrinsic that ensures that functions documented with this attribute will be called with the stdcall calling-convention. This applies to the function itself.
So the macros respectively:

*

*FMX_PROC expands into retType __stdcall, which provides __stdcall to the function. E.g.
FMX_PROC(fmx::errcode) Do_FMmp_ConvertToBase(...)

expands into:
fmx::errcode __stdcall Do_FMmp_ConvertToBase(...)

*FMX_PROCPTR expands into a typedef of a function pointer, that is also documented with __stdcall. This is necessary because function pointers don't normally carry calling conventions -- so the compiler doesn't implicitly know when a function expects a different calling convention. To bind a function marked __stdcall to a function pointer, the function pointer itself must carry this information (which is why this alias is needed).
This expands into part of the function typedef:
FMX_PROCPTR(fmx::errcode,Do_FMmp_ConvertToBase)(...);

will expand into
typedef fmx::errcode(__stdcall *Do_FMmp_ConvertToBase)(...);


text:
Q: Neural Networks Extending Learning Domain I have a simple function f : R->R, f(x) = x2 + a, and would like to create a neural network to learn that function, as entirely as it can. Currently, I have a pytorch implementation that takes in inputs of a limited range of course, from x0 to xN with a particular number of points. Each epoch, the training data is randomly perturbed, in efforts to not only learn the relationship on the same grid points each time.
Currently, it does a great job of learning on the function on the range it is trained on, but is it at all feasible to train in such a way that can extend this learning beyond what it is trained on? Currently the behavior outside the training range seems dependent on the activation function. For example, with ReLU, the true function (orange) compared to the networks prediction (blue) are below:

I understand that if I transform the input vector to higher dimensions that contain higher powers of x, it may work out pretty well, but for a generalized case and how I plan to implement this in the future it won't work as well on non-polynomial functions.
One thought that came to mind is from support vector machines and the choice of a kernel, and how the radial basis kernel gets around this generalization issue, but I'm not sure if this can be applied here without the inner product properties of svm.

A: What you want is called extrapolation (as opposed to interpolation which is predicting a value that is inside the trained domain / range). There is never a good solution for extrapolation and using higher powers can give you a better fit for a specific problem, but if you change the fitted curve slightly (either change its x and y-intercept, one of the powers, etc) the extrapolation will be pretty bad again.
This is also why neural networks use a large data set (to maximize their input range and rely on interpolation) and why over-training / over fitting (which is what you're trying to do) is a bad idea; it never works well in the general case.


text:
Q: Importing a dataset with button with tkinter I am making a program where a user will choose a dataset from a dropdown box, and will subsequently then load the data in for analysis later on in the program. My current problem is that the data is not being loaded in, and I am not sure why
from tkinter import *

datasets = ["dataset 1", "dataset 2", "dataset 3", "dataset 4"]
master = Tk()

variable = StringVar(master)
variable.set(datasets[0])

data_options = OptionMenu(master, variable, *datasets)
data_options.pack()

from sklearn import datasets
import pandas as pd

def dat_import():
    if variable.get() == "dataset 1":
        data = pd.DataFrame(datasets.load_iris().data)
        return data
    if variable.get() == "dataset 2":
        data = pd.DataFrame(datasets.load_diabetes().data)
        return data
    if variable.get() == "dataset 3":
        data = pd.DataFrame(datasets.load_digits().data)
        return data
    if variable.get() == "dataset 4":
        data = pd.DataFrame(datasets.load_boston().data)
        return data

button = Button(master, text = "Import Dataset", command = dat_import)
button.pack()

mainloop()

Simply, all I need is a user to select choice from dropdown box, press import dataset and that dataset is saved as a dataframe for access later in the program.
Any help would be greatly appreciated, because I cannot find anywhere that will explain how to do this!

A: You should not return anything from a button callback, as it is not accessible. Instead globalize it so you can use it in a later function or anywhere else:
def dat_import():
    global data

    value = variable.get()
    if value == datasets[0]:
        data = pd.DataFrame(datasets.load_iris().data)
    elif value == datasets[1]:
        data = pd.DataFrame(datasets.load_diabetes().data)
    elif value == datasets[2]:
        data = pd.DataFrame(datasets.load_digits().data)
    else:
        data = pd.DataFrame(datasets.load_boston().data)

A better way to reduce the code might be to use dictionary dispatching here, so something like:
datasets = ["dataset 1", "dataset 2", "dataset 3", "dataset 4"]
dis = {datasets[0] : pd.DataFrame(datasets.load_iris().data,
       datasets[1] : pd.DataFrame(datasets.load_diabetes().data,
       datasets[2] : pd.DataFrame(datasets.load_digits().data,
       datasets[3] : pd.DataFrame(datasets.load_boston().data,
       }

def dat_import():
    global data

    data = dis[variable.get()]


text:
Q: How to add an API Key to a UrlFetchApp in Google Apps Scripts Solved
Thanks to Dimu Designs for helping out.
The following works.
function myFunction() {
     var url = "https://api.fortnitetracker.com/v1/profile/pc/Ninja";   var apiKey = "xxx-xxx-xxx";

   var res = UrlFetchApp.fetch(
    url,
    {
        "headers":{
            "TRN-Api-Key":apiKey
        }
    } );  var content = res.getContentText();   Logger.log(res);   Logger.log(content);

}

Problem
I'm trying to use Google App Scripts within Google Sheets to call the external Fortnite API to request player data. The bit I'm stuck on how to add an API Key as a header when passing the request.
This is what I've built so far (please no laughing)!...
function myFunction() {
var res =
 UrlFetchApp.fetch("https://api.fortnitetracker.com/v1/profile/PC/Ninja?");
var content = res.getContentText();   Logger.log(res);
Logger.log(content);
}

When I try to run this I get back the following error:

Request failed for
https://api.fortnitetracker.com/v1/profile/PC/Ninja? returned code
401. Truncated server response: {"message":"No API key found in request"} (use muteHttpExceptions option to examine full response

I've tried adding my API key in a number of ways based on a number of different posts, but it doesn't work and just confuses me even more (easily done at this point).
Does anyone have any idea how I could go about completing the script to ensure I get information back? :)
---Edit---
First of all, thanks for the help guys, here's where we are at the moment. I've now tried the following:
var url = "https://api.fortnitetracker.com/v1/profile/pc/Ninja"; var apiKey = "xxx-xxxx-xxx";

var response = UrlFetchApp.fetch(
    url,
    {
        "headers":{
            "TRN-Api-Key":apiKey
        }
    } );

Rather than a 401 error, this time a 403 error is being returned.
Note, I've also tried to authenticate the header using "basic" but that doesn't work".

A: EDIT
I suspect that the API uses a custom header. When you register for an API key you get a string in the following form:
TRN-Api-Key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

I'm guessing here, but the text preceding the colon appears to be a custom header and the string of characters after the colon is the API key.
Without proper documentation this is STILL pretty much a shot in the dark but you can try the following:
var url = "[FORTNITE-API-ENDPOINT]";
var apiKey = "[YOUR-API-KEY]"; // sans header and colon

var response = UrlFetchApp.fetch(
    url,
    {
        "headers":{
            "TRN-Api-Key":apiKey
        }
    }
);

Also, make sure to check out the UrlFetchApp documentation for future reference:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app


text:
Q: Understanding android UDP server app code I'm novice with both android and Java. I'm trying to develop a very simple UDP server as my first android app (the second one if consider Hello World!).
I've collected the code from the web and this is the result:
package com.example.androidsocketserver;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

public void updateTextView(String toThis) {

    TextView textView = (TextView) findViewById(android.R.id.text2);
    textView.setText(toThis);

    }

private MyDatagramReceiver myDatagramReceiver = null;

protected void onResume() {
    myDatagramReceiver = new MyDatagramReceiver();
    myDatagramReceiver.start();
}

protected void onPause() {
    myDatagramReceiver.kill();
}

private class MyDatagramReceiver extends Thread {
    private boolean bKeepRunning = true;

    public void run() {
        String message;
        byte[] lmessage = new byte[200];
        DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);

        try {
            DatagramSocket socket = new DatagramSocket(2500);

            while(bKeepRunning) {
                socket.receive(packet);
                message = new String(lmessage, 0, packet.getLength());
                if (message != null) {
                    updateTextView(message);
                    message = null;
                }
            }
            if (socket != null) {
                socket.close();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

    public void kill() {
        bKeepRunning = false;
    }

}
}

Unfortunately the application is stopped as soon I launch it, but I don't understand why.
Is there someone so kind to help me to understand what I missed. I tryed with the emulator and with a real device obtaining the same result.
Thank you all in advance.

A: Whithout the error is very difficult to know were is the fault but try changing your receiver class to an async task
public class ReceiverBroadcastAsyncTask extends AsyncTask<Void, Integer ,String > {
boolean running = true;
Context context;
//public int counter = 1;
public ReceiverBroadcastAsyncTask(Context context) {
    this.context = context.getApplicationContext();
}

@Override
protected String doInBackground(Void... params) {
/////HERE YOUR CODE
}
protected void onPostExecute(String result) {
    //do whatever...nothing is required just pass a result on finish
}
protected void onProgressUpdate(Integer... Progress)
{
///you can pass data on here on the task progress to inform about the status
}
}

From your Activity you can call your async task like this
new ReceiverBroadcastAsyncTask(this).execute(); ///this refers to context


text:
Q: Rails dynamic state_machine In my rails application I am using the gem state_machine and want to make all states dynamic. For this I created a hash:
STATES = {
  :upload => {:step => 0, :text => 'Upload your file!'},
  :examination => {:step => 1, :text => 'Examine uploaded file!'},
  :download_model => {:step => 2, :text => 'Download created model!'},
  :choice => {:step => 3, :text => 'Choose different settings for your product!'},
  :payment => {:step => 4, :text => 'Pay for your product!'},
  :creation => {:step => 5, :text => 'Your product is currently assembled!'},
  :shipping => {:step => 6, :text => 'Your order was completed!'}
}

Now I want to iterate over the hash to create the states dynamically:
state_machine :state, :initial => STATES[:upload][:step] do
STATES.each_with_index do |state, index|
  state state[0].to_sym do
    def form_fields
      [state[0]]
    end

    def progress
      return {
          :step => index,
          :name => state[0][:text]
      }
    end
  end
end
end

After restarting my rails server I get the following error:
:upload state defined as Symbol, 0 defined as Fixnum; all states must be consistent

How can I use this hash to have dynamic states?


text:
Q: Regular Expression to match href link and replace it by a   I'm trying to make something pretty simple, but I simply suck at regular expressions.
My goal is to replace :
Link To Google

To :
Link To Google

In java.
I tried this :
String input = "Link to Google";
String Regex1 = "";
String Regex2 = "";
String output = test.replace(Regex1, "");
output = test.replace(Regex2, "");

But the first Regex1 is not matched with my input. Any clue ?
Thanks in advance!

A: It matches just fine, even tho it's wrong, and you should not use regex to parse HTML.
You want to make the second replace on the result of the first replace, not the original string:
String output = test.replace(Regex1, "");
output = output.replace(Regex2, "");

You can make it work for your example by using:
String Regex1 = "";

Which makes the quantifier ungreedy. But this expression will break very easily for the slightest changes in the input HTML, which is (one of the reasons) why you should't use regex to work with HTML.
Some simple examples the above regex would not work for:

">

A: Use a parser. They are easy to use and always the more correct solution.
jsoup (http://jsoup.org) would handle your task easily like this:
File input = new File("your.html");
Document doc = Jsoup.parse(input, "UTF-8");

Elements links = doc.select("a[href]");

while (links.hasNext()) {
  Element link = iterator.next();
  Element bold = doc.createElement("b").appendText(link.text());
  link.replaceWith(bold);
}

// now do something with...
// doc.outerHtml()

A: If you want it to work replace Regex1 with

And then:
output = output.replace(Regex2,"")

A: Don't know about using regexs in Java but there must be a "capture group" notion:
Your initial regex would be: "(.*?)"
That you would replace by: "$1"  (where $1 means the group captured between parenthesis in the first regex)


text:
Q: Resources for solving integration problems analytically I've started dealing with a lot of (many times nasty) integrals in my research.  When there an integral that I can't readily solve using usual methods (like substitution and integration by parts), I try the following sources, in this order:

*

*Gradshtein & Ryzhik 7th ed.

*Wofram Functions page

*Handbook of Mathematical Functions

*Google (which is how I found this website)
I am wondering what sources of help do others employ when faced with difficult integration problems that require analytical solution (other than posting here.)
Thank you!

A: Computer algebra systems could be of great help here. For example, Mathematica boasts to be able to solve most of indefinite and definite integrals from books like Gradshtein & Ryzhik.
There is also Wolfram alpha, which uses the Mathematica kernel. But the time spent on a problem is strictly limited, so it doesn't work for more or less complicated expressions.


text:
Q: Null<> Number displays nothing even if for id we have null in one and number in other Sorry if this is very basic.
Here is what i noticed
Here are the tables:
Table1                         Table2
ID     Value                 ID   Value
1      (null)                 1     0
2      2                      2     2
3      (null)                 3     3

So i used the following statement:
Select T1.ID,T1.Value,T2.value
from
Table1 T1,
Table2 T2
where
T1.ID=T2.ID
and T1.Value<>T2.Value;

I was expecting the output to show 1,3 ID but it showed nothing not i am confused suppose i want to see all values when one table has null for other table value how can i do that.

A: Well, the problem is that comparisons to NULL always result in FALSE, except for IS NULL.  So the clause should be:
where T1.ID=T2.ID and
      coalesce(T1.Value, t2.value - 1) <> coalesce(T2.Value, t1.value -1);

Or something that matches the NULL values.
By the way, you should also use proper join syntax.  So, the query should look more like:
Select T1.ID,T1.Value,T2.value
from Table1 T1 join
     Table2 T2
     on T1.ID=T2.ID and
        ((T1.Value <> T2.Value) or
         (t1.value is not null and t2.value is null) or
         (t1.value is null and t2.value is not null)
        );

A: you have to use LEFT JOIN rather than INNER JOIN because you want to find non matching values.
Select  t1.ID,T1.Value,T2.value
from    Table1 T1
        LEFT JOIN Table2 T2
            ON T1.ID=T2.ID AND
                t1.value = t2.value
where  t2.value IS NULL

*

*SQLFiddle Demo
To fully gain knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins

A: Select T1.ID,T1.Value,T2.value
from
Table1 T1,
Table2 T2
where
T1.ID=T2.ID
and (T1.Value<>T2.Value OR (T1.Value IS NULL AND T2.Value IS NOT NULL) OR (T2.Value IS NULL AND T1.Value IS NOT NULL));

A: Null values are special. You can do it with a complex query like
Select T1.ID,T1.Value,T2.value
  from
  Table1 T1,
  Table2 T2
  where
  T1.ID=T2.ID
  and ((t1.value is null or t2.value is null)
       and !(t1.value is null and t2.value is null)
       or t1.value <> t2.value);

Link to SQLFiddle
Note that the syntax is going to be different, depending on the flavor of SQL that you are using.


text:
Q: Telebit autostart I am currently working on a project with alexa skill to control a raspberry pi remotely.
https://tutorials-raspberrypi.com/develop-your-own-raspberry-pi-alexa-skill-and-control-pi-remotely/
As endpoint for alexa skill i want to use telebit.
Normaly I start telebit from the terminal and everything works fine.
sudo ./telebit http 5000
Now I want to start it automatically when starting the raspberry pi. For that i use the raspberry pi GUI.
[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=telebit
Exec=lxterminal -e bash -c 'sudo /home/pi/telebit http 5000;$SHELL'
Terminal=true

And I get this error message.
(unix socket: /root/.local/share/telebit/var/run/telebit.sock)

/home/pi/Applications/telebit/bin/telebit-remote.js:643
  var verstrd = [ pkg.name + ' daemon v' + state.config.version ];
                                                        ^

TypeError: Cannot read property 'version' of undefined
    at handleConfig (/home/pi/Applications/telebit/bin/telebit-remote.js:643:57)
    at /home/pi/Applications/telebit/bin/telebit-remote.js:359:22
    at /home/pi/Applications/telebit/usr/share/install-launcher.js:236:24
    at ChildProcess.exithandler (child_process.js:296:5)
    at ChildProcess.emit (events.js:182:13)
    at maybeClose (internal/child_process.js:962:16)
    at Socket.stream.socket.on (internal/child_process.js:381:11)
    at Socket.emit (events.js:182:13)
    at Pipe._handle.close (net.js:606:12)

I also tried rc.local and .bashrc but I always get the same error message.
Maybe some of you can help me

A: I solved the problem myself. You just have to omit sudo.
[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=telebit
Exec=lxterminal -e bash -c '/home/pi/telebit http 5000;$SHELL'
Terminal=true


text:
Q: Webservice different request design I'm a very beginner in webservices development and I would like to ask a design question to understand what's the best approach.
I have to create a webservice which will return some objects to the user, and it has to work like that:

*

*Request: Give me the red apples in the system

*Response: 5 Red Apples. Found Also 3 green apples. Should I return them too?

*Request: Yes -> response return 8 apples

*Request: No -> response return 5 apples

Would you use a single webservice to do that? If so, what's the best way to keep track of the current state? (I was thinking of 2 flags into the request/response but i don't know if it's a good idea..)

A: You would certainly use a single web service to do that, although you may choose to implement more than one operations (methods) in it.
State management will typically require some form of storage - you could use a database or an in-memory cache, and you will need to consider things such as handing scale, high-avialabilty, clean-up routines etc.
To correlate between request you will require to pass some token around, typically this will be provided by either the first request or first response and then re-used in subsequent calls, which would allow the service to pull the relevant context
Because standards exist to support this sort of implementation various frameworks and languages have built-in support for this, I would look for something in the relevant technology you use for implementation.
Last, but not least, typically when thinking about web implementations, state is undesirable, so - whenever possible opt for a stateless implementation. one where the requestor can issue a brand new request to get the next lot of data, without the service needing to remember anything.


text:
Q: Jenkins Git Plugin Could Not create .ssh folder I'm getting this error in my Jenkins server
Failed to connect to repository : Command "git -c core.askpass=true ls-remote -h git@mygitrepository.com:my_username/myrepository.git HEAD" returned status code 128:
stdout:
stderr: Could not create directory '/home/my_username/.ssh'.
Failed to add the host to the list of known hosts (/home/my_username/.ssh/known_hosts).
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I don't know why but the plugin tries to create .ssh under /home/my_username/, which doesn't exist in Windows. I'm trying to route it into another folder "say C:/Jenkins" but setting USERPROFILE or HOME envr. variable doesn't do the job.
Any help ?
Thanks


text:
Q: Multipole expansion of Coulomb function in 2D (Laplace expansion) In 3D, Coulomb function in Cartesian coordinates $(x, y, z)$ reads
$$\frac{1}{|\boldsymbol{x}-\boldsymbol{x'}|} = \frac{1}{\sqrt{(x-x')^2 + (y-y')^2 + (z-z')^2}}$$
which may be expanded in spherical coordinates $(r, \theta, \phi)$ with Legendre polynomials (see here) or spherical harmonics (see here) in Laplace expansion.
Consider function in 2D
$$\frac{1}{|\boldsymbol{x}-\boldsymbol{x'}|} = \frac{1}{\sqrt{(x-x')^2 + (y-y')^2}}$$
What forms of expansion in Cartesian coordinates  $(x, y)$ or polar coordinates  $(r, \theta)$?
What special functions used?

A: The Laplace expansion will work: since
$$ \frac{1}{\lvert (r\cos{\theta},r\sin{\theta})-(r'\cos{\theta'},r'\sin{\theta'}) \rvert} = \frac{1}{\sqrt{r^2+r'^2-2rr'\cos{(\theta-\theta')}}}, $$
one has
$$ \frac{1}{\sqrt{r^2+r'^2-2rr'\cos{(\theta-\theta')}}} = \frac{1}{r}\sum_{l \geq 0} \left( \frac{r'}{r}\right)^l P_{l}(\cos{(\theta-\theta')}), $$
since the left-hand side is always the generating function of the Legendre polynomials, whatever the dimension. That's fine, but while one can apply the formula
$$P_l(\cos{\theta}) = \frac{4\pi}{2l+1} \sum_{m=-l}^l Y^{-m}_l(\theta,0)Y^{m}_l(\theta',0), $$
it's rather low on physical meaning: it seems to suggest we are working on a great circle on the sphere, rather than in the plane proper.
On the other hand, the coordinate-free expansion of
$$ \frac{1}{\lvert \mathbf{x}-\mathbf{x}'\rvert} = \frac{1}{\lvert \mathbf{x}\rvert} \left(1 -\frac{2\mathbf{x} \cdot \mathbf{x}'}{\lvert \mathbf{x}\rvert^2} + \frac{\lvert \mathbf{x}'\rvert^2}{\lvert \mathbf{x}\rvert^2}  \right)^{-1/2} $$
using the binomial expansion works in exactly the same way, except that the expansion is no longer has traceless tensor in the $r^{-5}$ term: $3r_ir_j-\delta_{ij}r^2$ has nonzero trace for $d \neq 3$.


text:
Q: latex/overleaf table number start from 2 I am suffering from the numbering issue. The first table in my thesis start numbering from 1, which I have not idea why. I have tried longtable package, but it didn't work out in somehow. I use overleaf platform.
thank you all for the help in advance.
\begin{table}[H]
\resizebox{\textwidth}{22mm}{
\centering
\caption{Summary of the data collection}
\label{table:data collection}
\begin{tabular}{cccc}

\toprule
\multirow{2}{12em}{\diagbox[width=11em,height=2.5em]{Participant}{Condition}}
    & \multicolumn{2}{c}{Periodic} & Aperiodic \\ \cline{2-4}
  & without silence      & with silence     & with silence           \\
\midrule
1 & \checked & \checked & \checked \\
2 & \checked & \checked & -  \\
3 & \checked & \checked & -  \\
4 & \checked & \checked & -  \\
\bottomrule
\footnote{
Periodic condition: target stimuli is presented in the fifth position.\\
Aperiodic condition: target stimuli is presented in a random position.\\
without silence: there is not 100 ms silence after each stimuli. \\
with silence: there is a 100 ms silence after each stimuli.}
\end{tabular}
}
\end{table}


text:
Q: What C# database support multi connections over shared network? I want to build a simple database program in C# to add,update and remove information.
The program should be on shared network between 3-5 computers and each could add his information in the same time.
I searched and found that SQLite isn't good for that, and don't know what will be.
I'm looking for some simple database, not something that I should install in each PC to support it.
There isn't an access to the internet, its blocked except a few websites so its not possible to use MSSQL or mySQL.
Thank you.

A: The fact that the users don't have access to the internet doesn't mean that you can't use MySQL or MS SQL Server. You can install MySQL on one of the computers (the one that will play the server role) and have all the other computers connect to the MySQL instance installed on the local server since you say that they will be on an internal network.
As far as Databases go, there are plenty you can use: MySQL, SQL Server, PostgreSQL, etc... Just don't use MsAccess. ;)


text:
Q: Pass variable to template in Airflow In Airflow I am creating branches with different operators with a for loop, my code looks like this:
for table in ['messages', 'conversations']:
    Operator1 with operator1.task_id = 'operator1_{}'.format(table)
    Operator1 does kwargs['ti'].xcom_push(key='file_name', value='y')

    Operator2 is a BashOperator that needs to run:
    bash_command = "echo {{ ti.xcom_pull(task_ids='operator1_{}', key='file_name') }}".format(table)

    Operator1 >> Operator2

But in the UI the commands are rendered like that:
echo { ti.xcom_pull(task_ids='operator1_messages', key='file_name') }
echo { ti.xcom_pull(task_ids='operator1_conversations', key='file_name') }

How should I write the bash_command to have Airflow interpret correctly the template?
If I write directly
 bash_command = "echo {{ ti.xcom_pull(task_ids='operator1_messages', key='file_name') }}"

it works but I want to create this command from a for loop.
Thanks!

A: It's doing this because the .format(table) part of your bash command is stripping off the outer { and }. You may be able to fix this with the following instead:
bash_command = "echo {{ ti.xcom_pull(task_ids='operator1_" + table + "', key='file_name') }}"

Whether this is the best way to do it is probably another question.


text:
Q: Editing TXT file content using a wildcard I'm working on a content editor, which will edit the data inside a txt file, changing it to whatever you programmed it to.
This is my original script:
@echo off
setlocal enableextensions disabledelayedexpansion

set "search=Stars"
set "replace=Falling Stars"

set "textFile=0Originals\Document.txt"

for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%textFile%" echo(!line:%search%=%replace%!
    endlocal
)

This is my attempt:
@echo off
setlocal enableextensions disabledelayedexpansion

set "search=Stars"
set "replace=Falling Stars"

for /f "delims=" %%i in ('type "0Originals\*.txt" ^& break ^> "0Originals\*.txt" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"0Originals\*.txt" echo (!line:%search%=%replace%!%%
    endlocal
)

I am trying to to make it read any file, but everything I do fails to work.
Any idea on why the *.txt fails to work?


text:
Q: Calculation mistakes of SparseLU in Eigen (C++) Recently I found that in some certain circumstances, the SparseLU solver will get the wrong answer.
I give an example in the attachment, where "A.csv" is the coefficient matrix of the equation Ax=b, and "b.csv" is the right part of the equation.
The codes are like this:
// solve the linear system: Ax = b
Eigen::VectorXd sparselu_x, pardisolu_x;
SparseLU<spmat> solver_splu;
PardisoLU<spmat> solver_pdslu;

// SparseLU results
solver_splu.compute(A);
sparselu_x = solver_splu.solve(b);

// PardisoLU results
solver_pdslu.compute(A);
pardisolu_x = solver_pdslu.solve(b);

// print some of the difference
cout << "sparselu results - pardisolu results (last 5 items):\n\n" << (sparselu_x - pardisolu_x).tail(5) << endl;

cout << "\n\n\n\nA*x - b (sparselu results, last 5 items):\n\n" << (A * sparselu_x - b).tail(5) << endl;
cout << "\n\n\n\nA*x - b (pardisolu results, last 5 items):\n\n" << (A * pardisolu_x - b).tail(5) << endl;

And the output:
sparselu results - pardisolu results (last 5 items):

 6.25516e-10
 6.36814e-08
-1.45986e-05
  -0.0170633
   -0.437249

A*x - b (sparselu results, last 5 items):

           0
 1.81899e-12
-1.81899e-12
     18.0459
     621.588

A*x - b (pardisolu results, last 5 items):

1.81899e-12
          0
          0
          0
          0

Full data and codes about reading the csv file and solving the system are uploaded at:
https://github.com/cpc-tyym/SparseLU-eg
Because of the efficency, I really prefer the sparselu solver, but this mistake makes me choose the pardiso solver, which is 3 times slower than the sparselu solver. So could anyone find out whether the sparselu solver is wrong in somewhere, or did I make any mistakes when solving the equation?


text:
Q: sfWidgetFormChoice with multiple selections I'm using symfony 1.4 to make a CRUD from a client. This client need to have a select field with multiple choices to generate a newsletter and sent an email.
I'm setting the sfWidgetFormChoice with multiple => 'true', but always i can select just one of items on select. I don't know how to fix this, the googling don't help me.
Look at my code:
$this->widgetSchema['id_news'] = new sfWidgetFormChoice(array('label' => 'News',
    "choices" => $this->getNewsLimitUm(),
    'multiple' => true,
 ));

$this->validatorSchema['id_noticia'] = new sfValidatorString(array('required' => false));

A: The problem is with my Id, from select field. I change it and work fine.


text:
Q: Derive parent-child hierarchy in JSON from an array using DataWeave Hopefully this is the last of my questions related to this and this
The earlier questions were related to generating XML payload while this query is around generating JSON o/p in a specific format...
Thanks to @Harshank and @sudhish_s was able to make some progress with XML o/p. However I am not able to figure out how to go about json o/p
Here is the input payload ( have limited it to three rows / json objects but could be in thousands)
    [
  {
    "gp": "S1",
    "gp_eye_colour": "blue",
    "gp_name" : "John",
    "parent": "S1",
    "parent_eye_colour" : "blue",
    "parent_name" : "Sam",
    "child": "C1",
    "child_eye_colour" : "black",
    "child_name" : "C1-name"
  },
 {
    "gp": "S1",
    "gp_eye_colour": "blue",
    "gp_name" : "John",
    "parent": "P1",
    "parent_eye_colour" : "blue",
    "parent_name" : "Don",
    "child": "C1",
    "child_eye_colour" : "brown",
    "child_name" : "C1-name"
  } ,
  {
    "gp": "S2",
    "gp_eye_colour": "blue",
    "gp_name" : "David",
    "parent": "P2",
    "parent_eye_colour" : "blue",
    "parent_name" : "Martha",
    "child": "C1",
    "child_eye_colour" : "brown",
    "child_name" : "C1-name"
  }
]

Desired o/p is as below :
{
    "S2_blue": {
        "code": "S2",
        "eyeColour": "blue",
        "name": "David",
        "hierarchy": [
            {
                "code": "P2",
                "eyeColour": "blue",
                "name": "Martha",
                "hierarchy": [
                    {
                        "code": "C1",
                        "eyeColour": "brown",
                        "name": "C1-name",
                        "hierarchy": []
                    }
                ]
            }
        ]
    },
    "S1_blue": {
        "code": "S1",
        "eyeColour": "blue",
        "name": "John",
        "hierarchy": [
            {
                "code": "P1",
                "eyeColour": "blue",
                "name": "Don",
                "hierarchy": [
                    {
                        "code": "C1",
                        "eyeColour": "brown",
                        "name": "C1-name",
                        "hierarchy": []
                    }
                ]
            },
            {
                "code": "C1",
                "eyeColour": "black",
                "name": "C1-name",
                "hierarchy": []
            }
        ]
    }
}

Similar rules need to apply :

*

*Its a Grandparent >> Parent >> Child hierarchy

*If Grandparent and Parent share same characteristics (gp == parent and gp_eye_colour == parent_eye_colour then skip parent and directly include child(ren)
( as an example parent Sam is excluded since John (gp) has the same value for gp and eye_colour

*Don is not exluded ( same rule as above )

Using the solutions provided to the earlier asked questions - I came up with the following code:
    %dw 2.0
output application/json
var hierarchy = ["gp", "parent", "child"]
fun getDirectGeanologies(records, level) = do {
    var hLevel = hierarchy[level]
    var xyz =  if(level == 0)
    (records groupBy ((item, index) -> item.gp ++ "_" ++ item.gp_eye_colour) )
    else if(level == 1)
    (records groupBy ((item, index) -> item.parent ++ "_" ++ item.parent_eye_colour))
    else
    (records groupBy ((item, index) -> item.child ++ "_" ++ item.child_eye_colour))
    ---
     xyz mapObject ((children, code) ->
        (code): {
            code: children[0][hLevel],
            eyeColour: children[0][hLevel ++ "_eye_colour"],
            name: children[0][hLevel ++ "_name"],
            hierarchy:
                if (level == sizeOf(hierarchy) - 1) [] // if level = 2 ( child stop recursion)
                else do {
                    var nextLevel = level + 1
                    var nextGen = if(nextLevel == 1)(children groupBy ((item, index) -> item.parent ++ "_" ++ item.parent_eye_colour)) else (children groupBy ((item, index) -> item.child ++ "_" ++ item.child_eye_colour))
                    ---
                    nextGen mapObject ((nextGenChildren, nextGenCode) ->
                        if (nextGenCode == code)
                            getDirectGeanologies (nextGenChildren, nextLevel + 1 ) // skip parent
                        else
                            getDirectGeanologies (nextGenChildren, nextLevel)
                    )
                }

        }
    )
}
---
getDirectGeanologies(payload,0)

However it is not producing desired o/p :
    {
  "S1_blue": {
    "code": "S1",
    "eyeColour": "blue",
    "name": "John",
    "hierarchy": {
      "C1_black": {
        "code": "C1",
        "eyeColour": "black",
        "name": "C1-name",
        "hierarchy": [

        ]
      },
      "P1_blue": {
        "code": "P1",
        "eyeColour": "blue",
        "name": "Don",
        "hierarchy": {
          "C1_brown": {
            "code": "C1",
            "eyeColour": "brown",
            "name": "C1-name",
            "hierarchy": [

            ]
          }
        }
      }
    }
  },
  "S2_blue": {
    "code": "S2",
    "eyeColour": "blue",
    "name": "David",
    "hierarchy": {
      "P2_blue": {
        "code": "P2",
        "eyeColour": "blue",
        "name": "Martha",
        "hierarchy": {
          "C1_brown": {
            "code": "C1",
            "eyeColour": "brown",
            "name": "C1-name",
            "hierarchy": [

            ]
          }
        }
      }
    }
  }
}

The issues here are :

*

*hierarchy inside gp should be an array but I am getting a object

*Not 100% sure but because of above problem rather than having objects inside an array against hierarchy I am getting an object with key as parent/child and eye colour ( Ex : C1_black , P1_blue etc )

So not really sure how to get this part and I am having a tough time to visualise the recursive behaviour
Thanks in advance and once again really appreciate the help already provided by @Harshank and @sudhish_s

A: I have answered this in mulesoft help forum. LInk MuleSoft Help Forum link


text:
Q: get data with chrome.storage.sync How can I get data from
 chrome.storage.sync.get

and store his value on a variable?
I have been creating a CRUD within chrome extension but when trying to Retrieve the data, it looks like chrome.storage.sync.get don't return data.
const STORAGE = chrome.storage.sync;

function getURLs() {
  let urls = [];
  STORAGE.get(["urls"], result => {
    urls = result.urls || [];
  });
  return urls;
}

Any help?


text:
Q: How to implement mutex in iOS app
Possible Duplicate:
GCD : How to write and read to variable from two threads

I am developing a iOS app in which i am using sqlite database.I have to perform multithreading  but on sqlite database I am able to do only one thing at a time.So I need to implement concept of semaphore .So plz help me

A: You can use the @synchronized directive as a mutex. If you have all your methods for manipulating the sqlite database in a single data manager created using a singleton and shared throughout the project you can use that object as the lock token, e.g.:
- (void)myMethod:(id)globalDataManager {
    @synchronized(globalDataManager) {
        // Everything between the braces is protected by the @synchronized directive.
    }
}

And from within the data manager you can use @synchronized(self) for the same protection.
You will only need a mutex for this so don't worry about extra code for implementing semaphores.

A:
I need to implement concept of semaphore

semaphore implementations are found in #include <sys/semaphore.h>.


text:
Q: Creating a new method 'predict_proba' in keras.models.Model class that returns the output of existing method 'predict' I am trying to use a Functional API to create a model which I then use for calibration using CalibratedClassifierCV. Unfortunately it throws an error saying that predict_proba cannot be used with a Functional model. In my case, I have only one output so model.predict() would work just as well as model.predict_proba(). I was wondering if it is possible to create a new method in the keras.models.Model class called predict_proba that just returns the output of predict.
So far I have tried this:
def predict_proba(x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10,
                  workers=1, use_multiprocessing=False):

    return keras.models.Model.predict( x, batch_size=batch_size, verbose=verbose, steps=steps, callbacks=callbacks,
                          max_queue_size=max_queue_size,
                          workers=workers, use_multiprocessing=use_multiprocessing)

But it throws me the error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-6bb11e61a234> in <module>
     81 calibrator_0 = CalibratedClassifierCV(model_0, cv='prefit')
     82
---> 83 calibrator_0.fit(X_test_0, y_test_0, sample_weight = w_test_0)

~\anaconda3\lib\site-packages\sklearn\calibration.py in fit(self, X, y, sample_weight)
    153             calibrated_classifier = _CalibratedClassifier(
    154                 base_estimator, method=self.method)
--> 155             calibrated_classifier.fit(X, y, sample_weight)
    156             self.calibrated_classifiers_.append(calibrated_classifier)
    157         else:

~\anaconda3\lib\site-packages\sklearn\calibration.py in fit(self, X, y, sample_weight)
    332         Y = label_binarize(y, classes=self.classes_)
    333
--> 334         df, idx_pos_class = self._preproc(X)
    335         self.calibrators_ = []
    336

~\anaconda3\lib\site-packages\sklearn\calibration.py in _preproc(self, X)
    291                 df = df[:, np.newaxis]
    292         elif hasattr(self.base_estimator, "predict_proba"):
--> 293             df = self.base_estimator.predict_proba(X)
    294             if n_classes == 2:
    295                 df = df[:, 1:]

~\anaconda3\lib\site-packages\tensorflow\python\keras\wrappers\scikit_learn.py in predict_proba(self, x, **kwargs)
    262     """
    263     kwargs = self.filter_sk_params(Sequential.predict_proba, kwargs)
--> 264     probs = self.model.predict_proba(x, **kwargs)
    265
    266     # check if binary classification

<ipython-input-37-6bb11e61a234> in predict_proba(x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
      5                   workers=1, use_multiprocessing=False):
      6
----> 7     return keras.models.Model.predict( x, batch_size=batch_size, verbose=verbose, steps=steps, callbacks=callbacks,
      8                           max_queue_size=max_queue_size,
      9                           workers=workers, use_multiprocessing=use_multiprocessing)

TypeError: predict() missing 1 required positional argument: 'x'

I want to define this function so that when a keras.models.Model object calls predict_proba, say using model.predict_proba(x,..), it returns the output of model.predict(x,..).
Is there a solution?

A: Apparently this simple fix seems to work:
keras.models.Model.predict_proba = keras.models.Model.predict

Now I can use a functional model with CalibratedClassifierCV.


text:
Q: OOP maximum function nesting level I have a weird situation with OOP
My class is very simple
class Thing{

  private
    $children = array(),
    $parent;

  public function addChild(self $thing){
    $this->children[] = $thing;
    $thing->setParent($this);
  }

  public function setParent(self $thing){
    $this->parent = $thing;
    $thing->addChild($this);
  }

}

$a = new Thing();
$b = new Thing();

$b->setParent($a);

If I try to use these functions I get the Maximum function nesting level of 100 error and I know why, but how am I supposed to change the code? The way it is now it makes sense, but if I remove any of the function calls it would not work like it should.

A: As mentioned in the comments, your code creates an infinite loop between setParent() and addChild(), wherein a call to setParent() implicitly also calls setChild(), which in turn calls setParent() again.
If you want your code to work such that a call to setParent() or a call to addChild() enforces the relationship in properties in both objects, you can solve the infinite loop you are currently experiencing by adding an if () condition inside addChild(), calling setParent() only if the object's parent is not already the current object ($this).
Likewise, you  need to check if the object to be added as a child in addChild() has not already been added to the parent's $children array using in_array().
class Thing{

  private
    $children = array(),
    $parent;
  // A name property just to see the results
  public $name;

  public function addChild(self $thing){
    $this->children[] = $thing;

    // Only set this object to the passed-in $thing object's
    // $parent property if it has not already been set:
    if ($thing->parent !== $this) {
      $thing->setParent($this);
    }
  }

  public function setParent(self $thing){
    $this->parent = $thing;

    // Only add the child via addChild() if it is not
    // already in the array
    if (!in_array($this, $thing->children)) {
      $thing->addChild($this);
    }
  }

}

$a = new Thing();
$a->name = "THING A";
$b = new Thing();
$b->name = "THING B";
// Specify $a as the parent of $b
$b->setParent($a);

echo "\$a properties:\n";
print_r($a);
echo "\$b properties:\n";
print_r($b);

The output from the above is:
$a properties:
Thing Object
(
    [children:Thing:private] => Array
        (
            [0] => Thing Object
                (
                    [children:Thing:private] => Array
                        (
                        )

                    [parent:Thing:private] => Thing Object
 *RECURSION*
                    [name] => THING B
                )

        )

    [parent:Thing:private] =>
    [name] => THING A
)
$b properties:
Thing Object
(
    [children:Thing:private] => Array
        (
        )

    [parent:Thing:private] => Thing Object
        (
            [children:Thing:private] => Array
                (
                    [0] => Thing Object
 *RECURSION*
                )

            [parent:Thing:private] =>
            [name] => THING A
        )

    [name] => THING B
)

Now, using the inverse action, starting with $a and $b then adding $b as a child to $a instead of adding $a as the parent of $b:
$a = new Thing();
$a->name = "THING A";
$b = new Thing();
$b->name = "THING B";
// Add $b as a child of $a
$a->addChild($b);

Produces the same output:
$a properties:
Thing Object
(
    [children:Thing:private] => Array
        (
            [0] => Thing Object
                (
                    [children:Thing:private] => Array
                        (
                        )

                    [parent:Thing:private] => Thing Object
 *RECURSION*
                    [name] => THING B
                )

        )

    [parent:Thing:private] =>
    [name] => THING A
)
$b properties:
Thing Object
(
    [children:Thing:private] => Array
        (
        )

    [parent:Thing:private] => Thing Object
        (
            [children:Thing:private] => Array
                (
                    [0] => Thing Object
 *RECURSION*
                )

            [parent:Thing:private] =>
            [name] => THING A
        )

    [name] => THING B
)

(Note about the "RECURSION" in the print_r() output: That does not indicate the method calls are behaving recursively, just that there is a recursive relationship between the object references, which is what you want. $a has a child $b and print_r() attempts to display the parent of $b, which points back to $a)


text:
Q: Microsoft.EntityFrameworkCore dont have method IsOptional() for PropertyBuilder I try transfer my solution from .Net Framowork to .Net Core.When I did mapping and I dint found method IsOptional() for PropertyBuilder:
.Net Framowork:
    public class PictureMap : EntityTypeConfiguration<PictureExt>
{
    public PictureMap()
    {
        this.ToTable("Picture");
        this.HasKey(p => p.Id);
        this.Property(p => p.SeoFilename).HasMaxLength(300);
        this.Property(p => p.ExternalUrl).IsOptional();
    }
}

and its work , but use EntityFrameworkCore:look in image
where I might found IsOptional()?

A: There is not IsOptional in EntityFrameworkCore but there is IsRequired to do the oposite. By default field are nullable if the C# type is nullable.

A: You can achieve the same effect with IsRequired(false).  This will override annotations like [Required] so be careful.  On another thread, it was pointed out that annotations that affect EF models or make no sense [Display...] should not be part of the EF model.  Move them to a ViewModel or DTO object.


text:
Q: In which case will vertical alignment split the image and text into two lines Still not quite sure what is the cause of this issue. I have this html:
<button id="AddJudgeBt" type="button" class="positive block">
    Add

</button>

I can't paste all the css here because it is spread in all different files and too long. The brief idea is both spans have display: inline-block and the icon one has the image.

The generated button pretty much looks like this. As you can see, the img and button are splitted into two lines. I tried the margin, padding, position and width of the button and none of them is the issue. Finally I tried to change vertical-alignment from top to text-top and the problem got resolved!
But I am still unclear about what has caused the issue. I tried with this fiddle: https://jsfiddle.net/stqgdfcz/1/ But I could not reproduce what has happened.
Can anybody let me know what could be the potential issue?

A: This could be because the Image and the text are floating differently. Try floating the image and the text to left, this will align them in the same line and don't forget to clear the float afterwards.
You can do this.
img.del {
float:left
}

.astext{
float:left
}

A: Try applying width(may be 50%) and float:left for both SPAN and then adjust margin or padding to align as per the design.

A: html
<button>Next</button>

css
img.del {

}
.astext {
text-align: left;
    margin-left: 10%;
}
.aspic
{
cursor: pointer;
margin-left: 10px;
margin-right: 5%;
}
span {
display:inline-block;
}

button {
  box-sizing:border-box;
  width: 80px;
  display:block;
}

https://jsfiddle.net/stqgdfcz/6/


text:
Q: Alternatives/Competitors to RWWGuard 2008 Does anyone know of any alternatives or competitors to RWWGuard?
http://www.scorpionsoft.com/products/rwwguard2008/
I am looking for a two factor authentication system for Remote Web Workplace for Small Business Server 2008.  RWWGuard seems good but a little expensive and also I'd like something to evaluate it against.

A: If your SBS is behind a firewall then check for any two factor auth solutions supported by the firewall.
RSA SecurID is one alternative that you can evaluate against.  It's not cheap either, but plenty of features to compare.


text:
Q: Terminal quasi-affine varieties? Let $U$ be a normal, irreducible, quasi-affine variety over the algebraically
closed field $k$ and consider the ring $A = \mathscr{O}(U)$ of regular
functions on $U$. Write $Max(A)$ for the topological space of maximal ideals
of $A$ (in the Zariski topology). Let $V\subset Max(A)$ be the union of all open subsets
of the form $Max(A_f)$ where is $f\in A\setminus\{0\}$ is such that  $A_f$ is
a finitely generated $k$-algebra. Is it always the case that $V$ is quasi-affine?
i.e. We know from the definition that $V$ is locally Noetherian. But is it always
Noetherian?


text:
Q: Target.address for multiple rows in Excel I need to reference an entire column of Excel spreadsheet, with a drop-down list using VBA. The code i got online works only for a single cell which is "$M$2". How can i define  a range for the entire column?
Private Sub Worksheet_Change(ByVal Target As Range)

' To Select Multiple Items from a Drop Down List in Excel

Dim Oldvalue As String
Dim Newvalue As String

On Error GoTo Exitsub
If Target.Address = "$M$2" Then
    If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
    GoTo Exitsub
    Else: If Target.Value = "" Then GoTo Exitsub Else
        Application.EnableEvents = False
        Newvalue = Target.Value
        Application.Undo
        Oldvalue = Target.Value
        If Oldvalue = "" Then
            Target.Value = Newvalue
        Else
            Target.Value = Oldvalue & ", " & Newvalue
        End If
    End If
End If
Application.EnableEvents = True

Exitsub:
Application.EnableEvents = True

End Sub

A: Firstly, Target may be a single cell or multiple cells, depending on what the user changed
To test if any cell in (and only in) column M changed, use
If Target.EntireColumn.Address = "$M:$M" Then

To test if any cell in Target is in column M use
Dim rng As Range
Set rng = Application.Intersect(Target, Me.Columns("M"))
If Not rng Is Nothing Then

Note: the rest of your code will need to be modified to allow for Target being more than one cell


text:
Q: Having problems implementing Create User with FIRAuth I've ran into this issue and have been trying to solve it for a few days now and it seems everything I try it creates more errors. I'm having problems creating a user with this function use FIRAuth and its telling me to add in a ; right before in, but it doesn't fix the problem.
Picture of Errors:

func handleRegistration() {
        guard let email = emailTextField.text, let password = passTextField.text
            else {
                print("Form is not Valid")
                return
        }

        FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: FIRUser?, error) in

         if error != nil {
            print("Error")
            return
        }

        print("Login Successful")
    }

A: Try this :-
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: {(user, error) in

     if error != nil {
        print("Error")
        return
    }else{
        print("Login Successful")
        return
   }
})


text:
Q: Set datefirst permanently I'd like to change permanently the value of DATEFIRST (which is used for functions like DATEPART)
If I do this : SET DATEFIRST 1 the value stay during the execution but it return to the default value - 7 here - after the execution
I already had the problem, I know that it's related to the country of the login but I forgot which table & which property I had to change.

A: I must say this took some research on my part.  Take a look at the following query. You will notice the datefirst field. I would imagine there are all kinds of permission implications that go along with changing language settings at this level.
SELECT
    *
FROM
    sys.syslanguages

I don't have a server I can test this on at the moment but I would imagine through a set statement you could set the datefirst column to whatever you wanted it to be.
TEST TEST TEST as this will have huge implications across more than problem you are trying to solve.
Interesting Resource # 1
Interesting Resource # 2
Interesting Resource # 3

A: You can alter the default language of a sql login or windows user authenticated on SQL Server using the Microsoft SQL Server Management Studio or executing the below sample t-sql script :
USE [master]
GO
ALTER LOGIN [login] WITH DEFAULT_LANGUAGE = [you_language]
GO

The script was taken from this site

A: Perhaps a bit late to the party, but here's a way to "hack" it, regardless of the datefirst value, set either to the server, db, login or session and parametrizable (WOW, never used this word before) by the first day you actual want it to be :
declare
/*
 Let's say for a regular, boring day of Monday
, regarldess of the datefirst value, I want it to return Monday as 1 (first day of week)
*/
@ForDate datetime = '20170320',
-- you can play with any value here
@SetDateFirstValue int = 5

--this is only for testing
set datefirst @SetDateFirstValue;

select
  datepart(dw,@ForDate) as ActualReturnedDayOfWeek
, datepart(dw,dateadd(dd, @@DATEFIRST - 1,@ForDate)) As IWantItThisWay

P.S. : Perhaps the only situations you'll ever need this, is in a function  or constraint (computed columns maybe) where SET operations are not allowed. If SET is allowed, SET it as you need it and forget about it.


text:
Q: Messenger bot show attachment title when i'm sending an attachment to the user, he get something like " sent you an attachment", i saw other bot that sending and attachment, but the user get a message with the attachment title if it's an article or so, any ideas how can i do it?
Here's an example code:
{
    "attachment": {
    "type": "template",
    "payload": {
        "template_type": "generic",
        "elements": [
           {
          "title": "title",
          "image_url": "image_url",
          "item_url": "article_url",
          "buttons": [
          {
              "type":"element_share"
          }
          ]
      }
      ]
      }
   }
}


text:
Q: DB2: SQL to return all rows in a group having a particular value of a column in two latest records of this group I have a DB2 table having one of the columns (A) which has either value PQR or XYZ.
I need output where the latest two records based on col C date have value A = PQR.
Sample Table
A   B     C
--- ----- ----------
PQR Mark  08/08/2019
PQR Mark  08/01/2019
XYZ Mark  07/01/2019
PQR Joe   10/11/2019
XYZ Joe   10/01/2019
PQR Craig 06/06/2019
PQR Craig 06/20/2019

In this sample table, my output would be Mark and Craig records

A: Since 11.1
You may use the nth_value OLAP function.
Refer to OLAP specification.
SELECT A, B, C
FROM
(
SELECT
  A, B, C
, NTH_VALUE (A, 1) OVER (PARTITION BY B ORDER BY C DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) C1
, NTH_VALUE (A, 2) OVER (PARTITION BY B ORDER BY C DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) C2
FROM TAB
)
WHERE C1 = 'PQR' AND C2 = 'PQR'

dbfiddle link.
Older versions
SELECT T.*
FROM TAB T
JOIN
(
SELECT B
FROM
(
SELECT
  A, B
, ROWNUMBER() OVER (PARTITION BY B ORDER BY C DESC) RN
FROM TAB
)
WHERE RN IN (1, 2)
GROUP BY B
HAVING MIN(A) = MAX(A) AND COUNT(1) = 2 AND MIN(A) = 'PQR'
) G ON G.B = T.B;

A: A simple solution could be
SELECT A,B,C
  FROM tab
 WHERE A = 'PQR'
 ORDER BY C DESC FETCH FIRST 2 ROWS only


text:
Q: How to turn off Highlight File on Active Editor Change? The VS Code October 2019 update includes a feature to automatically highlight the active file in the tree/list view.
How do I turn off this feature?

A: The setting SCM: Auto Reveal seems to enable/disable that functionality for the source control tree, as in the image you linked to.  Uncheck it to disable.
Also Explorer: Auto Reveal for the explorer tree highlighting.


text:
Q: Why does Eclipse open my java files as a tab in the package explorer view? Whenever I want to open a file in the package explorer, it will be opened as a new tab in the same view as the package explorer. Last time I started Eclipse, the were all opened in a seperate editor view.

A: You can try resetting your perspective.
In the upper right hand corner you can see your currently selected "Perspective" (you can also set it through Window-->Open Perspective-->Other). It will probably be "Java" for you. You can right-click on the perspective and choose "Reset". This will reset the perspective to it's default settings.
There is also Window>Reset Perspective as another way to reset.

A: open  Window -> Perspective -> Reset Perspective
It worked fine for me.
Then you can just minimize all the other open tabs you don't need like Task List...

A: I faced the same issue and had to shift the newly opened tab manually.
Doing Window-> Perspective->Reset perspective brought the views to their default positions.


text:
Q: How do I add shell programs to the Unity search results? When you add no-install applications to Ubuntu, they don't come up in the Unity search. For example, I downloaded Eclipse and unzipped it in a folder: ~/SelfInstall/eclipse.
How do I get eclipse which is located in ~/SelfInstall/eclipse/ to show up in the search results?
Update:
Ah, if I add a 'desktop configuration file' to .local/share/applications and point it to the launch script, then it works, but I don't know how to create a file of type 'desktop configuration file'. I had to copy one and edit it's properties. Any idea on how to create these files from scratch?
Update 2:
Ok, so this is how the file had to look:
cat .local/share/applications/opt_eclipse.desktop

[Desktop Entry]
Type=Application
Name=Eclipse
Comment=Eclipse IDE
Icon=/home/me/SelfInstall/eclipse/icon.xpm
Exec=/home/me/SelfInstall/eclipse/eclipse
Terminal=false
Categories=Development;IDE;Java;

A: You would need to create, or copy an existing .desktop file, for the application, into your $XDG_DATA_HOME/applications directory.


text:
Q: What's the difference between USB_MASS_STORAGE and USB_FILE_STORAGE and how to best use it? In Linux kernel 3.4, what's the difference between USB_MASS_STORAGE and USB_FILE_STORAGE?
I would like to have an embedded device running kernel 3.4 to show a mount point when connected to a PC. This mount point should be writable on the PC and then readable on the embedded device from memory. In other words, the embedded device local storage should be in memory (such as ramfs). How can I do that?

A: As stated in Linux kernel 3.18 CONFIG_USB_MASS_STORAGE is replacement for USB_FILE_STORAGE:

The Mass Storage Gadget acts as a USB Mass Storage disk drive. As its
  storage repository it can use a regular file or a block device (in
  much the same way as the "loop" device driver), specified as a module
  parameter or sysfs option. This driver is a replacement for now
  removed File-backed Storage Gadget (g_file_storage).

So far I could successfully expose /dev/mmcblk0p1 (am335x SoC) to Windows using CONFIG_USB_MASS_STORAGE:
modprobe g_mass_storage file=/dev/mmcblk0p1


text:
Q: Removing Custom Domain in Github I want to remove custom Domain from Github. Any help, please.

Actually I want get https://myaseen208.github.io/DiallelAnalysisR/ rather than http://www.myaseen208.com/DiallelAnalysisR/ as given the following picture.

A: As illustrated in isaacs/github issue 1213 (which shows a similar problem), you should have a CNAME file
But not in: github.com/MYaseen208/DiallelAnalysisR
In the repo github.com/myaseen208/myaseen208.github.io (same as in the issue 1213): this CNAME file, which does include:
www.myaseen208.com

Apparently your user's GitHub domain automatically comes from your {username}.github.io repo

Start by removing that file, and see if that changes anything (wait a bit, and clear your browser local cache)

A: I was having the same issue. I resolved it by emptying the custom domain field, then entering a space in the same field so that you can activate the save button (Note: the save button will not let you save if the field is empty).
After you hit save, your page will reload and you will be able to see this again

A: Delete the content of the text box and press "Save"

A: If you want your user name's GitHub domain back which automatically comes from your {username}.github.io repo then simply empty the custom domain input field and enter a space in the custom domain field in order to activate the save button as the save button will not let you save until the field is empty.
Hit save & your page will reload and you will see your static site live on your Github username domain.


text:
Q: Trigger Elementor Popup via code PHP and JavaScript I have created a code which will check if zone is nz real then display popup otherwise do not. it should work on normal checkout process and page refresh also. right now it's working on page refresh only. without page refresh it isn't displaying popup.
File : Functions.php
add_action( 'woocommerce_cart_totals_after_shipping' , 'shipping_zone_targeted_postcodes_custom_notice' );
add_action( 'woocommerce_review_order_after_shipping' , 'shipping_zone_targeted_postcodes_custom_notice' );
function shipping_zone_targeted_postcodes_custom_notice() {
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    $popup_id = '3003';
    ElementorPro\Modules\Popup\Module::add_popup_to_location( $popup_id );

    ?>
    <script>
        jQuery( window ).on( 'elementor/frontend/init', function() {
            elementorFrontend.on( 'components:init', function() {
                console.log("loading ele");
            });
        });
    </script>

    <?php
    if(  $current_zone_name  == "NZ Rural"){
        $popup_id = '3003';
        ElementorPro\Modules\Popup\Module::add_popup_to_location( $popup_id );
        ?>
        <script>
            jQuery( window ).on( 'elementor/frontend/init', function() {
                elementorFrontend.on( 'components:init', function() {
                    console.log("loading ele 2");
                    elementorFrontend.documentsManager.documents[<?php echo $popup_id ;?>].showModal();
                    elementorProFrontend.modules.popup.showPopup({ id: 3003 });
                });
            });
        </script>
        <?php
    }
}

can you please help me?


text:
Q: Find all rectangles of sub densed matrix in a large sparse matrix This is part of image processing algorithm where more optimization is expected.
We have a large sparse matrix consisting of 0's and 1's. In this sparse matrix there are one or more dense region of 1's. Lets say the whole matrix represents an image and 0 represent non-video areas and 1 represents video areas. Basically All nearby 1's should be grouped together to find out the more approximate video region. So drawing a boundary around all 1's will give exact video areas in a image.

As shown in the above matrix of 0's and 1's. There are 4 dense areas of 1's. We have tried a naive approach which is of more time complexity and further improvements expected.
The approach we tried is converting all 0's in a block size of 3*3 or 2*2 if the number of 1's in the block are above a certain threshold value. But even this approach doesnt give us the exact boundary of video blocks.
So looking for a better algorithm which is good in both time and space complexity. Actually this calculation need to be done in real time so algorithm must have a very less time complexity. It would be great if we can achieve in O(n)  linear time.

A: The usual approach here is to apply a sweep line algorithm.
Basically, it works as follows: Look at each column. If it consists of all zeros, move on to the next column. If it contains 1's, save the smallest and largest vertical positions (they are likely candidates for rectangle coordinates). As you move the sweep line further, adjust your candidates accordingly. If you have found candidates and reach a line consisting of all zeros, your coordinate candidates are the actual coordinates of the rectangle.
You may as well (or additionally) sweep vertically and examine rows instead of columns.
Depending on the properties of your matrix (or your task), there are a lot of different possible solutions. Consider the following matrix:
1 1 1
1 1 1
1 1 1

How many rectangles does it contain? 1? 9? 4?
In your example, the two touching rectangles may as well be regarded as part of one larger rectangle.
Some advice: state your problem more clearly.


text:
Q: Why don't we use #!command for the shebang line? #!python3
print("Hello")

I find that this code works fine in my terminal. But everyone does #!/path/to/file or #!/usr/bin/env command.
Is there any reason to avoid using #!command in shebang lines?

A: A path-less shebang assumes that the command in the shebang is in the current directory, in the general case. More generically, a non-absolute shebang is interpreted relative to the current directory of the process executing the script.
Path-less shebangs where the command isn't in the current directory work only when the script is started from certain shells (Zsh at least, but not Bash), and it works because the shell helps out. When the script is run, execution fails, but the rule then is for the shell to try to run the script if it thinks it is a script; Zsh looks up shebang commands in its path, but that's not standard.
Scripts with path-less shebang commands won't work in any other context.
The idiomatic way to write a PATH-based shebang is to use /usr/bin/env, as you mention:
#! /usr/bin/env python3

or, with some versions of env,
#! /usr/bin/env -S python3 --

to avoid problems with paths to the script starting with dashes.


text:
Q: 404 error not found when debug = False in django multilanguages web app Hello I am making a multilanguages django web app,
When DEBUG = True => the multilanguages works fine means when i click on localhost:8000 it redirect me to localhost:8000/en or the last language I am puting anyway.
When DEBUG = FALSE => I enter to localhost:8000 it gives me an error of 404 not found,
here is my setting.py:
I am puting the '*' because I am testing if possible to work anyway I am testing all.
ALLOWED_HOSTS = ['localhost','localhost:8000','127.0.0.1','127.0.0.1:8000','*']
LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), )
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
  ('en', ('English')),
  ('ko', ('Korean')),
]

here is my urls.py
from django.conf.urls.i18n import i18n_patterns

urlpatterns = [
    path('i18n/', include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns (
    path('admin/', admin.site.urls),
    path('', include('app1.urls')),
    path('', include('app2.urls')),
)
handler404='app1.views.handle_not_found'

in my app1 urls.py
urlpatterns = [
     path('',views.index,name="index"),
]

in debug = False it doesn't work so it doesn't know the path of locahost:8000 only it knows only localhost:8000/en how can I do so whenever.

A: I don't know if this can help you but I had configured my translations this way on one of my Django projects:
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'fr'
TIME_ZONE = 'Europe/Paris'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
def gettext_noop(s):
    return s

LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
LANGUAGES = (
    ('fr', gettext_noop('French')),
    ('en', gettext_noop('English')),
    # ('es', gettext_noop('Spanish')),
    # ('it', gettext_noop('Italian')),
    # ('ar', gettext_noop('Arab')),
)

In my urls.py:
from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    path('admin/', admin.site.urls),
    path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]

This code is a bit dated but I hope it helps.


text:
Q: Git ignore mongod.log I tried several different combinations, but I was not able to exclude the mongodb log from git.
My gitignore:
mongodb/data/
mongodb/data/log/mongod.log
mongodb/data/**/*.log
/mongodb/data/**/*.log

None of them work. When I type

git status

I still get the following:

modified:   mongodb/data/log/mongod.log

How can I ignore this file?
The data under mongodb/data/db is ignored. I do not understand why the log file is constantly showing up again.

A: Once you have a file in the git tree, it's not enough to add it to the .gitignore file, as it still belongs to the tree and git will take care of.
The .gitignore file is intended to be used before you add files to the tree.
In your situation you have to remove the file from the tree with:
git rm path/to/file

You also will have to commit the deletion.
If you want to keep a copy where it is at the moment, move it to /tmp, issue a git status (it should be marked as deleted), make a commit and move it again to the original place.
I'd suggest to use the global git configuration for widely used common files that are likely to be ignored in other projects. You can check out this question: Global Git ignore


text:
Q: How to manually set a line number for end statement in algorithm2e? I can manually set line numbers in an algorithm2e environment using the \nlset command (together with \LinesNotNumbered). However, I can't figure out how to make the same for lines with the end or else statements, as in the following picture:

A: Here is a solution using

*

*A special if-then-else construct called \nlIf

*A wrapper macro \nlsetend redefining locally this \nlIf (to be called before it), to add the custom line number

\documentclass[margin=5mm]{standalone}
\usepackage{algorithm2e,amsmath}

\newcommand{\nlsetend}[1]{%
\SetKwIF{nlIf}{ElseIf}{Else}{if}{then}{else if}{else}{\nlset{#1}end}
}
\begin{document}
\begin{algorithm}[H]
    \eIf{$\hdots$}{
        \eIf{$rank \neq \hdots$}{
            send\;
            send\;
        }{
            $\hdots$
        }
    }{
        $\hdots$\;
    }
    \eIf{$\hdots$}{
        \nlsetend{test}
        \enlIf{$rank \neq \hdots$}{
            send\;
            send\;
            }{
                $\hdots$
                }
                }{
                    $\hdots$\;
    }

\end{algorithm}
\end{document}


text:
Q: How to display the latest called object on top? I'm creating a custom select plugin. Everything is going great, but the dropdowns (<ul>-objects) are overlapping on each other :(
I understand, that the overlapping order is set after the elements order on page or when they are created. So my question is: What is the method to make the latest opened/shown object (<ul>) on top of the hierarchy?
I just need the correct method. I'm not going to copy the full code, but a little example:
$('#trigger').click(function () {
    new_dropdown.slideDown();
});

(A picture is worth of 1000 words)

So lets say, that I open the green select the last.. How can I make it on top of the yellow one?
EDIT
For easier testing I created jsfiddle. For future references I'll post the link: http://jsfiddle.net/hobobne/uZV5p/1/ This is the live demo of the problem at hand.

A: What you're looking for is the CSS z-index property (higher values put elements at the front).
You could probably just set them in ascending order (e.g. set green one to 1000, yellow to 1001), but if you really need to bring it to the front when clicked, you can change the z-index with javascript
var zindex=100;

$("#trigger").click( function() {
    newdropdown.css('z-index', ++zindex);
});

Here's a demo: http://jsfiddle.net/waitinforatrain/Vf7Hu/ (click the red and blue divs to bring to front).
Edit: gilly3's approach is better, and as was mentioned there may be some issues with older versions of IE.

A: Two ways:
Set a z-index
Setting a z-index will change the default stacking order. You can have a counter that increments and use that to set the z-index of newly stacked items. You may have issues with IE 7 or earlier, though, and those can be fixed by setting the z-index of other items. https://developer.mozilla.org/en/Understanding_CSS_z-index/Adding_z-index
Use absolute positioning, and append the div to the body
If you use absolute positioning, you can append the div to the body and still have it appear below the element. If you append the div to the body, the one last added should be on top, because of the default stacking order.

A: Give it a class when it is opened, and remove that class from the previously opened ones:
$(".slidedown_active").removeClass("slidedown_active");
$(this).addClass(".slidedown_active");

Then your users can use z-index in their style definition for that class to ensure the active list is always visible.
The reason I don't recommend setting the z-index directly is because you can mess up your users' layout unnecessarily.  These kind of overlap issues can be a real headache for a web developer.  For a plugin to try to guess at how to resolve overlap issues, without any knowledge of the code or design, would be virtually impossible.  Instead, give your users the tools they need to fix the overlap issues themselves.  It may be that your users would never encounter overlap issues, so setting the z-index for them would be pointless at best, and potentially harmful.


text:
Q: THREEJS Shader Material overwritten I have a shader material that works as expected.
This shader has a texture attached.
I want to create 2 meshes using this shader material, with a different texture for each mesh.
Problem is that if I try to render my 2 meshes in the scene, the first object's material got overwritten somehow and uses the same material as the second object.
    var dataShader = VJS.shaders.data;
    var uniforms = dataShader.parameters.uniforms;
    // texture size (2048 for now)
    uniforms.uTextureSize.value = stack._textureSize;
    // array of 16 textures
    uniforms.uTextureContainer.value = textures;
    // texture dimensions
    uniforms.uDataDimensions.value = new THREE.Vector3(stack._columns, stack._rows, stack._nbFrames);
    // world to model
    uniforms.uWorldToData.value = stack._lps2IJK; //new THREE.Matrix4();

    var sliceMaterial = new THREE.ShaderMaterial({
      // 'wireframe': true,
      'side': THREE.DoubleSide,
      'transparency': true,
      'uniforms': uniforms,
      'vertexShader': dataShader.parameters.vertexShader,
      'fragmentShader': dataShader.parameters.fragmentShader,
    });

    var slice = new THREE.Mesh(sliceGeometry, sliceMaterial);
    // this is an Object3D that is added to the scene
    this.add(slice);

Does it make sense? Is it the expected behavior? If so, is there a good way to bypass this issue?
Thanks

A: You need to create two instances of the material, using the same shader, and assign the appropriate texture/uniforms for each.
edit
Copying uniforms is a bit tricky. You lose the reference i think when you clone the material, so you might want to be careful how you manage them.


text:
Q: What if I didn't turn off all caching under General Settings before deleting the plugin w3 total cache I installed the plugin W3 total cache but It crashed my website, so I had to delete it. The problem is that my site is still running. But I think I didn't delet it properly. I just renamed the folder of the plugin in the wp-content.
Another thing I did, I deleted the three files from the ftp : db.php, advanced-cache.php and object-cache.php
I didn't follow the instruction for delete the plugin and I didn't unchecked all options, disable and delete the plugin.
Is there any consequences and can I correct that?
Please help!

A: Usually renaming the folder does deactivate plugins as the folder is no longer detected. Some plugins however create files and database tables which will remain after this so you should always follow the recommended deactivation/uninstallation suggested by the developer. You can find a reply from the developer to a question similar to yours here - https://wordpress.org/support/topic/impossible-to-uninstall-completely/


text:
Q: Find the probability that Bob understands Alice correctly (detail below). Alice is trying to transmit to Bob the answer to a yes-no question, using a noisy channel. She encodes "yes" as 1 and "no" as 0, and sends the appropriate value. However, the channel adds noise; specifically, Bob receives what Alice sends plus N(0, σ2). If Bob receives a value greater than 0.5 he interprets it as "yes"; otherwise, he interprets it as "no".
I know that $$\frac{1}{2\pi} \int_{-\infty}^\infty e^\frac{-x^2}{2\sigma^4}$$
but I don't know where to go from there or how the value .5 plays a role here.


text:
Q: Running Homemade Operating System Starting out with an operating system you wrote, how could you run it and test it on a computer?  Would you have to delete the current operating system that is being used, or could you run one separately?

A: The easiest way to run or test new OS, whether or not it is home-made, without deleting current operating system would be to virtualize it. You can use free and commercial tools for that. Best known are VirtualBox (free), VMware Player (free), VMware Workstation (commercial), Windows Virtual PC and so on. You can find much more on Wikipedia Category:Virtualization software
Basically, you create a virtual hard disk image which behaves just like a new, blank hard drive. When you install operating system it is within that disk image entirely being totally isolated from your main operating system. Aside from testing and booting an operating system you can also test various programs within an isolated environment. There are many possibilities so I recommend you explore that area.

A: I used to use bosch for emulation back when I was playing around with OS development. IIRC I followed this tutorial:
http://linuxgazette.net/85/mahoney.html


text:
Q: How to extract a substring from a string in Python? Suppose I have a string , text2='C:\Users\Sony\Desktop\f.html', and I want to separate "C:\Users\Sony\Desktop" and "f.html" and store them in different variables then what should I do ? I tried out regular expressions but I wasn't successful.

A: os.path.split does what you want:
>>> import os
>>> help(os.path.split)
Help on function split in module ntpath:

split(p)
    Split a pathname.

    Return tuple (head, tail) where tail is everything after the final slash.
    Either part may be empty.

>>> os.path.split(r'c:\users\sony\desktop\f.html')
('c:\\users\\sony\\desktop', 'f.html')
>>> path,filename = os.path.split(r'c:\users\sony\desktop\f.html')
>>> path
'c:\\users\\sony\\desktop'
>>> filename
'f.html'


text:
Q: What is abstract attribute in a Django model? What's the purpose to define a Django model with abstract = True ?

A: abstract=True means this model is an abstract model class. It does not have a database table and is merely a shared parent model class so that the child models don't need to rewrite all the fields. Each child models will have their own table.
abstract=False means a normal model, django will create a table for it.


text:
Q: MYSQL - Combining two LEFT JOIN statements through UNION ALL but keeping the columns intact DB Structure
customer
---------
accountID
(other tuples not needed in this problem)

rental
-------
accountID
videoID

previousrental
-------
accountID
videoID

I am trying to write a query that shows accountID along with previous and current rentals.
I'd want the final table to show something along the lines of
| accountID |   videorented    |    videorentals  |
|-----------|------------------|------------------|
|   123     |       9987       |       NULL       |
|   123     |       9233       |       NULL       |
|   123     |       NULL       |       9987       |
|   101     |       9987       |       NULL       |
|   123     |       1589       |       NULL       |
|   123     |       NULL       |       8888       |
|   444     |       NULL       |       NULL       |

I came up with something along the lines of creating two left joins that that are able to correctly show the accountID along with which videos they have/are renting/rented and now I want to combine the two LEFT JOINS while keeping the single accountID column but also having videorented and videorentals as separate columns.
I've tried using UNION and UNION ALL but this just combines videorented and videorentals into one column
I'm currently lost as to where to go from here
SELECT c.accountID, pr.videoID as videorented
FROM customer c
LEFT JOIN previousrental pr
ON c.accountID=pr.accountID
UNION
SELECT c.accountID, r.videoID as videorentals
FROM customer c
LEFT JOIN rental r
ON c.accountID = r.accountID
;

A: You could left join to customer twice.
SELECT DISTINCT
  cust.accountID
, prev.videoID as videorented
, rent.videoID as videorentals
FROM customer cust
CROSS JOIN (SELECT 1 num UNION SELECT 2) nums
LEFT JOIN previousrental prev
  ON prev.accountID = cust.accountID  AND num = 1
LEFT JOIN rental rent
  ON rent.accountID = cust.accountID AND num = 2
ORDER BY cust. accountID, COALESCE(prev.videoID, rent.videoID)

accountID
videorented
videorentals

101
null
null

101
9987
null

123
1589
null

123
null
8888

123
9233
null

123
9987
null

123
null
9987

444
null
null

db<>fiddle here


text:
Q: How to test constructor that sets protected properties? Well, I'm new to unit-testing (with phpUnit) and just started to test one class of mine.
Actual constructor looks like this:
/**
 * Loads configuration.
 */
function __construct() {

    $config =
        Kohana::$config->load('koffee');

    $this->_table_name = $config->table_name;
    $this->_table_columns = $config->table_columns;

}

It basically gets configuration from another file and sets it as protected properties to that object.
Here is how unit-test looks (it's not finished and that's where I need help):
/**
 * Tests that config is loaded and correct.
 */
function testConfigIsLoadedAndCorrect() {

    $object = new Model_Article();

    $config = Kohana::$config->load('koffee');

    // Compare object's **protected** properties to local `$config`. How?!

}

The problem is that properties are protected and I cannot access them so easy...
Possible solutions I see at the moment:

*

*Change visibility of properties (I don't like this),

*Add, so called, "getters" to class I test - not unit-test (I don't like this neither);

Probably this is funny to you, but, as I said, I'm new to unit-tests. Any help much appreciated.

A: Unit-testing is about unit testing. Protected members are not part of the public interface of a unit, which is all you should need to care about when writing unit tests.
You don't test the inner guts of a unit, but that it works as expected.
If you regardless of that want to do such stuff, you can use SerializationDocs, casting to array and ReflectionDocs to inspect protected/private properties of an object or to execute protected/private methods of an object.

See as well: PhpUnit private method testingSO Q&A

A: A technique I've used in the past has been to create a Tester class that exposes the appropriate methods to test the object. In this case, Model_Article_Tester would inherit Model_Article and expose a get method. The benefit here is you expose what you need for tests without affecting production code.

A: You could create a subclass that does expose the data you need and only use it for unit testing.
You could also test the behavior of the class rather than the data. The Model_Article must do something with the table_name and table_columns so test that behavior. For example, if the Model_Article is used to create an html table, then you could set the config values, create the Model_Article, use it to create the html, then assert that it matches a hard coded string like

col1	col2newInstanceWithoutConstructor();


text:
Q: docker-compose + traefik - direct traffic to services outside the docker-compose network I apologize in advance for the length - but this is interesting, especially for architects and traefik wizards.
The Challange:
The bottom line is, I'm hoping that there's a setup in which we can leverage traefiks dynamic config capability to:
detect automatically when a container is stopped, and know to fallback to external services on developer machine / external host.
Alternatively - when a local-db container is started, know to prefer it over db service from external source.
The full picture
I need to optimize a workflow for a couple of teams.
The constraints:

*

*developers work on a multi-layer complex micro-service mesh

*number of services in the mesh is ~50, some of which are memory-intensive

*local demos & acceptance tests requires to show the whole mesh works from end-user point of view

*developers are now asked to run all the mesh locally, except for some shared databases with live data replicas - which may occasionally also be run locally instead.

This requires to run on developer machine the absolute minimum required.
Current solution relays on docker-compose and traefik@1.x, and I'm asked to preserve this, however, I believe upgrading to traefik@2.x would be accepted.
Pursued Use Cases
I'm actually pursuing with you here two use-cases, which I believe have the same solution - at least in theory...
Use-Case one - local dev of multiple micro-services
Dev-Mode = running a process in debug mode, with IDE, file-watch live reloads, etc.

AS A    - developer of services in mid layers of the service mesh
I WANT  - to be able to direct traffic to services under development to
          native processes on my machine, and keep the rest in the compose
          network
SO THAT - I can run in Dev-Mode only services under development,
          while all the rest in the mesh run using production-level docker
          images in docker-compose.

Use-Case two - local dev and external database
AS A    - developer of data brokers in the mesh
I WANT  - to control if containers get to the shared db or to local
          db container using traefik
SO THAT - I can keep applications in the containers completely agnostic to
          the topography in which they run

So what's missing?
As a start - Since Traefik is the service-buss through which all inter-container communications pass - I'm looking for a way to configure traefik to consume services from outside the docker-compose network.
The first use-case means to use traefik as the service buss - the sole entity that knows where each service runs, which could be a container, or a service external to the docker-compose network.
The second use-case means to setup traefik to direct traffic to a process runs outside the docker-compose network, but specifically on the developer's machine, which in turn, consumes services from the compose network (for this, the dev compose, unlike production compose - exposes an entrypoint for each node in the mesh, including for services that are consumed only internally on production).
Two for the price of one
I know there are two questions here, but I could not think of another way to ask each question separately and get answers relevant to the full picture...
I'm hoping that there's a setup in which we can leverage traefiks dynamic config capability to:

detect automatically when a container is stopped, and know to fallback to external services on developer machine or any other host for the matter.
Alternatively - when a db container is started, knows to prefer it over external db service.

We can ask developers to add records to their hosts file, but a DNS-based solution would be much preferred, especially if we can use the DNS built-in to docker :)
Help ?
Any help or point to the right direction would be very appreciated!

A: I've done it.
Check out the solution in isolation demonstrated here:
https://github.com/osher/lcdev-using-compose-and-traefik
TL;DR:

*

*the developer host machine is present inside the docker-compose network as host.docker.internal.

*file provider provides services and routes for each service the team maintains.
routes in file provider are set to low priority.

*docker provider provides services and routes for each docker-compose container.
routes created this way are set to high priority.

The result:

*

*when the container is present - it's used.

*when the container is stopped - traefik will try the developer machine.


text:
Q: Displaying same image multiple times at different locations in a web page using JavaScript I have a simple web page with a simple puzzle. There are some images that user is supposed to drag to their designated drop zones. I use solution in JavaScript generated by DreamWeaver.
I want to add a JavaScript function that will show a correct.png or wrong.png image next to the image a user just dropped. The straightforward way to do it is to just have correct and wrong div elements for each of the draggable images. But is there a more elegant way?
Another way to put it would be:Write a JavaScript functions Show(commonImageId, nextToImageId) and Hide(commonImageId, nextToImageId) that would be used like Show('correct', 'draggable1');.

A: Instead of having multiple divs that you show and hide, you can try this solution as well.
Create two styles, each with a different background image set.  Whenever you trap the event that a given image should be marked as correct or wrong, simply swap the style of the div, which will have the affect of switching the background image.
Very quick (and in need of some cleanup) sample code below, you've got the right idea with setting the type with a function...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<title>Image Swap</title>

Item 1

Item 2