text:
Q: Detecting current column in multicol I'm working in a two-column multicol environment, and trying to create pullquotes using wrapfig. The problem is, I'd like these pullquotes to hang in the margin: the left margin if I'm in the left column, the right margin if I'm in the right.
Is there any way to detect the current column number, so that I can tell wrapfig: "Hang the figure left if column number = 1, and hang it right if column number = 2"? I have a lot of this sort of text, and it would be pretty tedious to set this all by hand.
I've tried using this pullquote package, but so far have just gotten a bunch of microtype errors (I'm using XeLaTeX).
Edit: a sort of MWE would look like this, obviously \imaginarycolumnnumberidentifier is what I'm after. Clearly this isn't a "working" example, and I've not actually tried using etoolbox before so there might be other problems with this code, but you get the idea.
\documentclass{article}
\usepackage{multicol}
\usepackage{wrapfig}
\usepackage{lipsum}
\usepackage{etoolbox}

\newenvironment{pquote}{%
  \begin{wrapfigure}[3]{%
      \ifnumequal{1}{\imaginarycolumnnumberidentifier}{l}{r}%
    }[0.2\columnwith]{0.4\columnwidth}
  }{%
  \end{wrapfigure}}

\begin{document}

\begin{multicols}{2}
\lipsum[1]
\begin{pquote}
  Lorem ipsum!
\end{pquote}
\lipsum[2]
\begin{pquote}
  dolor sit amet!
\end{pquote}
\lipsum[3]
\end{multicols}

\end{document}

I don't have enough reputation to post an image, so you'll just have to imagine the output! Trust me, the first pquote is on the left side, and the second pquote is on the right side. In my mind.

A: As Andrew remarked in his answer a solution for multicols is rather more complicated as the "current" column is not at all known while doing the typesetting. So a rather complicated approach with multiple typesetting runs (using the .aux file) is needed.
Below is a first draft of a solution providing \docolaction{left}{middle}{right} for executing conditional code depending on the column type. If the column type is not yet known the first column is assumed (as default).
\begin{filecontents}{mccolaction.sty}
%
%    \begin{macrocode}
\ProvidesPackage{mccolaction}
          [2013/05/05 v0.9b  column actions for multicolumn formatting (FMi)]
%    \end{macrocode}
%
%    \begin{macrocode}
\RequirePackage{etoolbox}
\RequirePackage{multicol}[2011/12/20]
%    \end{macrocode}
%
%   Determining the current column in multicols is difficult because
%   (in contrast to the twocolumn mode of standard LaTeX) the
%   multicols columns are determined very late in the game and due to
%   the balancing routine it is not known where a piece of text is
%   going to end up at the time the text is typeset. Only afterwards,
%   when everything has be typeset into a single long galley, that
%   galley is split into individual columns (at the very end in a
%   possibly huge set of trials to balance the column material.
%
%   Therefore the approach taken here is to write out a single line
%   into the .aux file whenever a column is finally typeset:
%\begin{verbatim}
% \mc@col@status{<number>}
%\end{verbatim}
%   The number in the argument denotes the different kind of column: 1
%   for left column 2 for any middle column and 3 for the final column.
%
%   We only set this up for the LR typesetting case here, something
%   similar could be done for the RL version:
%    \begin{macrocode}
\patchcmd{\LR@column@boxes}{\box\count@}
         {\protected@write\@auxout{}{\string\mc@col@status
              {\ifmc@firstcol 1\else 2\fi}}%
          \mc@firstcolfalse
          \box\count@}
         {\typeout{juhu!}}{\typeout{oje!}}%

\patchcmd{\LR@column@boxes}{\box\mult@rightbox}
         {\protected@write\@auxout{}{\string\mc@col@status{3}}%
          \box\mult@rightbox}%
         {\typeout{juhu!}}{\typeout{oje!}}%

\newif\ifmc@firstcol
\mc@firstcoltrue
%    \end{macrocode}
%
%   Need to reinitiate \verb=\mc@align@columns= as this was let to
%   the old definition of \verb=\LR@column@boxes=.
%
%    \begin{macrocode}
\LRmulticolcolumns

%   Whenever we want to do something that depends on the current
%   column we execute \verb=\docolaction=. This command takes one
%   optional and three mandatory arguments. The mandatory ones denote
%   what to do if this is a ``left'', ``middle'', or ``right'' column
%   and the optional one is simply there to say what to do if we don't
%   know (default is to use the ``left'' column action in that case).
%
%   We use one counter \verb=\mc@col@check@num= to generate us unique
%   label names. Each time we execute \verb=\docolaction= we increment
%   this counter to get a new name.
%    \begin{macrocode}
\newcount\mc@col@check@num
%    \end{macrocode}

%   The generated ``labels'' are named
%   \verb=\mc@col-\the\mc@col@check@num= and they hold as values the
%   numbers 1, 2, or 3 denoting the current column type.

%    \begin{macrocode}
\newcommand\docolaction[4][1]{%
 \global\advance\mc@col@check@num\@ne
 \edef\mc@col@type{\expandafter\ifx
               \csname mc@col-\the\mc@col@check@num\endcsname\relax
                  0\else
                  \csname mc@col-\the\mc@col@check@num\endcsname
               \fi}%
%    \end{macrocode}
%    We prefix with 0 so that an unknown label (that returns
%   \verb=\relax=) will result in case 0
%    \begin{macrocode}
 \ifcase \mc@col@type\relax
%    \end{macrocode}
%    If column is unknown we use the default action or the action
%   denoted by the optional argument (so that arg can take the value
%   1, 2, 3)
%    \begin{macrocode}
     \ifcase #1\or #2\or#3\or#4\fi   % 0 not known use first col as default
  \or
%    \end{macrocode}
%    Otherwise we know (or think we know) that this is a first, middle,
%   or last column:
%    \begin{macrocode}
     #2%  % 1 First col
  \or
     #3%  % 2 any middle col
  \or
     #4%  % 3 last col
  \else
    \ERROR
  \fi
%    \end{macrocode}
%    But how does the column number get associated with our label? We
%   do do this by writing another line into the aux file at this point:
%    \begin{macrocode}
  \edef\next{\write\@auxout
     {\string\mc@set@col@status{mc@col-\the\mc@col@check@num}%
                               {\mc@col@type}}}%
  \next
}
%    \end{macrocode}
%
%   Because of extra data writing to the aux file the aux file will
%   now contain something like the following after the document is
%   processed the first time:
%\begin{verbatim}
%\relax
%\mc@col@status{1}
%\mc@set@col@status{lcol-1}{0}
%\mc@col@status{2}
%\mc@set@col@status{lcol-2}{0}
%\mc@col@status{3}
%\mc@set@col@status{lcol-3}{0}
%\mc@col@status{1}
%\mc@col@status{2}
%\mc@col@status{3}
%\mc@set@col@status{lcol-4}{0}
%\end{verbatim}
%   The \verb=\mc@col@status= line denotes the column type and has been
%   writting out just before corresponding the column box was placed
%   onto the page.
%   The\verb=\mc@set@col@status= lines have been written out as part
%   of shipping the column boxes out, e.g.,
%   \verb=\mc@set@col@status{lcol-1}{0}= was therefore somewhere within
%   the first column as it appears between \verb=\mc@col@status{1}=
%   and  \verb=\mc@col@status{2}=
%   The second argument in that line is the value used in the previous
%   run (or zero if there was no previous run. We can use this to
%   determine if a rerun is necessary.
%
%   Thus with this knowledge we can set things up to get the labels
%   working.
%
%   When the aux file is read in \verb=\mc@col@status= is used to set
%   \verb=\mc@curr@col@status=:
%
%    \begin{macrocode}
\def\mc@col@status#1{\gdef\mc@curr@col@status{#1}}
%    \end{macrocode}

%   And when \verb=\mc@set@col@status= is executed we can simply set
%   up the label by associating it with the \verb=\mc@curr@col@status=
%   and ignore the second argument:
%    \begin{macrocode}
\def\mc@set@col@status#1#2{%
   \global\expandafter\let\csname #1\endcsname\mc@curr@col@status}
%    \end{macrocode}
%
%   The above definition is being used when the \texttt{.aux} file is
%   read in at the beginning. At the end we need a different
%   definition to test if another typesetting run is needed. There we
%   compare the value used in the current run (stored in the second
%   argument) with the value used on the next run. If those two values
%   differ we set \verb=@tempswa= to false which will trigger the
%   ``Label(s) may have changed'' warning.
%    \begin{macrocode}
\AtEndDocument{\def\mc@set@col@status#1#2{%
     \ifnum #2=\mc@curr@col@status\else
       \@tempswatrue
     \fi}%
}
%    \end{macrocode}
\end{filecontents}

\documentclass{article}

\usepackage{mccolaction}

\usepackage{wrapfig}
\usepackage{lipsum}

% An application of \docolaction. We put the whole wrapfigure into the
% args so that the  internal label used is placed after wrapfigure.

\newcommand\pquote[2]{%
  \docolaction
     {\begin{wrapfigure}[#1]{l}[0.2\columnwidth]{0.4\columnwidth}%
        \raggedright\large\bfseries #2\end{wrapfigure}}%
     {\begin{wrapfigure}[#1]{l}[0pt]{0.4\columnwidth}%
        \raggedright\large\bfseries #2\end{wrapfigure}}%
     {\begin{wrapfigure}[#1]{r}[0.2\columnwidth]{0.4\columnwidth}%
        \raggedright\large\bfseries #2\end{wrapfigure}}%
  \ignorespaces
}

\setlength\columnseprule{.7pt}
\setlength\emergencystretch{2em}

\begin{document}

\begin{multicols}{3}
  \lipsum[1]
  \pquote{4}{Lorem ipsum!}
  \lipsum[2]
  \pquote{5}{Dolor sit amet!}
  \lipsum[4-5]
  \pquote{4}{Mauris ut est.}
  \lipsum[6-7]
  Only a few words left \ldots
  Here the pquote comes in the middle of the paragraph for a change
  \pquote{6}{Final test related to the edge}
  as we can see. Only a few words left so this drops off the column \ldots
\end{multicols}

\end{document}

If we run this file we get

The second page then shows that not all will be perfect but that is in this case due to the fact that I deliberately placed the \pquote too close to the end.

If we change the file to use 4 columns we end up with one wrapfigure cut across columns, clearly something where the two packages do not work together well enough to resolve this automatically.

In summary, I would say it works well enough. In combination with something like wrapfigure it will need some help in places, but this is to be expected as wrapfigure has no clue about multicols splitting up the columns later on.
Update
I slightly improved the code, so that it now also keeps track of any changes in the column types. If due to that the need for another LaTeX run is detected, it will generate the well-known warning "Label(s) may have changed. Rerun to get cross-references right."
Thus output like the following should only happen if the user ignores that warning.

Update II
The above version of mccolaction was written against the SVN version which is not on CTAN at the moment. In answer Column break only if within first column of multicol I provided an updated package that works with both versions of multicol.
Update III
The functionality described above is now available in multicol version 1.8 and above. It is not automatically enabled (as it is costly) --- you have to request it using the option colaction.  Afterwards \docolaction is enabled for use in your document.

A: Let me show you how to implement this for twocolumn layouts rather than via the multicol package.  This will fix some of your coding issues.

\documentclass[twocolumn]{article}

\usepackage{wrapfig}
\usepackage{lipsum}

\makeatletter
\newenvironment{pquote}[1][\relax]{%
  \ifx#1\relax\def\@mypl{\if@firstcolumn l\else r\fi}%
  \else\def\@mypl{#1}\fi%
  \wrapfigure[3]{\@mypl}[0.2\columnwidth]{0.4\columnwidth}%
  \large\bfseries}{\par\endwrapfigure}
\makeatother

\begin{document}

\lipsum[1]
\begin{pquote}
  Lorem ipsum!
\end{pquote}
\lipsum[2-4]
\begin{pquote}
  Dolor sit amet!
\end{pquote}
\lipsum[5-8]
\begin{pquote}[r]
   Mauris ut est.
\end{pquote}
\lipsum[9]

\end{document}

Your general method of setting pquote to a variation of wrapfigure using \begin{wrapfigure} unfortunately doesn't work, as you will see by making a simple test document with fixed positioning.  This has something to do with the way the arguments are processed.  Instead use \wrapfigure with the appropriate arguments, and balacnce it with \endwrapfigure.  Furthermore, the positioning argument needs to expand directly to one of the allowed strings so this should be done via an intermeadiate macro.
Now with twocolumn we have the test \if@firstcolumn which can be used to determine the positioning.  Unfortunately it is not 100% foolproof, so my definition above provides an optional argument allowing you to force the positioning.
In multicols things are rather more complicated, and I see no easily accessible variable to do this.  Essentially multicol typesets the material in to one long box and then splits off the correct amount from the top for each column.  There are some internal variables keeping count of the column number, but they are not easily accessible.  Furthermore multicol does some balancing of columns, trying split the given typeset material in to a number of boxes of equal height, if the typesetting is to change in the process, then this is more complicated.  One symptom of this is that \marginpars are not allowed in the multicols, see the package documentation, whereas in twocolumn margin pars work (fairly) nicely switiching sides as required.
ADDITION in response to comment:
If you want to use multicols and are prepared to specify placement then the coding is simpler, but still requires avoiding \begin{wrapfigure}:

\documentclass{article}

\usepackage{multicol,ragged2e}
\usepackage{wrapfig}
\usepackage{lipsum}

\makeatletter
\newenvironment{pquote}[2]{%
  \wrapfigure[#1]{#2}[0.2\columnwidth]{0.4\columnwidth}%
  \large\bfseries\Centering}{\par\endwrapfigure}
\makeatother

\begin{document}

\begin{multicols}{2}
  \lipsum[1]
  \begin{pquote}{4}{l}
    Lorem ipsum!
  \end{pquote}
  \lipsum[2-4]
  \begin{pquote}{6}{r}
    Dolor sit amet!
  \end{pquote}
  \lipsum[5-8]
  \begin{pquote}{5}{r}
    Mauris ut est.
  \end{pquote}
  \lipsum[9]
\end{multicols}
\end{document}


text:
Q: running EFI shell commands on windows command line I need to run EFI shell commands to get the directory listing of EFI partition.
Do i need to install some tool on my system(windows).
How can i run EFI shell commands on windows?

A: We can access the EFI system partition by mounting it to some drive letter.
1) run diskpart
2) select disk on which the EFI partition system is present (eg: sel disk 0)
3) select EFI partition (eg. sel part 1)
4) assign drive letter (eg.assign letter=h)
5) exit

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sqrt method doesn't return number I've got a method that computes two offsets for something else in my code. I wrote these offsets to the output and the result was: Isn't number. When I tryed to assign these values to another variables, these variables' value was 0.
This is my code:
int w = 1200;
int h = 1824;
double offsetX = System.Math.Sqrt (-((9 * w * w) / 16));
double offsetY = System.Math.Sqrt (((9 * h * h) / 16) + ((9 * w * w) / 16) - offsetX);

I don't know if it is a mathematical or a programming problem. Why does it return this weird value?

A: -((9 * w * w) / 16) expression returns a negative value which is -810000.
That's why this method returns NaN.
From the documentation of Math.Sqrt;
d parameter  | Return value
Negative     | NaN

From Wikipedia;

The square of any positive or negative number is positive, and the
  square of 0 is 0. Therefore, no negative number can have a real square
  root. However, it is possible to work with a more inclusive set of
  numbers, called the complex numbers, that does contain solutions to
  the square root of a negative number.


text:
Q: How to retrieve json data to laravel controller There are questions like this on StackOverflow, that I know.
Trust me, I have tried all the solutions to no avail.
I have been trying to post this json data from angularjs to a laravel controller method:
[
  {
    "id": 2,
    "name": "add-user",
    "display_name": "Add new user",
    "description": "Create a new worker",
  },
  {
    "id": 4,
    "name": "add-role",
    "display_name": "Add role",
    "description": "Add user role",
  }
]

this is the code that posts this json data to a laravel controller:
$http({
    method: 'POST',
    url:  '/api/roles/assignPermissions/' + name,
    headers: { 'Content-Type' : 'application/json' },
    data: $.param(role_perms)
}).success(function(data){
    console.log(data);
});

Now in this controller method, I just want retrieve this json data, return it and display it in the console to be sure that I received it in the controller.
Below is the controller and all the attempts I've made to get this json data and return it.
The controller:
public function massAssignPerms(Request $request, $roleName)
{
    $role = Role::where('name', $roleName)->first();

    // this returned nothing
    return json_decode(file_get_contents('php://input'),true);

    // this returned: add-user=&add-role=
    return file_get_contents('php://input');

    // returned nothing
    return json_decode($request->getContent(), true);

    // returned empty array []
    return $request->json()->all();
}

I am unable to find what's wrong with my code. Or it could be that I'm doing it wrongly?
Any help will be greatly appreciated.

A: You need to make sure you're returning your variable with your response. To return JSON from a controller function in Laravel, this is the proper syntax as laid out in the docs:
return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);

Assuming you wish to return the result of your roles query, you could do the following. You may also specify a status code if you wish.
return response()->json(['role' => $role], 200);

EDIT: If you wish to simply return the data from the original request, you can make that the content of the JSON response instead:
return response()->json($request->all(), 200);

A: If the data you showed is really what is sent (I'm guessing you're testing with hardcoded values?) then it's not proper JSON (extra comma after last key of each object).
Try with:
[
  {
    "id": 2,
    "name": "add-user",
    "display_name": "Add new user",
    "description": "Create a new worker"
  },
  {
    "id": 4,
    "name": "add-role",
    "display_name": "Add role",
    "description": "Add user role"
  }
]


text:
Q: T-SQL call table function passing multiple values and aggregate results I have a Table function which returns a set of rows based on a parameter, which looks like this example:
CREATE FUNCTION fn_get_records
(@PARENTID INT)
RETURNS  @returnTable TABLE
(
    -- columns returned by the function
    Id INT NOT NULL,
    Parent_Id INT NOT NULL,
    Name VARCHAR(255) NOT NULL
)
AS
BEGIN
   -- This select returns data
   INSERT INTO @returnTable (Id, ParentId, Name)
   SELECT Id, ParentId, Name FROM [whatever] where Parent_Id = @PARENTID
RETURN
END

I have another table which contains a list of those "Parent Ids" and I should call the previous function for each Parent_Id that matches a specific query and aggregate all results.
The parent Ids are retrieved using something like
SELECT Parent_Id
FROM Parent_Records
WHERE Country = 'USA'

This select returns, for example, 4 rows. For each row I have to execute my function fn_get_records and aggregate all results together in a view or in another function.
Is it even possible?
Of course I don't want to use cursors because I need something fast

A: Just a quick FYI: A more efficient TVF would be a single statement
CREATE FUNCTION fn_get_records (@PARENTID INT)
RETURNS TABLE
AS
RETURN (
   SELECT Id, ParentId, Name FROM [whatever] where Parent_Id = @PARENTID
)
END

Then you can call your function via a CROSS Apply.  For Example:
Select A.*
      ,B.*
 From  YourTable A
 Cross Apply dbo.fn_get_records (A.SomeIntValue) B


text:
Q: Showing an image only if content view of UITextView is larger than its fame I am doing a project in which I want show an image if the text doesn't fits to the UITextView frame.
I am using the following code
  if (self.textView.contentSize.height >= self.TextView.bounds.size.height)
{
    self.imageView.hidden = NO;
}

I am using Autolayout also. Does it cause such issues
And one more thing is that, when I print NSLog, the value of contentSize.height was NOT changing according to the text UITextView was showing.

A: You can use this method to check the height of multi line text according to the font size used
+  (CGSize) calculateLabelHeightWith:(CGFloat)width text:(NSString*)textString
{
    CGSize maximumSize = CGSizeMake(width, 9999);
    CGSize size = [textString sizeWithFont:[UIFont fontWithName:@"Helvetica" size:24]
                         constrainedToSize:maximumSize
                             lineBreakMode:UILineBreakModeWordWrap];
    return size;
}

you need to know

*

*width of text feild

*string

*font

*font size

iOS7
CGRect textRect = [text boundingRectWithSize:<text Feild Size>
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:[UIFont stuff here]}
                                 context:nil];

CGSize size = textRect.size;

A: yes, if you assign text to textView and check its size in the next instruction in viewControllers viewDidLoad, it wont work.It will just give you what contentSize you had set.
Check the contentSize in viewDidAppear of ViewController, and it will work.
It worked for me.
Hope this helps,


text:
Q: Wired "empty" element inside my array after using splice I use an data object  to store and remove blobs using data.instructAudios = [];
When I use splice to remove specific blob by its index like:
data.instructAudios.splice(index, 1);

I get a wired log with empty element in the array!!!

What is this and how can I remove blobs by their index without this bug?


text:
Q: Collection of measurable sets closed under countable unions implies existence of a set with maximal measure Let $(X,\mathcal{A}, \mu)$ be a finite measure space. Let $\mathcal{G} \subset \mathcal{A}$ be a subset, closed under countable unions, i.e., if $(G_n)_{n \in \mathbb{N}} \subset \mathcal{G}$, then $\cup_{n \in \mathbb{N}}G_n \in \mathcal{G}$. In this case, is it true that there exists a set $G \in \mathcal{G}$ with maximal $\mu$-measure, i.e.
\begin{align}
\mu(G) \geq \mu(G'), \text{ for all } G' \in \mathcal{G},
\end{align}
and if so, how do I see that this set exists?
Thanks a lot in advance!

A: Let $s$ be the supremum of the $\mu$-measures of members of $\mathcal G$. By definition of supremum, for each $n$, there is $G_n\in\mathcal G$ with $\mu(G_n)>s-1/n$. Letting $G=\bigcup_n G_n$, then $G\in \mathcal G$ since $\mathcal G$ is closed under countable unions, and $\mu(G)=s$, since it is at least $\sup_n\mu(G_n)$ but it is at most $s$ (by definition of $s$).

A: Yes it's a direct application of Zorn's lemma: https://en.wikipedia.org/wiki/Zorn%27s_lemma
Your order would be $A\geqslant B$ if $\mu(A)>\mu(B)$ or $B$ is included in $A$.
Then your set $\mathcal{G}$ is partially ordered, any chain has an upper bound, and the Zorn's lemma resulting maximal element is necessary maximal for the measure.


text:
Q: Can't connect to FTP or SSH URLs in my Azure app service API I have verified that FTP is turned on. I get this error when trying to connect in FileZilla:

Connection attempt failed with "EAI_NONAME - Neither nodename nor
servname provided, or not known".

My FTP URL looks like this:
ftp://dev-api.ase-name-dev.appserviceenvironment.net

Hmmm… can't reach this pageCheck if there is a typo in
dev-api.scm.ase-name-dev.appserviceenvironment.net.
DNS_PROBE_FINISHED_NXDOMAIN

This is what that URL looks like:
https://dev-api.scm.ase-name-dev.appserviceenvironment.net/webssh/host

I have two domains for this API. The default one and a new custom one. I looked in the domain settings and it all looks fine.

Any ideas on what's going on here?

A: Based on the above information shared, we understood that you are using app service environment.
If your app service environment is created with ILB then you need to use internal load balancer IP to do FTP adding to that you need to have any of these ports opened 21, 990, 10001-10020 as mentioned in this Documentation.
If your ASE is created with external Load balancer then you need to use the public IP address of the ASE to perform SSH or FTP.


text:
Q: How to setup development environment for a Python multi-package application? Working on a python application which consists of multiple packages which are supposed to be decoupled from each other and installed as dependencies if necessary. Each package is installable and can be accessed through a namespace. However, this means that every time I change anything in any of the dependency, I need to rebuild that package and re-run the application.
Is it possible to setup such an application to link the local packages directly and not from the External Libraries?
Example application structure
- myapp
    - package1
        - src
            - package1 (this becomes package1 namespace)
                - package 1 sub-packages and modules
        - setup.py
        - requirements.txt
        - pyproject.toml
    - package2
        - src
            - package2 (this becomes package2 namespace)
                - (python code which imports package1.*)
        - setup.py
        - requirements.txt (
        - pyproject.toml

In the source code of the package2, the modules import package 1 as follows
from package1.module1 import Class1

To be able to test any code that I'm writing in package1, I need to build that package, install it, and then re-run the application.
Is it possible to avoid having to rebuild and re-install the package in the development environment?
I'm new to Python and came into this project from JS, wondering if python can do something like Webpack live reload and hot module swapping?
Tried linking the packages via the file path, but that didn't fly for production.
Researched Python module linking and structure, but didn't find a good approach to this particular issue.
Expecting that when I run the application locally, changes to the modules within the application reflect in the running code. If that's not possible, at least expecting to only reload the application and not rebuild all the packages.


text:
Q: Why ES6 (7/8...) is able to be compatible with ES5(3) since there is so much difference in grammar? Addition: Why Python3 choose to design new features at cost of compatibility? Is there anything to do with the nature of language?

A:
Why ES6 (7/8…) is able to be compatible with ES5(3) since there is so much difference in grammar?

There aren't differences so much as additions. When new grammar/syntax is added in JavaScript, it's defined carefully so that it would have been a syntax error in earlier versions. That's important, because maintaining backward compatibility with the mind-bogglingly huge amount of JavaScript code out in the wild is an important goal for the committee that moves JavaScript forward (ECMA's TC39). (Backward compatibility isn't 100%, but it's about 99.9999%.) But if something new would have been a syntax error before, then there isn't any working code out there that has the new thing.
For example: Adding async functions. In JavaScript from the beginning, a function declaration looks like this:
function example() {
    // ...
}

To create async functions, it became possible to put async in front of function:
async function example() {
    // ...
}

That's new grammar. It only works because before it was added, that would have been a syntax error, the same one you get if you do this today:
blah function example() {]
    // ...
}

Similarly, with parameter default values, you specify the default value with an = and an expression in the parameter list:
function example(param = "default") {
    // ...
}

That was a syntax error until it was added. So were arrow functions, generator functions, class syntax, nullish coalescing, optional chaining, destructuring, and other new grammar/syntax.
So since these would have been syntax errors, they don't exist in working code out in the wild.


text:
Q: ASP.Net: If I have the Session ID, Can I get the Session object? This question is related to this one, though I think I was a little too long-winded there to really get a good answer. I'll keep this brief.
I'm working on a web handler (ashx) that accepts a form post from an aspx page. When the handler receives this form post, in order to do what it needs to do, it needs to know the user who is logged in (User.Identity.Name), but I can't rely on cookies being sent by the browser.
I know I can get the Session.SessionID and place it in a hidden form field, but once my handler receives the form post, how can I use that SessionID to figure out the logged-in user's identity?
I'm using the StateServer mode for session state.

A: I think you can do it be implementing the IReadOnlySessionState interface on your HttpHandler

A: Unless there is a need to use session directly, you could always store whatever information about the logged-in user's identity in a singleton dictionary or cache and reference it via the SessionID stored in a hidden field.  I personally see security issues in this but won't go into those.  I would consider issuing single use identities for this type of implementation.

A: Jonas posted a great answer to this question here:
Can I put an ASP.Net session ID in a hidden form field?

A: In an HttpHandler or HttpModule implementation, you cannot always access session from the BeginRequest event.  There is another event you can handle, called OnAcquireRequestState.  If you write your code in that event, then HttpContext.Current.Session will not be null.


text:
Q: How to get records from tables in custom order of ids? I have some Ids store in below variable:
List<int> Ids;

Now I want to get records based on above Ids but with same order as it is in above Ids.
For eg: Records are like this in database:
Employee:
Id
1
2
3
4
5

Now if Ids array holds Ids like this : 4,2,5,3,1 then I am trying to get records in this order order only:
Query:
  var data = context.Employee.Where(t => Ids.Contains(t.Id)).ToList();

But above query is giving me output like it is in table:
Id
1
2
3
4
5

Expected  output :
Id
4
2
5
3
1

Update:I have already tried this below solution but as this is entity framework it didn't work out:
var data = context.Employee.Where(t => Ids.Contains(t.Id))
                    .OrderBy(d => Ids.IndexOf(d.Id)).ToList();

For above solution to make it working I have to add to list :
var data = context.Employee.Where(t => Ids.Contains(t.Id)).ToList()
                    .OrderBy(d => Ids.IndexOf(d.Id)).ToList();

But I don't want to load data in memory and then filter out my record.

A: Since the order in which the data is returned when you do not specify an ORDER BY is not determined, you have to add an ORDER BY to indicate how you want it sorted. Unfortunately you have to order based on objects/values in-memory, and cannot use that to order in your SQL query.
Therefore, the best you can do is to order in-memory once the data is retrieved from the database.
var data = context.Employee
    // Add a criteria that we only want the known ids
    .Where(t => Ids.Contains(t.Id))
    // Anything after this is done in-memory instead of by the database
    .AsEnumerable()
    // Sort the results, in-memory
    .OrderBy(d => Ids.IndexOf(d.Id))
    // Materialize into a list
    .ToList();

A: Without stored procedures you can use Union and ?: that are both canonical functions.
I can't immagine other ways.
?:
You can use it to assign a weigth to each id value then order by the weigth. Also, you have to generate ?: using dynamic linq.
What is the equivalent of "CASE WHEN THEN" (T-SQL) with Entity Framework?
Dynamically generate LINQ queries
Union
I think this is the more simple way to obtain it. In this case you can add a Where/Union for each Id.
EDIT 1
About using Union you can use code similar to this
IQueryable<Foo> query = context.Foos.AsQueryable();
List<int> Ids = new List<int>();
Ids.AddRange(new[] {3,2,1});
bool first = true;
foreach (int id in Ids)
{
    if (first)
    {
        query = query.Where(_ => _.FooId == id);
        first = false;
    }
    else
    {
        query = query.Union(context.Foos.Where(_ => _.FooId == id));
    }
}

var results = query.ToList();

This generate the followiong query
SELECT
[Distinct2].[C1] AS [C1]
FROM ( SELECT DISTINCT
        [UnionAll2].[C1] AS [C1]
        FROM  (SELECT
                [Distinct1].[C1] AS [C1]
                FROM ( SELECT DISTINCT
                        [UnionAll1].[FooId] AS [C1]
                        FROM  (SELECT
                                [Extent1].[FooId] AS [FooId]
                                FROM [Foos] AS [Extent1]
                                WHERE [Extent1].[FooId] = @p__linq__0
                        UNION ALL
                                SELECT
                                [Extent2].[FooId] AS [FooId]
                                FROM [Foos] AS [Extent2]
                                WHERE [Extent2].[FooId] = @p__linq__1) AS [UnionAll1]
                )  AS [Distinct1]
        UNION ALL
                SELECT
                [Extent3].[FooId] AS [FooId]
                FROM [Foos] AS [Extent3]
                WHERE [Extent3].[FooId] = @p__linq__2) AS [UnionAll2]
)  AS [Distinct2]
p__linq__0 = 3
p__linq__1 = 2
p__linq__2 = 1

EDIT 2
I think the best approach is in memory approach because it has the same network load, EF does not generate the ugly query that could not work on databases different from SQL Server and code is more readable. In your particular application could be that union/where is better. So, generally I would suggest you to try memory approach then, if you have [performance] issues, you can check if union/where is better.


text:
Q: PHP if/else issue using true/false My code looks like this:
$muted = 'true'; //Note this is only for testing
if ($muted == 'false' || $muted == '' || $do_not_text == '' || $do_not_text =='false'){
//do this first thing
}
else{
//do something else
}

I can't get my else to run. What syntax am I messing up?
Related to this, I'm storing a value in my database (that will be what's called to set $muted in my real code) that's either 'true', 'false', or ''. What data type should I be storing these as? Currently, I'm using VARCHAR, but I suspect this is all part of the problem.

A: $do_not_text == '' evaluates to true. Why? Because $do_not_text is not defined which is a falsy value. You are comparing it to an empty string which also equates to a falsy value. So that comparison is true causing the first if statement to be evaluated as true.

A: I'm not sure why you're using strings for what should be boolean values.
$muted = true; // no need for quotes

You might also consider using the === operator when comparing boolean values.
if ($muted === false || // etc...

What data type should I be storing these as?

Boolean values in MySQL are typically stored as 1 or 0.
field_name TINYINT(1) UNSIGNED NOT NULL DEFAULT 0

A: Store them as TINYINT with length of 1 because its only 1 and 0,  and 0 as the default value.
Then you can make $muted = boolval($db_muted_val); if you want, or use $db_muted_val as is, because 1 is true and 0 is false.
if ($db_muted_val) {
    // do this first thing
} else {
    // do something else
}


text:
Q: Idle timeout not working as expected I have a problem with the code below and can't figure out why it's not working.
Basically when the timer function kicks in (user is idle for 30 minutes) I would like it to check to see if my child windows are open and if so close them.
If the window named "interpwindow" is open and not "child" it will close "interpwindow" and load my login page (this is good).
If both "interpwindow" and "child" are open it will also do what I expect.
If "child" is open but not "interpwindow", it closes "child" but does not load the login page.
It neither "child" or "interpwindow" are open it will not go to my login page.
Any ideas?
 <script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
   //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });
});
function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 29)
    { // 30 minutes
            if(child)
            {
         child.close();
             }
    if(interpwindow)
             {
         interpwindow.close();
             }
        location.href = "Login.html";
       }
}
</script>


text:
Q: When to use $and query in mongodb Can someone tell me the difference between these two queries?
db.foo.find({ $and: [{a: 1}, {a: {$gt: 5}}]})

and
db.foo.find({a:1, a:{$gt:5}})

EDIT
Ok let me change the question a little bit. Assume the following
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })

And I want to find all unread messages for user id 1. Do I do this
db.foo.find({UserID:1, Status:'unread'})

or this
db.foo.find({$and: [{UserID:1},{Status:'unread']})

A: With $and both conditions are taken into account when querying. Without $and only the last spec for a is considered in the query. This seems to happen with insert from mongo shell also.
In your edited question, I would definitely use db.foo.find({UserID:1, Status:'unread'})
Example below:
> db.sotest.insert({a : 1})
> db.sotest.insert({a : 2})
> db.sotest.insert({a : 6})
> db.sotest.insert({a : 7})
> db.sotest.insert({a : [1, 7]})
> db.sotest.find()
{ "_id" : ObjectId("50587c0164433af6a99c988f"), "a" : 1 }
{ "_id" : ObjectId("50587c0564433af6a99c9890"), "a" : 2 }
{ "_id" : ObjectId("50587c0d64433af6a99c9891"), "a" : 6 }
{ "_id" : ObjectId("50587c1064433af6a99c9892"), "a" : 7 }
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
> db.sotest.find({a:1, a:{$gt:5}})
{ "_id" : ObjectId("50587c0d64433af6a99c9891"), "a" : 6 }
{ "_id" : ObjectId("50587c1064433af6a99c9892"), "a" : 7 }
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
> db.sotest.find({a:{$gt:5}, a:1})
{ "_id" : ObjectId("50587c0164433af6a99c988f"), "a" : 1 }
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
> db.sotest.find({$and : [{a:{$gt:5}}, {a:1}]})
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
>

A: The second one isn't valid because you can't have an object with two properties that have the same name of a.  The first one is valid, so that's the difference.
EDIT
In your updated question, you definitely want to use:
db.foo.find({UserID:1, Status:'read'});

as it's the more natural syntax.


text:
Q: How to patch configmap in json file with kustomize? How to patch "db.password" in the following cm with kustomize?
comfigmap:
apiVersion: v1
data:
  dbp.conf: |-
    {
      "db_properties": {
        "db.driver": "com.mysql.jdbc.Driver",
        "db.password": "123456",
        "db.user": "root"
      }
    }

kind: ConfigMap
metadata:
  labels: {}
  name: dbcm

A: you can create new file with updated values and use command replace along wih create
kubectl create configmap NAME --from-file file.name -o yaml --dry-run | kubectl replace -f -

A: create a placeholder in your file and replace it with real data while applying kustomize
your code will be like this:
#!/bin/bash
sed -i "s/PLACE-HOLDER/123456/g" db_config.yaml
kustomize config.yaml >> kustomizeconfig.yaml
kubectl apply -f kustomizeconfig.yaml -n foo

And the db_config file will be:
apiVersion: v1
data:
  dbp.conf: |-
    {
      "db_properties": {
        "db.driver": "com.mysql.jdbc.Driver",
        "db.password": "PLACE_HODLER",
        "db.user": "root"
      }
    }

kind: ConfigMap
metadata:
  labels: {}
  name: dbcm

NB: This should be running on the pipeline to have the config file cloned from repo, so the real file won't be updated.


text:
Q: Can in-line initializations be done with python's Enum class I'm trying to do some C-style enumerations, by modding AutoNumber from https://docs.python.org/3.4/library/enum.html#interesting-examples
I'm unable to work out how to get the __init__ function coded.
class MyEnum (Enum):
    def __new__(cls):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

    def __new__(cls, value):
        super().__new__(cls, value) # It doesn't matter what I put here...

class ThingsToDo (MyEnum):
        first_thing = 30
        second_thing = ()
        ...
        another_thing = 50
        yet_another_thing = ()

And so on, being able to set the value during the initialization.  I've tried a whole bunch of different ways of defining __new__, but mostly get this error:
  File "/usr/lib/python3.7/enum.py", line 218, in __new__
      enum_member = __new__(enum_class, *args)
 TypeError: __new__() takes 1 positional argument but 2 were given

although the call in the code above give me this:
  File "/usr/lib/python3.7/enum.py", line 218, in __new__
    enum_member = __new__(enum_class, *args)
  File "./codecs.py", line 34, in __new__
    super().__new__(cls, value)
  File "/usr/lib/python3.7/enum.py", line 564, in __new__
    raise exc
  File "/usr/lib/python3.7/enum.py", line 548, in __new__
    result = cls._missing_(value)
  File "/usr/lib/python3.7/enum.py", line 577, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 30 is not a valid ThingsToDo

I'm either missing something simple, or this is a bigger task than I thought.  I'm not tied to Enum, so if there's a better way to do this, I'm up for it.

A: Hopefully, your second __new__ was meant to be __init__ -- but that would still be incorrect.  What you (possibly) want your __new__ to look like is:
    def __new__(cls, value=None):
        if value is None:
            value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

However, given the above __new__, your ThingsToDo enum members would be:
>>> list(ThingsToDo)
[
  <ThingsToDo.first_thing: 30>,
  <ThingsToDo.second_thing: 2>,
  <ThingsToDo.another_thing: 50>,
  <ThingsToDo.yet_another_thing: 4>,
  ]

Notice that second and yet_another_thing have values of 2 and 4, not 31 and 51.  If that's what you were expecting, then you are good to go!
Otherwise, if 31 and 51 are what you are looking for, then you'll need to have __new__ locate the value from the last defined enum and increment that:
    def __new__(cls, value=None):
        if value is None:
            if not cls.__members__:
                value = 1
            else:
                last_enum_name = cls._member_names_[-1]
                last_enum = cls.__members__[last_enum_name]
                value = last_enum.value + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj


text:
Q: Problems with update query I have a form in the previous page which allows users to fill in the details that they wish to edit which will be posted to another page.
 $first_name = $_POST['first_name'];
 $last_name = $_POST['last_name'];

$query = "UPDATE member SET first_name ='$first_name' WHERE member_id= '".$_SESSION['member_id']."'";
$query = "UPDATE member SET last_name ='$last_name' WHERE member_id= '".$_SESSION['member_id']."'";

// execute SQL statement
$status = mysqli_query($link,$query) or die(mysqli_error($link));

Apparantly, only the last query works. If the user edits the $first_name, the chang

A: you only execute one query and as you overwrite $query with the second declaration you'll only execute the last...
you can update both in query like so:
$query = "UPDATE member SET first_name ='$first_name' ,last_name ='$last_name' WHERE member_id= '".$_SESSION['member_id']."'";

A: Well, this is a basic Programming thing.
  $first_name = $_POST['first_name'];
 $last_name = $_POST['last_name'];

$query1 = "UPDATE member SET first_name ='$first_name' WHERE member_id= '".$_SESSION['member_id']."'";
$query2 = "UPDATE member SET last_name ='$last_name' WHERE member_id= '".$_SESSION['member_id']."'";

// execute SQL statement
$status1 = mysqli_query($link,$query1) or die(mysqli_error($link));
$status2 = mysqli_query($link,$query2) or die(mysqli_error($link));

A: try combining query
$query = "UPDATE member SET first_name ='$first_name',last_name ='$last_name' WHERE member_id= '".$_SESSION['member_id']."'";

A: You are changing the content of $query several times before executing. Apperently your $query contains the value that you last assignet to it.
This is the query that is then getting executed.


text:
Q: Удалить все элементы с классом, который содержит ..._ru | JS Есть небольшой одностраничник. Нужно через js удалить все элементы с классом которые содержат ..._ru. Например есть список

... именно оттуда нужно отыскать те эл. с классом. Но в дальнейшем понадобиться удалить те элементы, с указанным классом, во всей странице. Лучше уж показать тот пример, который чекает всю страницу и удаляет те классы (все равно стр маленькая, по оптимизации не ударит).
P.S: Пробовал через jquery, а именно функцию .each() и indexOf() отыскать, но индекс элемента некорректный, чтобы достучаться до него.

Washing

Cleaning

Доставка

Cargo

Сервировка

A:

$('li[class*="_ru"]').remove()

Washing

Cleaning

Доставка

Cargo

Сервировка

Использован данные по CSS селекторам, а именно звёздочка
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

A: Можно использовать document.querySelectorAll. Селектор: [class$=_ru] Выбирает все элементы со значением атрибута class, заканчивающимся на «_ru». Можете ознакомится с некоторыми примерами селекторов здесь https://www.w3schools.com/cssref/trysel.php?

document.querySelectorAll("[class$=_ru]").forEach(e => {
  e.remove()
})

Washing

Cleaning

Доставка

Cargo

Сервировка


text:
Q: Travel through a Tree I want to create a string depending on how I travel the tree I have created.
For example.
Structure_of_tree{

    int value;
    char ch;

}

I want to cycle through the tree until I find set value.
create_string(int val_toFind, treeStruct *treeRoot){

   char string[10];
   for(treeRoot != null && val_toFind == treeRoot->val){
      if(treeRoot goes left)
         strcat(string,0);

      if(treeRoot goes right)
         strcat(string,1);
   }
}

Is this possible? The idea is that the value to find gives me an output:
A: 01001

A is the ch inside the tree and the string is '01001'.

A: Your tree should have the struct as,
struct tree {
    int value;
    char ch;
    struct tree* left;
    struct tree* right;
};

Also you need to handle insert function appropriately. This is similar to binary search tree.
Have a look at Stanford University's tutorial here.


text:
Q: Call Java method from JNI In some C library exists function with signature: int someFunction(int a);
I need to call Java methods from this function (from native code) so as not to break the interface.
For example:
int someFunction(int a) {
    ...
    jbyteArray result = (jbyteArray)(*jEnv)->CallStaticObjectMethod(jEnv, clazz, methodId);
    ...
}

I can't put any extra arguments like JNIEnv in someFunction needed by JNI so I declare global variables and functions for initialization:
jmethodID globalMethodId;
jclass globalClass;
JavaVM* globalJVM;

void initJNI(JNIEnv * env, jclass clazz) {
    globalClass = (*env)->NewGlobalRef(env, clazz);
    (*env)->GetJavaVM(env, &globalJVM);

    globalMethodId = (*env)->GetStaticMethodID(env, clazz, "javaMethodName", "()[B");
}

JNIEnv * GetJniEnv() {
    JNIEnv * env;
    if((*globalJVM)->AttachCurrentThread(globalJVM, &env, NULL) != JNI_OK) {
        env = NULL;
    }
    return env;
}

and my someFunction function is as follows
int someFunction(int a) {
    JNIEnv * jEnv = GetJniEnv();
    jbyteArray result = (jbyteArray)(*jEnv)->CallStaticObjectMethod(jEnv, globalClass, globalMethodId);
    ...
}

And user of this new library must call initJNI function and thereafter call someFunction.
Is it not error prone way? How about multithreading? Is there more preferable solution.

A: I know this is old , but peoples still find it from searches .
Here is full solution , how to call C code from java ,and call back java code from jni c code:
Create Android.mk in your project jni dir
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_ALLOW_UNDEFINED_SYMBOLS=false
LOCAL_MODULE := testjni
LOCAL_SRC_FILES := testjni.c
LOCAL_LDLIBS    := -llog -ljnigraphics
include $(BUILD_SHARED_LIBRARY)

Create Application.mk in your project jni dir
APP_ABI := armeabi-v7a
APP_PLATFORM := android-8

Create testjni.c in your project jni dir
#include <jni.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>

#include <android/log.h>

#define LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,"TAG",__VA_ARGS__)

JavaVM *myVm;

static void *android_gui = NULL;

jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
    // Keep a reference on the Java VM.
    myVm = vm;

    LOGD("JNI interface loaded.");

    return JNI_VERSION_1_2;
}

void jni_setDataEnv(JNIEnv *p_env, int width, int height)
{
    if (android_gui == NULL)
        return;

    jclass cls = (*p_env)->GetObjectClass (p_env, android_gui);

    jmethodID methodId = (*p_env)->GetMethodID (p_env, cls, "setData", "(II)V");

    //add or delete II's depinding your number or variable passsed

    (*p_env)->CallVoidMethod (p_env, android_gui, methodId, width, height);

    (*p_env)->DeleteLocalRef(p_env, cls);
}

void jni_setData(int width, int height)
{

    JNIEnv *p_env;

    (*myVm)->AttachCurrentThread (myVm, &p_env, NULL);

    jni_setDataEnv(p_env, width, height);

    int check = (*myVm)->GetEnv(myVm, (void *) &p_env, JNI_VERSION_1_2);

    LOGD(" Detach destructor = %d", check);

    if (check != JNI_EDETACHED)
     {

        int detach = (*myVm)->DetachCurrentThread (myVm);

        LOGD("Detach result ==: %d", detach);

     }

}

//change this to your package

JNIEXPORT void JNICALL Java_com_example_test_LibTest_initM(JNIEnv *env, jobject thiz, jobject gui)
{

   android_gui = (*env)->NewGlobalRef(env, gui);

}

//when you need , in your c code call jni_setData(100.200 ) and
//MainActivity method , setData() will receive this values

void *call_from_thread()
{
    jni_setData(1,2);
    return NULL;
}

JNIEXPORT void JNICALL Java_com_example_test_LibTest_test(JNIEnv *env, jobject thiz)
{

    pthread_t t;
    //do hard work in a thread
    pthread_create(&t, NULL, call_from_thread, NULL);

}

in jni folder run ndk-build to compile the library libtest.so
Create : MyInterface.java in your java android project src
package com.example.test;

public interface MyInterface
{

    void setData(int width, int height);

}

Create LibTest.java  //used to send data to C code from java
package com.example.test;

public class LibTest
{

  static
  {
     System.loadLibrary("testjni");
  }

  private static LibTest sInstance;

  public static LibTest getInstance()
   {
        synchronized (LibTest.class)
          {
            if (sInstance == null)
              {
                /* First call */
                sInstance = new LibTest();
              }
           }

        return sInstance;
   }

   public native void initM( MyInterface myinterface );

   public native void test();

}

Create  MainActivity.java
package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity implements MyInterface
{
    int mHeight;
    int mWidth;

    LibTest libtest;

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

        libtest = LibTest.getInstance();

        libtest.initM( MainActivity.this );

        //tell jni to send us some data
        //we receive data in 'setData(int width, int height)' method

        libtest.test();

    }

@Override
public void setData(int width, int height)
{
    /// Here you receive data from C code
    //We can store the values C send to Java so we use latter

    mHeight = height;
    mWidth  = width;

    Log.d("TAG" ,"GOT SOME DATA FROM C CODE" + mHeight + " " + mWidth );

}

}


text:
Q: Adding/removing HTML elements dynamically I have created an angular 8 app that allows a user to choose a date from a angular material date picker control. The app then sends a request a Mongodb using NodeJS to return a list of available daily sessions. This part of my app is working fine. The returned daily sessions are dynamically displayed as buttons in the html. My code iterates through the list of available sessions and creates a button in the html using a angular *ngFor loop. My problem is that when the user then wants to choose another date from the date picker the new list of sessions is returned and the new list of available dates creates more buttons in the html using the *ngFor loop i.e. the new list of buttons is appended to the existing list of buttons. What I actually want is the previously displayed button in the HTML to be deleted from the DOM and the new list of buttons for the newly selected date to be displayed in their place. Does anybody know how to do this? Thanks!
Below is my component ts file:-
import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';
import { Tank } from '../../models/tank.model';

import { FormGroup, FormControl } from '@angular/forms';
import * as moment from 'moment';
import { TankService } from 'src/app/services/tank.service';

@Component({
  selector: 'app-booking',
  templateUrl: './booking.component.html',
  styleUrls: ['./booking.component.css']
})

export class BookingComponent implements OnInit {

  selectedDate: any;
  convertedDate: string;
  tankAvailability: Tank[];
  dateSelectionButtonPressed = false;
  tankOneAvailability: string[] = [];

  bookingForm: FormGroup;

  constructor(private tankService: TankService) { }

  ngOnInit(): void {
    this.bookingForm = new FormGroup({
       enteredDate: new FormControl(),
    });
  }

  onSelect(event) {
    this.selectedDate = event;

    this.convertedDate = moment(event).format('DD-MM-YYYY');
    this.bookingForm.patchValue({
      enteredDate: this.convertedDate
    });
  }

  getTankAvailabilityByDate() {
    this.dateSelectionButtonPressed = false;
    this.tankAvailability = [];
    if (this.convertedDate) {
      this.tankService.getTankAvailabilityByDate(this.convertedDate)
        .subscribe(tanks => {
          this.tankAvailability = tanks.tanks;
          this.populateAvailableSessions();
        });
    }
  }

  populateAvailableSessions() {
    this.dateSelectionButtonPressed = true;
    for(let i = 0; i < this.tankAvailability.length; i++) {
      if (this.tankAvailability[i].tankNumber === 1) {
          console.log(this.tankAvailability[i]);
          if (this.tankAvailability[i].sessionOne === false) {
            this.tankOneAvailability.push('07:00');
          }
          if (this.tankAvailability[i].sessionTwo === false) {
            this.tankOneAvailability.push('09:00');
          }
          if (this.tankAvailability[i].sessionThree === false) {
            this.tankOneAvailability.push('11:00');
          }
          if (this.tankAvailability[i].sessionFour === false) {
            this.tankOneAvailability.push('13:00');
          }
          if (this.tankAvailability[i].sessionFive === false) {
            this.tankOneAvailability.push('15:00');
          }
          console.log(this.tankOneAvailability);
        }
      }
  }
}

Below is my component HTML file:-
<mat-card>

Book a float

      Select a date on the calendar below and we will display all the available float times

    <form (submit)="getTankAvailabilityByDate()" [formGroup]="bookingForm">

        <mat-calendar [selected]="selectedDate" (selectedChange)="onSelect($event)"></mat-calendar>

      <mat-form-field class="invisible-field">
        <input matInput formControlName="enteredDate">
      </mat-form-field>
      <button mat-raised-button color="primary" type="submit">Get availability</button>
    </form>

</mat-card>

<mat-card *ngIf="dateSelectionButtonPressed">
    <mat-card-header>
        <mat-card-title>Tank 1</mat-card-title>
    </mat-card-header>
    <mat-card-content *ngFor="let session of tankOneAvailability">
       <button mat-raised-button color="primary">{{session}}</button>
    </mat-card-content>
</mat-card>

A: You would need to empty the array to show new list of buttons. Below code needs to be changed
populateAvailableSessions() {
    this.dateSelectionButtonPressed = true;
    // always create new array so new values are pushed
    this.tankOneAvailability = [];
    for(let i = 0; i < this.tankAvailability.length; i++) {
      if (this.tankAvailability[i].tankNumber === 1) {
          console.log(this.tankAvailability[i]);
          if (this.tankAvailability[i].sessionOne === false) {
            this.tankOneAvailability.push('07:00');
          }
          if (this.tankAvailability[i].sessionTwo === false) {
            this.tankOneAvailability.push('09:00');
          }
          if (this.tankAvailability[i].sessionThree === false) {
            this.tankOneAvailability.push('11:00');
          }
          if (this.tankAvailability[i].sessionFour === false) {
            this.tankOneAvailability.push('13:00');
          }
          if (this.tankAvailability[i].sessionFive === false) {
            this.tankOneAvailability.push('15:00');
          }
          console.log(this.tankOneAvailability);
        }
      }
  }

Hope this helps.

A: You need to reinitialise the tankOneAvailability array each time you run a new query like you do for the tankAvailability (currently you keep pushing more values into it)
i.e.
 getTankAvailabilityByDate() {
    this.dateSelectionButtonPressed = false;
    this.tankAvailability = [];
    this.tankOneAvailability = []


text:
Q: Get the parameter names of an interface method I need to get the parameter names of a method at runtime. Is there any way to achieve this?
I tried using LocalVariableTableParameterNameDiscoverer which is a Spring class. But it works only for classes and not the interfaces.

A: The only way to obtain the parameter names is to compile the source code using -g:vars options. This generates a LocalVariableTable attribute into the class file. This is generally removed for optimization.
For example: (taken from here)
public class Example {
   public int plus(int a){
     int b = 1;
     return a + b;
   }
 }

This will create a LocalVariableTable as follows
LocalVariableTable:
   Start  Length  Slot  Name     Signature
   0      6       0     this     LExample;
   0      6       1     a        I
   2      4       2     b        I

The LocalVariableTable can be read using any byte code instrumentation libraries like ASM or Javassist.


text:
Q: Extend ActiveRecord method_missing I've been looking around the web and have found a great deal of information on attempting what I am, however one bit of sugar I'd like to add to my Ruby/Rails mixin, is creating a function that looks for a pattern. I want to create a base function called
is_a_*
where * can be anything. Whatever that * is, needs to be retrievable so I can use it inside the function and act accordingly. Do I have to use method_missing?

A: This is what method_missing was made for, e.g. something like this should work:
module MyMixin

  def respond_to?(method, priv=false)
    (method.to_s =~ /^is_a_(\w+)$/) || super
  end

  def method_missing(sym, *args)
    if sym.to_s =~ /^is_a_(\w+)$/
      pattern = $1
      # then just do something with pattern here, e.g.:
      puts pattern
    else
      super
    end
  end

end

Then just include MyMixin in your class, e.g.:
class A
  include MyMixin
end

a = A.new
a.is_a_foo
#=> "foo"

p.s. you don't strictly need to override respond_to?, I just included it for completeness:
a.respond_to?("is_a_foo")
#=> true
a.respond_to?("is_a_bar")
#=> true
a.respond_to?("is__a_foo")
#=> false


text:
Q: How to make the watcher saga fire a worker saga only on the first dispatch on an action pattern? How to make the watcher saga fire a worker saga only on the first dispatch on an action pattern?
function* rootSaga() {
    yield takeEvery(CHATBOT.START, handleChatbotLoad); //I want watcher saga to trigger handleChatbotLoad only on the very first dispatch of CHATBOT.START
    yield takeEvery(CONVERSATION.ADD_QUERY, handleUserInput);
}

So ya, I want watcher saga to trigger handleChatbotLoad only on the very first dispatch of CHATBOT.START. I can have a flag in the state like started and dispatch CHATBOT.START only once.
But then I was expecting a method like takeFirst or something like that. Is there any such method to achieve this?

A: You can call (or spawn, fork) some function in root saga, which means it'll be called only once when app started. And  use take in this function to wait for action dispatched:
function* onlyVeryFirstStartWatcher() {
    const action = yield take(CHATBOT.START);
    // started, do stuff...
    yield call(handleChatbotLoad);
}

function* rootSaga() {
  yield takeEvery(CONVERSATION.ADD_QUERY, handleUserInput);
  yield call(onlyVeryFirstStartWatcher)
}


text:
Q: Why didn't the Sovereign Class have folding warp nacelles? In this question, the Intrepid Class' folding nacelles are explained as a feature designed to circumvent the problems stated in TNG 'Force of Nature'.  The Sovereign Class and Intrepid Class came into service around the same time.  The Intrepid class has these new folding nacelles, the Sovereign class seems not to (at least there is no mention of this on Memory Alpha and I for one don't recall seeing the Sovereign class folding its nacelles).  In-universe then, why didn't the Sovereign class get folding nacelles?

More on the folding warp nacelles:

According to the unpublished VOY Season 1 edition of the Star Trek:
  Voyager Technical Manual by Rick Sternbach and Michael Okuda, (p. 12)
  it was suggested that because of this new folding wing-and-nacelle
  configuration, warp fields might no longer have a negative impact on
  habitable worlds as established in TNG: "Force of Nature". According
  to Star Trek Encyclopedia, (3rd ed. p. 555) these nacelles did in fact
  prevent damage to subspace.

(Source)

A: Star Trek: A Call to Duty is a site which collects canon information and expands on it with some minimal degree of conjecture. It features the encyclopedias and technical manuals among its sources. It states:
"Computer-controlled rotation of the frame allows for manipulation of the manner in which the reactants meet, allowing for further control of the warp plasma into a "cleaner" power source.  Redesigned verterium cortenide components within each pair of warp field coils is then able to use the warp plasma to generate a more energy-efficient subspace field with less particle waste products and stresses that were found in older propulsion systems to damage subspace.  After the fleet-wide installation of this new variable warp geometry system, Starfleet was able to remove the so-called "Warp Speed Limit" of Warp 5, established in 2370 after the discovery of pollution by Dr. Serova in the Hekaras Corridor.  Pursuant to Starfleet Command Directive 12856.A, all starships traveling within Federation space are required to receive engine upgrades that prevent the further pollution of subspace by 2380."
So the Sovereign's propulsion system is 'cleaner' in the first place according to this source. As I said in my comment, I think it's clear that the Intrepid uses one method and the Sovereign another.


text:
Q: Python, SQLAlchemy: Storing business hours as binary bitmask I am programming in Python and using SQLAlchemy to store business hours.
The business hours are composed of three parts:

*

*The days of the week stored in binary as a bitmask

*the time the business opens,

*the time the business closes.

The bitmask works like this. There are 7 digits, which are either 0 or 1, which will represent different sequences of weekdays. Each position represents a day of the week. The first position stands for Monday and the last for Sunday. For example, 1111100 represents Monday-Friday, and 0000111, Friday-Saturday. Also, I am storing the hours in military time, 0600 meaning 6AM and 1800 meaning 6PM.
hours = Table('hours', Base.metadata,
    Column("id", Integer, primary_key=True),
    Column("businessid", Integer, ForeignKey('businesses.id')),
    Column("days", Integer),
    Column("open", Integer),
    Column("close", Integer),
)

class Hours(object):
    def __init__(self, days=None, open=None, close=None):
        self.days = days
        self.open = open
        self.close = close

mapper(Hours, hours)
mapper(Business, businesses, properties={
    'hours': relationship(Hours, backref='business'),
})

What is the Pythonic way to figure out when two of the bitmasks representing the days of the week overlap? And also, what is the best way to find out if a business is currently open when given two pairs of Hours objects?

A: As far as checking days of the week, if by binary you mean a string of the form '1011011':
overlap = [n for n in range(7) if (bitmask1[n] == bitmask2[n] == '1')]

will give you a list of the numbers (from 0-6) of the overlapping days -- [4] for Friday overlapping.
overlap = ''.join(('1' if (bitmask1[n] == bitmask2[n] == '1') else '0') for n in range(7))

Will give you a new bitmask string -- '00000100' for Friday overlapping.
If you're actually storing the number as an integer, it's probably easiest to just convert it to one, either with bin(bitmask)[2:] or "{0:b}".format(bitmask).
I'm not sure what you mean by "currently open ... two pairs of hours objects". Do you want the overlap of the two pairs of hours? If they are whole hours, its easy:
[hour for hour in range(firsthour, secondhour) if hour in range(openinghour, closinghour)

Will give you a list of the hours in both ranges.


text:
Q: Why doesn't my program work with different Linux distros? I'm working on a packet sniffer.
The big problem is that my code works perfectly only under Backtrack 5 R3, but it doesn't work under other distributions! In fact, on Ubuntu 12.10 and ArchLinux, when the sniffer gets the first packet, I experience a segmentation fault (I get "segmentation fault core dumped"). At first, I thought the fault lay with the libraries or the compiler, but after some tests, I think I can exclude them! This is the situation:

*

*Backtrack 5 R3 uses gcc 4.4.3 and libpcap 1.0.0

*Ubuntu 12.10 uses Gcc 4.7.2 and Libpcap 1.3.0

*ArchLinux the same as Ubuntu

So I tried to downgrade on Arch to gcc 4.4.3 e libpcap 1.0.0, but I get the same error.
I have some warnings while compiling the code, but nothing really important, and however it works perfectly under backtrack! That's the big mystery.
Here's the code which cause the problem:
void packet_dump(unsigned char *arguments, const struct pcap_pkthdr *pcap_data, const unsigned char *packet) {
    int packet_data_len, tcp_header_size=0, total_header_size;
    unsigned char *packet_data;
    const unsigned char *ip_src_dest;
    const struct header_ip *ip_header;

    //Calculate the value of variables
    ip_src_dest = (packet+LUNGHEZZA_INTESTAZIONE_ETH);
    ip_header = (const struct header_ip *)ip_src_dest;
    total_header_size = LUNGHEZZA_INTESTAZIONE_ETH+sizeof(struct header_ip)+tcp_header_size;
    packet_data = (unsigned char *)packet + total_header_size;
    packet_data_len = pcap_data->len - total_header_size;

    //THIS CAUSE THE PROBLEM (Solved removing inet_ntoa and converting it manually)
    printf("[ %s ] ============> ", inet_ntoa(ip_header->source_addr_ip));
    printf("[ %s ]  \n", inet_ntoa(ip_header->destination_addr_ip));

}

A: I suspect your program is crashing because ip_header->source_addr_ip points to memory that you're not allowed to access. You should be able to use GDB to determine whether this is the case.


text:
Q: How to add CircularProgressIndicator when loading web page using flutter_inappwebview? I am new in flutter,
I tried to add a CircularProgressIndicator while waiting to the web page to load,
and then the page display and the circular indicator dosen't show on screen.
where it's should be? maybe in onLoadStart function below?
Source code:
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class CoursesInformation extends StatefulWidget {
  @override
  _CoursesInformationState createState() => _CoursesInformationState();
}

class _CoursesInformationState extends State<CoursesInformation> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
        child: Scaffold(
        appBar: AppBar(
          title: const Text('מידע על קורסים'),
          centerTitle: true,
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl:
                "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
                  preferredContentMode: UserPreferredContentMode.DESKTOP),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) async {

            },
          ))
        ])),
      ),
    );
  }
}

A: You can onProgressChanged parameter and show the loader. You can also use LinearProgressIndicator (check commented code). Check the following example
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

void main() {
  // it should be the first line in main method
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark()
          .copyWith(scaffoldBackgroundColor: Color.fromARGB(255, 18, 32, 47)),
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: CustomPage());
  }
}

class CustomPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CustomPageState();
  }
}

class CustomPageState extends State<CustomPage> {
  InAppWebViewController webView;

  double progress = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('מידע על קורסים'),
        centerTitle: true,
      ),
      body: Container(
          child: Column(children: <Widget>[
        Expanded(
            child: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: InAppWebView(
                initialUrl:
                    "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx",
                initialHeaders: {},
                initialOptions: InAppWebViewGroupOptions(
                  crossPlatform: InAppWebViewOptions(
                      debuggingEnabled: true,
                      preferredContentMode: UserPreferredContentMode.DESKTOP),
                ),
                onWebViewCreated: (InAppWebViewController controller) {
                  webView = controller;
                },
                onLoadStart: (InAppWebViewController controller, String url) {

                },
                onLoadStop:
                    (InAppWebViewController controller, String url) async {
                },
                onProgressChanged: (InAppWebViewController controller, int progress) {
                  setState(() {
                    this.progress = progress / 100;
                  });
                },
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: _buildProgressBar()
            ),
          ],
        ))
      ])),
    );
  }

  Widget _buildProgressBar() {
    if (progress != 1.0) {
      return CircularProgressIndicator();
// You can use LinearProgressIndicator also
//      return LinearProgressIndicator(
//        value: progress,
//        valueColor: new AlwaysStoppedAnimation<Color>(Colors.orange),
//        backgroundColor: Colors.blue,
//      );
    }
    return Container();
  }
}


text:
Q: Getting information with Token. OAuth I am creating an app to get information from Fitbit.com using OAuth.
protected void btnConnect_Click(object sender, EventArgs e)
    {
        // Create OAuthService object, containing oauth consumer configuration
        OAuthService service = OAuthService.Create(
            new EndPoint(RequestTokenUrl, "POST"),         // requestTokenEndPoint
            new Uri(AuthorizationUrl),                     // authorizationUri
            new EndPoint(AccessTokenUrl, "POST"),          // accessTokenEndPoint
            true,                                          // useAuthorizationHeader
            "http://app.fitbit.com",                       // realm
            "HMAC-SHA1",                                   // signatureMethod
            "1.0",                                         // oauthVersion
            new OAuthConsumer(ConsumerKey, ConsumerSecret) // consumer
            );

        try
        {
            var personRepository = new PersonRepository();

            var person = personRepository.GetPersonById(int.Parse(personSelect.SelectedItem.Value));

            OAuthRequest request = OAuthRequest.Create(
                new EndPoint(ProfileUrl, "GET"),
                service,
                this.Context.Request.Url,
                //this.Context.Session.SessionID);
                person.FitbitAuthAccessToken,
                );

            request.VerificationHandler = AspNetOAuthRequest.HandleVerification;

            OAuthResponse response = request.GetResource();

            // Check if OAuthResponse object has protected resource
            if (!response.HasProtectedResource)
            {
                var token = new OAuthToken(TokenType.Request, person.FitbitAuthAccessToken,
                    person.FitbitAuthSecret, ConsumerKey);
                // If not we are not authorized yet, build authorization URL and redirect to it
                string authorizationUrl = service.BuildAuthorizationUrl(response.Token).AbsoluteUri;
                Response.Redirect(authorizationUrl);
            }

            person.FitbitAuthAccessToken = response.Token.Token;
            person.FitbitAuthSecret = response.Token.Secret;
            person.PersonEncodedId = Doc["result"]["user"]["encodedId"].InnerText;
            personRepository.Update(person);

            // Store the access token in session variable
            Session["access_token"] = response.Token;
        }
        catch (WebException ex)
        {
            Response.Write(ex.Message);
            Response.Close();
        }
        catch (OAuthRequestException ex)
        {
            Response.Write(ex.Message);
            Response.Close();
        }
    }

I save Fitbit Access Token and Secret in database.

How can I get information using just Access token and secret, without authorizing every time?

A: This would assume that the FitBit api was robust enough to not quire authentication every single time.  I have seen API's implementing OAuth where you have an authentication process, then from there most of your calls simply require the AccessToken or secret.  I would look at the method signatures for the service and see what types of parameters they are requiring.

A: If you look at the FitBit API about authentication and accessing resources, you will see that you just need to request the data you are interested in and add in the oAuth header with the access token. Here is what it should look like (from the API page):
GET /1/user/-/activities/date/2010-04-02.json HTTP/1.1
Host: api.fitbit.com
Authorization: OAuth realm="api.fitbit.com",
oauth_consumer_key="fitbit-example-client-application",
oauth_token="8d3221fb072f31b5ef1b3bcfc5d8a27a",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1270248088",
oauth_nonce="515379974",
oauth_signature="Gf5NUq1Pvg3DrtxHJyVaMXq4Foo%3D"
oauth_version="1.0"`

The base signature string will look like:
GET&http%3A%2F%2Fapi.fitbit.com%2F1%2Fuser%2F-%2Factivities%2Fdate%2F2010-04-02.json&oauth_consumer_key%3Dfitbit-example-client-application%26oauth_nonce%3D515379974%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1270248088%26oauth_token%3D8d3221fb072f31b5ef1b3bcfc5d8a27a%26oauth_version%3D1.0

A: I figured I'd offer my VerifyAuthenticationCore that is part of my FitbitClient that inherits from OAuthClient. It took me a while to get this working but I found that I was missing HttpDeliveryMethods.AuthorizationHeaderRequest when I was creating the web request. Adding this allowed the call to stop returning bad request (400) error messages.
The code below is basically using the user id and the access token to get the user profile information. All calls should basically work this way. All you would need to do is change the url and provide the id and token.
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
    {
        string username;
        var accessToken = response.AccessToken;
        var userId = response.ExtraData["encoded_user_id"];
        var httpWebRequest = WebWorker.PrepareAuthorizedRequest(new MessageReceivingEndpoint(new Uri("http://api.fitbit.com/1/user/" + userId + "/profile.json"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), accessToken);
        var dictionary = new Dictionary<string, string>();
        dictionary.Add("accesstoken", accessToken);
        dictionary.Add("link", "http://www.fitbit.com/user/" + userId);

        using (var webResponse = httpWebRequest.GetResponse())
        {
            using (var stream = webResponse.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var profile = JObject.Parse(reader.ReadToEnd())["user"];
                dictionary.AddItemIfNotEmpty("name", profile["displayName"]);
                dictionary.AddItemIfNotEmpty("pictureUrl", profile["avatar"]);
                username = dictionary["name"];
            }
        }

        return new AuthenticationResult(true, ProviderName, userId, username, dictionary);
    }


text: Q: Downsampling, AUROC and accuracy equal I am using downsampling to create perfectly balanced classes in my target feature. I have found that accuracy is exactly equal to the AUROC score. I was thinking that this is because I've used downsampling, is this possible or is it just a coincidence?


text:
Q: LDO Regulator Overshoot I'm using an LP38691 3.3V fixed regulator which is overshooting. This wasn't an issue for years, but now a component is being replaced and the current on the 3.3V rail has gone up from 300mA to 500mA. The datasheet claims an output voltage is within 2% of the nameplate, and 4% at worst. It jumps to 3.8V for 40ms, and then steps down to 3.3V.
Is this normal behaviour for LDO regulators? The input voltage is 5V and the thing is surrounded by bypass capacitors and a low ESR 100u capacitor.
Edit:
Here's the schematic. I can't post the entire schematic because there are a few dozen pages. The component that changed was a microprocessor. I also scoped the 5V rail, and it it ramps up and stabilizes 20ms before the regulator starts to ramp up. The odd thing is that we use the same exact circuit on other boards, and those boards don't have that issue with the new processor.

A: I figured out the cause. The inrush current to the new processor board was much greater than the old processor board. It exceeded maximum current of the LDO regulator, causing the odd startup behavior.


text:
Q: Create subnet with address_prefixes error I used below code to create subnet but the field address_prefixes shows following error. Please guide.
resource "azurerm_subnet" "datbrick_subnet" {
 count                   = length(var.subnet_address)
 name                    = element(var.subnet_name, count.index)
 address_prefixes          =  element(var.subnet_address, count.index)
 resource_group_name      = var.subscriptionrg_name
 virtual_network_name     = var.vnet_name
 }
  variable "subnet_address" {
  default = ["10.0.0.0/26", "10.0.1.0/26"]
  }

count.index is 1
| var.subnet_address is tuple with 2 elements. Inappropriate value for attribute "address_prefixes": list of string required.

A: Your address_prefixes should be list. Please try the following:
resource "azurerm_subnet" "datbrick_subnet" {
 count                   = length(var.subnet_address)
 name                    = element(var.subnet_name, count.index)
 address_prefixes        = [element(var.subnet_address, count.index)]
 resource_group_name     = var.subscriptionrg_name
 virtual_network_name    = var.vnet_name
 }


text:
Q: How to add the JavaFX examples to netbeans and adapt the platform? I try to load the javafx examples on http://www.oracle.com/technetwork/java/javase/overview/javafx-samples-2158687.html
to netbeans. I have loaded them but every time I start a java-File, I always get this error. I have no idea how to handle the platform property....
Thanks a lot
ant -f C:\JavaBeispiele\javafx-samples-2.2.79\src\Ensemble jfxsa-run
C:\JavaBeispiele\javafx-samples-2.2.79\src\Ensemble\nbproject\build-impl.xml:88: The J2SE Platform is not correctly set up.
 Your active platform is: default_platform, but the corresponding property "platforms.default_platform.home" is not found in the project's properties files.
 Either open the project in the IDE and setup the Platform with the same name or add it manually.
 For example like this:
     ant -Duser.properties.file= jar (where you put the property "platforms.default_platform.home" in a .properties file)
  or ant -Dplatforms.default_platform.home= jar (where no properties file is used)
BUILD FAILED (total time: 0 seconds)
:

A: I managed it by myself. I went to Projekt Properties and Librairies. There I added a new platform. In my Java-Ordner I copied jdk1.8 and renamed it to platforms.defauld_platform.home and this platform i


text:
Q: Add thick vertical line to table using CSS I have a table like so. How would I add a thick vertical line between columns 2 and 3 so it splits it in half? I did some searching but everything I found was for a border around an entire column/cell. I just want a line going down.

A: You could use border: http://jsfiddle.net/kzp36owo/3/
table {
    background: blue;
    color: #ffffff;
}
table tr td:nth-child(2) {
    border-right: 4px solid yellow;
}

In order to work properly it's important to reset cellspacing of table.


text:
Q: MySQL, Inserting data into multiple columns I'm trying to insert data from one table into another. I would like to put the info from unit_66 in one column and the info for unit_166 into another column but I'm having trouble using two SELECT statements, I get this error when executing the code:
[Err] 1242 - Subquery returns more than 1 row

CREATE TABLE time_test (unit_66 BIGINT, unit_116 BIGINT);

insert into time_test (unit_66, unit_116)
VALUES
(
(select time_stamp from `events` where unit_id = 66 LIMIT 50),

(select time_stamp from `events` where unit_id = 116 LIMIT 50)
);

Can anyone tell what the problem it is?

A: I think you want insert . . . select.  You are using a scalar subquery, but having it return up to 50 values.  That is causing your error.  If you had a limit 1 in each subquery, then it would work.
It is a little hard to guess what you are trying to do, but let me try:
insert into time_test(unit_66, unit_116)
    select e66.time_stamp, e116.timestamp
    from events e66 join
         events e116
         on e66.unit_id = 66 and e116.unit_id = 116
    order by rand()
    limit 50;

This is just a guess, because the intention of your query is not obvious to me.

A: I suppose your time_test table is not normalized. So, you can use INSERT INTO SELECT statement. With this solution you will copy 100 records from events table.
INSERT INTO time_test (unit_66)
SELECT time_stamp
FROM events
WHERE unit_id = 66 LIMIT 50

INSERT INTO time_test (unit_116)
SELECT time_stamp
FROM events
WHERE unit_id = 116 LIMIT 50

A: insert into time_test (&unit_66,
&unit_116)
VALUES
(
(select time_stamp from events
where unit_id = 66 LIMIT 50),
(select time_stamp from events
where unit_id = 116 LIMIT 50)
);
just try this


text:
Q: Jest limit concurrency of integration tests How can I limit the concurrency of test execution in jest? Let's say I only want to run 4 test cases in parallel at the same time.
My current problem is that I have a lot of integration tests using a real database connection. Jest executes too much test cases in parallel, thus often connections timeout or the performance of my test database instance drops significantly because there are too many queries at the same time.
All of my integration test suits have the following structure:
describe('<functionality x>', () => {
    test('case 1', async () => {...})
    test('case 2', async () => {...})
    test('case 3', async () => {...})
})

describe('<functionality y>', () => {
    test('case 1', async () => {...})
    test('case 2', async () => {...})
    test('case 3', async () => {...})
})

I already tried running jest with --maxWorkers=1, but I guess this is the same as --runInBand, which works, but really slows down the overall execution time.

A: Rather than --maxWorkers=1, you could provide a larger value like --maxWorkers=2 or --maxWorkers=50%.
However, if you are trying to limit the number of tests running in parallel, it seems like you want to use:
jest --maxConcurrency=N

Jest's documentation says:

Prevents Jest from executing more than the specified amount of tests at the same time. Only affects tests that use test.concurrent.

so, note you have to modify your tests by adding the .concurrent:
describe('<functionality x>', () => {
    test.concurrent('case 1', async () => {...})
    test.concurrent('case 2', async () => {...})
    test.concurrent('case 3', async () => {...})
})

describe('<functionality y>', () => {
    test.concurrent('case 1', async () => {...})
    test.concurrent('case 2', async () => {...})
    test.concurrent('case 3', async () => {...})
})


text:
Q: Getting Started with Python but want to implement Web services with Sql backend I have a mini project that I need to create website site where I can submit some information to a database but want to do it through Web services.
Is there any projects that I can reference or tutorial that shows me how to create a Web front end, python web service or django web services tied MS Sql backend.
I can do it in another language but really want to do it purely in python/Django or whatever framework that make sense to do it in so I can learn.

A: You can start off by reading the Django tutorial on official website https://www.djangoproject.com
Or read Django by examples. It will set you started with cool features and all you need to build an amazing app quickly. You will be excited after finishing the first  two chapters.
For MySQL follow the documentation and it is pretty easy


text:
Q: Jsp form submit get the dynamic response for defense on transaction complete My web application , i am submitting jsp page, after submit four transaction committed , i need to get  dynamic response in every transaction complete.
 example.
first transaction completed(server side) -> first transaction complete response to jsp page(client side)
any one help me?
i have used only for jsp and servlet.


text:
Q: Can cloud functions like AWS Lambdas or Google Cloud Function access databases from other servers? I have a webapp and database that aren't hosted on any cloud service, just on a regular hosting platform.
I need to build an API to read and write to that database and I want to use cloud functions to do so. Is it possible to connect to a remote databases from cloud functions (such as AWS Lambdas or Google cloud functions) even when they're not hosted that cloud service?
If so, can there be problems with doing so?

A: Yes it's possible.

If so, can there be problems with doing so?

There could high latency if the database is in a different network. Also, long-lived database connection pools don't really work well in these environments due to the nature of the functions being created and destroyed constantly. Also, if your function reaches a high level of concurrency you may exhaust the number of available connections on your database server.

A: Cloud Functions are just Node.js code that runs in a managed environment. This means your code can do almost anything that Node.js scripts can do, as long as you stay within the restrictions of that environment.
I've seen people connect to many other database services, both within Google Cloud Platform and outside of it. The main restriction to be aware of there, is that you'll need to be on a paid plan in order to be able to call APIs that are not running on Google Cloud Platform.

A: You could use FaaS the same as your web service hosted on any web server or cloud server.
You have to be careful with the duration of your call to DB because FasS functions are limited in time (15 min for AWS Lambda and 9 min on Google) and configure a firewall properly on your DB server.
A container of your lambda function could be reused, you could use some tricks with it - Best Practices for AWS Lambda Container Reuse
But you can't be sure that nothing changed during the work of your service.
You could read some good advice about it there - https://stackoverflow.com/a/37524237/182344
PS: Azure functions have always on setting, but I am not sure how pooling will work in this case.

A: Yes you can access on premise resources from Serverless products.
Please check this detailed tutorial where you can find 3 methods to achive your goal link:

*

*Connecting using a VPN

*Connecting using a Parner interconnect

*Connecting using Interconnect solution


text:
Q: Virtualbox shared folder reading problems from Apache I have a problem with files on a mounted share inside a Virtualbox machine.
The problem is that even though I can see the content of the files fine enough from the shell, the same files turn out slightly corrupted, truncated or in old versions, sometimes when served over http via an Apache web server.
The problem seems only to happen once the file reaches a certain length (100-200 characters). Sometimes non-readable characters are added to the end, resulting in little question marks in the browser. Another common symptom is that when the file is changed from the host, there is no way to get Apache to serve the new version. (The problem is not related to ETags and Apache has perfect read permissions on all files. I doubt it's solely related to encodings either.)
It really looks like a filesystem-level problem which only manifests itself in Apache.
Some facts:
Host: MacBook Pro/Snow Leopard
Guest: Fedora 16
Apache: 2.2.22
VirtualBox: 4.1.8
I have tried mounting in fstab but also manually, changing userid to apache.
I apologize for the vague (unresearched?) problem description, but I really don't know where to start with this and I am hoping to get some hints in the right direction.
Is it Mac, Virtualbox, Fedora or Apache that is the real problem?
UPDATE: I realize there is more to it than Apache httpd not serving the files correctly - sometime, when I create a new folder on the host, the entry is shown as a bunch of question marks when doing a directory listing in the shell of the guest. It almost goes without saying that I cannot traverse into that new folder, until I have rebooted the guest.

A: Have a look at the ticket at https://www.virtualbox.org/ticket/819, there they suggest what you already found which is the Apache's EnableSendfile directive. Turning this directive Off seems to solve the problem on our servers.

A: Some searching for "apache mmap" reveals that Apache will use mmap(2) to access files when the files exceed a certain size (which appears to default to 1 byte on non-SunOS systems).  This problem could be caused by a bug in VirtualBox's support for mmap'ed access to shared folders.


text:
Q: Cross-Platform Rails Development I have Linux as my main Rails dev platform, but I also have Rails installed and working on my Windows pc. All my apps are synced between the two computers, so a change on Linux will reflect on Windows.
I'm wanting to use postgresql on Linux, but sqlite3 on Windows. Is there a way to distinguish certain gem sets to load (Gemfile) based on which platform I'm using?

A: Bundler docs  does mentions about :platform option that you can use to specify which gems you want to install on certain platform.
There's another solution(I learned from other Ruby developers and online tutorials) is to wrap your gemset inside a group eg:
group :option do
  gem 'gem1'
  gem 'gem2'
  ...
end

Then run:
bundle install --without option

After you run this command, bundler will install gems that are not listed inside option group. You can set option to be either windows or linux. Hence the way to distinguish certain platform is solved.
Happy coding!

A: I'd recommed to use postgresql on both machines (linux and windows) it will give you the same developer experience.
For instance, if you want to use smth postgresql specific you should consider this when running that code on windows/sqlite. I'm pretty sure you don't want to have different code base for windows and linux.
Anyway,
take a look at this question
Multiple database.yml but one application


text:
Q: PHP null value returned by function is interpreted as $this Probably I'm a bit tired and I'm missing something but this, so far, is the strangest issue I have ever had with PHP and I'll try to explain it in the best way I can.
In the class Compiler\Bids I have a compileData function:
namespace Compiler;

class Bids extends CompilerItem
{
    protected $service;

    public function compileData()
    {
        foreach($bids as $bid)
        {
            $buyerGroup = $this->service->serviceProperty->whereEqual('id', 'idgoeshere');
            if($buyerGroup || $buyerGroup === null)
            {
                echo 'BuyerGroup class: '.get_class($buyerGroup).'<br>';
            }
        }
    }
}

As you can see in the previous class, in the compileData function I'm calling the whereEqual function which is set on an abstract class extended by the BuyerGroup class.
This is the whereEqual function set on the parent abstract class extended by BuyerGroup:
public function whereEqual($field, $value)
{
    foreach($this->{$this->className()} as $model)
    {
         // I'm skipping some logic here but basically the model
         // matching the conditions is returned...
         return Model;
    }

    // ... otherwise the conditions are not met and null is returned instead.
    return null;
}

Here's what's happening: the code runs and the echo statement in the compileData function is executed producing the following output:
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: Compiler\Bids
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: Compiler\Bids
BuyerGroup class: BuyerGroup
BuyerGroup class: Compiler\Bids

As you can see, when the conditions are not met in the whereEqual function null is returned but that is interpreted like $this in the compileData function.
If I modify the whereEqual function to just return; when the conditions are not met then the output is the following:
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup
BuyerGroup class: BuyerGroup

Which is correct.
Why is PHP behaving in this way? Am I missing something?.

A: The get_class() function returns the name of the current class (when called from within a class) when called without arguments in that context (which is equivalent to a null argument), thus explaining the behavior you're seeing.
http://php.net/manual/en/function.get-class.php


text:
Q: Convert String to double when comma is used I have a UITextfield and it is being populated by data from database. The value is formatted in a way that the fractional part is separated by comma. So, the Structure is something like 1,250.50
I save the data in a string and when I try to use the doubleValue method to convert the string to a double or floating number. I am getting 1. Here is my code.
NSString *price = self.priceField.text; //here price = 1,250.50
double priceInDouble = [price doubleValue];

Here I get 1 instead of 1250.50.
I guess, the issue is the comma, but I can't get rid of that comma as it is coming from the database. Can anyone please help me to convert this string format to double or float.

A: You can use number formatter like this;
NSString * price = @"1,250.50";
NSNumberFormatter * numberFormatter = [NSNumberFormatter new];

[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGroupingSeparator:@","];
[numberFormatter setDecimalSeparator:@"."];

NSNumber * number = [numberFormatter numberFromString:price];

double priceInDouble = [number doubleValue];

A: The solution on this really is to remove the commas. Although you are originally getting those commas from the database, you can just remove them before conversion. Add it as an additional step in between getting the data from the DB and converting it to a double:
NSString *price = self.priceField.text;  //price is @"1,250.50"
NSString *priceWithoutCommas = [price stringByReplacingOccurrencesOfString:@"," withString:@""];  //price is @"1250.50"
double priceInDouble = [priceWithoutCommas doubleValue]; //price is 1250.50

A: Swift 5
let price = priceField.text //price is @"1,250.50"
let priceWithoutCommas = price.replacingOccurrences(of: ",", with: "") //price is @"1250.50"
let priceInDouble = Double(priceWithoutCommas) ?? 0.0 //price is 1250.