text:
Q: Without using \hspace{…pt} how to make nice alignment of separate equations?
My code excluding preamble (don't judge please):
\subsection{Inverse Hyperbolic Trigonometric Identities}
\raggedright\setlength{\parindent}{45pt}
    \begin{enumerate}[align=left,widest=a,labelindent=16mm,leftmargin=!]
    \incrvariable\x
    \setcounter{enumi}{\x}
    \item%194
        $
        \begin{aligned}[t]
        \sinh(\cosh^{-1}{x})=\sqrt{x^2-1} \hspace{20pt} &\text{Domain: } [1,\infty) \hspace{26.5pt} &&\text{Range: } [0,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%195
        $
        \begin{aligned}[t]
        \cosh(\sinh^{-1}{x})=\sqrt{x^2+1} \hspace{20pt} &\text{Domain: } (-\infty,\infty) \hspace{10pt} &&\text{Range: } [1,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%196
        $
        \begin{aligned}[t]
        \sinh(\tanh^{-1}{x})=\frac{x}{\sqrt{1-x^2}} \hspace{16.4pt} &\text{Domain: } (-1,1) \hspace{22pt} &&\text{Range: } (-\infty,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%197
        $
        \begin{aligned}[t]
        \cosh(\tanh^{-1}{x})=\frac{1}{\sqrt{1-x^2}} \hspace{15.25pt} &\text{Domain: } (-1,1) \hspace{21.9pt} &&\text{Range: } [1,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%198
        $
        \begin{aligned}[t]
        \tanh(\sinh^{-1}{x})=\frac{x}{\sqrt{1+x^2}} \hspace{16.72pt} &\text{Domain: } (-\infty,\infty) \hspace{9.5pt} &&\text{Range: } (-1,1)
        \end{aligned}
        $
    \incrvariable\x
    \item%199
        $
        \begin{aligned}[t]
        \tanh(\cosh^{-1}{x})=\frac{\sqrt{x^2-1}}{x} \hspace{15.48pt} &\text{Domain: } [1,\infty) \hspace{26.1pt} &&\text{Range: } [0,1)
        \end{aligned}
        $
    \end{enumerate}

The \hspace{} is the important (and annoying) part.
How can I improve my code without changing "enumerate" and "aligned" or something else that looks almost identical? (Something that keeps track of elapsed pts?)
OR with preamble here: (it's looonnng)
\documentclass[12pt, twoside]{article}
\usepackage[utf8]{inputenc}
\usepackage{indentfirst}
\usepackage[left=1.2in,right=1.2in,top=1in,bottom=1in]{geometry}
\usepackage{titling}
\usepackage{titlesec}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.18, width=10cm}
\usepackage[fleqn]{amsmath}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{newunicodechar}
\DeclareMathOperator{\sgn}{sgn}
\newunicodechar{ℤ}{\mathbb{Z}}
\newunicodechar{ℝ}{\mathbb{R}}
\usepackage{enumitem}
\usepackage{graphicx}
\setlength\mathindent{3cm}
\usepackage{etoolbox}
\usepackage{microtype}
\usepackage{array}
\usepackage{booktabs}
\usepackage{xcolor}
\usepackage{romannum}
\usepackage{tocloft} %Change font size of TOC
%\renewcommand*{\arraystretch}{1.9}
\newcommand{\ra}[1]{\renewcommand{\arraystretch}{#1}}
\newcolumntype{C}{>{$\displaystyle}c<{$}}
\renewcommand{\contentsname}{Table of Content}
\DeclareMathOperator{\sech}{sech}
\DeclareMathOperator{\csch}{csch}
\usepgfplotslibrary{fillbetween}

\AtBeginDocument{\addtocontents{toc}{\small}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Odd page number on the right
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\align@preamble{%
   &\hfil
\strut@
\setboxz@h{\@lign$\m@th\displaystyle{##}$}%
\ifmeasuring@\savefieldlength@\fi
\llap{\set@field}%
\tabskip\z@skip
   &\setboxz@h{\@lign$\m@th\displaystyle{{}##}$}%
\ifmeasuring@\savefieldlength@\fi
\rlap{\set@field}
\hfil
\tabskip\alignsep@
}

\titleformat{\section}
{\normalfont\huge\bfseries}{\makebox[45pt][l]{\thesection}}{0pt}{}
\titleformat{\subsection}
{\normalfont\large\bfseries}{\makebox[45pt][l]{\thesubsection}}{0pt}{}
\titleformat{\subsubsection}
{\normalfont\normalsize\bfseries}{\makebox[45pt][l]{\thesubsubsection}}{0pt}{}

\setlength{\droptitle}{-1em}

\setlength{\parindent}{45pt}

\title{\Huge{\textbf{Mathematics Directory}}}
\author{\Large{Zhiyuan Liu}}
\date{}

%\newcommand\X{0}
%\renewcommand\X{0} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\newvariable#1{\gdef#1{0}}
\def\addtovariable#1#2{\xdef#1{\number\numexpr#1+#2\relax}}
\def\incrvariable#1{\addtovariable#1{1}}

\newvariable\x

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\maketitle

\section{}
\subsection{Inverse Hyperbolic Trigonometric Identities}
\raggedright\setlength{\parindent}{45pt}
    \begin{enumerate}[align=left,widest=a,labelindent=16mm,leftmargin=!]
    \incrvariable\x
    \setcounter{enumi}{\x}
    \item%194
        $
        \begin{aligned}[t]
        \sinh(\cosh^{-1}{x})=\sqrt{x^2-1} \hspace{20pt} &\text{Domain: } [1,\infty) \hspace{26.5pt} &&\text{Range: } [0,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%195
        $
        \begin{aligned}[t]
        \cosh(\sinh^{-1}{x})=\sqrt{x^2+1} \hspace{20pt} &\text{Domain: } (-\infty,\infty) \hspace{10pt} &&\text{Range: } [1,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%196
        $
        \begin{aligned}[t]
        \sinh(\tanh^{-1}{x})=\frac{x}{\sqrt{1-x^2}} \hspace{16.4pt} &\text{Domain: } (-1,1) \hspace{22pt} &&\text{Range: } (-\infty,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%197
        $
        \begin{aligned}[t]
        \cosh(\tanh^{-1}{x})=\frac{1}{\sqrt{1-x^2}} \hspace{15.25pt} &\text{Domain: } (-1,1) \hspace{21.9pt} &&\text{Range: } [1,\infty)
        \end{aligned}
        $
    \incrvariable\x
    \item%198
        $
        \begin{aligned}[t]
        \tanh(\sinh^{-1}{x})=\frac{x}{\sqrt{1+x^2}} \hspace{16.72pt} &\text{Domain: } (-\infty,\infty) \hspace{9.5pt} &&\text{Range: } (-1,1)
        \end{aligned}
        $
    \incrvariable\x
    \item%199
        $
        \begin{aligned}[t]
        \tanh(\cosh^{-1}{x})=\frac{\sqrt{x^2-1}}{x} \hspace{15.48pt} &\text{Domain: } [1,\infty) \hspace{26.1pt} &&\text{Range: } [0,1)
        \end{aligned}
        $
    \end{enumerate}
\end{document}

OR someone may have already answered it. Tell me the post. Cheers.

A: I can think of two ways to accomplish your typesetting objective: with an alignat* environment, and with a longtable environment.
First, the alignat*-based approach. Observe: not a single \hspace statement anywhere in sight.

\documentclass[12pt, twoside]{article}
\usepackage[hmargin=1.2in,vmargin=1in]{geometry}

\usepackage{amsmath}
\allowdisplaybreaks

\newcounter{mycount}
\newcommand{\increment}{\refstepcounter{mycount}\themycount.}

\begin{document}

\setcounter{section}{4} % just for this example
\stepcounter{subsection}
\subsection{Inverse hyperbolic trigonometric identities}

\begin{alignat*}{4}
&&&&& \text{Domain} && \text{Range} \\[\jot] % "header line"
\increment &\qquad&
\sinh(\cosh^{-1}{x}) &= \sqrt{x^2-1} &\qquad&
[1,\infty) && [0,\infty) \\
\increment &&
\cosh(\sinh^{-1}{x}) &= \sqrt{x^2+1} &&
(-\infty,\infty) &\qquad&
[1,\infty) \\ \increment &&
\sinh(\tanh^{-1}{x}) &= \frac{x}{\sqrt{1-x^2}} &&
(-1,1) && (-\infty,\infty) \\[\jot] % "\jot" inserts a bit more vertical whitespace
\increment &&
\cosh(\tanh^{-1}{x}) &= \frac{1}{\sqrt{1-x^2}} &&
(-1,1) && [1,\infty) \\[\jot]
\increment &&
\tanh(\sinh^{-1}{x}) &= \frac{x}{\sqrt{1+x^2}} &&
(-\infty,\infty) && (-1,1) \\[\jot]
\increment &&
\tanh(\cosh^{-1}{x}) &= \frac{\sqrt{x^2-1}}{x} &&
[1,\infty) && [0,1)
\end{alignat*}
\end{document}

Second, the longtable-based approach. Observe: Still no \hspace directive anywhere in sight. :-)

\documentclass[12pt, twoside]{article}
\usepackage[hmargin=1.2in,vmargin=1in]{geometry}

\usepackage{amsmath}
\allowdisplaybreaks

\usepackage{longtable,array,booktabs}
\newcounter{mycount}
\newcommand{\increment}{\refstepcounter{mycount}\arabic{mycount}.}
\newcolumntype{L}{>{$\displaystyle}l<{$}}
\newcolumntype{Z}{>{\refstepcounter{mycount}\arabic{mycount}.}l}

\begin{document}

\setcounter{section}{4}   % just for this example
\stepcounter{subsection}
\subsection{Inverse hyperbolic trigonometric identities}

\begingroup
\renewcommand\arraystretch{1.5}
\addtolength\tabcolsep{5pt}
\begin{longtable}{@{} Z LLLL @{}}

%% header
\multicolumn{1}{@{}l}{} &&& \textup{Domain} & \textup{Range} \\[1ex]
\endhead

%% body of table
& \sinh(\cosh^{-1}{x}) & \sqrt{x^2-1} &
  [1,\infty) & [0,\infty) \\
& \cosh(\sinh^{-1}{x}) & \sqrt{x^2+1} &
  (-\infty,\infty) & [1,\infty) \\
& \sinh(\tanh^{-1}{x}) & \frac{x}{\sqrt{1-x^2}} &
  (-1,1) & (-\infty,\infty) \\ \addlinespace
& \cosh(\tanh^{-1}{x}) & \frac{1}{\sqrt{1-x^2}} &
  (-1,1) & [1,\infty) \\ \addlinespace
& \tanh(\sinh^{-1}{x}) & \frac{x}{\sqrt{1+x^2}} &
  (-\infty,\infty) & (-1,1) \\ \addlinespace
& \tanh(\cosh^{-1}{x}) & \frac{\sqrt{x^2-1}}{x} &
  [1,\infty) & [0,1) \\

\end{longtable}
\endgroup
\end{document}

A: You have a set of tabulated data. A simple tabular would do. I'd enclose each math expression between separate delimiters \(...\). If you have a large data to present that exceed a page or you simply expect a page break somewhere between lines, you would need longtable instead.
The example below is based on longtable. Uncomment \everymath={\displaystyle} if all math expressions should be in display style. This may require additional vertical spacing via increased arraystretch or extrarowheight.
\documentclass{article}
\usepackage{array}
\usepackage{amsmath}
\usepackage{longtable}

\begin{document}
\section{Long table}
\begingroup
\newcounter{eqno}\setcounter{eqno}{190}
\newcommand\addeqno{\stepcounter{eqno}\theeqno.}
\setlength\extrarowheight{6pt}
% \everymath={\displaystyle}
%%%
\begin{longtable}[r]{@{}
        r
        >{\(}l<{\)}
        >{Domain: \(}l<{\)}
        >{Range: \(}l<{\)}
    @{}}
    \addeqno & \sinh(\cosh^{-1}{x})=\sqrt{x^2-1}           & [1,\infty)       & [0,\infty) \\
    \addeqno & \cosh(\sinh^{-1}{x})=\sqrt{x^2+1}           & (-\infty,\infty) & [1,\infty) \\
    \addeqno & \sinh(\tanh^{-1}{x})=\frac{x}{\sqrt{1-x^2}} & (-1,1)           & (-\infty,\infty) \\
    \addeqno & \cosh(\tanh^{-1}{x})=\frac{1}{\sqrt{1-x^2}} & (-1,1)           & [1,\infty) \\
    \addeqno & \tanh(\sinh^{-1}{x})=\frac{x}{\sqrt{1+x^2}} & (-\infty,\infty) & (-1,1) \\
    \addeqno & \tanh(\cosh^{-1}{x})=\frac{\sqrt{x^2-1}}{x} & [1,\infty)       & [0,1)
\end{longtable}
\endgroup
\end{document}

On the other hand, with enumerate, you would have to simulate columns. \makebox[<width>][<alignment>]{<content>} creates a box of a fixed width, no matter of the content. So if you place three such boxes  horizontally, you achieve the desired effect. The downside is the width for each box has to be set manually and might need readjustment once you have changed the content. The package eqparbox provides a convenient macros, such as \eqmakebox[<label>][<alignment>}{<content>}. It works exactly as a regular makebox but instead of the width, user provides labels. Then, the width is calculated based on the longest content per label.
You can see this solution requires more coding, while the final effect is exactly the same as with longtable/tabular.
\documentclass{article}
\usepackage{enumitem}
\usepackage{eqparbox}
\usepackage{amsmath}

\begin{document}
\section{Enumerate}
\begin{enumerate}[
    align=left,
    widest=a,
    labelindent=10mm,
    leftmargin=!,
    before={\setcounter{enumi}{190}},
]
\item
    \eqmakebox[eq][l]{\(\sinh(\cosh^{-1}{x})=\sqrt{x^2-1}\)}%
    \quad
    \eqmakebox[do][l]{Domain:\([1,\infty)\)}%
    \quad
    \eqmakebox[ra][l]{Range:\([0,\infty)\)}
\item
    \eqmakebox[eq][l]{\(\cosh(\sinh^{-1}{x})=\sqrt{x^2+1}\)}%
    \quad
    \eqmakebox[do][l]{Domain: \((-\infty,\infty)\)}%
    \quad
    \eqmakebox[ra][l]{Range: \([1,\infty)\)}
\item
    \eqmakebox[eq][l]{\(\sinh(\tanh^{-1}{x}) = \frac{x}{\sqrt{1-x^2}}\)}%
    \quad
    \eqmakebox[do][l]{Domain: \((-1,1)\)}%
    \quad
    \eqmakebox[ra][l]{Range: \((-\infty,\infty)\)}
\item
    \eqmakebox[eq][l]{\(\cosh(\tanh^{-1}{x})=\frac{1}{\sqrt{1-x^2}}\)}%
    \quad
    \eqmakebox[do][l]{Domain: \((-1,1)\)}%
    \quad
    \eqmakebox[ra][l]{Range: \([1,\infty)\)}
\item
    \eqmakebox[eq][l]{\(\tanh(\sinh^{-1}{x})=\frac{x}{\sqrt{1+x^2}}\)}%
    \quad
    \eqmakebox[do][l]{Domain: \((-\infty,\infty)\)}%
    \quad
    \eqmakebox[ra][l]{Range: \((-1,1)\)}
\item
    \eqmakebox[eq][l]{\(\tanh(\cosh^{-1}{x})=\frac{\sqrt{x^2-1}}{x}\)}%
    \quad
    \eqmakebox[do][l]{Domain: \([1,\infty)\)}%
    \quad
    \eqmakebox[ra][l]{Range: \([0,1)\)}
\end{enumerate}
\end{document}


text:
Q: How to call a web api via ajax over SSL from a local html file? I have a local html file in may desktop accessing a web api (JAX-RS) that responds with some JSON data. I enabled CORS and everything works fine, but only without SSL. How can I do to make it work with SSL? I use a self-signed certificate and can call this web api from a WPF application, but from a JavaScript application (standalone html file), when Chrome sends the OPTIONS pre-flight before the POST, the request seems not to even reach the server. I also tried to import the self-signed certificate in the browser, but nothing has changed.

A: The preflight request is not allowed to include an entity body or credentials. If you are using preflighted requests then you cannot use two way SSL.
The solution is to change the server to make the certificate optional. I've only done this using Apache HTTP server or Tomcat but I assume other servers are also capable of this.
In apache the setting should be changed to
SSLVerifyClient optional

and in Tomcat the SSL settings should be changed to
clientAuth="want"

Without this change only CORS simple requests will work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combinatorics: Permutation Problem, how to know if a solution is correct or wrong Question: Find the number of ways of arranging 8 Men and 2 Women in a row such that 2 Women are never together.
For the above question, I thought of 2 ways to proceed
1> Arrange 8 men in 8! ways(_M_M_M_M_M_M_M_M_) and the remaining 2 Women could be arranged in 9P2 ways (in the gaps "_" )
So the answer was 8!9P2
Moment I solved using the above way I thought of another way of using complement instead.
2>Complement
A=U-A'
U=10! and
A' is the number of ways 2 women are always together, this could be arranged in
(WW)MMMMMMMM = 9!*2! ways.
Therefore A= 10! - (9!*2!)
What's the answer to this Question?
Could someone help me figure out how the approaches are correct or wrong? and what is the right method to solve these types of problem, where they give X people and say Y number of people are to be met with a condition?


text:
Q: Android Studio Virtual Devices are gone (Emulator) I just started to work and noticed that something is wrong with AndroidStudio. I have 3 Emulators that I've been using for some time. TODAY tho when I went inside AS I only have the option to create new Emulators but I cant use my old ones.
I still can see them inside the .android folder under avd - but not inside AS eventhough the Path for the SDK is the right one and hasnt changed since yesterday where everything worked as expected.
Does anybody know how to fix this?


text:
Q: $(this).append() not working in angularjs When I try to append in angularjs, I got an error like

jquery.min.js:3 Uncaught TypeError: Cannot read property
'createDocumentFragment' of undefined

The line I got error was
  $(this).append(stringDir);

Where stringDir is the p element. I added context:this to my ajax call
  to fix the error, but still showing the error.
    var app = angular.module('fileApp', []);

    app.controller('fileController', function($scope,$http) {
    $scope.getFile = function(event) {
        $scope.status = $scope.clickStatus;
        if($scope.status=="0" ) {
            $scope.clickStatus = "1";
            $scope.arrowStatus = "1";

            $scope.data = {
               path : $scope.current_directory
            };

            $(this).find($(".arrow ")).removeClass('fa fa-caret-right').addClass('fa fa-caret-down');

            $.ajax({
                type: "post",
                url: "/cfc/file.cfc?method=show",
                dataType : 'JSON',
                data : { path : $(this).attr('current_directory') },
                context :this,
                success:function(response) {
                var i=0;
                    if(response) {
                        var stringFile='';
                        var stringDir = '';
                        for(i=0; i< response.DATA.length;i++){
                            var val=(response.DATA[i]);
                            if(val[2]==="Dir"){
                                var newPath = val[6]+"\\"+val[0];
                                console.log(newPath);
                                stringDir += '
 '  + val[0]+'
';
                            }
                            else{
                                var newPath = val[6]+"\\"+val[0];
                                stringFile += '
  '+ val[0] +'
';
                            }
                        }
                        $(this).append($(stringDir));
                        $(this).append($(stringFile));
                    }
                },
                error:function (data){
                console.log(data);
                }
            });
        }
    }

   });

 HTML

 Local Disc D

A: Don't use this inside an ajax success callback block. Instead create a variable for the element before the ajax call and then refer to that variable to access that element inside the success callback. Something like below
 var element = this; //Hold the element in 'element' variable

   //Your ajax call
    $.ajax({
       url: "Any Url",
       success: function(response){
     if (response) {
      var stringFile = '';
      var stringDir = '';
      for (i = 0; i < response.DATA.length; i++) {
        var val = (response.DATA[i]);
        if (val[2] === "Dir") {
          var newPath = val[6] + "\\" + val[0];
          console.log(newPath);
          stringDir += '

            <
            /i>    '  + val[0]+'
';
        } else {
          var newPath = val[6] + "\\" + val[0];
          stringFile += '
    '+ val[0] +'
 ';
        }
      }
      $(element).append(stringDir);
      $(element).append(stringFile);
    }
       }

    })

A: You're right here 'this' is the controller, sorry! my mistake, but if you replace 'this' with the element reference then this code will run


text:
Q: I think I have a CSS/JavaScript problem? I have two problems... I've tried altering my CSS file, the JavaScript files and all kinds of other things. A google search yielded no remedy to these problems, so I come to the awesome site of answers!
This page -> http://students.cmps.subr.edu/aaron.chauvin/misc/test2.html
has some issues in Chrome and Safari. Only when my CSS is in effect, the pictures that are supposed to be side-by-side aren't, but when the CSS is off, they are. This problem isn't evident in FF/IE9. I'm thinking it has something to do with the   but I'm not totally sure. Edit Edit: Thanks for the fix Genzer!
Also on that page, even if all my CSS/JavaScript isn't linked, I have a small gap between the bottom of the images that are links and the dotted link border... I want to get rid of the gap. What's causing this gap? This happens in all browsers.
Thanks in advance.
Edit: Here's the CSS: http://students.cmps.subr.edu/aaron.chauvin/misc/style.css
Edit Edit: Fixed the side-by-side image link problem, now trying to figure out what's causing the variation in the display of the custom a:focus border (non-existent in IE9, partially encases image link in Webkit browsers) and the gap between it and the bottom of the image link (all browsers BUT IE9).

A: The problem is you're wrapping all your column's info in a span: ...
IE9 and FF figure out that you want it to display as a block element, but Webkit (Chrome and Safari) don't. Set display:block on the "reg" class and you should be set. (I think this fixes the "dotted border" issue as well, but i'm not quite sure what you meant there)
To get the orange border to show up in IE9, make sure to set outline-style to something like "solid" or "double" in the a.piclink:hover css class, in style.css. Once i did that, the border shows up.
I'm still not entirely sure why your links and nested images are behaving like they are, but I found a little tweak (tweak = almost a hack) to get it to work: Set display:inline-block; on  a.piclink and set a fixed height on it. Note that inline-block tacks on 4px, so the height should be 4px taller than the height of the image; in your case: 47px. It's a bit of a hack, but it's valid and it works. Unfortunately IE7 doesn't like this, but zoom:1; *display:inline; get it working.

A: Adding following CSS code in your style will make Chrome display your TestPage the same as IE8.
span.reg a {
    display: inline;
}


text:
Q: Mono for Android - How It works? I found that Xamarin apps run in Mono runtinme on Android, and things get passed to Dalvik. But what I can not understant is how is it possible that app is running in Mono, but normal app are executed in Dalvik. What is so different in Mono app that it runs in Mono and not Dalvik.
How can Mono be on the same level as Dalvik? Mono should be somehow stored in the app which runs in Dalvik, I think.
Please explain to me how is it possible, and sorry for my bad language.

A: An app developed by xamarin has the mono runtime which it takes with it onto the device. The app apk contains .net intermediate code, p-code, which obviously is not Dalvik understandable.
Xamarin.Android developers access the various features in the operating system either by calling into .NET APIs that they know (for low-level access) or using the classes exposed in the Android namespaces which provides a bridge to the Java APIs that are exposed by Dalvik.
http://docs.xamarin.com/guides/android/under_the_hood/architecture/ this is where you can find more details.


text:
Q: How to get JavaScript variable through PHP post request? I am posting the PHP file (post.php) through jquery ajax. And I want to get the data from it in the form of a javascript variable. I successfully get the data in my console. But I don't know how can I use this variable. You can see my code below.
$.post(
    "post.php",
    {
      region: region,
      district: district
    },
    function(data) {
      console.log(data);
    }
  );

my post.php page looks like this
    @include('../../_partials/_dbConnect.php');
    $region = $_POST['region'];
    $district = $_POST['district'];
    $sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
    $result = pg_query($db_connection, $sql);
        while ($row = pg_fetch_row($result)) {
            $cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
        }
<script>
  var cols = [<?php echo '"'.implode('","', $cols).'"' ?>];
</script>

And the console.log(data) output like this,
<script>
  var cols = ["94","32","361","0","118","159","0","243","702","1775","8","0","2","0","150","135","381","2","0","0","0","0"];
</script>

Your help is highly appreciated.

A: In your post.php, you can simply echo the array and jQuery should automatically convert it to an array as the response
// post.php
<?php
    @include('../../_partials/_dbConnect.php');
    $region = $_POST['region'];
    $district = $_POST['district'];
    $sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
    $result = pg_query($db_connection, $sql);

    while ($row = pg_fetch_row($result)) {
        $cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
    }

    echo json_encode($cols);
?>

// Somewhere in your js
$.post(
    "post.php",
    {
      region: region,
      district: district
    },
    function(data) {
      console.log(data[0]);
    }
);

A: in javascript use  JSON.parse()
$.post(
    "post.php",
    {
      region: region,
      district: district
    },
    function(data) {
      data=JSON.parse(data);
    }
);```

And here you go, u can play with it as you need
Happy learning!


text:
Q: Isotope filter from block view to table view I'm not finding anything with my search terms, so I'm hoping this hasn't been asked before: I'm using the Isotope plugin to filter a bunch of items. So far, so good. These items are generally all in a block, like a portfolio. However, the client would also like a filter option where it goes from the block layout to a separate list layout, like in the vertical layout mode. But that actually means probably a whole separate div needing to replace the block layout mode, so the vertical layout can be sorted as well. I've tried using the following jQuery to replace the div when clicking the corresponding button, but it's not working.

     <button class="btn btn-outline-primary active" data-sort-value="original-order">by state</button>
     <button class="btn btn-outline-primary" data-sort-value="name">by name</button>
     <button class="btn btn-outline-primary" data-sort-value="size">by size</button>
     <button class="btn btn-outline-primary" id="listClick">list view</button>

  all the grid items here

  My Static Content

  This is where the new vertical layout and filtering buttons would appear

I'm assuming that there's something about the isotope script that's interfering with trying to bind that button to something else. Any ideas? I'm not a jQuery expert by any stretch, but I'm pretty good at figuring stuff out. Explanations are very very welcome.


text:
Q: How to convert ReStructuredText docs to ipython notebooks? A lot of documentation in the python community these days is written in ReStructuredText. I want to convert some of these docs to ipython notebooks so that it is possible to not just read the examples in the docs, but interact with them immediately.
How can I convert ReStructuredTexts to ipython notebooks? Is there any way to do this? Maybe using pandoc as an intermediate step?
I have already read some docs on how to convert ipython notebooks to other formates, but I am interested in doing it the other way around, from rst to iptyhon. Any ideas?

A: If you are still looking for a solution, we are building a Sphinx extension to convert a collection of RST files to Jupyter notebooks.
sphinxcontrib-jupyter

A: In addition to sphinxcontrib-jupyter/jupinx, Google found rst2ipynb. It seems to use pandoc. I haven't yet tried it myself though.

A: There's a package for markdown to ipynb. notedown 1.0.3. You could use pandoc for rst to md then md to ipynb.


text:
Q: Programatically identifing feature for activation I have a requirement where a custom action is only added to the root site of the site collection. So planning to add two features one Site scoped and the other Web scoped.
In the event receiver of a Site scoped feature, I'm activating the Web scope feature.
For this i can use
web.Features.Add(webFeatureId);

How can I find the web level features feature id programmatically ?

A: Well. It really depends on which feature you have to activate.
The id of a feature does not change during its life. This means that if you can find out the id you will be sure it stays the same, regardless of the specific SharePoint farm instance. That said, you can "hardcode" your ID in a support class, much like SharePoint does with fields id in the SPBuiltInFields class.
If for any reason you can't know the feature ID beforehand you will need some other way to identify the feature - for example the display name. With that info you can use the FeatureDefinitions property of the SPWeb object to browse the installed 'Web' level features, search the one you need and add it to the Features collection to activate it as required.


text:
Q: TFS Changeset among 2 TFS Builds I have created a TFS build using TFVC as a source code repository. Now, I want to get a full information on all changesets that happened among previous and current build.
Any rest api for this ?
Same sort of thing is available in jenkins using following rest api
http://server:port/job/jobname/lastBuild/api/xml

A: According to  get list of changesets rest api
GET https://{instance}/DefaultCollection/_apis/tfvc/changesets?api-version={version}

There are multiple options such as by item path, by person. However it's not able to do what you want directly.
You could use in a date range option. Then you just need to get the starttime and finshtime  of your previous and current build through this API- Get build details by Timeline
GET https://{instance}/DefaultCollection/{project}/_apis/build/builds/{buildId}/timeline?api-version={version}

A: You can use Get build details - Changes in VSTS Rest API.


text:
Q: Проблема с !empty У меня есть данный код:
$text = $attr['something'];
if (!empty($text)){
  echo ''; // ничего не выводит
} else {
  echo '
'.$attr['something'].'
';
}
$output = $text;

Код работает, если поле с атрибутом ['something'] пустое, то он ничего не выводит
Но если я ввожу туда просто текст, он выведет его, но уже без li элемента.
В чем может быть проблема?
Другими словами мне нужно чтобы если значение $attr['something'] было пустое, то не выводить ничего, а если там хоть что-то написано, то вывести то что написано внутри li элемента
С php познакомился не так давно, буду благодарен за любую помощь
p.s я понял почему $output выводится без li элемента, потому что он просто выводит то что написано в $attr['something'], но я по прежнему не понимаю как вывести html код если значение не пустует

A: Ну во первых:

...если значение $attr['something'] было пустое, то не выводить ничего...

if (!empty($text)){
  echo ''; // ничего не выводит
}

Как-то на реалии не похоже, надо убрать !.
Во вторых:
Как вы определили что у вас
 не выводится? в браузере? посмотрите исходный код страницы. Если вам нужно прям на экране увидеть
 то http://php.net/manual/ru/function.htmlspecialchars.php
В третьих:
Так что вы хотите в $output - видеть результат для вывода? тогда так:
$text = $attr['something'];
if (empty($text)){
   $output = ''; // ничего не выводит
} else {
  $output = '
'.$attr['something'].'
';
}
echo $output;


text:
Q: Error: Vector subscript out of range. Line 1201 I am facing the vector subscript out of range erro. I have managed to locate the code that is causing the problem but i dont know how to solve it.
the defined variable types are,
typedef vector <string> v1; //vector string

typedef vector <v1> v2; // vector (v1) to create a double vector

typedef map<string, int> mapstint; //vector (string, int)

typedef vector<int> vint; // vector (int)

typedef vector<double> vd;

The CODE is as follows,
string splitgain(v2 &table)
{
    int col, i;

    string coln;
    mapstint map;
    double min = DBL_MAX;
    int splitcol = 0;
    vint eval,nos;

    for (col = 0; col < table[0].size() - 1; col++)
    {
        coln = table[0][col];
        vint counts = countno(table, col);
        vd atteval;
        double colval = 0.0;
        for (i = 1; i < table.size() - 1; i++)
        {
            double val = 0.0;
            if (map.find(table[i][col]) != map.end())
            {
                map[table[i][col]]++;
            }
            else
            {   map[table[i][col]] = 1;
                v2 tempt = prune(table, coln, table[i][col]);

                vint ccounts = countno(tempt, tempt[0].size() - 1);
                int j, k;
                for (j = 0; j < ccounts.size(); j++)
                {
                    double temp = (double)ccounts[j];
                    val -= (temp / ccounts[ccounts.size() - 1])*(log(temp / ccounts[ccounts.size() - 1]) / log(2));
                }
                atteval.push_back(val);
                val = 0.0;
            }
        }

        //------THIS IS WHERE THE ERROR IS COMING FROM-------

        for (i = 0; i < counts.size() - 1; i++)
        {
            colval += ((double) counts[i] * (double) atteval[i]);
        }
        //----------------------------------------------------

        colval = colval / ((double)counts[counts.size() - 1]);
        if (colval <= min)
        {
            min = colval;
            splitcol = col;
        }
    }
    return table[0][splitcol];
}

A: Please pay attention to the warnings of your compiler (or increase the warning level)
All loops

for (col = 0; col < table[0].size() - 1; col++)
for (i = 1; i < table.size() - 1; i++)
for (i = 0; i < counts.size() - 1; i++)

are trouble.
Note std::size_t(0) - 1 == std::numeric_limits::max()


text:
Q: Counter Button in Android application is not working properly with SharedPreferences I am having an issue concerning saving an integer that is modified by a Button. When the Button is pressed, the integer value goes up; however, when I close and reopen the application the integer is not being saved. I would be grateful for any help.
public class MyActivity extends Activity implements View.OnClickListener {

public static final String PREFS_NAME = "MyPrefsFile";

Button btn1;
Button btn2;
Button btn3;
Button btn4;
Button save;
TextView textTitle;
EditText scoreText;
EditText scoreText2;
int counter = 0;

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

    btn1 = (Button) findViewById(R.id.add);
    btn2 = (Button) findViewById((R.id.sub));

    scoreText = (EditText) findViewById(R.id.intro);

    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);

    final SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);

    scoreText.setText(prefs.getString("autosave" , ""));

    scoreText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // Do nothing

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // Do nothing

        }

       @Override
       public void afterTextChanged(Editable s) {

           prefs.edit().putString("autosave", s.toString()).commit();

        }

    });

    @Override
    public void onClick(View v) {

        if (v == btn1) {

            counter++;
            scoreText.setText(Integer.toString(counter));

        } else if (v == btn2) {

        counter--;
        scoreText.setText(Integer.toString(counter));

        }

    }

}

A: First, try moving your commit() line to the onTextChanged() callback and add a Log.d() call to help you debug.
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    Log.d("onTextChanged", s.toString());

    prefs.edit().putString("autosave", s.toString()).commit();

}

Check your log when the text is modified to make sure the callbacks are being triggered.
If that does not work, I would suggest moving the commit() line to the onClick() callback.
@Override
public void onClick(View v) {

    if (v == btn1) {

        counter++;
        scoreText.setText(Integer.toString(counter));
        prefs.edit().putString("autosave", scoreText.getText()).commit();

    } else if (v == btn2) {

        counter--;
        scoreText.setText(Integer.toString(counter));
        prefs.edit().putString("autosave", scoreText.getText()).commit();

    }

}


text:
Q: How to use a column in dataframe as dictionary key value? Suppose there is a dataset.
Let's say that the dataset has a column A which contains city names like "New York", "California", or "Florida"
now we have a dictionary like
my_dict = {"New York":1, "California":2, "Florida":3}

So I need to generate a column B such that if column A has a row value "New York", then column B has the value 1 as in the dictionary.
I used the lambda function and it worked but is it possible without the use of the lambda function?

A: This seems rather contrived but works:
df = pd.DataFrame([my_dict]).stack().reset_index()
df.drop(df.columns[[0]], axis=1, inplace=True)
df.columns = ['A', 'B']

and gives
            A  B
0    New York  1
1  California  2
2     Florida  3

A: Method 1
import pandas as pd

my_dict = {"New York":1, "California":2, "Florida":3}

# creating dataframe from dictionary itself, for reproducing the scenario
existing_df = pd.DataFrame({"reference_column" : my_dict.keys()})

# duplicate the reference column (city column)
existing_df["value_column"] = existing_df["reference_column"]

# replace the values in duplicate column with corresponding values from dictionary
existing_df.replace({"value_column" : my_dict}, inplace = True)

Explanation :
df.replace({'column' : replacement_dictionary}) is a find and replace technique.  find compares the values of column with keys of replacement_dictionary.  If the key matches, its value is used to replace existing value of column
Method 2
import pandas as pd

my_dict = {"New York":1, "California":2, "Florida":3}

# reproducing original dataframe with reference city column
existing_df = pd.DataFrame({"reference_column" : my_dict.keys()})

# dictionary coverted into dataframe
replacement_df = pd.DataFrame({"reference_column" : my_dict.keys(), "value_column" : my_dict.values()})

# left join both on city column with original df as left table
merge_df = existing_df.merge(replacement_df, on = ["reference_column"], how = "left")

Explanation :
Dictionary can be converted into dataframe (replacement_df) with keys as one column and values as another column.  This converted dataframe can be merged with existing dataframe on the condition that city names in existing dataframe should match with city names in replacement_df
Output of both methods :


text:
Q: PHP : Cut Direction from string I have string like :
 /home/kamal/public_html/clients/book/wp-content/uploads/wpcf7_uploads/1983322598/k.jpg

i need to get only
wp-content/uploads/wpcf7_uploads/1983322598/k.jpg

How can do that ?

A: $string = "/home/kamal/public_html/clients/book/wp-content/uploads/wpcf7_uploads/1983322598/k.jpg";

$exploded_string = explode("/", $string);
//$exploded_string is now an array of: home, kamal, public_html.... ...k.jpg

$n = array_search("wp-content", $exploded_string);
//$n is now the index of "wp-content" in the $exploded_string array

$new_path = array_slice($exploded_string, $n);
$new_path = implode("/", $new_path);

echo $new_path;


text:
Q: elementary problem in combinatorics Let $X=\{1,2,3,4,5,6,7,8,9,10\}$ and $R$ be a set defined by $$\{(x,y)\in X\times X: \text{$x$ and $y$ have the same remainder when divided by $3$}\}$$  Then what's the numbers of elements in $R$?  My approach is
$\bar{0} = \{3,6,9\}$ so we can get $2!\binom{3}{2}$ numbers of elements
$\bar{0}= \{1,4,7,10\}$ we get $2!\binom{4}{2}$ elements
$\bar{2} = \{2,5,8\}$ we get $2!\binom{3}{2}$ elements
Now counting all the elements like $(1,1),(2,2)$ and so on..., I get the answer $34$.  Is it correct?

A: Your answer is correct.
$R\subset X\times X$ can be recognized as an equivalence relation. As comes forward in your question its equivalence classes are $\{3,6,9\}$, $\{1,4,7,10\}$ and $\{2,5,8\}$.
Then: $$R=\left[\{3,6,9\}\times\{3,6,9\}\right]\cup\left[\{1,4,7,10\}\times\{1,4,7,10\}\right]\cup\left[\{2,5,8\}\times\{2,5,8\}\right]$$
And its cardinality is $3^2+4^2+3^2=34$


text:
Q: Need clarification about the VOIP this is my continuation of my previous question Java SipServlet to build VOIP phone calls (between Computer and analog phone/mobile)
I've stumbled across a opensource softphone to use it to try make a phone call but the software requires the SIP provider. And according to my searching on google so far, purpose of SIP phone is to make a phone call between two SIP caller and callee which mean those two people have to have registered with one of a SIP provider. But my current goal is to make VOIP to call to my ordinary mobile phone or land line phones (no matter what phone providers they are using), and software like Skype or Google phone can already do that. I'm right now researching about sip servlet, am I going into a wrong direction right now?

A: For a SIP call to go to a cell or land line phone you need a piece of hardware called a VoIP Gateway that translates between the SIP protocol and a digital or analog phone line. I am sure Skype and Google have an infrastructure setup that hooks directly to the big carriers to handle this.
By the way, Skype is not SIP but uses their own proprietary VoIP protocol.
What is Google phone? Are you referring to Google Voice?


text:
Q: Angular 5 ng-select edit selected item I am using ng-select in my ionic application so that user can select multiple email address in a textarea.

I want to edit selected email address by tapping/clicking on the tile. Once user tap/click on the selected email address, email address should append in textbox in editable mode.


text:
Q: Ruby/Rails library for DRYing up resource access A common pattern in a Rails controller action is to

*

*Fetch a resource

*Do something to the resource (optional)

*Return the resource in a serialized format.

I am looking for a library that abstracts away the first step, so that my controller actions can assume a resource was successfully fetched and avoid checks for exceptional cases.
For example, here is a hypothetical show action:
def show
  attrs   = params.slice(:handle, :provider)
  account = Account.find_by(attrs)

  if account
    respond_with account
  else
    head 404
  end
end

And what I want is something more like this:
# controller
def show
  respond_with resource
end

# some initializer (basically pseudocode)
resource do |params|
  attrs = params.slice(:handle, :provider)
  Account.find_by(attrs)
end

Where the library would handle returning a 404 if find_by returns nil, or 400 if the provided params are invalid (missing :handle key, include an extra :id key, etc.).
Does anyone know of a library that provides something like this? It is a great use case for a Rack middleware on top of Application.routes.

A: The gem platformatec/inherited_resources does something very close to this.


text:
Q: Convert a `char *` to UTF-8 in C, or when using xmlwriter? I'm using libxml/xmlwriter to generate an XML file within a program.
const char *s = someCharactersFromSomewhere();
xmlTextWriterWriteAttribute (writer, _xml ("value"), _xml (s));

In general I don't have much control over the contents of s, so I can't guarantee that it will be well-formatted in UTF-8. Mostly it is, but if not, the XML which is generated will be malformed.
What I'd like to find is a way to convert s to valid UTF-8, with any invalid character sequences in s replaced with escapes or removed.
Alternatively, if there is an alternative to xmlTextWriterWriteAttribute, or some option I can pass in when initializing the XML writer, such that it guarantees that it will always write valid UTF-8, that would be even better.
One more thing to mention is that the solution must work with both Linux and OSX. Ideally writing as little of my own code as possible! :P

A: In case the string is encoded in ASCII, then it will always be valid UTF-8 string.
This is because UTF-8 is backwards compatible with ASCII encoding.
See the second paragraph on Wikipedia here.
Windows primarily works with UTF-16, this means you will have to convert from UTF-16 to UTF-8 before you pass the string to the XML library.

A: If you have 8-bit ascii input then you can simply junk any character code > 127.
If you have some dodgy UTF-8 it is quite easy to parse, but the widechar symbol number that you generate might be out of the unicode range. You can use mbrlen() to individually validate each character.
I am describing this using unsigned chars. If you must use signed chars, then >128 means <0.
At its simplest:
Until the null byte
 1 If the next byte is 0, then end the loop
 2 If the next byte is < 128 then it is ascii, so keep it
 3 If the next byte is >=128 < 128+64 it is invalid - discard it
 4 If the next byte is >= 128+64 then it is probably a proper UTF-8 lead byte
   call size_t mbrlen(const char *s, size_t n, mbstate_t *ps);
   to see how many bytes to keep
   if mbrlen says the code is bad (either the lead byte or the trail bytes),
     skip 1 byte. Rule 3 will skip the rest.

Even simpler logic just calls mbrlen repeatedly, as it can accept the low ascii range.
You can assume that all the "furniture" of the file (eg xml <>/ symbols, spaces, quotes and newlines) won't be altered by this edit, as they are all valid 7-bit ascii codes.

A: char is a single byte character, while UTF codepoints range from 0 to 0x10FFFFF, so how do you represent a UTF character in only one byte?
First of all you need a wchar_t character.  Those are used with wprintf(3) versions of the normal printf(3) routines.  If you dig a little on this, you'll see that mapping your UTF codepoints into valid UTF-8 encoding is straigtforward, based on your setlocale(3) settings.  Look at those manual pages referenced, and you'll get an idea of the task you are facing.
There's full support for wide character sets in the C standard... but you have to use it through the internationalization libraries and locales availables.


text:
Q: Visual Studio 2022 build failed, but Visual studio 2019 build succeeded I have a solution with many c# and c++ projects, but I'm interested in 2 of them: let's call them C++ proj1 and C# proj2 and proj2 is referensing to proj1.
Solution builds succesfully in vs2019, but build failed in vs2022.
When I try to build the solution in vs2022 I see the following in the build output:
Warning:
C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(2302,5): warning MSB3274: failed to resolve reference "C:\...\Debug\proj1.dll",because it was built using the platform ".NETFramework,Version=v4.7.2". This is a later version than the current target platform (".NETFramework,Version=v4.5").

And right after that I get the error:
C:\...\proj2\MyClass.cs(1,7,1,22): error CS0246: Could not find type or namespace name "proj1" (possibly missing using directive or assembly reference).

But there is no such error during design (in vs 2022) and no such waraning and error in vs 2019 during the build.
I understand that the error is that an older framework version targeting a newer framework version. But then I don't understand why in vs 2019 the solution builds successfully.
How can I resolve this build issue in vs 2022?


text:
Q: how to insert a row in table , mysql using bash - when $ is used? I am trying to insert a row in MySQL table using bash, I have saved the below script as script.sh and I run using
bash script.sh
When the script is executed, it is successful with no errors but the password field which contains an encrypted value('$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2') is stored as some other value like
b0.AwGA3VEtUs5YIAjjUWSSEI3Fqt2
instead of
$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2
I tried using '' and "" and `` , all of them didn't work
So how do I insert when having an $ value ?
#!/bin/bash
mysql <<EOF
GRANT ALL PRIVILEGES ON *.* TO "test_mysql_user"@"localhost" IDENTIFIED BY "test_password";

FLUSH PRIVILEGES;
create database cricket;
use cricket;

//created tables
.....
.....

INSERT INTO admin
(
admin_id,
first_name,
middle_name,
last_name,
email_id,
password,
address,
city,
state,
zip_code,
country,
phone_code,
phone_number,
email_campaign)
VALUES
(
'root',
'root',
'root',
'root',
'root@gmail.com',
'$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2', //this field is the error , saved as someother value
'root',
'root',
'root',
'root',
'root',
'root',
'root',
'root');
EOF

A: You have to quote the 'EOF' string for if you want no parameter substitution.
From man bash | less +/"Here Documents"
Here Documents
This type of redirection instructs the shell to read input from the current source until a line  containing  only  word
(with  no  trailing  blanks) is seen.  All of the lines read up to that point are then used as the standard input for a
command.
The format of here-documents is:
<<[-]word
        here-document
delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word.  If any
characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document
are not expanded.  If word is unquoted, all lines of the here-document are subjected to  parameter  expansion,  command
substitution,  and  arithmetic expansion.  In the latter case, the character sequence <newline> is ignored, and \ must
be used to quote the characters , $, and `.
If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line contain-
ing delimiter.  This allows here-documents within shell scripts to be indented in a natural fashion.
So, your script should look like this when you quote the 'EOF' string
mysql <<'EOF'
GRANT ALL PRIVILEGES ON *.* TO "test_mysql_user"@"localhost" IDENTIFIED BY "test_password";

FLUSH PRIVILEGES;
create database cricket;
use cricket;

//created tables
.....
.....

INSERT INTO admin
(
admin_id,
first_name,
middle_name,
last_name,
email_id,
password,
address,
city,
state,
zip_code,
country,
phone_code,
phone_number,
email_campaign)
VALUES
(
'root',
'root',
'root',
'root',
'root@gmail.com',
'$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2',
'root',
'root',
'root',
'root',
'root',
'root',
'root',
'root');
EOF

If quoting word is not an option for you and want to avoid the parameter substitution just for the encrypted password field, store the encrypted  value in a variable and use that variable in the doc.
password='$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2'

mysql <<EOF
INSERT INTO admin
(
admin_id,
first_name,
middle_name,
last_name,
email_id,
password,
address,
city,
state,
zip_code,
country,
phone_code,
phone_number,
email_campaign)
VALUES
(
'root',
'root',
'root',
'root',
'root@gmail.com',
'$password',
'root',
'root',
'root',
'root',
'root',
'root',
'root',
'root');
EOF


text:
Q: How to make this slide roll each time I press the button? I managed to make it run, but only once.
jsfiddle.net/geyck9jL/
How to make this slide roll each time I press the button?

A: I made a little something for you.
http://jsfiddle.net/Bes7weB/ajvdx2ct/
First, you have to correctly define the possible positions.
Then, using an array, you can "cycle" the elements on each click event.
$(document).ready(function() {

  // Define the 3 possible positions
  var pos1 = {    // Same as CSS slLeft
      height: '210px',
      width: '280px',
      left: "10%",
      'margin-left':0,
      top: "8%"
    };
  var pos2 = {    // // Same as CSS slMiddle
      height: '300px',
      width: '400px',
      left: '50%',
        'margin-left':'-25%',
        top: '3%'
    };
  var pos3 = {    // // Same as CSS slRight
      height: '210px',
      width: '280px',
      left: "55%",
      'margin-left':0,
      top: "8%"
    };

  // Define an array of divs containing pictures an caption
  var divArray = [$("#slRight"),$("#slLeft"),$("#slMiddle")];

  // The click function
  $("button").click(function() {

    divArray[0].animate(pos1, "slow");
    $(divArray[0]).css('z-index', '2', "slow");

    divArray[1].animate(pos2, "slow");
    $(divArray[1]).css('z-index', '3', "slow");

    divArray[2].animate(pos3, "slow");
    $(divArray[2]).css('z-index', '1', "slow");

    // Rotate elements in divArray
    divArray = [divArray[2],divArray[0],divArray[1]];
  });
});

A: First, I would change your css to be classes not ids.  So you would have '.sl1 {//some css}, etc.
Second, I would iterate over an array of the divs, so if you want to add another in the future, your code doesn't have to be completely re-written.
$(document).ready(function(){
    index       = 0;
    arrDivs     = [$("#derp"),$("#dorp"),$("#dirp")];

    $("button").click(function(){
        curDiv          = arrDivs[index];       //get the next div
        $.each(arrDivs,function(i){ //loop over your divs
            if(arrDivs[i] == curDiv) {  //this is the active div
            //...... do something to your active div
            } else {
            //.....do something to your inactive divs
            }
        })
        if(index >= (arrDivs.length-1)) {       //check if we are at the end of the array
            index = 0;                          //set the index to zero or first position
        } else {
            index++;                            //increment the index
        }
    });
});


text:
Q: please help me to align the formulas as follows For Crushing Glass,
Mini pressure applied in the cylinder (P) = 6.86x105N/m2
Diameter of the cylinder (D) = 32 mm
Diameter of the piston rod (d) = 17 mm
Stroke length = 100 mm
Area of cylinder (A) = (3.14/4*(D2)
                 = (0.785x.0322)
               A= 8.0384 x 10-4 m2
Force during forward stroke,
F = {π/4x D^2 x P}
F = (6.86 x 105 N /m2) (3.14/4*(0.0322)
F = 551.43 N
       1kg = 9.81 N
    Load capacity during forward stroke W= F / a
                                      W =    551.43 / 9.81
                                      W =     56.21 KG
Force during return stroke,
F = {π/4x (D^2 – d^2) x P}
F = {π/4x (0.032^2 – 0.017^2) x 6.86x105}
 F = 395.99 N
Load capacity during return stroke W= F / a
                                      W =    395.99 / 9.81
                                      W =     40.36 KG
For  Plastic bottles,
Mini pressure applied in the cylinder (P) = 5.39x105N/m2
Diameter of the cylinder (D) = 32 mm
Diameter of the piston rod (d) = 17 mm
Stroke length = 100 mm
Area of cylinder (A) = (3.14/4*(D2)
                 = (0.785x.0322)
               A= 8.0384 x 10-4 m2
Force during forward stroke,
F = {π/4x D^2 x P}
F = (5.39 x 105 N /m2) (3.14/4*(0.0322)
F = 433.26 N
       1kg = 9.81 N
    Load capacity during forward stroke W= F / a
                                      W =    433.26 / 9.81
                                      W =     44.16 KG
Force during return stroke,
F = {π/4x (D^2 – d^2) x P}
F = {π/4x (0.032^2 – 0.017^2) x 5.39x105}
 F = 311.13 N
Load capacity during return stroke W= F / a
                                      W =    311.13/ 9.81
                                      W =     31.71 KG

For Crushing aluminium cans,
Mini pressure applied in the cylinder (P) = 4.41x105N/m2
Diameter of the cylinder (D) = 32 mm
Diameter of the piston rod (d) = 17 mm
Stroke length = 100 mm
Area of cylinder (A) = (3.14/4*(D2)
                 = (0.785x.0322)
               A= 8.0384 x 10-4 m2
Force during forward stroke,
F = {π/4x D^2 x P}
F = (4.41 x 105 N /m2) (3.14/4*(0.0322)
F = 354.49 N
       1kg = 9.81 N
    Load capacity during forward stroke W= F / a
                                      W =    354.49 / 9.81
                                      W =     36.135 KG
Force during return stroke,
F = {π/4x (D^2 – d^2) x P}
F = {π/4x (0.032^2 – 0.017^2) x 4.41x105}
 F = 254.56 N
Load capacity during return stroke W= F / a
                                      W =    254.56 / 9.81
                                      W =     25.94 KG

A: I think you should set up a two-column table, with the textual descriptions on the left and the formulas and numerical examples on the right. Do also take care to typeset the scientific units correctly.
The first few rows might look as follows:

\documentclass{report}
\usepackage{amsmath,longtable,booktabs,array,siunitx}
\sisetup{per-mode=symbol}
\begin{document}

\begin{longtable}{@{}l >{$}l<{$} @{}}
\toprule
\endhead
\bottomrule
\endfoot
For Crushing Glass,\\
Mini pressure applied in the cylinder & P = 6.86 \cdot 105\, \si{\newton\per\meter\squared} \\
Diameter of the cylinder &D = \SI{32}{\milli\meter}\\
Diameter of the piston rod & d = \SI{17}{\milli\meter}\\
Stroke length & \SI{100}{\milli\meter}   \\
Area of cylinder &
\!\begin{aligned}[t]
A &= \pi/4\cdot D^2\\
  &= 0.785\times .0322\\
  &= \SI{8.0384e-4}{\meter\squared}
\end{aligned} \\
Force during forward stroke &
\!\begin{aligned}[t]
F &= \pi /4\cdot D^2 \cdot P\\
  &= 6.86 \cdot 105\,\si{\newton\per\meter\squared} \quad(3.14/4\cdot 0.0322)\\
 &= \SI{551.43}{\newton} \quad (\SI{1}{\kilo\gram} =\SI{9.81}{\newton})
\end{aligned} \\
Load capacity during forward stroke & W=\dots \\
\end{longtable}
\end{document}


text:
Q: How to sandbox an Rscript command I am currently in the directory /root/mydir. I have an R script (myscript.R) which contains:
list.files("/var/www/html/")

I execute the script using the following command:
Rscript myscript.R

The output is the list of contents of directory /var/www/html/ as expected.
How can I run Rscript in a sandbox mode that prevents the script from accessing files outside the current directory?


text:
Q: Execution of Visual Force page using Apex class I Have a Apex class:
global with sharing class AccountRemoter {

    public String accountName { get; set; }

    public static Account account { get; set; }

    public AccountRemoter() { } // empty constructor

    @RemoteAction

    global static list<Account> getAccount(String accountName) {

        list<account> account1 = [SELECT Id, Name, Phone, Type, NumberOfEmployees

                   FROM Account WHERE Name = :accountName];

        return account1;

    }

}

Visual Force Page:
<apex:page controller="AccountRemoter">

    <input id="acctSearch" type="text"/>

    <button onclick="getRemoteAccount()">Get Account</button>

    <apex:pageBlock id="block">

        <apex:pageBlockSection id="blockSection" columns="2">

            <apex:pageBlockSectionItem id="firstItem">

            </apex:pageBlockSectionItem>

            <apex:pageBlockSectionItem id="secondItem">

                <apex:outputText id="acctNumEmployees"/>

            </apex:pageBlockSectionItem>

        </apex:pageBlockSection>

    </apex:pageBlock>

</apex:page>

Output for the Above Code:

But the output is Showing is undefined and undefined?when entering the account in the search account textbox? why? I want perfect output and why we have to use @Remote action annotation in the Apex class? what is the use?Please anyone guide me for the Answer

A: Your Apex code return a list of Account objects not a single Account object so you need to handle the result value accordingly:
if (event.status) {
    for (var i = 0; i < result.length; i++) {
        var account = result[i];
        var id = account.Id;
        var n = result.NumberOfEmployees;
        // You will need to create e.g. a table here
        console.log('id=' + id + ' n=' + n);
    }
}

You get undefined when you try to access a field of a JavaScript object that does not exist.
Note that the debug tools in browser's are excellent and a small investment in time learning about them will quickly pay back.
Have you considered not using JavaScript here? You can write a Visualforce page that has no JavaScript that does the same thing with much less code.


text:
Q: Retrieve value from a form and write to a file i have a form named

index.cgi

and a configuration file named

video.start

After the user select from the drop down menu and press submit, the value will be read and write into the configuration file. Here is a snippet from my form:

<form method="POST" action="index.cgi">

Video

Video Source :
<select name="channel1" size="1">
<option value="/dev/video0">/dev/video0</option>
<option value="/dev/video1">/dev/video1</option>
<option value="/dev/video2">/dev/video2</option>
<option value="/dev/video3">/dev/video3</option>
</select>

<input type="submit" value="Submit"><input type="reset" value="Clear">

</form>

and here is the code from index.cgi:
my $file = "video.start";

open (my $in, "+<", $file);
open (my $out, "+<", $file);

my $a = CGI->new();
$video = $a->param('channel1');

while(<$in>)
{
    print $out $_;
    last if $.==3;
}

while(my $data = <$in>)
{
    #logic

    print $out $data;
    last if $.==5;
}

Finally, here is what my configuration file looks like:
#Only change at [udp://#] segment
#This config file is for video

ffmpeg -f video4linux2 -i /dev/video0 -vcodec libx264 -preset ultrafast -tune zerolatency -s qvga -r 30 -qscale 5 -an -flags low_delay -bsf:v h264_mp4toannexb -maxrate 750k -bufsize 3000k -rtbufsize 300k -f h264 udp://#

If you can see from the configuration form, after the user submitted the value, the /dev/video0 will change in the configuration file according to the value submitted by the user. But how can i achieve this in my logic?

A: The biggest trick to this is that you need to flock your files before editing them so there isn't a race condition.
use strict;
use warnings;
use autodie;

use Fcntl qw(:flock);

open my $fh, '<+', 'foobar.txt';
flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";

After that, just read How do I change, delete, or insert a line in a file, or append to the beginning of a file?.   I personally would go with Tie::File as I think that's probably the easiest way to edit a file in this context.


text:
Q: Why php variable cant work with javascript loop? I expected that the number will increase on every alert, but it ended up being the same number which is 0.
Can I know why ?
I need to do this because in my real code, $wow represent the value I retrieved from server and I need to use javascript for loop to count the number element which I targeted.
How can i do this ?
Here is my Code :
<html>
<head>
<script>
<?php $wow = 0; ?>
for(var i =0; i < 4; i++){
   alert("<?php echo $wow; ?>");
    <?php $wow++; ?>
    }
</script>
<body>
</body>
</html>

A: PHP is executed on the server side, JavaScript on the client side.
The way it works is like this:

*

*browser makes request

*server receives request

*server executes PHP

*server sends response/HTML

*browser receives response/HTML

*browser parses HTML / executes JS.

Just have a look at the document source in the browser, there is no PHP in there because it was already executed (on the server).

What you can do instead is inject the value of the PHP variable into the JavaScript source code and manipulate the value with JavaScript:
var wow = <?php echo $wow; ?>
for(var i =0; i < 4; i++){
  alert(wow);
  wow++;
}

See also

*

*Pass a PHP string to a JavaScript variable (and escape newlines)

*How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

A: how about this one:
<html>
<head>
<script>
<?php
    $wow = 0;
    while($wow < 4){
        echo "alert('" . $wow++ . "')";
    }
?>
</script>
<body>
</body>
</html>

A: php script is executed server side as per @Felix Kling comment..
dont define variable in php as php script executed server side not client side like javscript
u need to change script like ..
var wow = <?php echo $wow; ?>

for(var i =0; i < 4; i++){
   alert("<?php echo wow; ?>");
    <?php echo wow++; ?>
    }

but there is no meaning to use/create variable via php script
you can just simply write like this
var wow = <?php echo $wow; ?>
    for(var i =0; i < 4; i++){
       alert(wow);
       wow++;
        }


text:
Q: Real Analysis: Uniform Continuity Proof Verification I currently attempting a proof of Uniform Continuity and am unsure if need an extra step. I have put the question and work I've done down below.
Q: Show that if $f$ is continuous on $[0,\infty)$ and $\lim \limits_{x \to \infty} f(x)=L$, then $f$ is uniformly continuous on $[0,\infty)$
Pf:   Let $\epsilon>0$
Since it is stated that $\lim \limits_{x \to \infty} f=L$ exists we can state by def: For every $\epsilon$, there exist a $K>0$ s.th for any $x>K$ then $\lvert f(x)-L\rvert < \frac{\epsilon}{2}$
We will now split our domain into three cases and since our domain goes to infinity we will let $K$ distinguish our three cases.
(1) Suppose our interval is $[K,\infty)$ and $x\ge K$. Since we know $\lvert f(x) -L \rvert < \frac{\epsilon}{2}$ it follows that:
For every $\epsilon > 0$ there exist $K>0$ s.th for every $x,u$ if $\lvert x-u \rvert <\delta$, then $\lvert f(x) -f(u)\rvert = \lvert f(x) - L + L -f(u)\rvert \le \lvert f(x)-L \rvert + \lvert L -f(u)\rvert \le \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon$
Therefore $f$ is uniformly continuous on $[K,\infty)$.
(2)Suppose our interval $I=[0,K]$. Since the interval is closed and bounded and $f$ is continuous on $I$, BOW uniform continuity theorem $f$ is uniformly continuous.
(3).......
I know I need to prove that $K \in (x,y)$ is uniformly continuous but I don't know if I need seprate step for this or if I can just draw from ideas from steps 1 and 2 to prove that $K \in (x,y)$ is uniformly continuous.
Any help for proving the last part and improving previous steps would be greatly appreciated.

A: Assume that $|f(x)-L|<\epsilon/3$ for all $x\geq K$. So the part $[K,\infty)$ has been controlled.
Now $f$ is continuous at $x=K$, so there is some $\delta_{1}>0$ such that $|f(x)-f(K)|<\epsilon/3$ for all $|x-K|<\delta_{1}$.
Now $f$ is continuous on $[0,K]$, so it is uniformly continuous on $[0,K]$, so there is some $\delta_{2}>0$ such that $|f(x)-f(y)|<\epsilon/3$ for all $x,y\in[0,K]$ and $|x-y|<\delta_{2}$.
By taking $\delta=\min\{\delta_{1},\delta_{2}\}$, for all $x,y\in[0,\infty)$ and $|x-y|<\delta$, we have several cases.
Case I. Both $x,y\in[0,K]$, then $|f(x)-f(y)|<\epsilon/3<\epsilon$.
Case II. One of $x\in[0,K]$ and $y\in(K,\infty)$, then $0\leq K-x=K-y+y-x<y-x<\delta$, then $|f(x)-f(y)|\leq|f(x)-f(K)|+|f(K)-L|+|f(y)-L|<\epsilon/3+\epsilon/3+\epsilon/3=\epsilon$.
Case III. Both $x,y\in[K,\infty)$, then $|f(x)-f(y)|\leq|f(x)-L|+|f(y)-L|<\epsilon/3+\epsilon/3<\epsilon$.

A: For $e>0$ take $K_e\in \Bbb R^+$ such that $x\geq K_e\implies |f(x)-L|<e/2.$
Take $d_e>0$ such that $$x\in (-d_e+K_e,d_e+K_e)\cap [0,\infty)\implies |f(x)-f(K_e)|<e/2.$$ Since $f$ is uniformly continuous on $[0,K_e],$ take $d'_e>0$ such that $$\;(x,y\in [0,K_e] \land |x-y|<d'_e\;) \implies |f(x)-f(y)|<e.$$ Let $d''_e=\min (d_e,d'_e).$
If $x,y \in [0,K_e]$ then $|x-y|<d''_e\implies |x-y|<d'_e\implies |f(x)-f(y)|<e.$
If $x,y\in [K_e,\infty)$ then $$ |f(x)-f(y)|\leq |f(x)-L|+|L-f(y)|<e/2+e/2=e.$$
If $x\in [0,K_e]$ and $y\in [K_e,\infty)$ then $$|x-y|<d''_e\implies (\;x\in (-d''_e+K_e,K_e]\;\land \; y\in [K_e,d''_e+K_e)\;)\implies$$ $$\implies (\;x,y \in (-d_e+K_e,d_e+K_e)\;)\implies$$ $$\implies|f(x)-f(y)|\leq |f(x)-f(K_e)|+|f(K_e)-f(y)|<e/2+e/2=e.$$


text:
Q: Standard charger for Macbook Pro insufficient I recently bought a MacBook Pro (15-inch, 2018) and I am using the OOTB Power Adaptor (87W) and USB-C cable.
I am finding that when I run computationally expensive processes (e.g. I utilize multiple cores for data analysis), that the laptop will discharge (albeit at a slower pace) even when plugged in. This is obviously problematic if I have a continuous process, that is meant to last multiple hours.
This laptop is an upgrade from a 2015 MacBook Pro, with the Magsafe 2 Power Adaptor, on which I never experienced this problem.
Is there a solution to this? Perhaps an upgrade to the Power Adaptor (I think 87W is the max Apple provides) or the USB C Cable? Or is there something else?


text:
Q: How to apply linear gradient to the border of circle? I am trying to achieve linear gradient in the circle of the label like below image in ionic:

At first, i made a circle at the start of the input using below code:
// in .html
<ion-item class="wrapper border-radius-23">
  <ion-label class="email-label">
    <ion-icon name="person" class="text-red"></ion-icon>
  </ion-label>
  <ion-input clearInput type="text" placeholder="Email" class="user-email-input"></ion-input>
</ion-item>

// in .scss file
  .user-email-input {
    height: 46px;
    width: 100%;
    display: block;
    border-radius: 23px;
    box-sizing: border-box;
    padding-left: 50px;
    outline: none;
  }

  .email-label {
    border-radius: 50%;
    border: 2px solid red;
    position: absolute;
    top: -13px;
    left: 0;
    width: 46px;
    height: 46px;
    z-index: 9;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
  }

and achieved like below:

Now, when i tried to apply gradient in the circle, i could achieve only like below:

I changed the css of the email label like below:
.email-label {
        border-image: linear-gradient(to right, red 0%, orange 100%);
        border-image-slice: 1;
        border-radius: 50%;
        border: 2px solid;
        position: absolute;
        top: -13px;
        left: 0;
        width: 46px;
        height: 46px;
        z-index: 9;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
      }

Can anyone point my mistake?

A: You can make the gradient circle as follows:

.rounded {
  width: 100px;
  height: 100px;
  border: 4px solid transparent;
  border-radius: 80px;
  background-image: linear-gradient(white, white), linear-gradient(to right, red, orange);
  background-origin: border-box;
  background-clip: content-box, border-box;
}


text:
Q: Django 1.6 ORM count subset of related items I have these models
class BlogEntry(models.Model):
    tags = models.ManyToMany(Tag, ...)
    ...

class Tag(models.Model):
    ...

and a subset of tags:
tag_list = list(*some tag objects*)   # can refactor to queryset

I need to get the number of tags for each BlogEntry that is in my tags list, so something like this:
# Non-working code ahead
BlogEntry.objects.annotate(match=Count(tags__in=tag_list))

I've got this code to run just fine
# working code ahead
for entry in BlogEntry.objects.all():
        match = len(set(entry.tags.all()).intersection(tag_list))

But I feel like doing the counting and intersecting in python rather than in the database could pose a performance issue down the road.

A: See the documentation on the order of annotate() and filter() clauses.
As that section says, if you filter before you annotate, then the annotation will only include elements matched by the filter. So:
BlogEntry.objects.filter(tags__in=tag_list).annotate(match=Count(tags))


text:
Q: Latest libraries for jQuery drag drop I have a website which uses drag drop. At the moment I use
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>

Which ones are needed, and can someone explain the difference between

*

*jquery.min.js

*jquery-ui.min.js

*jquery-ui.css (I guess its for the design of jQuery function?)

And can I use different versions of them or do I need to use the same version.
1.9.1/jquery.min.js
and
1.10.1/jquery.min.js
At the moment dropable isn't working in ie10 but i want to see if the version of jQuery makes any difference.

A: jQuery and jQuery UI are two entirely different projects.
jQuery:
jQuery is javascript library which provides easy and browser compatable dom manipulation, traversl, ajax etc. It has no dependency with jQuery UI.
jQuery UI:
It is a provides a rich set of user interface tools like datepicker, drag-drop etc, it depends on jQuery project.
In your case you can use jQuery 1.9.1 and jQuery UI 1.10.1 without any problems


text:
Q: Mac Command key on Virtualbox OS X Virtual Machine On Windows Not Registering So I was having a hard time with getting the command key to work when trying to use keyboard shortcuts in a OS X virtual machine on Windows 10.
So I was trying to see if the shortcut Command + Space to open Spotlight would work.
Pressing Ctrl + Space, Right Ctrl + Space, Alt + Space, Right Alt + Space, Windows + Space, and Right Windows + Space would not work. The host key was set to Right Ctrl in Virtual Box and changing this made no difference. Right Ctrl + Space was also not set as a shortcut key in VirtualBox.
The solution to the problem is below.

A: I stumbled upon this article.
Lo and behold, going to System Preferences > Keyboard > Modifier Keys in OS X and changing:
Option Key to Command Key
and
Command Key To Option Key
...fixed my problem!
Now all I have to do is press Alt + Space for Spotlight to show up. All other Mac shortcuts will now work as well.
Hope this helps others who may have the same problem.

A: Thanks @Kian for settings location (System Preferences > Keyboard > Modifier Keys).
While swapping Option and Command keys didn't work for me, assigning
Control: Command
Option: Command
Command: No action
made both Ctrl and Alt keys work properly


text:
Q: select td elemensts with colspan How can I get all td elements with 'colspan' greater than 1 in jQuery?
var nodes = $('td[colspan>1]');

The code above seems doesn't work.

A: Use filter:
var nodes = $('td[colspan]').filter(function() {
  return +$(this).attr('colspan') > 1
});

The + prepended to $(this).attr('colspan') converts the string into a number

A: var tds = $('td').each(function(){
    if($(this).attr('colspan') > 1){
        return  $(this);
    }
})

A: Since there is no colspan=0 you can just do
$('td[colspan]').not('[colspan=1]')


text:
Q: Perl data structure traversal -- reference followed key Result: Many lines of HASH(0x1948958) ARRAY(0x1978250)        ./directory/filename
Desired result: [Key of first hash]    [Key of second hash]    ./directory/filename #(elements of array, currently working)
Catch: Should carry across to N level structures, hence my attempt at using Data::Walk.
What I really want to do as I walk the structure is to reference the key that is being used. Kind of like Data::Dumper but tab-separated instead of in code format. I think the likely solutions (in order of preference) are:

*

*Some call to Data::Walk that I've overlooked.

*A better module for this task that I don't know about.

*A quick code snippet that I can inline

*My own module / fork of Data::Walk / Data::Dumper (big frown) that will add this functionality.

use strict;
use File::Basename;
use Data::Walk;

my $files;
while (<>) {
        chomp;
        #ls -l output in a file; referencing filename from it (8th column)
        my @line = split(/ /, $_, 8);
        #fileparse exported by File::Basename
        my ($name,$path) = fileparse($line[7]);
        open (my $fh, '<', $path . $name);
        my $sha = Digest::SHA->new('sha1');
        $sha->addfile($fh);
        #finding files by basename, then unique hash, then however many places it is stored.
        #question not why I don't use the hash as the first field.

        #basename    digest    path
        push(@{$files->{$name}->{$sha->hexdigest}}, $path . $name);
}

my @val;
sub walkit {
        $val[$Data::Walk::depth - 1] =  $_;
        if ($Data::Walk::depth == 3) {
                print join("\t", @val), "\n";
        }
}

&walk (\&walkit, %$files);

Gurus?

A: for my $name (keys(%$files)) {
   for my $digest (keys(%{$files->{$name}})) {
      my @qfns = @{ $files->{$name}{$digest} };
      if (@qfns > 1) {
         say "For $name and $digest,";
         say "   $_" for @qfns;
      }
   }
}

(I'm assuming you're looking for duplicates, so I print nothing when there's only one path associated with a name-digest combo. You can remove the if if you want to print everything.)
Some other cleanup:
use strict;
use warnings;
use 5.010;

use Digest::SHA    qw( );
use File::Basename qw( basename );

sub calc_digest {
   my ($qfn) = @_;
   open(my $fh, '<', $qfn) or die $!;
   my $sha = Digest::SHA->new('sha1');
   $sha->addfile($fh);
   return $sha->hexdigest();
}

my $files;
while (<>) {
   my $qfn = (split)[7];
   my $name = basename($path);
   my $digest = calc_digest($qfn);
   push @{ $files->{$name}{$digest} }, $qfn;
}

("qfn" stands for "qualified file name", which means the path to the file, which wasn't what $path contained. You were repeatedly building the path even though $line[7] contained it.)

A: Edit: against my better judgement, I'll try to answer this question again.
Here's a simple approach to print what you want. Using Data::Walk is not feasible because you don't have key context when you are inside a hash (you just get a pointer to the container.)
This function works for somewhat complicated structures. Of course it will not give proper output if you put a function reference or something wonky in there.
use strict;
use warnings;

my $res;
sub walk {
    my ($item, $path) = @_;
    if (ref $item eq 'ARRAY') {
        foreach (@$item) {
            walk($_, $path);
        }
    } elsif (ref $item eq 'HASH') {
        foreach (keys %$item) {
            push @$path, $_;
            walk($item->{$_}, $path);
            pop @$path;
        }
    } else {
        print join('-', @$path, $item), "\n";
    }
}

my $struct = {
    a => {
            a1 => { a11 => [ 1, 2, 3 ] },
            a2 => { a22 => [5, 6, 7] }
    },
    b => { b1 => [ 99 ], },
    c => [ 100, 101, ],
    d => [ 101, { d2 => { d3 => [200, 210] }, }, ],
};

walk $struct;


text:
Q: How to sequence SQL commands to execute a series of transformations? I'm used to Powerquery's sequential command structure where each new step references the output of the previous one, like ...

*

*Declare source Table1 with columns a, b, c. [RESULT: a, b, c]

*Calculate some new field x [RESULT: a, b, c, x]

*Merge (left join) with Table2 [RESULT: a, b, c, x, T2.y]

*Group by x [RESULT: agg(a), agg(b), agg(c), x, agg(T2.y)]

*Merge (left join) with Table3 [RESULT: agg(a), agg(b), agg(c), x, agg(T2.y), T3.z]
etc.

I'm having trouble figuring out how to structure a series of transformations like the one above.
I'd appreciate any advice, or links to references or helpful hints out there for someone going from PowerBI to SQL.

A: There are multiple ways to achieve this. One simple way is

*

*Combining steps 1 and 2. Selecting a,b, and c columns, and then calculating a new column iseven.
select a,b,c,
case when b%2 = 0 then 'even' else 'odd' end iseven,
from t1

*Left join with t2.
select a,b,c,
case when b%2 = 0 then 'even' else 'odd' end iseven,
[t2.y] y
from t1
left join t2
on t1.a = t2.y

*Using groupby on iseven column and aggregating columns a,b and c. Here we use will wrap the above query in a subquery.
select sum(a) sumofA, sum(b) sumofB, sum(c) sumofC, Sum(y) sumOfY
from
   (
    select a,b,c,
    case when b%2 = 0 then 'even' else 'odd' end iseven,
    t2.z y
    from t1
    left join t2 on t1.a = t2.y
    ) master
 group by iseven

*For the final left join with t3.
select sumofA,sumofB,sumofC, t3.Z from
(
   select sum(a) sumofA, sum(b) sumofB, sum(c) sumofC, Sum(y)
   sumOfY
   from
     (
         select a,b,c, case when b%2 = 0 then 'even' else 'odd' end
         iseven, t2.z y
         from t1
         left join t2 on t1.a = t2.y
      ) master group by iseven
 ) resultTillstep4
 left join t4 on resultTillstep4.sumofA = t3.Z


text:
Q: F# MailboxProcessor questions I've created a console program using the code from http://fssnip.net/3K. And I found that

*

*I'd to add "System.Console.ReadLine() |> ignore" at the end to wait for the finish of threads. Is it possible to tell all the MailBoxProcessors are done and the program can exit itself?

*I tried to change the test url "www.google.com" to something invalid url and I got the following output. Is it possible to avoid the "outputting race"?

     http://www.google.co1m crawled by agent 1.
     AgAAAent gent 3 is done.
     gent 2 is done.
     5 is done.
     gent 4 is done.
     Agent USupervisor RL collector is done.
     is done.
     1 is done.

[Edit]
The last output/crawling is still terminated after using Tomas's update http://fssnip.net/65. The following is the output of the program after I changed the "limit" to 5 and added some debugging messages. The last line shows the truncated URL. Is it a way to detect if all the crawlers finish their execution?
[Main] before crawl
[Crawl] before return result
http://news.google.com crawled by agent 1.
[supervisor] reached limit
http://www.gstatic.com/news/img/favicon.ico crawled by agent 5.
Agent 2 is done.
[supervisor] reached limit
Agent 5 is done.
http://www.google.com/imghp?hl=en&tab=ni crawled by agent 3.
[supervisor] reached limit
Agent 3 is done.
http://www.google.com/webhp?hl=en&tab=nw crawled by agent 4.
[supervisor] reached limit
Agent 4 is done.
http://news.google.com/n

I changed the main code to
printfn "[Main] before crawl"
crawl "http://news.google.com" 5
|> Async.RunSynchronously
printfn "[Main] after crawl"

However, the last printfn "[Main] after crawl" is never executed, unless I add a Console.Readline() at the end.
[Edit 2]
The code runs fine under fsi. However it will have the same problem if it was run using
    fsi --use:Program.fs --exec --quiet

A: I created a snippet that extends the previous one with the two features you asked about: http://fssnip.net/65.

*

*To solve this, I added Start message that carries AsyncReplyChannel<unit>. When the supervisor agent starts, it waits for this message and saves the reply channel for later use. When it completes, it sends a reply using this channel.
The function that starts the agent returns asynchronous workflow that waits for the reply. You can then call crawl using Async.RunSynchronously, which will complete when the supervisor agent completes.

*To avoid race when printing, you need to synchronize all prints. The easiest way to do this is to write a new agent :-). The agent receives strings and prints them to the output one by one (so that they cannot be interleaved). The snippet hides the standard printfn function with a new implementation that sends strings to the agent.


text:
Q: Link to my CSS in my wordpress template, css file is in the sibling folder of the template I have temp.php in wp-content/themes/fifthteen/paytest.php, the css file is **wp-content/themes/fifthteen/paytest/paytest.css**
I want to link to the paytest.css in my paytest.php
<link rel="stylesheet" href="????/paytest/paytest.css />

How can I do this?

A: You should use  get_template_directory_uri() to have the template directory URI of your current theme.
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/paytest/paytest.css "/>

A: You'll want to link to the theme directory
<?php echo get_template_directory(); ?>

So in working example:
<link rel="stylesheet" href="<?php echo get_template_directory(); ?>/paytest/paytest.css />


text:
Q: Haskell - Boolean RoseTree Hello Haskell community,
Given the usual definition of a Rose Tree:
RoseTree a = Node a [RoseTree a]

I've been scratching my head over the implementation of this particular function:
boolRoseTree :: Blocks -> Blocks -> RoseTree a -> Bool
boolRoseTree blocksA blocksB roseTree

Where Blocks is simply a [Int] that is always contains 6 elements which are greater or equal to 0.
Now the function I wish to implement checks if a certain element of blocksA is a certain value and a certain element of blocksB is also a certain value, and return True if the conditions are met. That is very vague, so allow me to clarify with an example:
| (blocksA !! 0 == 1 || blocksA !! 0 == 10) && blocksB !! 1 /= 0 = True
i.e. if the 1st element of blocksA is either 1 or 10 and the 2nd element of blocksB is not 0, then return True. This I wish to do for all elements of blocksA, however each time, the elements increase by +1. Through that I mean the next guards would be:
| (blocksA !! 1 == 2 || blocksA !! 1 == 11) && blocksB !! 2 /= 0 = True
| (blocksA !! 2 == 3 || blocksA !! 2 == 12) && blocksB !! 3 /= 0 = True
| (blocksA !! 3 == 4 || blocksA !! 3 == 13) && blocksB !! 4 /= 0 = True
| (blocksA !! 4 == 5 || blocksA !! 4 == 14) && blocksB !! 5 /= 0 = True

Obviously, I could code this with a long list of guards, going through all blocksA !! 0,blocksA !! 1,blocksA !! 2,blocksA !! 3,blocksA !! 4,blocksA !! 5 eventually reaching an otherwise statement which returns False. However, this could be done significantly more effectively (I think) with a Rose Tree.
I imagine that on the first level of the Rose Tree there would have to be six nodes, 0 to 5, representing the elements of the tree. Each of those nodes would then have to have 2 values, which are the two values I want for blocksA at that particular element of the list - but then I would also somehow have to check if the corresponding element of blocksB is not zero.
I don't really know even where to start on a problem like this... Any help would be greatly appreciated.

A: Don't know how a Rose tree would work here, but what about this
data structure:
checks =
    [ ((0,0), [ (1, 10, 1) , (2, 11, 2) , (3, 12, 3) , (4, 13, 4) , (5, 14, 5) ])
    , ((1,..), [ ... ]
    , ((2,..), [ ... ]
    , ...
    , ((5,..), [ ... ]
    ]

Here's how to deconstruct it:
[ ( (0,0) [ (1, 10, 1) , (2, 11, 2) , (3, 12, 3) , (4, 13, 4) , (5, 14, 5) ]
     i z     x   y  j     x   y  j     x   y  j     ...

Each set of values for i, z, x, y, and j corresponds to
the guard:
| ((a !! i) == x || (a !! i) == y) && (b !! j /= z) = True

To perform all of the checks, just use a list comprehension:
func :: [Int] -> [Int] -> Bool
func a b = or $ do ((i,z), triples) <- checks
                   (x,y,j) <- triples
                   return $ ((a !! i) == x || (a !! i) == y) && (b !! j /= z)

All of the elements of the list are or-ed together. Due to laziness the function will return with True as soon as the first True check is encountered.


text:
Q: text inside div overflows... but returns to normal only after refresh I'm doing a dynamic div that resizes accordingly to the amount of text. (Which means I can't define the width of the main div)
Problem is, with my current CSS, this is what's happening at the first load of the page:

However, when I press F5, the page automatically resizes itself back to this:

Why is this happening? How do I solve it? I'm stumped on this part and I've even tried advanced CSS functions such as calc, etc.
I can't replicate the problem on jsFiddle, but I did provide the code I'm using.
HTML

Home

        /

blog

        /

On the Go.

CSS
.breadcrumbz { padding:6px 6px 6px 6px; margin:2% 0 0 4%; position:relative; background-color:#3b3c3e; float:left; }
.breadcrumbz ul { white-space:nowrap; float:left; }
.breadcrumbz ul li { display:inline; }
.breadcrumbz ul li:first-child a { padding:0 4% 0 0; }
.breadcrumbz ul li a { padding:0 4%; }
.breadcrumbz ul li span { padding:0 4%; }
.breadcrumbz ul li:last-child a { padding:0 0 0 4%; }
.breadcrumbz ul li.single { padding:0 0 0 4%; }

A: It's the percentages causing it, the browser doesn't know what the width will be before the content is rendered, and the percentages in the margins of the content are based on the width. (A sort of chicken-and-the-egg problem.)
You also have invalid html ( is not allowed as children of
).
If you change the units from percentages, you won't have this issue.
Sample at http://jsfiddle.net/sdMTJ/5/

Sidenote: instead of the invalid spans, you could add separators between the elements using pseudo-elements;
li + li:before {
    content: " / ";
}

http://jsfiddle.net/sdMTJ/9/

A: You need to change the display style of li. Try "inline-block" insted of "inline".
.breadcrumbz ul li { display:inline-block; }

Check this http://jsfiddle.net/Yg58f/. Hope it helps.

A: Percentages and padding can have this effect on floated items without set width, particularly. For reliability I would sugget you use em and not %
DEMO http://jsfiddle.net/kevinPHPkevin/sdMTJ/8/
.breadcrumbz ul li.single { padding:0 0 0 0.625em; }

A: try this:
.breadcrumbz ul li {
   display: inline-block;
}


text:
Q: What exception should be thrown when Guava CacheLoader is unable to load the data? I am implementing simple guava CacheLoader as it is stated here
   CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
     public Graph load(Key key) throws AnyException {
       return createExpensiveGraph(key);
     }
   };
   LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);

Does this mean that I should create my own exception class and throw it if the value is null or is there any better way to hande the situation?

A: You're allowed to throw whatever exception you want -- that can be something you made, or something built-in.  There's no special rule for what exception is most appropriate for caches -- just use whatever exception would be most appropriate otherwise.


text:
Q: php - loop through a directory files and run script I have a simple XML parser that i want to run sequentially all files within a directory, my question is how to loop through all xml files and run the script one after another. Instead of doing so manually.
$string = file_get_contents('epgs/file1.xml'); // loop through all files
$xml = new SimpleXMLElement($string);
$events=$xml->xpath("/DVB-EPG/Service/Event");

if ($events) {

    foreach ($events as $event) {
        $id = $event["id"];

        $start_date = $event["start"] ;

        $name = $event->ShortEventDescriptor->EventName ;
        $text = $event->ShortEventDescriptor->Text;

        $values = array (
            ':event_id'=>$id,
            ':event_name'=>$name,
            ':event_desc'=>$text,
            ':start_date'=>$start_date
        );

        $stmt = $dbh->prepare ($sql);
        $stmt->execute($values);
    }
}

Where the directory epgs has multiple files : file1.xml, file2.xml, file3.xml ect..
ANSWER
$files = glob("epgs/*.xml");
foreach ($files as $file) {
 //script...
 }

A: Although your question was answered in the comments already, I advise against using glob(). You can use SPL iterators instead:
<?php
$folder = __DIR__;
$pattern = '/^.*\.xml$/';

$iterator = new RecursiveDirectoryIterator($folder);
$iterator = new RecursiveIteratorIterator($iterator);
$iterator = new RegexIterator($iterator, $pattern);
$files  = [];
foreach ($iterator as $file) {
    $files []= $file->getFilename();
}
var_dump($files);

Even though the code is much bigger, I still find it more useful. The benefits are as follows:

*

*You get absolute paths, period. With glob() that is the case only if your original pattern is absolute as well. That's not very obvious, isn't it?

*Actually, you get a lot more information that absolute path - you can check file size, its owner etc. Check documentation on SplFileInfo.

*The second you find yourself in need of handling recursive pattern, e.g.:
folder/*.xml
folder/branch/*.xml
folder/even/deeper/*.xml

...you'll realize that there's no built-in recursive glob() in PHP.

*glob() supports many more patterns than simple *. Unfortunately, they are barely documented:

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Are you seriously wanting to depend on libc implementation that can change for any reason?

*The patterns glob() actually supports seem to be described best on some random blog™:

* (an asterisk)

Matches zero of more characters.

?

Matches exactly any one character.

[...]

Matches one character from a group. A group can be a list of characters, e.g. [afkp], or a range of characters, e.g. [a-g] which is the same as [abcdefg].

[!...]

Matches any single character not in the group. [!a-zA-Z0-9] matches any character that is not alphanumeric.

\

Escapes the next character. For special characters, this causes them to not be treated as special. For example, \[ matches a literal [. If flags includes GLOB_NOESCAPE, this quoting is disabled and \ is handled as a simple character.

*To me, using regular expressions is much more readable. People are much less likely to need to refer to documentation if they see simple regex.


text:
Q: How to find out user pressed "enter" in text input? I'm trying to add text input's element to my array when user pressed enter key. but I don't know how to do that. I tried this if statements but they didn't work:
var val = $("#txbxfeeds").val();
if (val[val.length-1] == "\r") {
    alert("HI");
}
if (val[val.length-1] == "\n") {
    alert("HI");
}

How can I do this?

A: I can suggest the following:
var vals = [];

$("#txbxfeeds").on("keypress", function(e) {
    if (e.which == 13) {
        vals.push(this.value);
    }
});

DEMO: http://jsfiddle.net/Q4CUf/

A: $("#txbxfeeds").on('keyup', function(e) {
   //13 is the code for enter button

   var val = $(this).val(); // or this.value

   if(e.which == 13) {
    alert( val );
   }
});

Working sample
Read more about jQuery event.which


text:
Q: Is my time difference accurate? I am working on a password reset and I am at the part of where I am checking if the token is within the time range.
This is my code :
            $tokentime = substr($dbtoken[0], 0, 4); // get the DB time that I store with date('hi') . $token
            $now = date('hi'); // Create the now time in same format as $tokentime

            var_dump($now); // This generates : 0838 (couple mines ago)
            var_dump($tokentime); this generates : 0652 (102 minutes ago)
            var_dump(strtotime($now)); // convert 8380 to unix time
            var_dump(strtotime($tokentime)); // convert 0652 into unix time

            if (strtotime($now) - strtotime($tokentime) >= 600) { // If the unix seconds are equal to or greater then 600 seconds
                echo "Token Expired";
            } else {
                echo "Not Expiered";
            }

Is my way of thinking correct?
This is the var_dump values :

string(4) "0838" string(4) "0652" int(1377175080) int(1377168720) Token Expired

I have it set to expire in 10 minutes of 600 seconds.
This is my first time working checking differences in time, and storing date values inside of a token like so. I just wanted to know if this is correct way of finding differences in time.

A: That's simple:
At some moment in time value of time() in your token. Later:
if (time()-tokentime) > 600)
{
    // expired
}

time() will get you so called UNIX timestamp which is timezone independent.


text:
Q: ScreenManager kivy&python У меня есть меню, в нём есть кнопка "играть". Нажав на кнопку пользователя перебрасывает на другой экран с игрой, и в экране с игрой, есть кнопка "Выйти в меню". Проблема в том что если пользователь нажмет на "Играть", а потом на "Выйти в меню", То он попадет в меню но функции в игре так и будут работать.
main.py
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
from kivy.core.window import Window

import random

Window.size = (320,640)
class Manager(ScreenManager):
    pass
class Menu(Screen):
    pass
class Game(Screen):
    def on_enter(self, *args):

        Clock.schedule_interval(self.printing, 2)

    def printing(self, *args):
        print('TEST')
class Main(App):
    pass

if __name__ == '__main__':
    Main().run()

Main.kv
Manager:
    Menu:
        name:'menu'
    Game:
        name:'game'

<Menu>:
    BoxLayout:
        orientation: 'vertical'

        BoxLayout:
            orientation: 'vertical'
            padding: '50dp'
            spacing: '20dp'

            Button:
                text: 'Игра'
                on_release:
                    app.root.transition.direction = 'down'
                    app.root.current = 'game'
<Game>:
    BoxLayout:
        orientation: 'vertical'

        Button:
            text: 'Выйти в меню'
            on_release:
                app.root.transition.direction = 'down'
                app.root.current = 'menu'

не знаю как сделать так чтобы при нажатие кнопки "выйти в меню" - игра останавливалась.

A: class Menu(Screen):
    def on_enter(self, *args):
        if self.manager.has_screen('game'):
            Clock.unschedule(self.manager.get_screen('game').printing)


text:
Q: Help for writing a click event for a custom map I have an image of the political map of the USA. I want to write separate click events for each of the 50 states in Visual Studio. How would I do that?

A: Suggest you get your hands on something like Macromedia Fireworks which allow you to create image maps.
This article explains how to do it using photoshop.
http://www.createblog.com/photoshop-tutorials/736-photoshop-image-maps/
Or even online web site
http://www.image-maps.com
Or even this
http://en.wikipedia.org/wiki/Template:USA_imagemap_with_state_names

A: If a static HTML map is what you want, then use an ImageMap control
In winforms that may be a little more work than you want to do.
There are no 'shape' controls so you would have to define a virtual map and just monitor click events.
Your best bet is to use WPF or Silverlight. That would be a piece of cake. polys in WPF are first class citizens and have events. It will look real purty too.
And I am sure there are already defined maps xaml on the google. (map, article)


text:
Q: Visual Studio For Mac Debugging Unit Tests I just downloaded VS 2019 for Mac.  Console projects debugging works fine hitting break points. If I try to debug a MSTest or NUnit test project the break points are ignored with no error message.
I have tried changing the options, I am in debug mode, I have tried restarting, and creating new projects. I have downloaded the MSTest.TestFramework, and MSTest.TestAdapter from nuget. None of these have worked.
Any ideas on how to resolve this?

A: Go to "Menu" -> "View" - "Test'.
Find your test... right click on it... and "Debug test"


text:
Q: Docker in Docker(DND) is not starting I have a simple Ubuntu 16.10 container which has docker.io installed.
The docker process terminates after it starts and log has this information. Any troubleshooting suggestions?
$ docker run -it --name dcos-ubuntu-python5 python-docker /bin/bash

root@5ff6bb6b6dc7:/# docker run hello-world
docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.
See 'docker run --help'.

root@5ff6bb6b6dc7:/# service docker start
 * Starting Docker: docker                                                                                [ OK ]
root@5ff6bb6b6dc7:/# service docker status
 * Docker is not running

root@5ff6bb6b6dc7:/# tail -f /var/log/docker.log
time="2017-12-21T17:09:45.464736873Z" level=info msg="libcontainerd: new containerd process, pid: 50"
time="2017-12-21T17:09:46.472578239Z" level=fatal msg="Error starting daemon: error initializing graphdriver: operation not permitted"

A: Why do you want to run docker within docker container?
Docker-in-Docker is developed to help docker development. And it needs --privileged flag to run docker container.(Please read jpetazzo's blog here.)
If you really want to execute docker in docker container, you also have other options.

*

*Bind mount docker.sock. Some people call this DooD(Docker-outside-of-Docker)
docker run -v /var/run/docker.sock:/var/run/docker.sock ...

*Install docker(client) and specify DOCKER_HOST to access remote docker daemon. Be careful about socket protection with certificates.

A: Are you running docker as sudo  if not run as sudo or
Else add user group to docker
docker group. For this run following command:
sudo usermod -aG docker $USER

A: The answer was simple.
docker run -it --privileged --name dcos-ubuntu-python5 python-docker /bin/bash

(This was also mentioned partly in @SunghoMoon's response. So Credits to him).