text:
Q: biblatex (authoryear-ibid) InCollection with editors between main title and booktitle with "in:" I would like to have the InCollection (also: InProceedings) source type to be changed up.
So I would like to have

*

*main title

*an "in:" behind the (main) source title

*the editor name after said source title

*then an ":"

*booktitle
All the rest is good to go and should not be changed please.
An example of what it should be like is here:

Brandt, A. von/Hoffmann, E. (1987):
  Die nordischen Länder von der Mitte des 11. Jahrhunderts bis 1448, in: Seibt, F./Smith, J. (editors): Europa im Hoch und
  Spätmittelalter, no. 2, 4th ed., Klett-Cotta, Stuttgart, pp. 884–917.

The status quo, produced by the MWE, looks like this currently:

Brandt, A. von/Hoffmann, E. (1987):
  Die nordischen Länder von der Mitte des 11. Jahrhunderts bis 1448, in: Europa im Hochund
  Spätmittelalter, Seibt, F./Smith, J. (editors), no. 2, 4th ed., Klett-Cotta, Stuttgart,
  pp. 884–917.

MWE
\documentclass[
a4paper
]
{scrreprt}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{lmodern}
\renewcommand{\familydefault}{\sfdefault}

\usepackage[
language=auto,
style=authoryear-ibid,
backend=bibtex,
hyperref=true,
isbn=false,
doi=false,
citereset=chapter,
maxcitenames=3,
dashed=false,
sorting=nyt,
firstinits=true,
ibidtracker=true,
maxbibnames=99
]{biblatex}
\usepackage{xpatch}

%% comma after every item for bibiliography entries
\renewcommand*{\newunitpunct}{\addcomma\space}

%%  parentheses around year in references
\renewbibmacro*{cite:labelyear+extrayear}{%
\iffieldundef{labelyear}
{}
{%
\printtext[bibhyperref]{%
\printtext[parens]{%
\printfield{labelyear}%
\printfield{extrayear}}}}}

%% correct order of publisher and location
\renewbibmacro*{publisher+location+date}{%
\newunit
\printlist{publisher}%
\newunit
\printlist{location}%
\newunit}

%%  right order of words 'volume' und 'issue' with comma in front
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\renewbibmacro*{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\addspace}%
  \iffieldundef{series}
    {}
    {\newunit
     \printfield{series}%
     \setunit{\addspace}}%
  \usebibmacro{volume+number+eid}
  \setunit{\addcomma\space}% THIS LINE CHANGED to add comma
  \usebibmacro{issue+date}%
  \setunit{\addcolon\space}%
  \usebibmacro{issue}%
  \newunit}

%taken from standard.bbx
\renewbibmacro*{issue+date}{%
  \printtext{%   REMOVED parenthesis here
    \iffieldundef{issue}
      {\usebibmacro{date}}
      {\printfield{issue}%
       \setunit*{\addspace}%
       \usebibmacro{date}}}%
  \newunit}

%% bold bibliography "label" followed by colon and linebreak
\renewbibmacro*{begentry}{\mkbibbold\bgroup}
\xapptobibmacro{date+extrayear}{\addcolon\egroup}{}{}
\renewcommand*{\labelnamepunct}{\par\nobreak}

%% linebreak before URLs and colon before date of last visit
\xpretobibmacro{url+urldate}{\setunit{\newunitpunct\par\nobreak}}{}{}
\DefineBibliographyStrings{english}{%
urlseen = {last visit\addcolon}
}

%% colon before date of last visit
\DeclareFieldFormat{urldate}{\mkbibparens{\bibstring{urlseen}\addcolon\space#1}}

%% no indent
\setlength{\bibhang}{0pt}

%% one empty line between to bib-entries
\setlength{\bibitemsep}{\baselineskip} %% \baselineskip gibt hier an, dass Zeilenabstand unterhalb des Absatzes der dokumentweite Abstand ist

%% ``(editor)'' or ``(editors)''
\renewbibmacro*{byeditor+others}{%
  \ifnameundef{editor}
    {}
    {\printnames[byeditor]{editor}%
     \setunit{\addspace}%
     \usebibmacro{byeditor+othersstrg}%
     \clearname{editor}%
     \newunit}%
  \usebibmacro{byeditorx}%
  \usebibmacro{bytranslator+others}}
\xpatchbibmacro{byeditor+othersstrg}{\printtext}{\printtext[parens]}{}{}

%%  ``(editor)'' or ``(editors)'' instead of ``(ed. by)''
\DefineBibliographyStrings{english}{%
byeditor = {editor},%
byeditor = {editors},%
issue  = {\lowercase{i}ss\adddot},%
}

%% edition behind series number ("no.")
\AtEveryBibitem{%
  \iffieldequalstr{edition}{1}
    {\clearfield{edition}}
    {\savefield*{edition}{\savededition}%
     \clearfield{edition}}}

\renewbibmacro*{series+number}{%
  \restorefield{edition}{\savededition}
  \printfield{series}%
  \setunit*{\addspace}%
  \printfield{number}%
  \setunit{\addcomma\space}%
  \printfield{edition}%
  \newunit}

%% all titles in references in normal formatting
\DeclareFieldFormat*{citetitle}{#1\isdot}

%% annul format of any (main) title in bibliography and add comma+space
\DeclareFieldFormat*{title}{#1\addcomma\addspace}

%% annul format of any other (parent) titles in bibliography
\DeclareFieldFormat*{booktitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{journaltitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{issuetitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{maintitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{proceedingstitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{collectiontitle}{#1\addcomma\addspace}
%new
\DeclareFieldFormat*{volume}{\bibstring{volume}~#1\space}
\DeclareFieldFormat*{issue}{\bibstring{issue}~#1}
\DeclareFieldFormat*{number}{\bibstring{number}~#1} %comment to leave number as before
\DeclareFieldFormat*{series}{{#1}\addcomma\space} %comment to leave number as before

%% Names: Lastname, Firstname
\DeclareNameAlias{default}{last-first}
\DeclareNameAlias{sortname}{last-first}

\AtBeginBibliography{%
    %% only slash signs between names
    \renewcommand{\multinamedelim}{\addslash}
    \renewcommand{\finalnamedelim}{\addslash}
    %% only slash signs between multiple locations
    \renewcommand{\multilistdelim}{\addslash}
    \renewcommand{\finallistdelim}{\addslash}
}

\begin{filecontents*}{lit.bib}
@InCollection{brandt,
  options     = {useprefix=false},
  hyphenation     = {german},
  author      = {von Brandt, Ahasver and Hoffmann, Erich},
  editor      = {Seibt, Ferdinand and Smith, John},
  title       = {Die nordischen L{\"a}nder von der Mitte des 11.~Jahrhunderts bis 1448},
  booktitle  = {Europa im Hoch- und Sp{\"a}tmittelalter},
  number      = {2},
    edition = {4},
  publisher   = {Klett-Cotta},
  location    = {Stuttgart},
  date        = {1987},
  pages       = {884--917}
}
\end{filecontents*}
\addbibresource{lit.bib}

\begin{document}
\begin{itemize}
    \item Place holder for \verb+InCollection+.\footcite[See][p. 5--11]{brandt}
\end{itemize}

\printbibliography
\end{document}

A: I made an attempt on my own and it seems to work so far.

*

*I took the definition of {maintitle+booktitle} from the file standard.bbx and simply copy and pasted it as \renewbibmacro*{maintitle+booktitle}

*I commented out \usebibmacro{booktitle}% from said code bit

*I then added
\setunit{\addcolon\space}
\usebibmacro{booktitle}

to the already included redefinition of {byeditor+others} (see MWE above or below), which resulted in:
\documentclass[12pt,
a4paper
]
{scrreprt}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{lmodern}
\renewcommand{\familydefault}{\sfdefault}

\usepackage[
language=auto,
style=authoryear-ibid,
backend=bibtex,
hyperref=true,
isbn=false,
dashed=false,
doi=false,
citereset=chapter,
maxcitenames=3,
sorting=nyt,
firstinits=true,
ibidtracker=true,
maxbibnames=99
]{biblatex}
\usepackage{xpatch}

%% comma after every item for bibiliography entries
\renewcommand*{\newunitpunct}{\addcomma\space}

%%  parentheses around year in references
\renewbibmacro*{cite:labelyear+extrayear}{%
\iffieldundef{labelyear}
{}
{%
\printtext[bibhyperref]{%
\printtext[parens]{%
\printfield{labelyear}%
\printfield{extrayear}}}}}

%% correct order of publisher and location
\renewbibmacro*{publisher+location+date}{%
\newunit
\printlist{publisher}%
\newunit
\printlist{location}%
\newunit}

%%  right order of words 'volume' und 'issue' with comma in front
\renewbibmacro*{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\addspace}%
  \iffieldundef{series}
    {}
    {\newunit
     \printfield{series}%
     \setunit{\addspace}}%
  \usebibmacro{volume+number+eid}
  \setunit{\addcomma\space}% THIS LINE CHANGED to add comma
  \usebibmacro{issue+date}%
  \setunit{\addcolon\space}%
  \usebibmacro{issue}%
  \newunit}
%taken from standard.bbx
\renewbibmacro*{issue+date}{%
  \printtext{%   REMOVED parenthesis here
    \iffieldundef{issue}
      {\usebibmacro{date}}
      {\printfield{issue}%
       \setunit*{\addspace}%
       \usebibmacro{date}}}%
  \newunit}

%% booktitle after editors
\renewbibmacro*{maintitle+booktitle}{%
  \iffieldundef{maintitle}
    {}
    {\usebibmacro{maintitle}%
     \newunit\newblock
     \iffieldundef{volume}
       {}
       {\printfield{volume}%
        \printfield{part}%
        \setunit{\addcolon\space}}}%
  %\usebibmacro{booktitle}%
  \newunit}

%% bold bibliography "label" followed by colon and linebreak
\renewbibmacro*{begentry}{\mkbibbold\bgroup}
\xapptobibmacro{date+extrayear}{\addcolon\egroup}{}{}
\renewcommand*{\labelnamepunct}{\par\nobreak}

%% linebreak before URLs and colon before date of last visit
\xpretobibmacro{url+urldate}{\setunit{\newunitpunct\par\nobreak}}{}{}
\DefineBibliographyStrings{english}{%
urlseen = {last visit\addcolon}
}

%% colon before date of last visit
\DeclareFieldFormat{urldate}{\mkbibparens{\bibstring{urlseen}\addcolon\space#1}}

%% no indent
\setlength{\bibhang}{0pt}

%% one empty line between to bib-entries
\setlength{\bibitemsep}{\baselineskip} %% \baselineskip gibt hier an, dass Zeilenabstand unterhalb des Absatzes der dokumentweite Abstand ist

%% ``(editor)'' or ``(editors)''
\renewbibmacro*{byeditor+others}{%
  \ifnameundef{editor}
    {}
    {\printnames[byeditor]{editor}%
     \setunit{\addspace}%
     \usebibmacro{byeditor+othersstrg}%
     \clearname{editor}%
     \newunit}%
  \usebibmacro{byeditorx}%
  \usebibmacro{bytranslator+others}
    \setunit{\addcolon\space}
    \usebibmacro{booktitle}}
\xpatchbibmacro{byeditor+othersstrg}{\printtext}{\printtext[parens]}{}{}

%%  ``(editor)'' or ``(editors)'' instead of ``(ed. by)''
\DefineBibliographyStrings{english}{%
byeditor = {editor},%
byeditor = {editors},%
issue  = {\lowercase{i}ss\adddot},%
}

%% edition behind number (no.)
\AtEveryBibitem{%
  \iffieldequalstr{edition}{1}
    {\clearfield{edition}}
    {\savefield*{edition}{\savededition}%
     \clearfield{edition}}}
\renewbibmacro*{series+number}{%
  \restorefield{edition}{\savededition}
  \printfield{series}%
  \setunit*{\addspace}%
  \printfield{number}%
  \setunit{\addcomma\space}%
  \printfield{edition}%
  \newunit}

%% all titles in references in normal formatting
\DeclareFieldFormat*{citetitle}{#1\isdot}

%% annul format of any (main) title in bibliography and add comma+space
\DeclareFieldFormat*{title}{#1\addcomma\addspace}

%% annul format of any other (parent) titles in bibliography
\DeclareFieldFormat*{booktitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{journaltitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{issuetitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{maintitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{proceedingstitle}{#1\addcomma\addspace}
\DeclareFieldFormat*{collectiontitle}{#1\addcomma\addspace}
%new
\DeclareFieldFormat*{volume}{\bibstring{volume}~#1\space}
\DeclareFieldFormat*{issue}{\bibstring{issue}~#1}
\DeclareFieldFormat*{number}{\bibstring{number}~#1} %comment to leave number as before
\DeclareFieldFormat*{series}{{#1}\addcomma\space} %comment to leave number as before

%% Names: Lastname, Firstname
\DeclareNameAlias{default}{last-first}
\DeclareNameAlias{sortname}{last-first}

\AtBeginBibliography{%
    %% only slash signs between names
    \renewcommand{\multinamedelim}{\addslash}
    \renewcommand{\finalnamedelim}{\addslash}
    %% only slash signs between multiple locations
    \renewcommand{\multilistdelim}{\addslash}
    \renewcommand{\finallistdelim}{\addslash}
}

\begin{filecontents*}{lit.bib}
@InCollection{brandt,
  options     = {useprefix=false},
  hyphenation     = {german},
  author      = {von Brandt, Ahasver and Hoffmann, Erich},
  editor      = {Seibt, Ferdinand and Smith, John},
  title       = {Die nordischen L{\"a}nder von der Mitte des 11.~Jahrhunderts bis 1448},
  booktitle  = {Europa im Hoch- und Sp{\"a}tmittelalter},
  number      = {2},
    edition = {4},
  publisher   = {Klett-Cotta},
  location    = {Stuttgart},
  date        = {1987},
  pages       = {884--917}
}
\end{filecontents*}
\addbibresource{lit.bib}

\begin{document}
\begin{itemize}
    \item Place holder for \verb+InCollection+.\footcite[See][p. 5--11]{brandt}
\end{itemize}

\printbibliography
\end{document}


text:
Q: Smartly replace strings I am working with JSON API. As c# doesn't accept characters like - (minus) or . (point), I had to replace each character by _ (underscore). The replacement happens when the JSON response is received as a string so that every attribute name containing a - or a . will have it replaced by a _ , then every attribute name will be the same as the attributes names in the class it will be deserialized into.
To make it clearer, here are some examples:
I recieve the following JSON : { "id": 1, "result": [ { "data": [ { "adm-pass": ""}]}
In the class I want to deserialize into I have this attribute : public String adm_pass {get; set;}
So I replace the minus with an underscore so that the NewtonSoft parser can deserialize it accordingly.
My problem is that I sometimes I get some negative integers in my JSON. So if I do the string replacement in: {"beta" : -1}, I get a parsing exception since the -1 (integer here) becomes _1 and cannot be deserialized properly and raises an exception.
Is there a way to replace the string smartly so I can avoid this error?
For example if - is followed by an int it's not replaced.
If this way does not exist, is there a solution for this kind of problems?

A: Newtonsoft allows you to specify the exact name of the JSON property, which it will use to serialize/deserialize.
So you should be able to do this
[JsonProperty("adm-pass")]
public String adm_pass { get; set; }

This way you are not restricted to name your properties exactly as the JSON property names. And in your case, you won't need to do a string replace.
Hope this helps.

A: You'll have to check that you are replacing the key and not the value, maybe by using a regex like http://regexr.com/3d471

A: Regex could work as wlalele suggests.
But I would create a new object like this:

*

*Create a new object:
var sharpObj = {};

*loop through the objects as properties as described here:
Iterate through object properties
for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

*In the // do stuff section, create a property on sharpObj with the desired string replacements and set the property to the same value.
var cleanProperty = cleanPropertyName(property);
sharpObj[cleanProperty] = orginalObject[property];

Note: I assume you can figure out the cleanPropertyName() method or similar.

*Stringify the object
var string = JSON.stringify(sharpObj);

A: You can substring to check whether the next character is an integer, this can adapt into your code easily as you already find a character, as such you could do
int a;

if(int.TryParse(adm_pass.Substring(adm_pass.IndexOf("-") + 1,1),out a))
{
    //Code if next character is an int
}
else
{
    adm_pass = adm_pass.Replace("-","_");
}

This kind of code can be looped until there are no remaining hyphens/minuses

redpajama_set_name: RedPajamaStackExchange


text:
Q: delayed_job passing instance methods & variables? I have a problem with getting application data from outside of self.method.
To useModel.delay.method, the method has to be a class one.
I really like that, it does all I need (like saving input parameters when calling method), but what I need to do is get variables from outside of method.
For example:
User clicks button and starts the timer.
QuizzesController.delay(run_at: @quiz.time_limit.minutes.from_now).form_timeout(session[:user_id],session[:test_password])

Method form_timeout looks like this:
def self.form_timeout(id, test_password)
  if test_password == session[:test_password]
    Score.create(user_id: id, name: test_password, points: -1)
    session.delete(:test_password)
  end
end

When I try to do that, I get an error "undefined method session" which means that I cannot reach that data when using self.method.
Any idea how to bypass that and let session[:test_password] (session has to pass most up-to-date information, because I compare session[:test_password] from time when timer has started (old one) and from time when it ends(new one)) like i did in self.method?

A:
Any idea how to bypass that and let session[:test_password]...

Nope, no way of doing that. session is not a simple instance methods. It gets data from cookies (by default). And cookies are inaccessible in a background worker context.
Rule of thumb for background workers is: delayed method must receive all data it needs in its parameters.


text:
Q: Collision detection between two general hexahedrons I have 2 six faced solids. The only guarantee is that they each have 8 vertex3f's (verticies with x,y and z components). Given this, how can I find out if these are colliding?

A: I'm hesitant to answer after you deleted your last question while I was trying to answer it and made me lose my post. Please don't do that again. Anyway:
Not necessarily optimal, but obviously correct, based on constructive solid geometry:

*

*Represent the two solids each as an intersection of 6 half-spaces. Note that this depends on convexity but nothing else, and extends to solids with more sides. My preferred representation for halfspaces is to choose a point on each surface (for example, a vertex) and the outward-pointing unit normal vector to that surface.

*Intersect the two solids by treating all 12 half-spaces as the defining half-spaces for a new solid. (This step is purely conceptual and might not involve any actual code.)

*Compute the surface/edge representation of the new solid and check that it's non-empty. One approach to doing this is to initially populate your surface/edge representation with one surface for each of the 12 half-spaces with edges outside the bounds of the 2 solids, then intersect its edges with each of the remaining 11 half-spaces.

It sounds like a bit of work, but there's nothing complicated. Only dot products, cross products (to get the initial representation), and projections.

A: It seems I'm too dumb to quit.
Consider this. If any edge of solid 1 intersects any face of solid 2, you have a collision. That's not quite comprehensive because there are case when one is is fully contained in the other, which you can test by determining if the center of either is contained in the other.

Checking edge face intersection works like this.

*

*Define the edge as vector starting from one vertex running to the other. Take note of the length, L, of the edge.

*Define the plane segments by a vertex, a normal, an in-plane basis, and the positions of the remaining vertices in that basis.

*Find the intersection of the line and the plane. In the usual formulation you will be able to get both the length along the line, and the in-plane coordinates of the intersection in the basis that you have chosen.

*The intersection must line as length [0,L], and must lie inside the figure in the plane. That last part is a little harder, but has a well known general solution.

This will work. For eloquence, I rather prefer R..'s solution. If you need speed...well, you'll just have to try them and see.

A: Suppose one of your hexahedrons H1 has vertices (x_1, y_1, z_1), (x_2, y_2, z_2), .... Find the maximum and minimum in each coordinate: x_min = min(x_1, x_2, ...), x_max = max(x_1, x_2,...), and so on. Do the same for the other hexahedron H2.
If the interval [x_min(H1), x_max(H1)] and the interval [x_min(H2), x_max(H2)] do not intersect (that is, either x_max(H1) < x_min(H2) or x_max(H2) < x_min(H1)), then the hexahedrons cannot possibly collide. Repeat this for the y and z coordinates. Qualitatively, this is like looking at the shadow of each hexahedron on the x-axis. If they don't overlap, the polyhedrons can't collide.
If any of the intervals do overlap, you'll have to move on to more precise collision detection. This will be a lot trickier. The obvious brute force method is to check if any of the edges of one intersects any of the faces of the other, but I imagine you can do a lot better than that.
The brute force way to check if an edge intersects a face... First you'd find the intersection of the line defined by the edge with the plane defined by the face (see wikipedia, for example). Then you have to check if that point is actually on the edge and the face. The edge is easy - just see if the coordinates are between the coordinates of the two vertices defining the edge. The face is trickier, especially with no guarantees about it being convex. In the general case, you'll have to just see which side of the half-planes defined by each edge it's on. If it's on the inside half-plane for all of them, it's inside the face. I unfortunately don't have time to type that all up now, but I bet googling could aid you some there. But of course, this is all brute force, and there may be a better way. (And dmckee points out a special case that this doesn't handle)


text:
Q: How can I see exactly where in a string and how many times something appears in a list Let's say I have a list: x = [1, 2, 4, 4, 6, 7]
What can I do to get an output that tells me that 4 appears in x[2] and x[3]?

A: I'm not aware of any built-in functions that can accomplish this, but certainly it can be done with a list comprehension:
indices = [i for i, num in enumerate(x) if num == 4]

A: import numpy as np
x = np.array([1, 2, 4, 4, 6, 7])

print(x == 4)

You can use a numpy array to check the list. If the value is 4, it will show the indices that are 'True', meaning the value of that index is 4. This can work for large lists, and it will return the True/False values.
Here is the output:
[False False  True  True False False]

As you can see, index 2 and 3 return True.

A: You can create a dict and capture the index no :
x = [1, 2, 4, 4, 6, 7]

def place_(value_,list_):
    d={}
    for i,j in enumerate(list_):
        if j==value_:
            if j not in d:
                d[j]=[i]
            else:
                d[j].append(i)
    return d

print(place_(4,x))

output:
{4: [2, 3]}


text:
Q: Is there an operator for appending to a string variable in ASP? What's the ASP equivalent to PHP's .= when concatenating strings? I'm referring to asp NOT asp.net.
I meant to specify that I'm in a for-loop. So I want to know the equivalent for .= (in php) not standard concatenation.
Example:
For Each Item In Request.Form
    If (Item = "service") then
        For x=1 To Request.Form(item).Count
            service = "&service="&Request.Form(Item)(x)
        Next
    End If
Next

A: In VBScript:
Variable = Variable & "something more"

In JScript I believe you can use:
variable += "something more";

Specifically:
service = service & "&service=" & Request.Form(Item)(x)

assuming you want your result to look something like...
&service=blah1&service=blah2&service=blah3

Though you may need to URL encode your Request.Form(Item)(x) values because any "&" (and other characters) could really muck up what you are trying to do.  Also be careful when using unsanitized input like this directly from an HTML form, its very dangerous.

A: I can't remember for certain, but &= should work in ASP.  I know it works in VB.Net.  Although I can't recall if that worked in asp.  If that doesn't work, the only solution is a = a & b.


text:
Q: Detect if web app is running as PWA through the Microsoft Store I submitted a PWA to the Microsoft Store and got the following notes on my submission:

10.8.5
  Your app or app metadata includes links that promote installation or
  purchase of software outside the Store.
  Your app may promote or distribute software only through the Microsoft Store.

The reason for this is that my web app has a products page with links to the various platforms the app is available on. This is so that users visiting my web app using a browser get the ability to install it as "native" app on their platform rather.
How can I detect if my web app is running as PWA through the Microsoft Store, so that I can render a trimmed version of my app without the products page?
My first idea would be to check the navigator.userAgent, but this seems ambiguous, since the user agent will be Microsoft Edge whether the app is running "natively" or is visited manually in the browser.
I'd prefer solutions for distinguishing these use cases in JavaScript, but I'm also open for completely different approaches.

A: The correct official way is to check for window.Windows. The whole WinRT API surface is injected when running as a Store app. So, you can (and should) do the following rather than user-agent sniffing:
if (window.Windows) {
  // running as a Windows app
}
else {
  // running in browser
}

A: I realized that the user agent wasn't so ambiguous after all.
Microsoft Edge does indicate when it is running as an app host by adding MSAppHost/<WebView Rev> to its user agent.
Example:
On my machine, the user agent of my hosted PWA lists "MSAppHost/3.0":
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; MSAppHost/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063

Solution:
Testing navigator.userAgent for the string MSAppHost/ discloses if the web app is running as an hosted app.
I'm using this check now for my server-side and client-side rendering to strip any content linking to external stores.

A: You can check document.referrer. If it equals to "app-info://platform/microsoft-store", your Web app was installed from Microsoft Store. This feature was first introduced in Edge version 91.


text:
Q: Why aren't my processes running concurrently? My questions are:
1.) How can I get the parent process to always die last? I get that this isn't being accomplished because the parent is the first pid that gets ran, but I don't know how to change it.
2.) How do I get my child processes to execute at the same time like his? I've even bumped the number up really high to see if it was just a coincidence, but it appears to not be.
EDIT: SOLUTIONS
1.) added wait(NULL) twice in inner Default
2.) was happening. used sleep(1) to prove it.
My code is as follows
#include <stdio.h>
int main() {
    int pid, i;
    pid = fork();
    switch(pid) {
        case -1:
            // error
            printf("Fork error");
            break;
        case 0:
            // child process
            printf("First child is born, my pid is %d\n", getpid());
            for(i=1; i<10; i++)
                printf("First child executes iteration %d\n", i);
            printf("First child dies quietly.\n");
            break;
        default:
            // parent process
            printf("Parent process is born, my pid is %d\n", getpid());
            pid = fork();
            switch(pid) {
                case -1:
                    // error
                    printf("Fork error");
                    break;
                case 0:
                    // child process
                    printf("Second child is born, my pid is %d\n", getpid());
                    for(i=1; i<10; i++)
                        printf("Second child executes iteration %d\n", i);
                    printf("Second child dies quietly.\n");
                    break;
                default:
                    // parent process
                    printf("Parent process dies quietly.");
        }
    }
    return 0;
}

My output always looks like this:

Parent process is born, my pid is 7847
First child is born, my pid is 7848
First child executes iteration: 1
First child executes iteration: 2
First child executes iteration: 3
First child executes iteration: 4
First child executes iteration: 5
First child executes iteration: 6
First child executes iteration: 7
First child executes iteration: 8
First child executes iteration: 9
First child executes iteration: 10
First child dies quietly.
Parent process dies quietly.
Second child is born, my pid is 7849
Second child executes iteration 1
Second child executes iteration 2
Second child executes iteration 3
Second child executes iteration 4
Second child executes iteration 5
Second child executes iteration 6
Second child executes iteration 7
Second child executes iteration 8
Second child executes iteration 9
Second child executes iteration 10
Second child dies quietly.

My assignment is:
Write a C program ("procs.c") that creates three processes: a parent process that creates two child processes.
The first child should do the following:

*

*display "First child is born, my pid is ..."

*display ten times the message "First child executes iteration X", where X is the number of the iteration

*display "First child dies quietly."
The second child should do the following:

*

*display "Second child is born, my pid is ..."

*display ten times the message "Second child executes iteration X", where X is the number of the iteration

*display "Second child dies quietly."
The parent process should do the following:

*

*display "Parent process is born, my pid is ..."

*create the first child

*create the second child

*display "Parent process dies quietly."
Compile the program using gcc and name the executable "procs". Execute the program several times and notice how the output of the two children interlace.
A possible output of this program is:

nova> ./procs

Parent process is born, my pid is 7847
First child is born, my pid is 7848
First child executes iteration: 1
First child executes iteration: 2
First child executes iteration: 3
First child executes iteration: 4
First child executes iteration: 5
Second child is born, my pid is 7849
Second child executes iteration 1
Second child executes iteration 2
Second child executes iteration 3
First child executes iteration: 6
Second child executes iteration 4
Second child executes iteration 5
Second child executes iteration 6
First child executes iteration: 7
Second child executes iteration 7
Second child executes iteration 8
Second child executes iteration 9
Second child executes iteration 10
Second child dies quietly.
First child executes iteration: 8
First child executes iteration: 9
First child executes iteration: 10
First child dies quietly.
Parent process dies quietly.

A: *

*The appropriate parent process should wait (using wait() or waitpid() or a platform-specific variant) for its children to die before exiting.

*Concurrent execution requires the scheduler to get a chance to run.  You can force the issue with appropriate sleep (micro-sleep, nano-sleep) operations.  Some system calls will help (so fflush(0) might help).

#include <stdio.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

int main(void)
{
    int pid, i;
    struct timespec tw = { .tv_sec = 0, .tv_nsec = 10000000 };
    pid = fork();
    switch(pid)
    {
        case -1:
            printf("Fork error");
            break;
        case 0:
            printf("First child is born, my pid is %d\n", getpid());
            for(i=1; i<10; i++)
            {
                printf("First child executes iteration %d\n", i);
                nanosleep(&tw, 0);
            }
            printf("First child dies quietly.\n");
            break;
        default:
            printf("Parent process is born, my pid is %d\n", getpid());
            pid = fork();
            switch(pid)
            {
                case -1:
                    printf("Fork error");
                    break;
                case 0:
                    printf("Second child is born, my pid is %d\n", getpid());
                    for(i=1; i<10; i++)
                    {
                        printf("Second child executes iteration %d\n", i);
                        nanosleep(&tw, 0);
                    }
                    printf("Second child dies quietly.\n");
                    break;
                default:
                    printf("Parent process waiting for children.\n");
                    int corpse;
                    int status;
                    while ((corpse = waitpid(0, &status, 0)) > 0)
                        printf("Child %d died with exit status 0x%.4X\n", corpse, status);
                    printf("Parent process dies quietly.\n");
                    break;
            }
    }
    return 0;
}

Example output:
Parent process is born, my pid is 46624
First child is born, my pid is 46625
First child executes iteration 1
Parent process waiting for children.
Second child is born, my pid is 46626
Second child executes iteration 1
First child executes iteration 2
Second child executes iteration 2
First child executes iteration 3
Second child executes iteration 3
First child executes iteration 4
Second child executes iteration 4
Second child executes iteration 5
First child executes iteration 5
Second child executes iteration 6
First child executes iteration 6
Second child executes iteration 7
First child executes iteration 7
Second child executes iteration 8
First child executes iteration 8
Second child executes iteration 9
First child executes iteration 9
First child dies quietly.
Second child dies quietly.
Child 46625 died with exit status 0x0000
Child 46626 died with exit status 0x0000
Parent process dies quietly.

Note that the 10 millisecond delays almost force alternating execution.  Without something similar, you are stuck with the idiosyncrasies of your system and its scheduler, and many a modern machine is just too fast!

A: fork() creates a new child process, which run's independently from the parent.
If you want the parent process to wait for the children to finish, you can use the system call wait, passing a PID, which will block until the process has finished.
See the article wait(System Call) on Wikipedia


text:
Q: Configuration Issue For OpenVswitch Version 2.8.1 on Ubuntu 16.04 I am a new user on Linux platform, I have tried to install openvswitch 2.8.1 on Ubuntu 16.04; but after installation I am observing below error.
root@syed-VirtualBox:/home/syed# ./openvswitch.sh
ovs-vsctl: unix:/usr/local/var/run/openvswitch/db.sock: database connection failed (No such file or directory)

I have done below configuration in openvswitch.sh file
ovsdb-server /usr/local/etc/openvswitch/conf.db \
--remote=punix:/usr/local/var/run/openvswitch/db.sock \
--remote=db:Open_vSwitch,Open_vSwitch,manager_options \
--private-key=db:Open_vSwitch,SSL,private_key \
--certificate=db:Open_vSwitch,SSL,certificate \
--bootstrap-ca-cert=db:Open_vSwitch,SSL,ca_cert --pidfile --detach --log-file

ovs-vsctl --no-wait init
ovs-vswitchd --pidfile --detach
ovs-vsctl show

Can anyone help me in resolving this issue ?.
Thanks

A: Ovs-vsctl needs to connect to ovsdb when it executes, but it seems to be off by default. To start it manually:
sudo /usr/share/openvswitch/scripts/ovs-ctl start


text:
Q: using directive in angularjs for getting filepath I am creating a web app in angularjs but i am not very familiar with directives in angularjs
i want to get the file path of the selected file by a particular user
<script>
 var myApp = angular.module('myApp', []);
myApp.controller('myCtrl',  function($scope, $http, $q){
    $scope.uploadFile=function(){
    var f = document.getElementById('file').files[0];
    console.log(f);
    console.log(files);
    }
});

myApp.directive('customFileInput', [function () {
        return {
            restrict: "EA",
            scope: false,
            link: function (scope, element, attrs) {
                element.on('change', function (evt) {
                    var files = evt.target.files;
                    scope.filename = files[0].name
                });
            }
        }
    }]);
</script>

this is my script in which i used angularjs app, controller and directive
but i am not able to call the directive on the button click
  <div ng-app="myApp" ng-controller="myCtrl">
  ggggg
<input id="file" type="file" ng-model="mdfile" ng-change="filepath()" class="form-control" custom-directive custom-file-input />
    <button ng-click="uploadFile()">upload me</button>
</div>

this is my button and input field with file upload
when i click on the button i am getting the following error
ReferenceError: files is not defined
    at b.$scope.uploadFile (image.html:22)
    at fn (eval at compile (angular.js:14539), <anonymous>:4:221)
    at b (angular.js:15628)
    at e (angular.js:25172)
    at b.$eval (angular.js:17378)
    at b.$apply (angular.js:17478)
    at HTMLButtonElement.<anonymous> (angular.js:25177)
    at Rf (angular.js:3487)
    at HTMLButtonElement.d (angular.js:3475)

what i need to do if i want to get the file path and use this directive?

A: See this Plunkr:
https://embed.plnkr.co/dmNRL8bj7E5ZtnArQ0sm/
I changed your directive to make it alert the url on change
  app.directive('customFileInput', [function () {
    return {
        restrict: "EA",
        scope: false,
        link: function ($scope, element, attrs) {
            element.on('change', function (evt) {
                var files = evt.target.files;
                var filename = files[0].name;
                alert(URL.createObjectURL(files[0]));
                });
        }
    }


text:
Q: ARM template with DSC extension fails with security error after reboot during create new AD forest and domain For months I have reliably used an ARM template that creates primary and backup domain controllers (based on 'active-directory-new-domain-ha-2-dc' in the quick start templates). On Friday it stopped working without any modifications being made.
The problem is on the primary DC. The xADDomain DSC resource triggers a reboot as shown in this excerpt from the first DSC log:
VERBOSE: [2020-05-22 15:22:17Z] [VERBOSE] [tipaADPDC]: LCM:  [ End    Resource
]  [[xADDomain]FirstDS]
VERBOSE: [2020-05-22 15:22:17Z] [VERBOSE] [tipaADPDC]:
   [] A reboot is required to progress further. Please reboot the system.
Configuration will not be continued after the reboot. To continue
configuration, use Start-DscConfiguration -UseExisting after reboot.
VERBOSE: [2020-05-22 15:22:17Z] [WARNING] [tipaADPDC]:
   [] A reboot is required to progress further. Please reboot the system.
Configuration will not be continued after the reboot. To continue
configuration, use Start-DscConfiguration -UseExisting after reboot.

After the reboot the following security error can be seen in the second DSC log:
VERBOSE: [2020-05-22 15:23:28Z] Will continue the existing configuration.
Executing Start-DscConfiguration with -UseExisting option ...
VERBOSE: [2020-05-22 15:23:28Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-05-22 15:23:29Z] [VERBOSE] Perform operation 'Invoke CimMethod'
with following parameters, ''methodName' = ApplyConfiguration,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-05-22 15:23:29Z] [ERROR] WinRM cannot process the request. The
following error with errorcode 0x80090350 occurred while using Negotiate
authentication: An unknown security error occurred.

As no changes had been made to the ARM template or the DSC resources I assume that this is due to the deployment picking up the latest version of something.
Things I have tried:

*

*Using DSC 2.76 instead of 2.80

*Using WMF 5.0 instead of 5.1

*Using Windows Server 2019-Datacenter instead of 2016 (it seems
there has been no update to the 2016 image since 20190603).

I have also looked into preventing DSC from restarting after the reboot (there are no more resources to process). However, I think that those settings are already made due to the following entries in the first DSC log:
VERBOSE: [2020-05-22 15:18:42Z] WMF 5 or newer, Injecting RebootNodeIfNeeded =
False and ActionAfterReboot = "StopConfiguration"

VERBOSE: [2020-05-22 15:18:47Z] Get-DscLocalConfigurationManager:
ActionAfterReboot              : StopConfiguration
RebootNodeIfNeeded             : False

I am stuck. Does anyone have any ideas?
Thanks.

A: Encountered similar issue recently. A little bit different is that instead of xADDomain, I'm using ActiveDirectoryDsc.
And the error was gone when I upgraded OS to Windows Server 2019-Datacenter.
A potential root cause might because of the version of Powershell between 2016 and 2019. Here's my log.

*

*Windows Server 2016

VERBOSE: [2020-06-01 03:47:34Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:47:34Z] Retrieving system information ...
VERBOSE: [2020-06-01 03:47:40Z]     OS Version : 10.0
VERBOSE: [2020-06-01 03:47:40Z]     Server OS  : True
VERBOSE: [2020-06-01 03:47:40Z]     64-bit OS  : True
VERBOSE: [2020-06-01 03:47:40Z]     PS Version : 5.1.14393.3471
VERBOSE: [2020-06-01 03:47:40Z] Validating user provided settings for the DSC
Extension Handler ...

And after reboot
VERBOSE: [2020-06-01 03:53:05Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:53:05Z] Will continue the existing configuration.
Executing Start-DscConfiguration with -UseExisting option ...
VERBOSE: [2020-06-01 03:53:05Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Perform operation 'Invoke CimMethod'
with following parameters, ''methodName' = ApplyConfiguration,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-06-01 03:53:07Z] [ERROR] WinRM cannot process the request. The
following error with errorcode 0x80090350 occurred while using Negotiate
authentication: An unknown security error occurred.

 Possible causes are:

  -The user name or password specified are invalid.

  -Kerberos is used when no authentication method and no user name are
specified.

  -Kerberos accepts domain user names, but not local user names.

  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.

  -The client and remote computers are in different domains and there is no
trust between the two domains.

 After checking for the above issues, try the following:

  -Check the Event Viewer for events related to authentication.

  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.

 Note that computers in the TrustedHosts list might not be authenticated.

   -For more information about WinRM configuration, run the following command:
winrm help config.
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Operation 'Invoke CimMethod'
complete.
VERBOSE: [2020-06-01 03:53:07Z] [VERBOSE] Time taken for configuration job to
complete is 0.039 seconds

*Windows Server 2019

VERBOSE: [2020-06-01 08:33:17Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:33:18Z] Retrieving system information ...
VERBOSE: [2020-06-01 08:33:22Z]     OS Version : 10.0
VERBOSE: [2020-06-01 08:33:22Z]     Server OS  : True
VERBOSE: [2020-06-01 08:33:22Z]     64-bit OS  : True
VERBOSE: [2020-06-01 08:33:22Z]     PS Version : 5.1.17763.1007
VERBOSE: [2020-06-01 08:33:22Z] Validating user provided settings for the DSC Extension Handler ...

And after reboot
VERBOSE: [2020-06-01 08:38:49Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:38:49Z] Will continue the existing configuration. Executing Start-DscConfiguration with
-UseExisting option ...
VERBOSE: [2020-06-01 08:38:50Z] Settings handler status to 'transitioning'
(C:\Packages\Plugins\Microsoft.Powershell.DSC\2.80.0.0\Status\0.status)
VERBOSE: [2020-06-01 08:38:51Z] [VERBOSE] Perform operation 'Invoke CimMethod' with following parameters, ''methodName'
 = ApplyConfiguration,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' =
root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: [2020-06-01 08:38:51Z] [VERBOSE] An LCM method call arrived from computer adPDC with user sid S-1-5-18.

A: We faced the same issue. And we realized that this issue only occurs on some particular type of Vms with win_2016Datacenter.

*

*Reproduced this issue with vm type "Standard_F4s_v2"

*But it doesn't occur with other vms, such as "Standard_DS2_v2"

I'm not sure which type of vm are you using, as a work around you can have a try with a different vm type.

A: The same problem is described here:
DSC Configuration 'AD' completed with error(s). Following are the first few: WinRM cannot process the request
The solution for me was to run the following CMDlet after the creation of the VM but before running PowerShellDSC:
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\WindowsAzureGuestAgent" -Name DependOnService -Type MultiString -Value DNS

I added the following to my Bicep file:
resource setScript 'Microsoft.Compute/virtualMachines/runCommands@2021-07-01' = {
  name: 'RunCommand'
  location: location
  parent: vm
  properties: {
    asyncExecution: false
    source: {
      script: 'Set-ItemProperty -Path "HKLM:\\SYSTEM\\CurrentControlSet\\Services\\WindowsAzureGuestAgent" -Name DependOnService -Type MultiString -Value DNS'
    }
  timeoutInSeconds: 30
  }
}

The parent is the 'Microsoft.Compute/virtualMachines@2021-03-01' resource. There is a subsequent PowerShellDSC VM extension resource which depends on this "runCommand" resource. So the VM is created, the Set-ItemProperty command runs, then the PowerShell DSC configuration runs. The AD domain creation then works fine.
The CMDlet sets the Windows Azure Guest Agent service to wait for the DNS Server service before starting. Presumably without this setting the Windows Azure Guest Agent service would start before DNS and name resolution would fail, which screwed up WinRM. An inconsistent service start order may also explain the different experience with different VM sizes.


text:
Q: Accessing the HoloLens Accelerometer I'm trying to get the HoloLens's accelerometer data for the purpose of movement speed while in a car.

*

*I tried using the Windows 'Devices' namespace to access their 'Sensors.Accelerometer' object, but that's inexplicably incompatible with the HoloLens ... a Windows Device.

*I was able to cheat by calculating the speed of the camera object in Unity, but that only works relative to the headset wearer (when I test the app in the passenger seat of a car, I just the speed at which I move my head around).

*Some time ago I'd found a Github repo from MS about HoloLens sensor streams, but I can no longer find it (Dear Future Me, clone EVERYTHING).

Does anyone know if there's another way I can get the accelerometer data? Either in C# or C++.
PS I have Research Mode and MS's demo app on my HoloLens and I've been analyzing that code for answers too. Didn't want anyone to think I show up here looking for a magic bullet!

A: If you want to use accelerations to calculate speed, you will run into problems because of error propagation and the lack of a reference point. Even if there is no direction change the integration of acceleration over the time will make values are useless after a short period of time. (s. Getting displacement from accelerometer data with Core Motion for example)
An alternative would be GPS but HoloLens doesn't a built in GPS sensor and pairing to phones over bluetooth was not possible in the past (maybe now). That said the only thing I can imagine is oopening a WiFi hotspot on a phone connect the HoloLens to it and write an app that will transfer GPS data via WiFi to the HoloLens app listening on the other end.


text:
Q: How do I upgrade the IONIC1 project to the IONIC3 project? I have an IONIC1 project but I need to use ionic3 to extend the original functionality of this project.
1.I have tried using TS to call JS in the same ionic3 project, but I am not sure the same method can make ionic3 TS using ionic1 JS?
2.I don't know what are these codes mean? And how to turn these codes into ionic3 can be used
(function() {
    angular.module('starter')
    .factory('AccMeter', [ '$rootScope', '$interval', '$timeout', 'BTCommLE', 'EmmParser', accMeterService ]);

    function accMeterService($rootScope, $interval, $timeout, bt, accParser) {...}

Please tell me how to Solve these two problems.

A: Ionic v1 was based on AngularJs which was the first version of Angular. Whereas Ionic v3 is based on the latest version of Angular. Further, you can look into this article -

iOS and Android support is only indirectly done by Ionic itself, but
  more by Cordova. You can package old Ionic v1 apps in current Cordova
  versions (cordova-android and cordova-ios), as this is controlled by
  the Ionic CLI whose current versions still support Ionic v1 just fine.
  I don't expect this to change.

ionic framework v1 to v3

A: I guess you have to migrate your code to the new Angular version.
And if you migrate, I advise going straight to the Ionic version 4.
Maybe these articles can help you.
Angular upgrade guide
Migrating from Ionic 1.0 to Ionic 4.0 - Overview

A: All above answers are correct. There is no magic button to make ionic 3/4 project from Ionic 1.
AngularJS and Angular 2+ are very different. The same applies for CSS styles comparing to old Ionic.
From my personal experience: I had to almost completely rewrite my app.
Follow the upgrade guide, start with a new blank Ionic 3 (or better Ionic 4) project. Be ready to spent at least a week on learning principles of new Angular.


text:
Q: How many 301 redirects can I point to a page without hurting SEO? I have several pages with the same topic, but different content that I write every year on a WordPress site, but because the information is useful for an exact period of time, instead of keep creating different pages every year, I thought on consolidating the pages into one master-page and keep updating it every year, instead of creating more pages.
So the question is how many 301 redirects can point to a page without hurting the SEO of the site with search engine?
I have around 5 topic that I would like to simplify with a master-post. One of the topics would have 15 redicters to the main page, and the other 4 topics would less than 6 redirects.
Is it better this way or it's better to delete the pages using 410 code?
Also, is there a rule of thumb of how many redirects can you use per day?

A: Well, there is no limit to the number of HTTP 301 redirects and this number does not impact SEO.
The only thing to avoid is too many redirect for the same page (i mean redirects in series) because it produces a lack of performance (loading speed) and so it damages the user experience.
Between choosing 301 rather than 410, you just need to know that a page with enough traffic should be redirected (HTTP 301), instead a page without traffic can be definitely closed (HTTP 410).

A: Don't use more than 5 redirects in a redirect chain. Google Bot will not follow 301 redirects over multiple hubs.


text:
Q: How to print log inside release aar I want to build an apk and inside it I need to use release aar inside it.
The aar must be release build since I need to shrink and obfuscate it.
But I would like to print the log for network log to see if my obfuscation will not bother the request payload.
I tried to use System.out.println, but I could not see any log from aar.
Any suggestions?

A: You can use gradle build config field to enable/disable log print.
Default value for Gradle buildConfigField boolean used across flavors
First create a log wrapper function with a boolean parameter, true means enable log print. And then you can create an init funtcion for your aar, in which you can set log enable parameter.
Meanwhile define a build config field in your app.gradle:
 debug {
        buildConfigField "boolean", "ENABLE_LOG", "true"
    }
 release {
        buildConfigField "boolean", "ENABLE_LOG", "false"
    }

Then just call aar.init(BuildConfig.ENABLE_LOG) on Application.oncreate()

A: You should be able to turn it on in the manifest/build.gradle. Enable LogCat on Release Build in Android Studio
There have been a few changes to it over the years so you may have to look at more than the accepted answer.
You can also use this library https://github.com/tony19/logback-android
It can create log files on the device, that you can open and inspect.


text:
Q: MongoDb CSharp driver: Select rows where fieldX in set (val1,val2,val3) var database = new MongoClient("mongodb://192.168.3.122").GetDatabase("TestDb");
var collection = database.GetCollection<Post>("Post");
var res = collection.AsQueryable().Where(x => x.Id.In(new List<int> { 1, 2, 3 })).Select(y => y).ToList(); //error here
foreach (var post in res)
{
    Console.WriteLine(post.Id + " " + post.Code);
}

I want results similar to this SQL query:
Select * From Post Where Id In(1, 2, 3)

A: Try this
var Ids = new int[] { 1, 2, 3};
var res = collection.AsQueryable().Where(x => Ids.Contains(x.Id)).Select(y => y).ToList();

A: I think you can use In filter like this:
var filter = Builders<Post>.Filter.In(f=> f.Id, new []{ 1, 2, 3 });

And get your expected result:
// As an Async way
var res = collection.Find(filter).ToListAsync().Result;

// As a Sync way
var res = collection.Find(filter).ToList();


text:
Q: Exchange 2007 email over quota One of our users had their email over quota during this weekend.
He and me are both sure he received quite some emails this weekend.
When chaning his quota, I dont see the old mails from this weekend getting in ?! Anyone knows what happens with mails which are received during the period when the user is over quota ?

A: I believe the sender would've received an error code / mail delivery failure message when the quota of the receiver was exceeded.
Exchange mailbox

*

*Exchange mailboxes have two quotas, a soft lower quota and an hard
upper quota.

*Users with mailboxes approaching the lower quota limit
will receive warning notification
via email.

*Some mail programs display a quota warning message onscreen, but others do not and rely on your noticing the email reminder.

*An account that exceeds the lower quota limit will not be able to send mail (but see Commentary).

*Attempts to send mail will show an error message. Incoming mail can still be received, as long as the account has not yet exceeded the upper quota limit.

*You must delete items to get below the quota limit to be able to resume sending mail. - Note that messages in your Deleted Items folder still count against your quota. You must get them out of your Deleted Items folder, by shift-deleting individual items or by emptying the whole Deleted Items folder.

*An account that exceeds the upper quota limit will be blocked from receiving mail and from storing new messages. Your account will not be able to send mail and will not be able to receive mail.

*New mail addressed to an account that is over the upper quota may be immediately returned to the sender with an error message, without being stored for delivery attempts.

http://kb.mit.edu/confluence/display/istcontrib/What+happens+when+a+mailbox+goes+over+quota


text:
Q: Retrieve Users' Passwords SQL Server Is there a way to view the password of non-sysadmin accounts on SQL Server 2016?
I'm a database admin. I can simply change the password for the user, but I'd love to know if there is a way I can retrieve the password without resetting it.

A: In SQL Server user and login passwords are never stored; they are hashed.  When a user logs in by presenting a password, that password is hashed and compared to the stored hash.


text:
Q: MYSQLI Query ORDER by most amount of matching characters I have created a search function on my project utilizing mysqli LIKE query.
My final hurdle is the ORDER in which it outputs.
Current Scenario:
if(isset($_GET['userInput']))
{
$search = $_GET['userInput'];
$search = explode(" ", $search);
if($search[0] != ''){
    $firstterm = $search[0];
}else{
    $firstterm = '@@@';
}
if($search[1] != ''){
    $secondterm = $search[1];
}else{
    $secondterm = '@@@';
}}

$contact = $mysqli->query("
SELECT * FROM contact WHERE
f_name LIKE '%$firstterm%'
OR l_name LIKE '%$firstterm%'

OR f_name LIKE '%$secondterm%'
OR l_name LIKE '%$secondterm%'

order by id LIMIT 5");

My question is, is there a way to ORDER by the most amount of matching characters as apposed to id. The reason being if I type 'C Blogs' looking for 'Craig Blogs' the 'C' will register a hit on everyone of my contacts because of the email address '.[c]om'.
So if I can get it to ORDER by most amount of matching characters (the added amount from both explodes where there is more than 1) the top result should theoretically be 'Craig Blogs'.

A: You can count the number of matches using +.  In MySQL, a boolean expression is treated as a number with 1 being true and 0 being 1:
ORDER BY ((f_name LIKE '%$firstterm%') +
          (l_name LIKE '%$firstterm%') +
          (f_name LIKE '%$secondterm%') +
          (l_name LIKE '%$secondterm%')
         ) desc

EDIT:
If you want the number of matching characters, you can start with the length of the search terms.  However, terms could appear more than once.  So:
ORDER BY ((length(replace(f_name, 'firstterm', concat('firstterm', 'x'))) - length(f_name)) +
          (length(replace(l_name, 'firstterm', concat('firstterm', 'x'))) - length(l_name)) +
          (length(replace(f_name, 'secondterm', concat('secondterm', 'x'))) - length(f_name)) +
          (length(replace(l_name, 'secondterm', concat('secondterm', 'x'))) - length(l_name))
         ) desc


text:
Q: How to populate a List from results of sqlite query in Universal Windows App I have a List:
public class DateAmountList
    {
        public string Date { get; set; }
        public int Amount { get; set; }
    }

List<DateAmountList> itemsList1 = new List<DateAmountList>();

I have an sqlite query:
var getmonthsquery = "SELECT Date, SUM(Amount) FROM incomeamounts GROUP BY Date";

The result looks like you'd expect for the query, something like:
Jan, 200
Feb, 250
Mar, 700

etc...
I'm not sure why in Windows Universal Apps, but sqliteDataReader is not available even though I've installed the nuget package, so I'd like an alternative way to populate the list with the query results and also the best way to 'execute' the query.

A:
so I'd like an alternative way to populate the list with the query results and also the best way to 'execute' the query.

I am using SQLite.Net-PCL to implement SQLite Local Storage in Universal Windows App:
// get the total amount for each date
public static List<DateAmountList> GetTotalAmount()
{
    List<DateAmountList> results = new List<DateAmountList>();
    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DBPath))
    {
        results = conn.Query<DateAmountList>("SELECT Date, SUM(Amount) AS 'Amount' FROM DateAmountList GROUP BY Date");
    }
    return results;
}

Here is the entire sample for your reference, and following is the output:

A: I think if you prefer to work with queries directly, you should take a look at SQLitePCL library. Executing query and populating a list is pretty simple:
var results = new List<DateAmountList>();

using (var statement = this.connection.Prepare(
    "SELECT Date, SUM(Amount) FROM incomeamounts GROUP BY Date"))
{
    while (statement.Step() == SQLiteResult.ROW)
    {
        var dateAmount = new DateAmountList
        {
            Date = DateFromInternalValue(statement[0]),     // This depends on what format you use to store your date
            Amount = (long)statement[1],                    // Could also be: Amount = statement.GetInteger(1),
        };

        results.Add(dateAmount);
    }
}

Here are more samples of working with SQLitePCL.
As opposite approach, you can try sqlite-net and get nice LINQ-like syntax for working with your sqlite database.


text:
Q: How to use onChange event to detect deleted rows with a Google Sheets Apps Script onChange event has the "REMOVED_ROW" type for a SpreadsheetTriggerBuilder
However, nowhere in the documentation do I see a way to see which row(s) was removed from the event. Is there a way to get the row number(s) that were deleted with this event?

A: You can use getActiveRange(). When a user removes a row it will automatically select the row that is below the deleted row.


text:
Q: open source web interface to create svn projects? Is there an open source web front for me to put on my server? I would like to give friends a url so we all can create our own svn projects without restrictions and great speed. optional SSL would be nice with it too.
Web interface like trac is a bonus

A: There are several options available, the one i have seen in use is WebSVN. Have you tried googling for Web based SVN ?


text:
Q: Mix ImageView and VideoView in GridView I have some urls that can be either images or videos. I just want to mix them together in a GridView (2*2). So when constructing the Adapter, how can I instantiate it with either ImageView or VideoView, based on the url?
The old implementation just used a layout that only has a ImageView for both images and videos, and used clickListeners to start another activity to play the videos. A default image is used as a placeholder for all the videos, which is ugly.
I just want to display the image if the url is image, and the first frame of the video if it is a video, like Instagram, but within a 2*2 grid.

A: You can use ImageView and VideoView together on your grid item layout.
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/post_image_size">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="@dimen/post_image_size"/>

            <VideoView
                android:id="@+id/videoView"
                android:layout_width="match_parent"
                android:layout_height="@dimen/post_image_size" />

        </FrameLayout>

In adapter#getView(), you should check the type of your url and set one of them, and set invisible other one.
    if (!isVideo(url)) {
        videoView.setVisibility(View.GONE);
        Picasso.with(this).load(imageUrl)
                .into(imageView);
    } else {
        Uri uri = Uri.parse(url);
        videoView.setVideoURI(uri);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                imageView.setVisibility(View.GONE);
                videoView.setBackgroundColor(Color.TRANSPARENT);
                videoView.requestFocus();
                videoView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // start your new activity to play video
                        return false;
                    }
                });
            }
        });
    }

PS1: I used Picasso to set ImageView.
PS2: In Instagram, we can get images of a video post by using Instagram API. Also we have mediaType flag to determine that it is a video or image. You can check Instagram API from here. I've developed an instagram repost app. In gridView, I am using the image that is coming from API of a video post. When clicking a video item, I start a new activity to play video as well. But, if you really need capture a frame of a video, you can see this entry.


text:
Q: show the numerical labels only in one subsections or entities of multibib package uncommenting the following line in moderncv with multibib package show the numerical labels in the bibliography.
\makeatother
\renewcommand*{\bibliographyitemlabel}{[\arabic{enumiv}]}

But how to show the numerical labels only in one subsections or entities of multibib.

A: Well, by uncommenting that command you've created a global change, but if you want to only do it for specific sections, put:
\renewcommand*{\bibliographyitemlabel}{[\arabic{enumiv}]}

Before the sections you want it to be this way, and
\renewcommand*{\bibliographyitemlabel}{[\roman{enumiv}]}

before those you don't.
This is a bit of a hack solution though, and a better way would be to create multiple bibliographies, each with a different style.
You can read more about multiple bibliographies here: Multiple bibliographies?


text:
Q: Python script causes git publickey error when not run in IDLE On windows 7 64bit have installed Python 2.7, I have no choice over which version to use.
I have used IDLE to write a script and when I press F5 to run the script everything works as expected.
However, if I double-click the Python file from within explorer or use Py2Exe to make it into an executable the script fails.
This is the part that screws up:
print subprocess.check_output(["git", "pull", "origin", "master"], shell=False)

I keep receiving the git error:
Permission denied (publickey).
Fatal: the remote end hung up unexpectedly.

As I said, if I open the script in IDLE and run from there it works a charm. I have compared the output of os.environ from both Environments and the output of:
print subprocess.check_output(["ENV"], shell=False)

I can see no differences relating to git inparticular and paths in general. I'm stumped!
PS. If you have a git repo and python installed and  a moment to help me then please put the following code in to a file in your git repo:
import sys, subprocess
try:
    print "pulling from github"
    print subprocess.check_output(["git", "pull", "origin", "master"], shell=False)
except:
    print "Failed"
    print sys.exc_info()[0]
raw_input("Any key to exit.")
sys.exit(0)

Right-click on the file and choose "Edit with IDLE" and hit F5. Then try double clicking the .py file directly... What happens for you guys?

A: Try to run the python script under cmd,
make sure the cmd is running in administrator privileges.
If this works, try to run it from the explorer with mouse right click->run as administrator,
or in the python.exe properties in the Compatibility tab, mark the "Run this program as an administrator" checkbox.


text:
Q: Примеры алгоритмов с логарифмической сложностью (основание отличное от 2) Допустим, говорят, что алгоритм имеет сложность O(log(N)). Всегда ли эта запись означает, что логарифм берется по основанию 2? Понимаю, что обычно людей интересует поведение функции, а не конкретные числа, но все же интересно, есть ли конкретные распространенные алгоритмы, которые оцениваются логарифмом с другим основанием?

A: Ну это просто. Асимптотическая оценка сложности алгоритма O(N) не принимает во внимание константу перед множителем, тк при больших N она становится несущественной, следовательно O(N) = C1 * log(N) + C2 записывается как O(N) = log(N)
Известно также, что логарифм с любым основанием можно представить как логарифм по основанию 2 умноженный на множетель-константу, который по описанной выше причине просто не учитывается в оценке сложности O(N)

A: При учете асимптотической сложности константы не учитываются. Основание логарифма в данном случае не имеет значение. Т.к. логарифм можно привести к любому основанию, пользуясь свойством   .
Соответственно, если у нас есть обозначение O(логарифм n по основанию a), где a - это какая то константа, это выражение упрощается до O(логарифм n по основанию с разделить на логарифм a по основанию c), где c - это какая то константа. Получаем, что логарифм, на который делят, можно не учитывать в нотации O, т.к. он от n не зависит, и является константой.


text:
Q: custom setting error when test classes run in parallel I have a few test classes that fail but only when all the test classes are run in parallel.I'm using a hierarchy custom setting as part of the test code. In order to narrow down the problem I have the following in my test code:
My_Setting__c settings = My_Setting__c.getOrgDefaults();
settings.some_app_date__c = System.today()+1;
upsert settings;

Ctl_SomePage ctrl = new Ctl_SomePage();
My_Setting__c settings1 = My_setting__c.getOrgDefaults();
system.assert(false,'date: ' + settings1.some_app_date__c);

When run by itself or with parallel disabled this produces a date:
System.AssertException: Assertion Failed: date: 2016-03-01 00:00:00

When run with all tests and parallel enabled I get:
System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: SetupOwnerId duplicates value on record with id: 00DP0000003oTNU: []

If I try to just log out the custom setting its just an empty object. It seems like it won't let me update it but if I try to get the values from it, its empty...
Any suggestions?

A: Just an example of how mocking could work (based on @kurunve's comment):
public class MySettingMock
{
    @TestVisible static Date mockSettingDate;
    public static Date getOrgWideDefaultDate()
    {
        return Test.isRunningTest() ? mockSettingDate :
            My_Setting__c.getOrgDefaults().Date_To_Mock__c;
    }
    public static void setOrgWideDefaultDate(Date value)
    {
        My_Setting__c defaults = My_Setting__c.getOrgDefaults();
        defaults.Date_To_Mock__c = value;
        if (Test.isRunningTest()) { mockSettingDate = value; }
        else { upsert mockSettingDate; }
    }
}

The way the above is structured, the only line you can't hit from a test is the upsert operation. I haven't tried it myself, but it's an interesting idea. It doesn't scale especially well if you have a bunch of values to work with, but there could be workarounds for that.


text:
Q: Optimize TO_TIMESTAMP() query within Oracle every time I execute this query it takes like 2 minutes to execute:
select * from CPOB_Monitoring_Dashboard
where  VOYAGE_STRT_DT >= TO_TIMESTAMP('2014-07-03 00:00:00.000','YYYY-MM-DD HH24:MI:SS.FF')
and    VOYAGE_STRT_DT <= TO_TIMESTAMP('2018-07-03 00:00:00.000','YYYY-MM-DD HH24:MI:SS.FF')

However if I change it to use TO_DATE instead of TO_TIMESTAMP is really fast.
Linq is generating the query using TOTIMESTAMP and I've not found yet a way to change that to use TO_DATE, is there any way that I can optimize the TOTIMESTAMP query??
Here is the Execution Plan for the query using TOTIMESTAMP:
PLAN_TABLE_OUTPUT
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Plan hash value: 246273147

---------------------------------------------------------------------------------------------------------------------
| Id  | Operation                       | Name                      | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                |                           | 21842 |  4820K|       |  1336   (1)| 00:00:17 |
|   1 |  VIEW                           |  CPOB_Monitoring_Dashboard| 21842 |  4820K|       |  1336   (1)| 00:00:17 |
|   2 |   HASH UNIQUE                   |                           | 21842 |  3988K|  4384K|  1336   (1)| 00:00:17 |
|   3 |    NESTED LOOPS                 |                           | 21842 |  3988K|       |   442   (1)| 00:00:06 |
|   4 |     NESTED LOOPS                |                           |    47 |  7661 |       |   160   (1)| 00:00:02 |
|*  5 |      TABLE ACCESS FULL          |      VOYAGE_INFO          |    46 |  1012 |       |    68   (0)| 00:00:01 |
|   6 |      TABLE ACCESS BY INDEX ROWID|      PROCESS_CTRL         |     1 |   141 |       |     2   (0)| 00:00:01 |
|*  7 |       INDEX RANGE SCAN          |      VOYAGE_ID_IDX        |     1 |       |       |     1   (0)| 00:00:01 |
|*  8 |     INDEX RANGE SCAN            |      PLY_IDX2             |   467 | 11208 |       |     6   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   5 - filter(INTERNAL_FUNCTION("CPVI"."VOYAGE_STRT_DT")>=TIMESTAMP' 2014-07-03 00:00:00.000000000' AND
              INTERNAL_FUNCTION("CPVI"."VOYAGE_STRT_DT")<=TIMESTAMP' 2018-07-03 00:00:00.000000000')
   7 - access("CPC"."VOYAGE_ID"="CPVI"."VOYAGE_ID")
   8 - access("CPC"."BRAND_NAME"="CPOB"."BRAND_ID" AND "CPC"."SHIP_NAME"=""SHIP_NAME")
       filter("CPC"."SHIP_NAME"="CPOB"."SHIP_NAME")

24 rows selected.


text:
Q: Java VisualVM missing features I have a Java application, and I'd like to monitor it using Java VisualVM (jvisualvm).
However, in the VisualVM window very little data can be seen. Also, I can't take a heap dump.
Here is a screenshot of what it looks like, with another test app I wrote:

I can monitor memory usage, classes loaded and threads. Heap dumps, performing GC as well as sampling is disabled.
I have tried adding -Dcom.sun.management.jxmremote to VM arguments, as described here. This is showing up in the Installation Details window. However, it does not appear in the Java process arguments. (should it?)

I also tried to click the button in my test app until an OutOfMemoryError occurred. No heap dump; that is not weird as Heap Dump on OOME is disabled.
What could I do to solve this?

A: I had this problem because I was running JVisualVM from a different JRE/JDK installation than the target process.  It seems that the two must be coming from the same place or it grays out the Heap Dump button.

A: It seems there was a problem with different Java versions.
A long story short: If JDK is outdated re-install it, and delete Java executables from C:\Windows\System32 and C:\Windows\SysWOW64.
Firstly, I want to tell you that I have multiple versions of Java on my computer. My JDK is 32-bit because of some drivers not running with 64-bit Java. Also, I have both 32-bit and 64-bit JRE installed, the latter for better performance for Java games.
My JDK was version 7, update 40. The VisualVM was so also that version. However, my JRE with auto updates was version 7, update 45.
java -version told me it was version 45 (which it was), so I didn't think the problem was there.
Then, I checked the versions via Control Panel. I now knew my JDK was outdated, so I uninstalled it and redownloaded it.
Uninstalling removed Java from the system path, so jvisualvm wouldn't run. I added it to the path. Now both the app and VisualVM ran normally, but still the problem persisted.
The final problem was that the system was using the java.exe from C:\Windows\System32 instead of the JDK one. By the date it seemed to be the latest one, but maybe it was that the JRE was installed in a different location that the VisualVM (= the JDK).
Finally, I just deleted the Java executables in both C:\Windows\System32 and C:\Windows\SysWOW64.


text:
Q: How to open a Kali Linux fold from Windows to recover photos Backstory:
So I am in the log-in loop. I can't log into my account.
And because of the fact that I've previously made the alt key responsible for changing layouts now, I can't access the virtual console (when I press all combination alt+ctrl+f* Linux just changes layouts from eng to ru). But I can perfectly access the console in Ubuntu, which I installed just yesterday.
Problem:
Because I've never expected such a problem to arise I stored part of my photos in the folder on Kali Linux desktop.
I wanted to download them to the Google disk later, but I didn't make it in time.
Question:
Can I somehow open the folder with my photos (which is located on Kali Desktop) from other operating system: Windows or Ubuntu?

A: Yes, if you have a live disc or multi boot installation of Ubuntu or other linux distributions, you can boot from it. Then you have the open the file manager and double-click the Kali linux partition to mount it. Then you can navigate to the photos directory of Kali linux. Windows cannot access linux extended partitions natively, and I also don't know of there is any tool available for this.


text:
Q: How to use ngrok with fastapi on windows 10? I'm trying to use ngrok to test a fastapi application. I'm working on a windows 10 machine. When I send the post request, I get a 405 Not Allowed error. In postman, the call works as expected if I use 127.0.0.1 but not if I use localhost. Therefore, I think this might be the issue but I don't know how to fix it. Has anyone experienced this issue before and know how to fix it?

A: The issue that the hosts file isn't mapping 127.0.0.1 to localhost. Go to this folder:
C:\Windows\System32\drivers\etc
Open notepad as an admin and edit the "hosts" file. You need to make sure you have this line and it is uncommented.
127.0.0.1       localhost

Then restart your machine.


text:
Q: Can I start an NSOperation inside of another NSOperation without a queue? My application gets the current device location, POSTs this to my server, and returns a dictionary to be displayed in a table view. Currently I am using the CLLocationManager delegate methods and AFJSONRequestOperation (AFNetworking's retrieve-data-through-NSURLConnection-in-NSOperation class) to do the job, but this functionality is inside one view controller method and I'd like to be able to reuse this across other view controllers.
I am planning to make my own NSOperation subclass, but first I wanted to know if there are any unseen pitfalls in having NSOperations (AFJSONRequestOperation) start inside of another NSOperation. Does this work as expected or should I find a way to make a queue with dependencies among the operations?

A: Scheduling a NSULRL connection operation within a NSOperation will fail unless you schedule it on the main run loop. AFJSONOperation (or any subclass of AFURLOperation) will succeed because under the hood, AFNetworking operations are scheduled on their own NSOperationQueue and on a custom run loop.
So - Yes. Go for it. I use NSOperation subclasses to isolate all of my worker processes. It is much cleaner than flat out GCD in the middle of your VCs or Models.
Caveat - Since all AFNetworking operations are block based and return asynchronously, your NSOperation subclass will need to be concurrent. Apple provides a detailed description of how to build this in their docs for Concurrent NSOperation Subclasses
Optionally - you could just skip building a concurrent NSOperation subclass, and fire your network operation synchronously from within your NSOperation since you're already off of the main queue.

A: All the NSOperation stuff uses GCD under the hood, and GCD has no issues with nested dispatch_async calls, so I doubt nesting NSOperations will cause you problems as long as your logic is correct.


text:
Q: Python shortest distance between a point and a line segment in 3D and intersection point on the segment I'm looking for a python implementation of the shortest distance between a point and a line segment in 3D and the intersection point on the segment

A: Here's an implemenation using numpy:
def min_distance(r: np.ndarray, a: np.ndarray):
    """ Compute the minimal distance between a point and a segment.

    Given a segment of points xa and xb and a point p

    Parameters
    ----------
    r
        xb - xa

    a
        xa - p

    Returns
    -------
    d
        The minimal distance spanning from p to the segment
    """

    min_t = np.clip(-a.dot(r) / (r.dot(r)), 0, 1)

    d = a + min_t * r

    return np.sqrt(d.dot(d))

Explanation

Given a segment, identified by two points xa and xb, and a generic point p . We define the following quantities

A generic point on the segment, has coordinates:

So the distance of the point p from  a generic point on the segment is:

We want to minimize the squared distance (we use the squared distance to make calculations a bit easier)

i.e.

This gives us the value of t that minimizes the distance (actually makes stationary).

Now we need to remember that we are constrained to keep , so we can clamp t.
Computing d(t_min) will gives the minimum distance.
The distance will be the norm of the returned d: np.linalg.norm(d) or, equivalently, np.sqrt(d.dot(d)).

A: I suggest to use the scikit-spatial library.
The point-line distance can be computed in the following way:
from skspatial.objects import Line

line = Line([5, 2, -3], [3, 8, 2])
line_point_distance = line.distance_point([5, -5, 3]).round(3)

Then, what you call the intersection point is just the projection of this point onto the line:
point_projected = line.project_point(point)


text:
Q: how get the "parent name" and read the object in the ng-repeat AngujarJs? if i have a response object like this:

Object Json format from my js file and i need use the ng-repeat for this element but i need to get the name "street 1" too, how can use the ng-repeat for get all values with the "parent name" and his properties. Thanks

A: try something like this

{{key}}

contract : {{value[0].contract}} status: {{value[0].status}}

contract : {{value[1].contract}} status: {{value[1].status}}

or

{{key}}

        {{item.contract}} / {{item.status}}


text:
Q: How to search for a string in a text file using Qt I'm trying to search for a string in a text file; my aim is to write it only if it isn't already written inside my text file.
Here's my function (I don't know how to put inside the while loop):
QFile MyFile("text.txt");
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);

while(!MyFile.atEnd())
  { //do something to search string inside }

MyFile.close();

How can I do that? From Qt's Help, method "contains" works with const variable only; can I use it to look for my string?

A: You can do the following:
[..]
QString searchString("the string I am looking for");
[..]
QTextStream in (&MyFile);
QString line;
do {
    line = in.readLine();
    if (!line.contains(searchString, Qt::CaseSensitive)) {
        // do something
    }
} while (!line.isNull());

A: In case of not large file
QFile MyFile("text.txt");
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);
const QString content = in.readAll();
if( !content.contains( "String" ) {
//do something
}
MyFile.close();

To not repeat other answers in case of larger files do as vahancho suggested


text:
Q: Transforming an object value in an array of objects? What is the best way to transform the following array
           [{
                "language":"de",
                "title": "test DE",
                "content": "Context DE Test",
                "summary": "Cummary DE test",
            }]

to the following format.
            [{
                "language": { "name": "de" },
                "title": "test DE",
                "content": "Context DE Test",
                "summary": "Cummary DE test",
            }]

I need to change the structure of the language key in the object.

A: Yes. I think this should do it?
languages.map(({ language, ...rest }) => ({
  language: { name: language },
  ...rest,
});

A: Try this:

let array1 = [{
  "language": "fr",
  "title": "test FR",
  "content": "Context fr Test",
  "summary": "Cummary fr test",
},
{
  "language": "de",
  "title": "test DE",
  "content": "Context DE Test",
  "summary": "Cummary DE test",
}]
let res = array1.map((value, index) => {
  return { ...value, language: { name: value.language } }
})
console.log(res);

A:

const arr =    [{
                "language": "fr",
                "title": "test FR",
                "content": "Context fr Test",
                "summary": "Cummary fr test",
            },
            {
                "language":"de",
                "title": "test DE",
                "content": "Context DE Test",
                "summary": "Cummary DE test",
            }];

const newObj = arr.map( obj => {...obj , language : {name : obj.language}});

console.log(newObj)

With map and the spread operator, like you said.


text:
Q: Help me differentiate between a truly distributed setup and a merely redundant system i understand that a master/slave setup is redundant, in that data is mirrored to all slaves from a central master. how does this vary from a distributed architecture?

A: A master/slave relationship implies either a backup solution, or a failover solution.  When the master becomes unavailable, the slave takes over, and functions as the new master until the master comes back up.
In a distributed architecture, the servers are basically equals.  Any request can be served by any server, so long as the request is atomic.

A: A master slave relationship in the context of databases says that all slaves will replicate data from the master... However, in the end, every server is doing an equal number of writes (the master receives writes from the application, and the slaves receive the same writes from the master).
In a distributed system that implements horizontal scaling, you have multiple servers containing the same table schema, but each responsible for a portion of the overall data... No one machine needs to contain all the data.
For example, let's say you are storing user bookmarks. You could store each user's list in one table in a replicated setup, and every machine would receive all the data. Or you can store the list for users with uid%100<50's data on server1 and the rest on server2. As long as you don't need to do analytical queries over the full userbase, you're fine! Of course, you still need backups for each half anyway, considering server1 won't have server2's data.


text:
Q: difference between getChildHtml() and getChildChildHtml() in Magento I want to know the differences between this two functions. I understand the behavior of getChildHtml(). It returns the html of the block or all the blocks if you don´t pass any parameters.
And I can see
getChildHtml($name, $useCache, $sorted)
getChildChildHtml($name, $childName,$useCache, $sorted)

at first sight I a $useCache param that I suposed is to use cache.

A: Let's say you're in the root block's phtml template file, and you have a simplified block structure that looks like this
root
    left
        promo_top
        navigation
        promo_bottom
    center
    right

From the root block's template file, to print the left block you'd use getChildHtml.
echo $this->getChildHtml('left');

However, if for some reason you wanted to print the promo_top block in the root template, you'd have to do something like this
$left = $this->getChildBlock('left')
echo $left->getChildHtml('promo_top')

The getChildChildHtml method allows you to do this sort of thing in one simple method call.  Again, from the root template
echo $this->getChildChildHtml('left','promo_top');

So, the semantics are

*

*Get My Child Block with the name X

*Then, get it's child block with the Y

*Render the HTML

If you look at the source code you can see that, ultimately, this method just wraps a call to getChildHtml
#File: app/code/core/Mage/Core/Block/Abstract.php
public function getChildChildHtml($name, $childName = '', $useCache = true, $sorted = false)
{
    if (empty($name)) {
        return '';
    }
    $child = $this->getChild($name);
    if (!$child) {
        return '';
    }
    return $child->getChildHtml($childName, $useCache, $sorted);
}


text:
Q: How do I fix the SSL warning I get when visiting github.com? I see the following warning when visiting http://www.github.com/ after July 26, 2014. I get this warning in both Chrome and Safari on my OS X Mavericks-equipped iMac.
Should I worry about this? How do I fix it?

A:
Should I worry about this?

You should always distrust SSL connections that are using expired certificates. This could indicate a simple oversight on the part of the website operator or it could indicate a malicious attempt to intercept encrypted communications between the website and your browser. Heed your browser's warnings and don't load the page when these warnings occur.

How do I fix it?

OS X users can delete the expired certification from their keychains. This certificate was issued by DigiCert and they have a blog post that details what happened and how to fix it. Paraphrased from the post:

*

*Start the Keychain Access application (you may be asked for your password when you do this)

*In Keychain Access go to View -> Show Expired Certs and search for DigiCert High to find the DigiCert High Assurance EV Root CA that expired on July 26, 2014. It's important you only delete the expired certificate here.

*Delete this certificate and close Keychain Access.

You may also need to restart Chrome and Safari for the warning to disappear. Also, make sure you check all Keychains and verify your Category filters - certificates or All Items should be selected.


text:
Q: How can I get the access_token of the current login? I am using the OAuth.io JavaScript client SDK to authenticate via GitHub.  On authentication success I receive a GitHub access_token.  I have also set cache: true so the user only gets the popup if they aren't already logged in.
Because I have caching enabled, when I call OAuth.popup no popup actually appears and instead my callbacks are immediately called with the access_token available.
How can I check to see if the user is already logged in and get the access token without showing the popup in the case where they aren't already logged in?
The reason for this is because I want to show the login button if they are not logged in, but I want to show data from GitHub if they are logged in.  In either case, I don't want to show the pop-up window unless they actually click the login button.
Note: I am specifically looking for a way to do this with OAuth.io client JavaScript SDK.  I know that I can manually save off credentials when they authenticate, but I would rather not have to if oauth.io already has that information cached somewhere.

A: Turns out it was right in front of my face on the documentation: http://docs.oauth.io/#caching-the-request-object
In particular, OAuth.create('github') is what I needed.  It will give back the cached result object, the same one I would get back from attempting to authenticate.


text:
Q: Row-Flexbox with vertical scrollbar: background color is cut I have a side bar and a main content, each have its own scrollbar.
I try to achieve a result where the red background of the main content is always visible, no matter if one scrolls or not, and no matter if the flex-items have more height than their parent.
Is this possible?
My current problem is that when I try to scroll, the background of the main div disappears. The background has exactly the same height as the body, which is not the goal.
If I change the align-items of the main content from the default stretch to flex-start, the background extends correctly for the long(in height) flex-items, but not for the short ones.
If I let this to stretch, I get the other problem, as you can see in the following snippet: the background goes to the bottom (correct) until one scrolls, in which case the background is lost.
Can I somehow have my red/orange background always?

* { box-sizing:border-box; }
html, body {
    width:100%;
    height:100%;
    padding:0;
    margin:0;
}
.flex-item {
    background-color:red;
    border:solid 1px white;
}
.box {
    width:300px;
    height:300px;
    border:solid 2px black;
    margin:4px;
}
.orange {
    background:orange;
}

        We are two divs, I am the sidebar and the one next to me is the main content. Each of us has its own scrollbar. But my red brother has an issue with his background if you scroll...

        How could we solve that?

        Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

A: Looks like this is not possible with flexbox. I happen to notice that if the container is a grid container (instead of a flexbox), it works if the grid items are placed in a row.
Use grid-auto-flow: column on the grid container now to set the flex-item boxes in a row with the proper backgrounds - see demo below:

* {
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

.flex-container { /* added */
  display: grid;
  grid-auto-flow: column;
  overflow: auto;
}

.flex-item {
  background-color: red;
  border: solid 1px white;
}

.box {
  width: 300px;
  height: 300px;
  border: solid 2px black;
  margin: 4px;
}

.orange {
  background: orange;
}

    We are two divs, I am the sidebar and the one next to me is the main content. Each of us has its own scrollbar. But my red brother has an issue with his background if you scroll...

 How could we solve that?

 Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

A: I decided to come back to this to show how it can be done with neither Flex nor Grid. (I did not make it responsive, so be sure to click the "full page" link when viewing the result of the code.)

* { -moz-box-sizing:border-box;box-sizing:border-box; }
html, body {
    width:100%;
    height:100%;
    padding:0;
    margin:0;
}

.row {
    height: 100%;
}
.row>.col {
    overflow: auto;
    height: 100%;
    float: left;
    width: 300px;
    background: green;
}
.row .row>.col {
  background: none;
    overflow: visible;
    height: auto;
    width: 308px;
    border-bottom: 0 none;
}
.row>.colWide { /* prefixed gradient angles are different from the final version of the standard */
    background: -moz-linear-gradient(0deg,#fff 1px,red 1px,red 307px,#fff 307px,#fff 309px,orange 309px,orange 615px,#fff 615px,#fff 617px,red 617px,red 923px,#fff 923px,#fff 924px,transparent 924px);
    background: -webkit-linear-gradient(0deg,#fff 1px,red 1px,red 307px,#fff 307px,#fff 309px,orange 309px,orange 615px,#fff 615px,#fff 617px,red 617px,red 923px,#fff 923px,#fff 924px,transparent 924px);
    background: linear-gradient(90deg,#fff 1px,red 1px,red 307px,#fff 307px,#fff 309px,orange 309px,orange 615px,#fff 615px,#fff 617px,red 617px,red 923px,#fff 923px,#fff 924px,transparent 924px);
    float: none;
    width: auto;
}
.row>.colWide:after { /* to fake an even bottom border without further complicating the backgrounds */
  content: '\a0';
    display: block;
    clear: both;
    height: 0;
    overflow: hidden;
    border-bottom: solid 1px #fff;
    width: 924px; /* set the width and border as desired */
}

.col {
    border:solid 1px #fff;

}
.box {
    width:300px;
    height:300px;
    border:solid 2px black;
    margin:4px;
}

        We are two divs, I am the sidebar and the one next to me is the main content. Each of us has its own scrollbar. But my red brother has an issue with his background if you scroll...

        How could we solve that?

        Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

A: The way I see it is that you're using height:100% too much. The parent flex container can't expand in height to fit the content because its height is limited to the viewport height and therefore the content extends beyond the end of the background.

* {
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

.flex-row {
  display: flex;
  min-height: 100%;
  align-content: stretch;
}

.flex-row .flex-row {
  overflow: auto;
}

.flex-item {
  background-color: red;
  border: solid 1px white;
}

.box {
  width: 300px;
  height: 300px;
  border: solid 2px black;
  margin: 4px;
}

.orange {
  background: orange;
}

    We are two divs, I am the sidebar and the one next to me is the main content. Each of us has its own scrollbar. But my red brother has an issue with his background if you scroll...

 How could we solve that?

 Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be orange.

i am a box. The background behind me should be red.

i am a box. The background behind me should be red.