text:
Q: How can we open the Maps app for ios 6 within the app interface I am using the following code  for Map turn by turn navigation for iOS 6,
Class mapItemClass = [MKMapItem class];
    if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
    {
        // Create an MKMapItem to pass to the Maps app
        CLLocationCoordinate2D coordinate =
        CLLocationCoordinate2DMake(16.775, -3.009);
        MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate
                                                       addressDictionary:nil];
        MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
        [mapItem setName:@"My Place"];
        // Pass the map item to the Maps app
        [mapItem openInMapsWithLaunchOptions:nil];

    }

It's redirecting me onto the Maps app so ,What i need,i need to open up this within my app interface so as user can remain in the app and not quit the app interface.
Please suggest some ideas to control this.

A: MKMapKit does not support navigation in MKMapView, you will need to send the user to map.app.
Your only option is to build the navigation your self if you really want to turn by turn navigation with in your app.

A: As rckoenes said, you have to implement this yourself if you don't want to launch an external app.
If you plan to do a simple version of turn-by-turn navigation, you can get the relevant data via the Google Maps Directions API:
https://developers.google.com/maps/documentation/directions/
From the JSON (or xml) response you get the driving instructions and location data for every step and waypoint. Also a string under the tag "overview_polyline" is provided here. You can draw the route directly on the map by using this string as GMSPath if your're working with the Google Maps IOS SDK.
The main challenge of a self-written navigation app is constructing a robust logic for tracking the user and providing turn-by-turn instructions accurately, as well as exception handling (e.g. losing signal in tunnels...). But just showing the route and the instructions visually should be relatively easy.


text:
Q: Husky pre-commit not running in Windows I have set anything possible up, followed most guides & documentations,
but yet - the pre-commit hook does not run.
What I did:

*

*npx husky install

*created a file called: ".huskyrc.json"

*Wrote to file:
{
"hooks": {
"pre-commit": "npm run lint && npm run test:no-watch && npm run format && git add ."
}
}
By the way, output of: git config --get core.hooksPath is .husky
Please advice? I do git commit -m "test" and nothing happends. It commits it without the hook being run

redpajama_set_name: RedPajamaStackExchange


text:
Q: Usage of ampersand I am trying to convert a linear program into standard form, but I can't use & to make the equality sign and inequality sign in the same column.
The following gives some error if I try to add more &.
\documentclass[12pt]{article}
\begin{document}
\begin{eqnarray*}
&\min & x_1+3x_2-5x_3+2x_4-7x_5\\
&s.t. & 3x_2-8x_4+x_5=15\\
&&4x_1-8x_2+2x_4+x_5=25\\
&&x_1+8x_2-5x_4-29\geq 0\\
&&-2x_1-5x_2-5x_3+3x_5+27\geq 0\\
&&x_2, x_4 \geq 0\\
&&-x_5\geq 0
\end{eqnarray*}
\end{document}

A: I suppose you want the first solution, but I think the second solution looks nicer:
\documentclass[12pt]{article}
\usepackage{amsmath}

\begin{document}

\begin{align*}
\min {}&x_1+3x_2-5x_3+2x_4-7x_5\\
\textup{ s.t.} & \begin{aligned}[t] 3x_2-8x_4+x_5 & =15\\
4x_1-8x_2+2x_4+x_5 & =25\\
x_1+8x_2-5x_4-29 & \geq 0\\
-2x_1-5x_2-5x_3+3x_5+27 & \geq 0\\
x_2, x_4 & \geq 0\\
-x_5 & \geq 0
\end{aligned}
\end{align*}
\begin{align*}
\min {}&x_1+3x_2-5x_3+2x_4-7x_5\\[1ex] \textup{ s.t.} &\enspace \begin{array}[t] {|l} 3x_2-8x_4+x_5 =15\\
 4x_1-8x_2+2x_4+x_5 =25\\
 x_1+8x_2-5x_4-29 \geq 0\\
 -2x_1-5x_2-5x_3+3x_5+27 \geq 0\\
 x_2, x_4 \geq 0\\
 -x_5 \geq 0
\end{array}
\end{align*}

\end{document}

A: I'm not sure I've understood what you want: see if this can do.

This output is generated by the following code:
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{amsmath}

\begin{document}

Text before the equation.
\begin{alignat*}{1}
    \min\quad & x_1+3x_2-5x_3+2x_4-7x_5 \\
    \text{s.t.}\quad &
        \begin{aligned}[t]
            3x_2-8x_4+x_5 &= 15\\
            4x_1-8x_2+2x_4+x_5 &= 25\\
            x_1+8x_2-5x_4-29 &\geq 0\\
            -2x_1-5x_2-5x_3+3x_5+27 &\geq 0\\
            x_2, x_4 &\geq 0\\
            -x_5 &\geq 0
        \end{aligned}
\end{alignat*}
Text after the equation.

\end{document}

Still another possibility:

The code:
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{amsmath}

\begin{document}

Text before the equation.
\begin{alignat*}{1}
    \min\quad & x_1+3x_2-5x_3+2x_4-7x_5 \\
    \text{s.t.}\quad &
        \left\{
            \begin{aligned}
                3x_2-8x_4+x_5 &= 15\\
                4x_1-8x_2+2x_4+x_5 &= 25\\
                x_1+8x_2-5x_4-29 &\geq 0\\
                -2x_1-5x_2-5x_3+3x_5+27 &\geq 0\\
                x_2, x_4 &\geq 0\\
                -x_5 &\geq 0
            \end{aligned}
        \right.
\end{alignat*}
Text after the equation.

\end{document}

A: The following is a purely aesthetic option using a [t]op-aligned array:

\documentclass{article}

\usepackage{lipsum}
\usepackage{amsmath}

\begin{document}

\lipsum*[1]
\begin{align*}
    \min \quad & x_1 + 3 x_2 - 5 x_3 + 2 x_4 - 7 x_5 \\
    \text{subject to} \quad &
      \renewcommand{\arraystretch}{1.2}
      \setlength{\arraycolsep}{0pt}
      \begin{array}[t]{ *{7}{r} }
               & {}   3 x_2 &            & {} - 8 x_4 & {} +   x_5 & {}  =  {} &  15 \\
         4 x_1 & {} - 8 x_2 &            & {} + 2 x_4 & {} +   x_5 & {}  =  {} &  25 \\
           x_1 & {} + 8 x_2 &            & {} - 5 x_4 &            & {}\geq {} &  29 \\
        -2 x_1 & {} - 5 x_2 & {} - 5 x_3 &            & {} + 3 x_5 & {}\geq {} & -27 \\
                                      \multicolumn{5}{r}{x_2, x_4} & {}\geq {} &   0 \\
                                           \multicolumn{5}{r}{x_5} & {}\leq {} &   0
      \end{array}
\end{align*}
\lipsum[2]

\end{document}


text:
Q: Button is hidden only in iOS6 In my app,I am playing video using MPMoviePlayer.
I am adding a "Skip Ad" (you can see that on the right side of movie player)button on Movie Player.It works fine in iOS5, but when I run my app in iOS6, the button is hidden when Movieplayer becomes fullscreen.
Why this happens..any idea ?
Help me to overcome this..thanks in advance
Here are the code for adding button on MPMovieplayer,and the screen shots
UIButton *skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
skipButton.frame = CGRectMake(264.0,195.0, 67.0, 25.0);
[skipButton setTitle:@"" forState:UIControlStateNormal];
skipButton.backgroundColor = [UIColor clearColor];
[skipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal3 = [UIImage imageNamed:@"skipad.png"];
UIImage *strechableButtonImageNormal3 = [buttonImageNormal3 stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[skipButton setBackgroundImage:strechableButtonImageNormal3 forState:UIControlStateNormal];
UIImage *buttonImagePressed3 = [UIImage imageNamed:@"skipad.png"];
UIImage *strechableButtonImagePressed3 = [buttonImagePressed3 stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[skipButton setBackgroundImage:strechableButtonImagePressed3 forState:UIControlStateHighlighted];
[skipButton addTarget:self action:@selector(skipAction:) forControlEvents:UIControlEventTouchUpInside];

[[[UIApplication sharedApplication] keyWindow] addSubview:skipButton];

in iOS5 -

in iOS6 -

A: bringSubviewToFront should work, just make sure you're using it correctly. The usage is:
[skipButton.superview bringSubviewToFront:skipButton];

If that doesn't work you can change the zPosition like so:
skipButton.layer.zPosition = 1024.0;


text:
Q: ssh into folder Is there a simple unix command to SSH into a folder? I'd like to make my aliases doing that extra step for me! Feeling dense.
Does this just not exist? ssh username@mydomain.com:/var/www/mysite

A: Try running:
ssh -t username@mydomain.com 'cd /var/www/mysite; $SHELL -il'

This will start a batch command with an attached tty.  On the remote side, the batch command will change to the desired directory and start an interactive, login shell (using the shell from /etc/passwd on the remote site).  After that things should work normally.  You might even want to go as far as prepending env - TERM=$TERM DISPLAY=$DISPLAY.

A: On the servers you connect to, you can add cd /var/www/mysite to the ~username/ssh/rc file .  This would run on all ssh connections but not on normal login sessions.


text:
Q: How to resolve this new bug/change in behaviour in PHP 8.x in regards to NumberFormatter? I thought I was going crazy before I went out of my way to restore PHP 7.4.13 to try it to make sure. It has changed in PHP 8.x!
Code:
$a = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 8);
$a->setSymbol(NumberFormatter::CURRENCY_SYMBOL, ''); // It's empty because I want it "minimal" for a table.
var_dump($a->formatCurrency(0.0043, 'BTC'));

Output in PHP 7.4.13:
string(6) "0.0043"

Output in PHP 8.0.1:
string(11) "BTC 0.0043"

Conclusion:
Something has changed.
Question:
How to make PHP 8.0.1 behave like it used to?
Clarification:
That is, to make the money sum outputted in a "minimal" manner, with just the number.
Prediction 1:
Somebody might respond something like: "Just output the number manually for these cases!"
To this, I respond: It has to be the number formatter in currency mode. There are wild differences between locales/languages in how money sums are to be formatted. I need to use this and tell it to forgo the symbol.
Prediction 2:
Somebody might respond something like: "Just str_replace/preg_replace out the symbol! Easy!"
To this, I respond: Not all locales/languages use the same format. It's a whole science of numerous different formats, impossible to account for with a simple string replacement.
I want to do this right, which is what I thought I had. Until just now, when PHP 8 has decided to change this around. I'm not sure if it's a bug or what.
Research:
I cannot find any mention whatsoever of PHP 8 here: https://www.php.net/manual/en/numberformatter.formatcurrency.php


text:
Q: How do I install pillow in Ubuntu 16.04 LTS? I went to This site for installing Pillow since the original PIL is a discontinued project and so now not so good to use. But, in the table support for Ubuntu 16.04 LTS is unmentioned. It appears neither in the 4.2.x installation guide, or in the 3.0.0 installation guide.
Further, just installing pillow is said to be not enough. There are some dependencies that should be installed first which is also unmentioned for Ubuntu 16.04 LTS. Would the installation steps for Pillow for python 3 given for 14.04 LTS be OK for Ubuntu 16.04 LTS?
If not, How do I install pillow in 16.04 LTS for Python 3.6? (There is support for Python 2.)

A: Ubuntu 18.04 and Python 3
This will interest users past Ubuntu 16.04 LTS: install_pillow.sh
#!/bin/bash

apt update
apt install python3-pip -y
apt install libjpeg8-dev zlib1g-dev libtiff-dev libfreetype6 libfreetype6-dev libwebp-dev libopenjp2-7-dev libopenjp2-7-dev -y

pip3 install pillow --global-option="build_ext" --global-option="--enable-zlib" --global-option="--enable-jpeg" --global-option="--enable-tiff" --global-option="--enable-freetype" --global-option="--enable-webp" --global-option="--enable-webpmux" --global-option="--enable-jpeg2000"

This also addresses some of the "dependencies" which I believe OP was referring to:

*

*Many of Pillow's features require external libraries

A: According to Wikipedia Pillow is packaged as python-pil and python3-pil in Ubuntu 13.04 and later.
To install the Python Imaging Library in Ubuntu 16.04 and later (and also in Ubuntu 14.04), open the terminal and type:
sudo apt install python-pil # for python 2.X

and/or...
sudo apt install python3-pil # for python 3.X including python3.6

And if the imageTk import doesn't work, just do this:
sudo apt install python3-pil.imagetk

A: $sudo easy_install pip==20.3.4
$sudo apt-get build-dep pillow
$sudo pip2 install pillow

Successfully installed pillow-6.2.2

This solution was tested on:
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.7 LTS
Release:    16.04
Codename:   xenial

It was run on 32bit Chromenotebook :)


text:
Q: ServerVariables("REMOTE_HOST") returns different response on different web servers We are using ServerVariables("REMOTE_HOST") to identify the workstation accessing a classic ASP page (internal company workstations, not scanning public users) as I cannot assume that an IP address will always apply to the same workstation.
I find that the REMOTE_HOST value returned to a Win7 IIS server includes the domain name after the host name, but a VM server 2008 instance of IIS does not include the domain name.
I would like to be able to program for a consistent value and not have to mess around trying to match values with/without a predefined domain name string on the end.
Does anybody know if this is determined by configuration on IIS or the server O/S?


text:
Q: Angular Material and materialize css together I was using angular material but it does not have the full angular material css classes . So I tried adding materialize css to index.html but now I am getting 2 css styles one from angular materialize theme and other from the materialize css which I added to index.html
Is there any way by which I can add add materialize css without breaking a angular-material theme


text:
Q: Three dimensional Height and distance problem of trigonometry Due to limitation of characters in the title section the original problem is quoted here
A man finds that at a point due south of a tower the angle of elevation of the tower is 60 degrees. He then walks due west 10√6 metres on a horizontal plane and finds that the angle of elevation of the tower at that point is 30 degrees. Then the original distance of the man from the tower,in metres , is?
My attempt(See the picture )

A: Consider the tower to be PM with base M and height $x$  .And you first walk to A and then  horizontally  $10\sqrt6 $ m to B
now Triangles $\triangle PMA \triangle PMB  $ and $\triangle MBA $ are right angle triangles , with $\angle PAM = 60^\circ$ and $\angle PBM = 30^\circ$
in $\triangle PMA $
$cot(60^\circ) =  \frac{AM}{x} \implies AM = \frac{x}{\sqrt3}$
in $\triangle PMB $
$\cot(30^\circ) = \frac{MB}{x}\implies MB = \sqrt3 .x$
Therfore in $\triangle MBA$
$MB = \sqrt3.x, AB =10\sqrt6$ and $MA = \frac{x}{\sqrt3}$
Apply Pythagoras theorem ,
$(MA)^2+(BA)^2=(MB)^2$
$\frac{x^2}{3} +600=3x^2$
$x^2(\frac13-3)=-600$
$x^2 =\frac{(600 )(3)}{8}$
$x= 15 $m
hence the original distance $AM =\frac{15}{\sqrt3}$m

A: Hint: the sides of a $60^o{-}30^o{-}90^o$ triangle are in the ratios $1:\frac{1}{2}:\frac{\sqrt{3}}{2}$ (this follows from the fact that $\sin\,30^o = \frac{1}{2}$). There are two such triangles in your problem each with the tower as one leg and one of the two observation points as the opposite vertex. Compare the ratios of the edges and conclude that the move west tripled the distance from the tower. Hence looking at the plan view of the situation you see a right-angled triangle with one leg and the hypotenuse in the ration $1:3$. Applying Pythagoras, the edges of the plan view triangle are in the ratio $1 : 2\sqrt{2} : 3$ and you are given the length of the longer of the two legs, from which you can calculate the length of the shorter leg, which is what you are asked for.
See https://en.wikipedia.org/wiki/Trigonometric_functions for lots of information and figures involving $\sin$, $\cos$ etc.

A: Let $h$ be the height of the tower, let $x$ be the distance you are trying to find, and let $y$ be the distance to the base of the tower in the second position.
The horizontal triangle is right-angled therefore $$y^2=x^2+(10\sqrt{6})^2$$
You also have, in the first position, $$h=x\tan60\implies x=\frac{h}{\sqrt{3}}$$
In the second position, $$h=y\tan30\implies y=h\sqrt{3}$$
Now substitute these expressions into the first equation and find $h$ then you can find $x$.


text:
Q: Why is my server getting connections from its own IP? The most numerous connecting IP is my server's own IP.
It's Debian 10, Nginx, Mysql machine serving a single Wordpress and phpBB site. It's a virtual machine on Google's Cloud.
I'm obviously not too hot with this stuff, but good enough to build up a machine and have it serve the site.
$ sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr

returns
5122 104.198.149.xxx
4268 157.90.209.xxx
3752 93.158.90.xxx
1982 68.68.32.xxx
[...]
~ ~ ~
104.198.149.xxx is my server.
Output of
grep 104.198.149.xxx /var/log/nginx/access.log

162.158.252.xxx - - [11/Nov/2021:00:00:25 -0700] "GET /forums/ HTTP/1.1" 200 12459 "https://104.198.149.xxx/forums" "Mozilla/5.0 (compatible;Cloudflare-Healthchecks/1.0;+https://www.cloudflare.com/; healthcheck-id: bfa5d32ce9a5eaf8)"

172.69.32.xxx - - [11/Nov/2021:00:00:59 -0700] "GET /forums/ HTTP/1.1" 200 12471 "https://104.198.149.xxx/forums" "Mozilla/5.0 (compatible;Cloudflare-Healthchecks/1.0;+https://www.cloudflare.com/; healthcheck-id: bfa5d32ce9a5eaf8)"

104.198.149.xxx - - [11/Nov/2021:00:01:00 -0700] "POST /wp/wp-cron.php?doing_wp_cron=1636614060.6961169242858886718750 HTTP/1.1" 200 31 "https://www.example.com/wp/wp-cron.php?doing_wp_cron=1636614060.6961169242858886718750" "WordPress/5.8.2; https://www.matthewsvolvosite.com"

108.162.220.xxx - - [11/Nov/2021:00:01:03 -0700] "GET /forums/ HTTP/1.1" 200 12465 "https://104.198.149.xxx/forums" "Mozilla/5.0 (compatible;Cloudflare-Healthchecks/1.0;+https://www.cloudflare.com/; healthcheck-id: bfa5d32ce9a5eaf8)"

104.198.149.xxx - - [11/Nov/2021:00:01:07 -0700] "GET /forums/download/file.php?id=30434&mode=view HTTP/1.0" 200 641193 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:07 -0700] "GET /forums/download/file.php?id=30435&mode=view HTTP/1.0" 200 933139 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:10 -0700] "GET /forums/download/file.php?id=55475&mode=view HTTP/1.0" 200 1015069 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:10 -0700] "GET /forums/download/file.php?id=55476&mode=view HTTP/1.0" 200 933149 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:10 -0700] "GET /forums/download/file.php?id=55477&mode=view HTTP/1.0" 200 916765 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:17 -0700] "GET /forums/download/file.php?id=30691&mode=view HTTP/1.0" 200 121584 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:18 -0700] "GET /forums/download/file.php?id=30692&mode=view HTTP/1.0" 200 137607 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:18 -0700] "GET /forums/download/file.php?id=30693&mode=view HTTP/1.0" 200 133153 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:24 -0700] "GET /forums/download/file.php?id=33292&mode=view HTTP/1.0" 200 949523 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:25 -0700] "GET /forums/download/file.php?id=33293&mode=view HTTP/1.0" 200 1047827 "-" "-"

104.198.149.xxx - - [11/Nov/2021:00:01:25 -0700] "GET /forums/download/file.php?id=33294&mode=view HTTP/1.0" 200 916755 "-" "-"

A: The reason you will see connections from your servers IP is usually due to using a reverse proxy. Over the years there has been changes to how this can be resolved.
The original way was using the X-Forwarded-For header. Then there was a standardised way of doing it with RFC 7239 which is called Forwarded. Here is an article from NGINX explaining this.
The final option is to use the proxy protocol. HERE is the official documentation around this from NGINX.
To understand this all more in depth here is a fantastic post explaining it all.

A: This is an educated guess.
You have a WordPress plugin that somehow views files uploaded to the phpBB forum you have. Internally it downloads the file from phpBB, and then presents it via some WordPress -side page.


text:
Q: SQL greater than IN I'm using Postgres 9.4 and want to do something like this:
movement_id|counter|standardized_output
---------------------------------------
1          |      3|                 10
1          |      3|                 12
1          |      5|                 10
2          |      4|                  5

I have the following query:
SELECT movement_id, counter, MAX(standardized_output) AS standardized_output
FROM "outputs"
WHERE "outputs"."user_id" = 1 AND "outputs"."movement_id" IN (1,2) AND (counter in (1,3,5))
GROUP BY movement_id, counter

Which gives me:
movement_id|counter|standardized_output
---------------------------------------
1          |      3|                 12
1          |      5|                 10

But what I want to find is what the MAX(standardized_output) is for counter >= (1,3,5). So the following result:
movement_id|counter|standardized_output
---------------------------------------
1          |      1|                 12 (MAX value where movement_id is 1 and counter is >=1)
1          |      3|                 12 (MAX value where movement_id is 1 and counter is >=3)
1          |      5|                 10 (MAX value where movement_id is 1 and counter is >=5)
2          |      1|                  5 (MAX value where movement_id is 2 and counter is >=1)
2          |      3|                  5 (MAX value where movement_id is 2 and counter is >=3)
2          |      5|               null (MAX value where movement_id is 2 and counter is >=5)

(small edit: movement_id is IN, not =)

A: You could probably put a CASE statement on the counter field?
CASE WHEN counter >= 5 THEN 5
WHEN counter >=3 THEN 3
WHEN counter >=1 THEN 1
ELSE 0 END

Then add it to the select and the group by clause.
SELECT movement_id,
    (CASE WHEN counter >= 5 THEN 5
      WHEN counter >=3 THEN 3
      WHEN counter >=1 THEN 1
      ELSE 0 END) as new_counter,
    MAX(standardized_output) AS standardized_output
FROM "outputs"
WHERE "outputs"."user_id" = 1 AND "outputs"."movement_id" = 1
GROUP BY movement_id,
    (CASE WHEN counter >= 5 THEN 5
      WHEN counter >=3 THEN 3
      WHEN counter >=1 THEN 1
      ELSE 0 END)

A: I was about to post something in the lines to what Kez did (making use of the case statement), but a bit different.
I am not sure of which conditions you need in the case here, I don't know if counter >= (1, 3, 5) could be translated to counter >= 5 ? In the sample below I am considering that counter >= (1, 3, 5) means that counter >= 5 (question is how to understand the semicolons here - if they are to be translated into ANDs or ORs - I went with ANDs, so counter >= (1,3,5) is the same as counter >= 5, but if the semicolons are to be understood as ORs it means counter values of 2 or 4 are of your interest)
In any case, for whatever conditions you do NOT want to consider your standardized output in the max function, include them in the case condition and make the counter for them return zero, so it does not affect your max (or a negative number, if needed)
SELECT
       movement_id,
       counter,
       MAX(CASE WHEN COUNTER < 1 THEN 0 ELSE COUNTER END ) AS standardized_output
  FROM outputs
 WHERE
   outputs.user_id = 1
   AND outputs.movement_id = 1
   AND counter in (1, 3, 5)
 GROUP BY movement_id, counter

A: You can use a CASE statement with MAX() function like
SELECT movement_id,
counter,
MAX(CASE WHEN movement_id = 1 and counter >= 1 THEN standardized_output
WHEN movement_id = 1 and counter >= 3 THEN standardized_output
WHEN movement_id = 1 and counter >= 5 THEN standardized_output
WHEN movement_id = 2 and counter >= 1 THEN standardized_output
WHEN movement_id = 2 and counter >= 3 THEN standardized_output
WHEN movement_id = 2 and counter >= 5 THEN standardized_output
ELSE NULL END) AS standardized_output
FROM "outputs"
WHERE "outputs"."user_id" = 1
AND "outputs"."movement_id" = 1
AND (counter in (1,3,5))
GROUP BY movement_id, counter;

A: Unless I'm completely misunderstanding what you're trying to do, you should be able to handle this with a join:
SELECT o.movement_id,
    o.counter_id,
    MAX(oagg.standardized_output) AS standardized_output
FROM outputs o
LEFT JOIN outputs oagg
    ON  o.user_id       =  oagg.user_id
    AND o.other_primary =  oagg.other_primary
    AND o.movement_id   =  oagg.movement_id
    AND o.counter_id    <= oagg.counter_id
WHERE o.user_id = 1;

If you're explicitly wanting counter_ids that don't exist, you'll need to create them somehow.  I'd probably join with a tally table, but I'm not sure I fully understand what you're looking for.

A: As you want results for rows that don't have any values you first need to create a set consisting of the rows that should be there, in this case the cartesian product of {movement_id} X {1,3,5}. To do this we can use a cross join and the table value constructor, and then it's just a case of using a left join and a subquery to get the max values.
I'm sure this query can be improved, but it should work.
select
    all_values.movement_id,
    all_values.num,
    (
       select max(standardized_output)
       from outputs
       where counter >= all_values.num
         and movement_id = all_values.movement_id
    ) as standardized_output
from (
  select movement_id, t.num
  from outputs
  cross join (values (1), (3), (5)) as t(num)
  where "movement_id" in (1 ,2)
-- and "outputs"."user_id" = 1 --this was missing in your sample so I left it commented out.
) all_values
left join outputs o on all_values.movement_id = o.movement_id
                   and (counter in (all_values.num))
group by all_values.movement_id, all_values.num
order by all_values.movement_id, all_values.num;

Sample SQL Fiddle
Given your sample data the result from the query above is:
| movement_id | num | standardized_output |
|-------------|-----|---------------------|
|           1 |   1 |                  12 |
|           1 |   3 |                  12 |
|           1 |   5 |                  10 |
|           2 |   1 |                   5 |
|           2 |   3 |                   5 |
|           2 |   5 |              (null) |

Edit: the same result can be achieved using this query:
select
  o1.movement_id,
  t.num as counter,
  max(o2.standardized_output) as standardized_output
from outputs o1 cross join (values (1), (3), (5)) as t(num)
left join outputs o2 on o1.movement_id = o2.movement_id and t.num <= o2.counter
where o1.movement_id in (1,2)
group by o1.movement_id, t.num
order by o1.movement_id, t.num;

Sample fiddle


text:
Q: linux-source-3.5.0 for ubuntu 12.04.2? I have Ubuntu 12.04.2 with kernel 3.5.0 and need to recompile some modules, but i`m getting hard to find the correct sources. apt-get only has sources for 3.2.0? Where i can get the correct sources for the installed kernel 3.5.0??

A: Looks like a major breakage to me. There are meta-packages that don't work at all, some link to the old 3.2.0 kernel.
For example, doing apt-get source linux-image-$(uname -r) will fail, as it tries to use linux-lts-quantal instead, and then fails as that package cannot be found. We've been trying around for two hours, before resorting to using their kernel git repository (which involved changing our scriptomatic relying on apt-get source, which we tried to prevent).
It's beyond me how you can "update" a release you call LTS in such a messed up way.
The solution for us right now is to use their kernel git repository, although it is huge and takes ages to clone.
git clone git://kernel.ubuntu.com/ubuntu/ubuntu-precise.git
cd ubuntu-precise
git tag -l Ubuntu-*     # show all tagged versions
git checkout -b temp Ubuntu-lts-3.5.0-28.48     # pick the one matching "uname -r"


text:
Q: запись в куки php При просмотре товара записываю его значение в куки:
setcookie("UserProductsView[]", (int)$this->request->get['product_id'], time()+3600);
но почему-то записывается максимум 2 товара, и когда делаю: print_r($_COOKIE['UserProductsView']);
то выдает вот это:
Array ( [product] => 50 [0] => 50 )

A: Не уверен, что запись setcookie("UserProductsView[]") валидна, так как в документации такого варианта нет, есть только с явным указанием ключа.
Попробуйте формировать массив на уровне кода + сериализовать. Примерный код:
$usersProducts = unserialize(($_COOKIE['UserProductsView'] ?? NULL));
if(!is_array($usersProducts))$usersProducts = [];
$usersProducts[] = (int)$this->request->get['product_id'];
setcookie("UserProductsView", serialize($usersProducts), time()+3600,"/");


text:
Q: scikit-neuralnetwork on Raspberry Pi We are trying to run scikit-neuralnetwork[1] in a raspberry pi zero running Raspbian.
We have searched in apt-get and couldn't find an available version. We have tried compiling it in the raspberry and (after a couple of hours) it failed.
What's the best way to install it in the raspberry? Is it available in any repository that we might be missing? Or is there a way to compile it for arm in some other computer (ie. PC running ubuntu) faster than on the pi zero itself?
Thanks,
Jorge
[1] http://scikit-neuralnetwork.readthedocs.io/en/latest/


text:
Q: Basic question about expectation Let $(A,\mathcal{A},P)$ be a probability space, $f$ real, bounded, nonnegative, measurable function and $X,Y$ real random variables so that $E(Y)=0$.
Then $E(f(X)Y)=0$.
My arguments
$$0=-C\int YdP\leq\int -f(X)YdP\leq\int f(X)YdP\leq C\int YdP=0,$$
for some constant $C>0$.
*I just realize that the second inequlity does not need to hold.
Can you give me feedbacks about it?
Thank you in advance!


text:
Q: RxJava how to filter sub tree and then return the tree If I have an Observable<JsonOrderList>.
JsonOrderList defined below :
public class JsonOrderList {

  public List<Order> data;
  public int currentCount;
  public int currentPage;
  public int pageCount;

}

API defined below :
Observable<JsonOrderList> orderApi.orderList(before, after, limit, state)

I want to filter/process List<Order> data and then return JsonOrderList
orderApi.orderList(before, after, limit, state){
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
//How to process List<Order> data

.subscribe(new Action1<JsonOrderList>() {
    @Override
    public void call(JsonOrderList rpOrderList) {
        pushSuccessData(ID_GET_ORDER_LIST, rpOrderList);
    }
}, new Action1<Throwable>() {
    @Override
    public void call(Throwable throwable) {
        pushErrorData(ID_GET_ORDER_LIST, throwable);
    }
}));

EDIT:
doOnNext(new Action1<JsonOrderList>() {
        @Override
        public void call(JsonOrderList jsonOrderList) {
            //can i use rxjava operator replace loop
            for(Order order : jsonOrderList.data){
                order.setBuyer(goodsApi.getBuyer(order.getBuyerId));
            }
        }
})

goodsApi.getBuyer(id) request server to get BuyerInfo

Could I use rxjava operator replace loop??

A: Use .map operator:
orderApi.orderList(before, after, limit, state)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .map(new Func1<List<Order>, JsonOrderList>() {
            @Override
            public JsonOrderList call(List<Order> orders) {
                JsonOrderList jsonOrderList = new JsonOrderList();
                // ... do some stuff to fill jsonOrderList
                return jsonOrderList;
            }
        })
        .subscribe(new Action1<JsonOrderList>() {
            @Override
            public void call(JsonOrderList rpOrderList) {
                pushSuccessData(ID_GET_ORDER_LIST, rpOrderList);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                pushErrorData(ID_GET_ORDER_LIST, throwable);
            }
        });

EDIT:
After further explanation of the problem, I suggest you use the following code.
I would advice you NOT to use .filter(...) operator as it will change your stream (you would get a different object in subscribe).
orderApi.orderList(before, after, limit, state)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(new Action1<JsonOrderList>() {
            @Override
            public void call(JsonOrderList jsonOrderList) {
                //do something with jsonOrderList.data
            }
        })
        .subscribe(new Action1<JsonOrderList>() {
            @Override
            public void call(JsonOrderList rpOrderList) {
                pushSuccessData(ID_GET_ORDER_LIST, rpOrderList);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                pushErrorData(ID_GET_ORDER_LIST, throwable);
            }
        });


text:
Q: Adding additional Metadata field in AEM-DAM I want to add a custom metadata field in DAM assets, is there any way to add custom metadata apart from overlaying a workflow or writing custom workflow?

A: Metadata profiles is the way to add default properties to assets on upload. Metadata profiles are linked to assets at folder level. You could have different default properties for assets based on folder they are uploaded to. For e.g. attached default tags based on folder
Checkout this link for the detailed documentation on how to add metadata profile to a DAM folder
Metadata Profiles


text:
Q: How is it possible use SVM Light inside the C++ code? (Possibly without invoking the executable from C++ code) I have to use the tool SVM Light in my C++ code. I compiled and linked the SVM Light to my code like in http://svmlight.joachims.org/  but now how can I call
./svm_learn -v 0 -x 1  example1/train.dat example1/model

for example from my C++ code instead that from command line?
Namely in the original code with
./svm_learn -v 0 -x 1  example1/train.dat example1/model

i get the svm model. How can I get now the same model from my C++ code?Preferably calling a function from my C++ code rather than calling the executable from command line? (May be that I'm enforced to use system or similar functions to invoke the C object code (the executable) from my c++ code.... Is like this?)
(I'm using C++11 compiler, on Linux)
Thanks in advance

A: I found a possible solution from myself. I post here for anyone was interested. I modified svm_learn_main.c, I left here a empty main  alone. I added a new file svm_mylearn.c and svm_mylearn.h . I copied the original svm_learn_main.c in svm_mylearn.c.  I added here in the extern declaration the header svm_mylearn.h. I moved the signature of functions in svm_mylearn.h . I changed the name of the main function in svm_my_exec(int,char* []) with the same code of the main. I modified the makefile so create the object code (the .o) for svm_mylearn.c
Later naming my .cpp file Test.cpp i have to do:
make all
g++ -c Test.cpp
g++ Test.o svm_learn.o svm_common.o svm_hideo.o svm_mylearn.o    (linking)
./a.out

Furthemore, I was forgetting that in Test.cpp I have to add a extern declaration like this:
extern "C"
{
# include "svm_common.h"
# include "svm_learn.h"
# include "svm_mylearn.h"
}

and call the svm_my_exec function in this way(for example) :
const char *comando[]={"./svm_learn" ,"-v", "1", "-x", "1", "-o",
"2.0", "-k" ,"100", "example1/train.dat", "example1/model"};
svm_my_exec(sizeof(comando)/sizeof(char *),comando );

A: This link http://svmlight.joachims.org/ has a DLL Interface near the bottom of the page under Extensions and Additions.  I'd start there.
Better yet, under the version history, under V6.01 - V6.02 the second sentence says "Updated makefile to add the ability for compiling SVM-light into a shared-object library that gives external code easy access to learning and classification functions."  This library interface should be documented.


text:
Q: Castle Dynamic Proxy not working? I have the following class:
public class MyTest
{
    public void Test()
    {

    }
}

and I created the following interceptor:
public class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
    }
}

and in my code, I do:
        ProxyGenerator g = new ProxyGenerator();

        g.CreateClassProxy<MyTest>(new MyInterceptor());

        MyTest t = new MyTest();
        t.Test();

Shouldn't that hit the Intercept method in the debugger? It is not. Am I missing something?
EDIT: this is specific to Castle DynamicProxy.

A: You have to make public void Test() to be public virtual void Test() so Castle DynamicProxy is allowed to intercept that method.

A dynamic proxy is a way of generating a subclass from a class or
  interface of which is generally a model. That subclass overrides every
  method that it can (make your methods virtual to allow to do it).

For more documents about Castle Dynamic Proxy:
https://richardwilburn.wordpress.com/2009/12/17/using-castles-dynamic-proxy/
http://putridparrot.com/blog/dynamic-proxies-with-castle-dynamicproxy/

A: CreateClassProxy creates so called Inheritance-based proxy. Inheritance-based proxies are created by inheriting a base class. The proxy intercepts calls to virtual members of the class and forwards them to base implementation. Thus only virtual members of the class can be intercepted. In your sample you should mark Test method as virtual. See here.
public class MyTest
{
    public virtual void Test()
    {
        Console.WriteLine("Hi");
    }
}

public class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("Was here");
        invocation.Proceed();
    }
}

void Main()
{
    ProxyGenerator g = new ProxyGenerator();
    var t = g.CreateClassProxy<MyTest>(new MyInterceptor());
    t.Test();
}


text:
Q: Modern solution to WebSocket servers? For my website I wrote a WebSockets server in C# (most preferred language to code in) that uses Fleck and it's approximately 600 lines of code. Everything seems to be working decently (a little unstable at times though. Not sure if it's a problem with my code or Fleck).
However, I want to move this from my computer to an actual domain and I'm not sure if there are any hosting providers that would support .NET console applications like that.
I was thinking that maybe I would have to rewrite it in another language like PHP but I'm slightly unsure about the whole idea. Are there any popular hosting providers that would support what I am looking for? And even if they are, is it such a good idea? I imagine it may be less secure or slower than the typical solution of using Perl, PHP, or Python for servers. (lots of P's)
Lastly, if it was a good idea to rewrite, I'm not sure of which language I would write it in. It's been a while and I'm not sure what everyone still uses. Is PHP still considered to be the most supported and secure for web servers?
Which WebSockets implementation is best suited? It took me a while to find Fleck and there seem to be twice as many PHP derivatives and I'm feeling a bit overwhelmed again. Also, a lot of posts on Stackoverflow about WebSockets are from two years ago when they were not as supported.
Sorry for my naivete and lack of focus in my question but as you can see I'm a bit confused as to what my course of action here should be and I'm looking for some insight. Thanks for reading.

A: Probably the most popular WebSocket server is Socket.IO. It is implemented in Node (Javascript) and has fallbacks to long-polling/AJAX when WebSockets support is not available.
The most well supported implementation of WebSockets is the python pywebsocket project which is used by both Mozilla and Google for developing and testing their client browser implementations. In addition, pywebsocket is designed to easily integrate with Apache allowing you to run your web server and websocket service on the same port(s).
If your application just needs a WebSocket based messaging service and is largely peer-to-peer you might consider using a commercial WebSocket service like Pusher. That could save you from having to host and manage your own server for this.
I would not recommend PHP for WebSocket servers. Until recently there wasn't a PHP implementation that supported both the older and newer WebSocket protocol variation. The older is still used by current iOS devices and the newer IETF 6455 version of the protocol is used by Chrome, Firefox, IE10 and the Flash based WebSocket polyfill web-socket-js.
Also, you ask if PHP is still considered to be the most supported and secure for web servers. Certainly, PHP has always had great documentation and examples and very wide deployment so you could argue it's well supported. However, PHP falls near the bottom of the list in terms of security. I would certainly not rewrite your application from scratch in PHP.
If you are partial to C like languages, you might consider libwebsockets which you could use to build a C or C++ WebSocket server. Andy Green developed and maintains libwebsockets and participated in the IETF working group that developed the standard.
Ruby is another language/community that has seen a lot of uptake of WebSockets (perhaps second behind Node). The most popular websocket library for Ruby is em-weboskcet.

A: you can try node.js, is "new" and it look good.
Regards


text:
Q: Asynchronous RPC in c++ (using visual studio) I am trying to program an Asynchronous RPC in c++ (using visual studio). As per the documentation provided by the MSDN (Docs), I need to modify the ".ACF" file. But I am not able to find that file. I need suggestions on how to find that file.

A: If it doesn't exist, create it.
Note that this is truly ancient technology.


text:
Q: Octobercms select with ajax not working as expected I have the following code on a page:
PHP code section
function onSelecaoGE(){
$this['temp'] = post('selecaoge');
}

and on page html

    <select class="form-control"
            name="selecaoge"
            data-request="onSelecaoGE"
            data-request-update="_foe_rec_nivel: '#selnivel'"
            id="escolhage">
        <option disabled selected> -- Escolha um Grande Edifício --</option>
        {% for ge in ge_all %}
        {% if ge.era_id == 0 %}
        {% set conta = ge.recompensa_ge_conta2[0].count %}
        {% else %}
        {% set conta = ge.recompensa_ge_conta[0].count %}
        {% endif %}
        <option value="{{ ge.id }}">{{ ge.nome }} ({{ conta }})</option>
        {% endfor %}
    </select>

{% partial "_foe_rec_nivel" %}

and on partial just have
{{ temp }}

also i have jquery loaded and {% framework extras%} in layout file.
Everything looks good as per documentation and some examples i found.
But when i make any selection on the select it starts the ajax call, but it never ends.
After several changes i can't figure out what is wrong. Any help will be appreciated.
TIA
JL

A: With the help of "alxy" on Slack we found that the problem is related with the version of jquery loaded. I'm loading jquery-3.3.1.slim.min.js that appears to not have complete ajax support. I changed to load the regular version jquery-3.3.1.min.js and is working perfectly.
JL


text:
Q: Insert html pages into wordpress I have an html site with a page of info for each county in the US. I want to convert this into a new wordpress site. I can do this one by one but my issue comes when I have mass changes to affiliate code or common text. I would have to got to each page and manually change it. but with over 3000 pages it would be way to time consuming. I dont want to use Iframes but would like to know if there is a way to call the html pages into the wordpress page that makes sense seo wise.
I am open to creating a page for each county or have one page with text or buttons on it with each county listed and when clicked will insert the info below. I know alot about static html coding but am new to php.

A: If you dont want Iframes, I think there only remain two options. I don't know if they will work in WordPress though.
1. PHP Include
With the very simple PHP include() statement, you can include the old html files in your new website. If you have a HTML-file for example, name your file yourname.php and add this in the position you want your old page to appear:
<?php include(path_to_old_page/name.html); ?>

This will include the full old page, but the file needs to be on the same server.
2. AJAX
With JavaScript you can perform XHTTP-requests to load files from the server. This is easiest when using jQuery. Here you can use the $(selector).load(path_to_old_page/name.html) statement. This will load the file in the HTML elements to which the selector applies.
(The selector works the same as CSS selectors, see the w3schools page for more)
This will also include the full old page, when it is on the same server

A: You can have your static pages in WordPress as well. Like if you want to create a new county named "example" you can create new WordPress page named "example" by entering title " example" .... now come to content. Just copy page content (only "example" county related html code from your static website) and place that code inside newly created WordPress "example" page. Make sure you add this html content inside 'text' tab in editor. Your page will be created with all your existing data ... now you can view this page and can use this page's URL where ever you want.


text:
Q: Drag scroll is not working in fullcalendar In my application i have used fullcalendar for event scheduling. I can change event to same month by dragging it (which is in month view). But i want the event can be changed to next month while drag the event so that i have used

dragScroll: true,

But its not working. Anyone please help me for this issue.
Below is my fullcalender coding
$('#calendar').fullCalendar({
        selectable: true,
        dragScroll: true,
        selectConstraint: {
            start: $.fullCalendar.moment().subtract(1, 'days'),
            end: $.fullCalendar.moment().startOf('month').add(1, 'month')
        },
        defaultView: 'month',
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay,basicDay,basicWeek'
        },
        timeFormat: 'H(:mm)t',
        buttonText: {
            basicDay: 'List Day',
            basicWeek: 'List Week'
        },
        allDayDefault: false,
        editable: true,

        droppable: true, // this allows things to be dropped onto the calendar
        eventLimit: true, // allow "more" link when too many events
        events: data,
        eventRender: function (event, element) {
            element.attr('href', 'javascript:void(0);');
            element.click(function() {
                $("#startTime").html(moment(event.start).format('h:mm A'));
                $("#endTime").html(moment(event.end).format('h:mm A'));
                $("#eventInfo").html(event.title);
                $("#employee").html(event.employee);
                $("#date").html(moment(event.start).format('MMM Do'));
                $("#price").html(event.price);
                $("#duration").html(event.duration);
                $("#services").html(event.services);
                $("#eventLink").attr('href', 'appointments');
                //$("#services").dialog({ modal: true, title: event.title, width:350});
                $("#eventContent").modal();
            });
        },

        eventConstraint: {
            start: moment().format('YYYY-MM-DD'),
            end: '2100-01-01' // hard coded goodness unfortunately

            //start: moment('YYYY-MM-DD'),
            // start: '2000-01-01',
            // end: '2100-01-01' // hard coded goodness unfortunately
        },

        eventDrop: function(event, delta, revertFunc,date) {
                swal({
                    title: "Are you sure?",
                    text: "To reschedule the "+ event.title +" appointment to "+event.start.format('MMM Do h:mm A'),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Reschedule",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function(isConfirm){

                    if (isConfirm) {
                        $.ajax({
                            type: "GET",
                            url: 'reschedule',
                            data: {id:event.id,date:event.start.format()},
                            success: function (result) {
                                if(result==1)
                                {
                                    swal("Success!", "The appointment was rescheduled.", "success");
                                }
                                else
                                {
                                    swal("Failure!", "Failed to reschedule.", "warning");
                                    revertFunc();
                                }
                            }
                        });
                    } else {
                        swal("Cancelled", "Appointment reschedule calcelled", "error");
                        revertFunc();
                    }
                });
        }

    });


text:
Q: Is there an example WebSockets for Qt? Is there an example WebSockets for Qt?

A: You can also have a look at QtWebSockets. QtWebSockets can be used both for client and server applications, and passes the Autobahn test suite.

A: QWebView inside of QtWebKit supports the use of Web Sockets (from the HTML5 standard). I have used them multiple times without any issue.

A: I have created an example. Here is the code:
inspection_server.hpp:
#ifndef __INSPECTION_SERVER_HPP__
#define __INSPECTION_SERVER_HPP__

#include <QWebSocketServer>
#include <QWebSocket>
#include <QObject>
#include <iostream>
#include <memory>

class InspectionServer;

typedef std::shared_ptr<QWebSocketServer> QWebSocketServerPtr;
typedef std::shared_ptr<QWebSocket> QWebSocketPtr;
typedef std::shared_ptr<InspectionServer> InspectionServerPtr;

class InspectionServer: public QObject
{
    Q_OBJECT

    QWebSocketServerPtr websocketServer;
    QList<QWebSocketPtr> clients;

public:
    InspectionServer(uint16_t port);

signals:
    void closed();

private slots:
    void onNewConnection();
    void processTextMessage(const QString& message);
    void socketDisconnected();

};

#endif

inspection_server.cpp:
#include "inspection_server.hpp"

#include <QDebug>

InspectionServer::InspectionServer(uint16_t port)
    : websocketServer(new QWebSocketServer(QStringLiteral("Inspection server"), QWebSocketServer::NonSecureMode))
{
    if(this->websocketServer->listen(QHostAddress::Any, port))
    {
        QObject::connect(websocketServer.get(), SIGNAL(newConnection()), this, SLOT(onNewConnection()));
    }
    else
    {
        throw std::runtime_error("InspectionServer: failed to listen");
    }
}

void InspectionServer::onNewConnection()
{
    qInfo() << "InspectionServer::onNewConnection";
    QWebSocketPtr socket(this->websocketServer->nextPendingConnection());

    QObject::connect(socket.get(), SIGNAL(textMessageReceived(const QString&)), this, SLOT(processTextMessage(const QString&)));
    QObject::connect(socket.get(), SIGNAL(disconnected()), this, SLOT(socketDisconnected()));

    this->clients.append(socket);
}

void InspectionServer::processTextMessage(const QString& message)
{
    qInfo() << "InspectionServer::processTextMessage: " << message;
}

void InspectionServer::socketDisconnected()
{
    qInfo() << "InspectionServer::socketDisconnected";
}

main.cpp:
#include "inspection_server.hpp"

#include <QCoreApplication>

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    InspectionServer server(1234);

    return app.exec();
}

And here is how to test that in your Web browser:
<html>
<body>
<button onClick="initWebSocket();">Connect</button>
<br>
<input type="text" id="messageInput">
<button onClick="sendMessage();">Send message</button>
</body>
</html>

<script type="text/javascript">

var websocket = null;

function initWebSocket()
{
    websocket = new WebSocket("ws://localhost:1234");
}

function sendMessage()
{
    websocket.send(document.getElementById("messageInput").value);
}

</script>

This is a good link for reference:
http://code.qt.io/cgit/qt/qtwebsockets.git/tree/examples/websockets/echoserver


text:
Q: How to use Regex to tell if there are two non-alphanumeric charters together in string? This is the requirement:

If field contains characters other than alphanumeric characters,
  space, single quote, or dash without beginning or ending with a space,
  or two non-alphanumeric charters together, system displays error
  message

This is what I done.
regx = /^(?![ '-])[a-zA-Z '-]{1,30}([^ '-])$/;

It does all the job but not "two non-alphanumeric charters together". If I want to examine if there are two non-alphanumeric charters together in the string (eg. First Name), how to write that?
And I don't know much about what I write means actually, comments are welcomed, I just look online and write that regx...
And I don't know why if I remove {1,30}, the compiler will report error.
By non-alphanumeric charters, I mean [ '-]

A: I assume you want to match strings with length from 1 to 30.
I suggest a regex (demo) based on look-aheads to meet the requirements:
^(?![ ])(?!.*[ ]$)(?!.*[ '-]{2})[a-zA-Z0-9 '-]{1,30}$

See demo
Here, the 2 non-alphanumeric characters that cannot appear consecutively are [ '-]. The (?![ ])  look-ahead makes sure the string does not start with a space (replace [ ] with \s if any whitespace is meant, by the way). The (?!.*[ ]$) lookahead makes sure the string (without newline symbols - else, replace .* with [\s\S]*) does not end with a space. The (?!.*[ '-]{2}) lookahead makes sure there are no consecutive non-word symbols , ', or - in the string (again, use [\s\S]* instead of .* if you have newline symbols in the string).
You can also use an expression with just 2 look-aheads to minimize overhead:
^(?!.*[ '-]{2})(?![ ])[a-zA-Z0-9 '-]{0,29}[a-zA-Z0-9]$

Another demo
If you could allow minimum 2 characters, you could use a more optimal ^(?!.*[ '-]{2})[a-zA-Z0-9][a-zA-Z0-9 '-]*[a-zA-Z0-9]$, but I guess it is not the case.
Note in your regex, you have & instead of $ (end of string/line) and you did not allow digits (alphanumeric symbols usually include letters and digits).

A:
If I want to examine if there are two non-alphanumeric charters
  together in the string (eg. First Name), how to write that?

/[^a-zA-Z\d]{2}/g

I'll leave it to you to determine how to incorporate that into your regex. Check out this site for help building Regular expressions. It's saved me a bunch of times :)

A: This expression should work: /\W{2}|[^\w' -]|^ (.*) $/

var reg = /\W{2}|[^\w' -]|^ (.*) $/;
var strings = ['My own text', 'This. Is a bad string', 'This  is also a bad string', ' This is also a bad string '];
strings.forEach(function(string){
  document.getElementById('results').innerHTML += 'String: "' + string + '" is valid? ' + (string.match(reg) === null) + '\n';
  });

A: ^(?!.*\W\W)(?![ '-])[a-zA-Z '-]{1,30}([^ '-])$

  ^^^^^^^^^

Just add a lookahead to make sure non-alphanumeric charters \W doesnt come 2 times.
See demo.
https://regex101.com/r/sS2dM8/40


text:
Q: nginx passenger is showing 404 not found error for every urls in my rails app in development I am preparing my development environment with nginx and passenger but seems like only root of the app is loading the home page every other url are showing a nginx 404 not found error. but the app works perfect with webrick.I am running on ubuntu 16.04.
    # Here is the routes.rb file of the app

    Pinteresting::Application.routes.draw do
    root 'pins#index'
       resources :pins

      devise_for :users
      # root "pages#home"

      get 'about' => 'pages#about'

    end

root path is working anyway with nignx but because of assets not loading home page seems like cluttered
    # AND THE NGINX CONF FILE

       gzip on;
       gzip_disable "msie6";

        include /etc/nginx/passenger.conf;

# NGINX DEFAULT FILE[enter image description here][1]
# passenger configuration
    server {

passenger configuration are done using the doc, and has specified app environment, app path etc..
          server_name localhost;
          passenger_enabled on;
          passenger_app_env development;
          root /home/aju/pinteresting/public;
        listen 80 default_server;
        listen [::]:80 default_server;


text:
Q: Drush add aliases for ubuntu drush? I natively installed ubuntu with the package manager through apt-get install drush .
After a find i discovered that they're natively installed at /usr/share/drush.
My question is the following: is it possible to add aliases with the ubuntu brewed drush? If so where? in the /usr/share/drush/ folder?
The ubuntu version seems to be missing the example folder as well as some other files: ini, topic files.

A: For instructions on creating aliases, see drush topic docs-aliases, which can also be found at http://drupalcode.org/project/drush.git/blob/refs/heads/7.x-4.x:/examples/example.aliases.drushrc.php
The best place to put global aliases would be in /etc/drush; user-specific aliases should go in $HOME/.drush.

A: You can create a folder in your drush folder called 'aliases'. In that folder you can create a file aliases.drushrc.php (or project specific -> myproject.aliases.drushrc.php) and i guess it should work then. so first try /usr/share/drush/aliases/aliases.drushrc.php, and see if that works.
If you put the drush location in your path, you can place the alias file in a drush folder in your home directory
there's more linux specific info in the readme.txt
http://drupalcode.org/project/drush.git/blob/refs/heads/7.x-4.x:/README.txt


text:
Q: How do I create a UITableView with UIImages? - Cocoa/Objective-C I'm trying to create an application for the iPhone with a table of categories. If I select a category it will display a UIImage. However, I've been looking into it and I'm not sure exactly what to do. Can anyone lend a hand?

A: It sounds like the easiest solution would be to use a UITableView in a Navigation Based Application.
(Apple has samples on how to use this)
Load the table with your categories.
When the user selects a category, push a new View from a Nib file onto the navigation stack.
This will allow you to use the same Nib for all categories and you just pass the image to load to the class, which handles loading it into a UIImageView.
For example:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:NO];

imageCatView *catView = [[imageCatView alloc] initWithNibName: @"imageCatView" bundle: nil];
catView.categoryID = [[[categories objectAtIndex: _selectedRow] objectForKey:@"CatID"] intValue];

[[self navigationController] pushViewController:catView animated:YES];
[catView release];
}


text:
Q: How to remove older unneeded devices? So this is related to a prior question I posted - how to remove 4.3 simulators. I stupidly installed the iOS 5.0 Simulator, and now the technique offered in my last post does not work. When you remove the 5.0sdk, then restart Xcode, it forces you to install the legacy simulators or quit.
I even deleted Xcode 4.4 and re-installed it to no avail (it must store my unfortunate choice deep in the preferences file).
The reason I want to get rid of it is that the Scheme popup now has 5 options in it instead of 3, making it a real pain to test a Universal App.
EDIT:
When I cd to ~/Library/Caches/com.apple.dt.Xcode/Downloads I see:
$ ls

Xcode.SDK.iPhoneSimulator.5.0-5.0.0.1.dmg
Xcode.SDK.iPhoneSimulator.5.0-5.0.1.1.dmg
eded78df8bfabaf6560841d10cf8e53766f74f28.dvtdownloadableindex
f7133e82a08bdb4ebf724f16beed2bbac2a265cf.dvtdownloadableindex

$

I have both Xcode 4.4 and 4.5DP3 on my machine, so assume that the first two files are one per Xcode release - in any case I moved both to /tmp.
The earlier suggestion had been to remove:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk

A: In addition to removing the iPhoneSimulator5.0.sdk folder, delete the corresponding .dmg file in ~/Library/Caches/com.apple.dt.Xcode/Downloads. Then Xcode will not force you to reinstall it anymore.

A: Do the following in terminal:
cd ~/Library/Caches/com.apple.dt.Xcode/Downloads
ls

You'll see the files now; then run the bash command to remove them.


text:
Q: automorphism of a commutative monoid let $M$ be a finitely generated, commutative monoid.
What are in general the relations between $\mathrm{Aut}(M)$ and $\mathrm{Aut}(M^{\rm gp})$?
When is it true that $\mathrm{Aut}(M)$ determines $\mathrm{Aut}(M^{\rm gp})$?

A: I don't think there's much to say in general. For example, if every element of $M$ is idempotent ($m^2 = m$) then $M^{gp}$ is trivial. To generate examples of this you can take any finite lattice with join as the monoid operation.
Of course since $M^{gp}$ is a functor every automorphism $M \to M$ induces an automorphism $M^{gp} \to M^{gp}$. But my point is this need not be injective.


text:
Q: Add survey reply in document library on each uploaded document I would like to link the survey reply item to the document library so that the user can provide survey response to the document which uploaded in this library. Is it possible to do so?
Thanks a lot
Kim

A: If you would like a link directly to survey question instead of requiring clicking to respond, please use NewForm.aspx and see if it meet your requirement:
http://sp/sites/sitename/lists/survey1/newform.aspx


text:
Q: Calling component from service - angular I already tried a few approaches but none of them seems to work so far.
I am trying to call a function in one component on click event in another component. I don't have any errors in the console.
First component
constructor(public projectService: ProjectOverviewService) {  }
delete(event) {
    this.projectService.onFirstComponentButtonClick();
}

Service
invokeFirstComponentFunction = new EventEmitter();
subsVar: Subscription;

onFirstComponentButtonClick() {
    this.invokeFirstComponentFunction.emit();
}

Second component
constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
if (this.projectOverviewService.subsVar == undefined) {
      this.projectOverviewService.subsVar = this.projectOverviewService.
        invokeFirstComponentFunction.subscribe((name: string) => {
          console.log("I am here!!!");
        });
    }
}

I am not hitting console.log ever.

A: You can use RXJS import Subject
First component
constructor(public projectService: ProjectOverviewService) {  }

delete(event) {
  this.projectService.invokeFirstComponentFunction.next();
}

Service
 public invokeFirstComponentFunction = new Subject();

Second Component
subsVar: Subscription;

constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
      this.subsVar = this.projectOverviewService.invokeFirstComponentFunction.
       .subscribe(() => {
          console.log("I am here!!!");
        });
}
ngOnDestroy(){
this.subsVar && this.subsVar.unsbscribe()
}

A: If you are planning to establish communication between 2 components using a service, then event-emitter is not the approach. This is what I would do:
First component
constructor(public projectService: ProjectOverviewService) {  }
delete(event) {
    this.projectService.onFirstComponentButtonClick("Name");
}

Service
invokeFirstComponentFunction = new Subject<string>();
subs$ = this.invokeFirstComponentFunction.asObservable();

onFirstComponentButtonClick(name: string) {
    this.invokeFirstComponentFunction.next(name);
}

Second component
constructor(public projectOverviewService: ProjectOverviewService){}

ngOnInit(): void {
  this.projectOverviewService.subs$.subscribe((name: string) => {
    console.log("I am here!!!");
  });
}


text:
Q: SQL Query - wrong results I have a problem with a SQL query:
SELECT *
FROM
   Tickets T
INNER JOIN
   Facts F on T.Ticket_Nummer = F.Ticket_Nummer
INNER JOIN
   Dates D on D.DatetimeKey = F.Datum
WHERE
   F.Datum in
        (SELECT
           max(x.Datum)
         FROM
           Facts x
         WHERE x.Ticket_Nummer = F.Ticket_Nummer
         and
             X.Status in ('HD50', 'SD50', 'HD53', 'HD55', 'SD55', 'HD56')
         and
             cast(F.Datum as date) between '09.05.2022' and '13.05.2022'
         and
             D.Process_Code not like 'Analyse')
ORDER BY D.Bereich,T.Gruppe, Datum

So it should show me all results with 'HD50', 'SD50', 'HD53', 'HD55', 'SD55', 'HD56' in the specified timeline ...
I get the above results but I also get some results with HD05, HD16 what I think is not possible because I said only results with HD/SD >= 50.
What may be the problem here?
SAMPLE DATA:

No
Status
Cast(…as Date)
Date original

14539
HD05
12.05.2022
12.05.2022 13:11

14539
SD55
12.05.2022
12.05.2022 13:11

I was expecting results with 'HD50', 'SD50', 'HD53', 'HD55', 'SD55', 'HD56' not HD05.


text:
Q: Which version of Python is preferable for Windows 7 (32-Bit)? I am currently using Python version 3.3.0.
But it shows me syntax error in else, elif though I did everything correct.

A: If it's giving you a syntax error then I would suggest you haven't done everything correctly. That's my answer by the way, the rest below is just extra help.
It's incredibly unlikely you found a bug in Python's if statement when it's been tested by millions of people on the planet, millions of times a day. Far more likely is that there's a problem in your use of it, which has been tested by, well, just you :-)
Post your code, that's the only way to be sure. It's possible that you're relying on Python2 code in your Python3 environment but I don't think the if construct changed so it's doubtful.
It's possible your indentation is incorrect. It's possible you may be missing a :.
There are a hundred things you could be doing wrong but, unfortunately, we can't tell without the code.
By the way, the best version of Python to use is the latest stable release for your OS of choice, in either the Python2 or Python3 stream (depending on whether you need the older one). That's (at the time of this answer) 2.7.4 and 3.3.1.


text:
Q: htaccess can't redirect if directory has uppercase characters I'm trying to perform a redirect for one of my directory's that has a mixture of uppercase and lower case characters. However the uppercase characters are causing issues.
For example attempting the following redirect works correctly:
RewriteRule ^mydirectory\/(.*)$$ "http\:\/\/www\.google\.com\/" [R=301,L]

However the directory i'm trying to redirect is has a mixture of uppercase and lowercase i.e
RewriteRule ^MyDirectory\/(.*)$$ "http\:\/\/www\.google\.com\/" [R=301,L]

However, this does not redirect and is simply ignore.
Any suggestion on how to fix this?
Thanks

A: Try using NC (ignore case) flag:
RewriteRule ^mydirectory/(.*)$ http://www.google.com/ [R=301,L,NC]


text:
Q: How to match and import data from other sheet by using apps script? I just want to match and import the matching data from sheet1 to sheet2 with correct cell.
for example, this is sheet1

and this is sheet2

How to insert the matching data automatically by using Apps Script??
Cuz, I want to update it auto continually.
This is the result that I wanna get.

A: I believe your goal is as follows.

*

*You want to convert from upper 2 images in your question to the bottom image in your question.

*You want to achieve this using Google Apps Script.

In this case, how about the following sample script?
Sample script:
In this sample script, the values of columns "A" to "C" are the key for searching values. For example, when you want to use the key of column "A", please modify o[a + b + c] to o[a].
function myFunction() {
  // 1. Retrieve sheets.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [sheet1, sheet2] = ["Sheet1", "Sheet2"].map(s => ss.getSheetByName(s));

  // 2. Retrieve values from Sheet1 and create an object for searching values.
  const obj = sheet1.getRange("A2:D" + sheet1.getLastRow()).getValues().reduce((o, [a,b,c,d]) => (o[a + b + c] = d, o), {});

  // 3. Retrieve values from Sheet2 and create an array for putting to the column "D" of Sheet2.
  const values = sheet2.getRange("A2:C" + sheet2.getLastRow()).getValues().map(([a,b,c]) => [obj[a + b + c] || ""]);

  // 4. Put the array to the column "D" of Sheet2.
  sheet2.getRange(2, 4, values.length, 1).setValues(values);
}

*

*When this script is run, the values are retrieved from Sheet1 and put to the values to the column "D" of Sheet2 by searching the values from Sheet1 and Sheet2. By this, your goal can be achieved.

References:

*

*reduce()

*map()


text:
Q: Matlab error with vertcat and cell arrays I'm trying to concatenate two arrays as follows:
z={ '35' {'test'} ; '45' {'test'}}
z={z{:} ;{'55' {'test'}}}

I would expect the result to be
 {35 {'test'}
 45  {'test'}
 55 {'test'}}

but instead I get:
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
What am I forgetting? Thanks.

A: The error is caused by z{:} which lists all content of z 'into' a N by 1 vector and when you try to collect all the elements with the outer {} it throws the error due to mismatching dimensions.
You might be using too many { } and you can concatenate cell arrays with [ ]:
z = { '35' 'test'
     '45'  'test'};
z = [z; {'55' 'test'}]

The command window will display:
z =
    '35'    'test'
    '45'    'test'
    '55'    'test'


text:
Q: Processing certain URL in apache when configured with Websphere application server, plugin-cfg.xml I have configured Drupal apache server with WAS using the mod_was plugin. Now certain URI have to be processed by the drupal server and these URI come under the URI configured in plugin-cfg.xml
EX:
 this the URI inside plugin-cfg.xml:
 <Uri AffinityCookie="JSESSIONID" AffinityURLIdentifier="jsessionid" Name="/foobar/*"/>

 But the URIs /foobar/new and /foobar/[ID] , ID being a variable have to be served by drupal.

I saw this URL Blocking url on web server (websphere), but they only talk about block certain URI but not serving those blocked URI in apache.

A: The answer should be here: WebSphere reverse proxy plugin - skipping domains
SetEnvIf Host ^dimsim\.domain\.com$ skipwas=1 (I was looking for a similar question.)


text:
Q: How to print the array column value using the if statement in Java? I am having a problem with my Static Point of Sale (POS) System in Java.
I'm using the 2D-Array with the help of a for-loop and if-statement but I've got a problem of displaying the Array Column on the receipt of my POS.
POS Output1
public static void productdata(){

    for(int row = 0; row < Product.length; row++) {
    for (int col = 0; col < 4 ; col++){
        Product[row][col] = "";

        }
    }
    for(int row = 0; row < POS.length; row++){
    for (int col = 0; col < 3 ; col++){
    if(col == 0){
        POS[row][col] = "0";
    } else{
        POS[row][col] = "";
            }
        }
    }
    // Product [x] [y] x = row; y = col //
    Product [0] [0] = "PP1"; // PRODUCT CODE //
    Product [0] [1] = "\t9350"; // PRODUCT PRICE //
    Product [0] [2] = "FVP PowerPack Guyabano\t\t\t\t"; // PRODUCT NAME //
    Product [0] [3] = "12"; // PRODUCT QUANTITY //

In the attached image I've showed the Array that I used for my Product Data. The problem there is, the receipt of the Product Purchased was showing the Product Code (PP1) [--see the small red box--] instead of the Product Name (FVP PowerPack Guyabano) [--see the violet box--], with that I don't know how to change it or display the Product Name...
POS Output2
System.out.print("\n============================================================================");
    System.out.print("\n POS SYSTEM");
    System.out.print("\n FIRST VITA PLUS");
    System.out.print("\n 2/F Suntree Tower,");
    System.out.print("\n No. 13 Meralco Avenue,");
    System.out.print("\n Ortigas Center, Pasig City");
    System.out.print("\n 1605 Philippines\n");

    if (TryAgain == 'n' || TryAgain == 'N'){
        System.out.print("\n \t\t\t\t****PRODUCT PURCHASED****\n\n");
        stop4:
    for(int row = 0; row < POS.length; row++){
    for(int col = 0; col < 3; col++){

            if((POS[row][col].equals("0")) || (POS[row][col].equals(""))){
                break stop4;
            } else{
        System.out.print(POS[row][col] + "\t");
            }
        }
            System.out.println();
            Double totalprice = Double.parseDouble(POS[row][2]);
            TOTAL = totalprice + TOTAL;
    }
    System.out.print("\n============================================================================");

...and on this part I've showed the Output and the method of how I created the receipt of the customer (with product code (that should be a product name), the product price and quantity was purchased).

A: It seems you are trying to print two dimensional array data.
You can try this :
for (int row = 0; row < rowLength; row++)
 {
   for (int col = 0; col < colLength; col++)
    {
       System.out.print(arrayName[row][col]+" ");
     }
    System.out.print("\n");
 }


text:
Q: Long running task in ApiController (using WebAPI, self-hosted OWIN) I would like to run a long running task (say 4-5 minutes) in an ApiController within a self-hosted OWIN environment. However I would like to  send a response back after starting that task (as soon as I started the long running task) without waiting it to finish. This long running task has nothing to do with the HTTP and sequentially runs some methods which may take very long.
I have a look at this blog post and decided to give a try to QueueBackgroundWorkItem. However, I am not sure if it is possible to use this method in a self-hosted (console application) owin environment or necessary to use it. In a self-hosted console application I think, the application itself manage the requests and all request run within the same AppDomain (applications default AppDomain, we do not create any new appDomain), so may be I can just run a long running task in a fire-and-forget fashion, without doing anything special?
Anyway, when I use QueueBackgroundWorkItem, I always get the error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Operation is not valid due to the current state of the object.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(Func`2 workItem) at BenchMarkService.SmokeTestController.IsItWorking() in C:\Devel\Code\Projects\BenchMarkService\BenchMarkService\SmokeTestController.cs:line 18 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
</Error>

Also I found this question on SO and to be honest it seems a little bit confusing to me as the only way to achieve that is IRegisteredObject or not?
I am just trying to run a long running task in a self-hosted application and I appreciate any ideas about that. Almost all of the resources, questions I found are based on asp .net and I am not sure where to start.

A: Self-hosted OWIN applications are typically regular console applications, therefore you can spin off some long running task in the same way you would do that in a console application, e.g.:

*

*Task.Run

*ThreadPool.QueueUserWorkItem

*new Thread(...).Start()
In IIS hosted ASP.NET applications it is not advisable to use such methods because application pools are commonly recycled, hence your application gets shut down and restarted pretty often. In such a case your background task would be aborted. In order to prevent (or postpone) that, APIs like QueueBackgroundWorkItem have been introduced.
However because you are self-hosted and do not run in IIS, you can just use the APIs listed above.

A: This is pretty much what Hangfire was created to do (https://www.hangfire.io/).
Sounds like a fire-and-forget job.
var jobId = BackgroundJob.Enqueue(
    () => Console.WriteLine("Fire-and-forget!"));

A: You need to provide a mechanism for adding a task to something outside of the controller.
Typically in the apps I use owin for the actual host is IIS so I figured out I could use "Hosted Processes" but in a console app it's likely to be a lot simpler.
The most obvious approach that comes to mind is to pass in some sort of global object / singleton that your DI framework knows about can be sure is always the same object as a "container for the job"
public class FooController : ApiController
{
    ITaskRunner runner;

    public FooController(ITaskRunner runner) { this.runner = runner; }

   Public IActionResult DoStuff() {
       runner.AddTask(() => { Stuff(); });
       return Ok();
   }
}

The task runner could do the job by being little more than a simple wrapper around Task.Run() if you wanted, but having that hook there and passed in means that after the request is "handled" and the controller gets cleaned up, the task is still considered "in scope" so the application can continue to process it instead of attempting to clean it up.

A: I wanted to comment on the answer of War, but answering my own question seem better for a long explanation. This may not be a complete answer, sorry.
War's solution is a possible way to implement this feature and I did something similar to that. Basically, create a task store and whenever a new task is fired or completed add/remove this task to the task store. However, I would like to mention some issues, because I believe its not as simple as like that.
1) I agree with using a dependency injection framework in order to implement a singleton pattern. I used 'SingleInstance()' method of Autofac to do that. However, as you can see in many answers and resources on the Internet, singleton pattern is not popular pattern although sometimes seems to be indispensable.
2) Your repository should be thread-safe, so adding/removing tasks from that task store should be thread-safe. You can use a concurrent data structure like 'ConcurrentDictionary' instead of locking (which is a expensive operation in terms of cpu time).
3) You may consider using CancellationToken for your async. operations. It is highly possible that your application may be shutdown by user or an exception which can be handled may occur during the runtime. Long running tasks may be a bottleneck for graceful shutdown/restart operations especially if you have sensitive data to lose and use different resources like files which may be closed properly in that case. Although async. methods may not be cancelled immediately whenever you try to cancel the task by using the token, it is still worth giving a try to CancellationToken or similar mechanisms in order to stop/cancel your long running tasks whenever necessary.
4) Just adding a new task to your data store is not enough, also you have remove the task whwnever it completed whether successfully or not. I tried firing an event which signals the completion of task and then I removed this task from the task store. However, I am not happy with that because firing an event and then binding a method to this event to receive completion of a task is more or less like a continuation in TPL. It's like reinventing the wheel and also events may cause sneaky problems in a multithreaded environment.
Hope this helps. I prefer sharing some experiences instead of posting code, because I do not believe that I have an ultimate solution to this problem. War's response gives a rough idea, but you need to consider many issues before doing that in a production ready system.
Edit: For long running tasks you may have a look at this thread. It's a good practice to manage the thread pool.

A: PushStreamContent may be the answer you're looking for. PushStreamContent helps to stream the response. Looking at the following blog post to get some idea about the implementation.
STREAMING DATA WITH ASP .NET WEB API AND PUSHCONTENTSTREAM


text:
Q: Using a CNN encoder with TimeDistributed LSTM layers for jigsaw puzzle solution I'm trying to build an encoder-decoder model that solves jigsaw puzzles of images.
basically, I have an image that is divided into t*t equal sized crops that I want to reconstruct.
I'm using tensorflow backed keras API.
My encoder is a pretrained CNN model with its last layer removed. So for a single crop its output is a feature vector with 256 features.
Now I want to build the LSTM decoder that should return the predicted positions of the t*t crops within the image.
The idea is that the decoder will predict the position of each crop with the position predictions of all the other crops in mind.
I'm not sure if I'm using the TimeDistributed and LSTM layers the way I need to...
I'm asking because the full model doesn't produce any improved performance over just using the CNN part (with its final layer), so I must be doing something wrong..
My model:
input_shape =  [t**2, image_size, image_size, num_channels]
model = Sequential()
# CNN model:
model.add(TimeDistributed(CNN, input_shape=input_shape))
model.add(Bidirectional(LSTM(128, dropout=0.3, recurrent_dropout=0.05, return_sequences=True)))
model.add(Bidirectional(LSTM(128, dropout=0.3, recurrent_dropout=0.05, return_sequences=True)))
model.add(Dense(128, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(t**2, activation='softmax'))
output_shape = [t**2, t**2] # t**2 crops, each with a one-hot encoded position

Is this the right way to do what I intended?


text:
Q: How to reverse path for custom user when testing Django Rest Framework I'm building a Django 3 app using a Custom User. I'm trying to test the Custom User, but I can't get the url using reverse. I'm using Django Rest Framework. I'm using Django Rest Auth.
myapp.api.urls.py:
app_name = 'myApp'

from django.urls import include, path, re_path

urlpatterns = [
...
path('users/', include('users.urls'), name='UsersURLS'),
]

myapp.users.urls.py
from django.urls import include, path

from . import api
app_name = 'users' # namespace for reverse
urlpatterns = [
    path('', api.UserListView.as_view(), name='UsersPath'),
]

myapp.users.api.py
class UserListView(generics.ListCreateAPIView):
    queryset = models.CustomUser.objects.all()
    serializer_class = serializers.UserSerializer
    authentication_classes = (TokenAuthentication,)

And in test_users_api.py:
from users.api import UserListView
user_detail_url = reverse('myApp:UsersURLS-list')

...

def test_user_detail(self):
    self.client.force_authenticate(user=self.user)
    response = self.client.post(user_detail_url, {'pk': self.user.id }, format='json')

Whatever I try for the reverse, I get an error that is it not a valid view or function name. So far I have tried:
reverse('myApp:UsersURLS-list')
reverse('users:UsersPath-list')
reverse(UserListView)
reverse('UsersPath')
I'd be grateful for any idea what I'm doing wrong, and how to get the reverse URL. I have it working for the rest of my endpoints which use router, but I can't see what's needed for my Custom User, which I set up following a tutorial and it works fine otherwise.

A: I found an answer in the rest-auth source code, at venv36/lib/python3.6/site-packages/rest_auth/tests/test_api.py, and mixins.py in the same folder. I don't know why my attempts to reverse fail, but this works:
user_detail_url = reverse('rest_user_details')

All names for reverse can be found in the mixins.py file.


text:
Q: Playing music in background when app closed in Ionic/ngCordova I have made auto play sound effect, when the current time will be matched with some fixed time. The following code is working well for match time and playing sound when the app is open. But if I turn off my application then the application is not working.
I'm trying to play the sound when my application are closed. However, If my application is closed, Its check the app functionality & It'll be work like as when then app is open.
I'm also study about this issue and get $cordovaNativeAudio, but I'm not sure how can I apply with my functionality.
<-- Ionic code -->
<ion-toggle ng-repeat="item in settingsList track by $index"
                ng-model="item.checked"
                ng-checked="item.checked">
               {{ item.text }}---{{item.date}}---{{item.time}}

    </ion-toggle>

<-- In controller -->
$scope.settingsList = [
                { text: "Wireless", checked: true, date: '2016-06-04', time: '11:12 pm' },
                { text: "Wireless", checked: true, date: '2016-06-04', time: '11:13 pm' },
                { text: "Wireless", checked: true, date: '2016-06-04', time: '11:14 pm' },
                { text: "Wireless", checked: true, date: '2016-06-04', time: '11:15 pm' }
];

var media;

$scope.init1 = function(){
   var sound1 = mediaService.getPathMedia() + 'assets/sound.mp3';
   media = $cordovaMedia.newMedia(sound1);
   media.play();
}
$scope.init2 = function(){
  media.stop();
  media.release();
}

A: Try this plugin to run the service in background https://github.com/katzer/cordova-plugin-background-mode
and try this plugin to play native audio https://github.com/floatinghotpot/cordova-plugin-nativeaudio


text:
Q: CSS3/HTML5 Responsive images I want to use different sized images depending on the webpage size.
For example, my images has two different sizes:

The data-small image has a width of 100px.
@media (max-width:600px) {
    img[data-small] {
        content: attr(data-small, url); <-- not working
       /*width:10px;*/ <-- this would work
    }
}

I testet it on Firefox 37.0.1, Chrome 42.0.2311.90 m and IE 11
If I resize the browser to a very small width (< 600px), the image is still the same.

A: content attr is used in :before and :after selectror. How ever you can use media query.

and the css will be
@media (max-width:600px) {
    .small_image{ display:block }
    .big_image{ display:none }
}

@media (min-width:601px) {
    .small_image{ display:none }
    .big_image{ display:block }
}

A: Image tags work using the src attribute. In order to change the image, you need to change the src attribute, which you cannot do with CSS.
content: attr(data-small, url); does not change the src attribute. You're setting the content of the element to the data-small attribute, which does nothing on an img tag. As I mentioned, you cannot change the src attribute with CSS.
I'd advise using srcset. This will gracefully degrade in old browsers, and will work well in new browsers.

Otherwise, user1936285's solution also works well.

A: Maybe you can use  CSS background-image: url("image.png") instead of
Something like this:
@media (max-width:600px) {
    .container{ background-image: url("imagebig.png") }
}

@media (min-width:601px) {
     .container{ background-image: url("imagesmall.png") }
}

WebPlatform CSS backgrounds

A: Use:
content: url(attr(data-small));


text:
Q: Current selected value in DataGridView using C# I'm trying to get the current selected value from a DataGridView
MessageBox.Show(""+dataGridView1.SelectedCells.ToString()+"")

but it never shows the selected value.
It shows

System.Windows.Forms.DataGridViewSelectedCellCollection

A: you should do it this way
MessageBox.Show(dataGrdiView1.SelectedCells[0].Value.ToString());

try to access Value or Text of a single cell, and not the entire collection
you can also iterate through the entire SelectedCells collection
 string text;
 foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
 {
     //MessageBox.Show(cell.Value.ToString());
     text +=cell.Value.ToString();
 }
 MessageBox.Show(text);

A: string message = string.Empty;
foreach (var c in _dataGridView1.SelectedCells)
    message += " " + c.Value.ToString();
MessageBox.Show(message);

A: If it always a single cell selected you could just use. dataGridView1.SelectedCells[0].tostring. The reason you are getting the class name ia because you are getting back a collection of selected cells as their couls be more than one cell selected at a time.


text:
Q: Checking SPF in PHP An IT service provider have to write our SPF changes on Internet, I just mail my instructions.
I created a program in PHP to check in one click all my domains, to see if it is correct (sometimes a bad copy-paste include bad characters)
I tried to test the SPF with
if (strpos(strtolower($spf), 'v=spf')

but this doesn't check bad characters
I tried with a preg_match but it's not working
A spf record can contain only these characters
[a-z] [0-9] . ? - ~ (space) and must start with v=spf
all other characters must echo "Invalid syntax"
Example:
$spfdata='v=spf1 mx 1.2.3.4 ~all';

if (preg_match('/(v=spf)([a-z0-9-~?.])/i', $spfdata)){
    echo "SPF seems to be ok";
} else {
    echo "Invalid syntax";
}

This doesn't work it always says "ok" even if I type a bad character.

A: You may use
'/^v=spf[a-z0-9~? .-]+$/i'

Or, if you want to allow any kind of whitespace:
'/^v=spf[a-z0-9~?\s.-]+$/i'

PHP code:
$spfdata='v=spf1 mx 1.2.3.4 ~all';

if (preg_match('/^v=spf[a-z0-9~?\s.-]+$/i', $spfdata)){
    echo "SPF seems to be ok";
} else {
    echo "Invalid syntax";
}

See the PHP demo
The regex matches

*

*^ - start of string

*v=spf - a literral text

*[a-z0-9~?\s.-]+ - 1+ ASCII letters, digits, ~, ?, whitespaces, . or -

*$ - end of string.

A: I don't know why but when I delete the first block (v=spf) the regex seems to be good
I tried a lot of differents things and finally this works (I invert the logic with the ^)
So the regex says "if your are NOT in the bracket expression you are ok"
$spfdata='v=spf1 mx 1.2.3.4 ~all';

if (preg_match('#[^a-z0-9 :\+=.\-~\?]#', $spfdata)){
    echo "Invalid syntax";
} else {
    echo "SPF seems to be ok";
}


text:
Q: Subtract in moment js not exactly I have function calculate last month when send start day of month like this

last_date_from = moment(date_from).subtract(1, 'months');
last_date_to = moment(last_date_from).endOf("month").startOf("day");

When i send object moment start day
Moment {_isAMomentObject: true, _isUTC: true, _pf: Object, _locale: Locale, _d: Tue Mar 01 2016 00:00:00 GMT+0700 (ICT)…}
_d: Tue Mar 01 2016 00:00:00 GMT+0700 (ICT)
_isAMomentObject: true
_isUTC: true
_isValid: true
_locale: Locale
_offset: 0
_pf: Object
__proto__: Moment

Funtion will return 2 result last_date_from and last_date_to:
d: Sat Jan 30 2016 00:00:00 GMT+0700 (ICT)
_isAMomentObject: true
_isUTC: true
_isValid: true
_locale: Locale
_offset: 0
_pf: Object
__proto__: Moment

Last_date_to is:
_d: Sun Jan 31 2016 07:00:00 GMT+0700 (ICT)
__proto__: Date
_isAMomentObject: true
_isUTC: true
_isValid: true
_locale: Locale
_offset: 0
_pf: Object
__proto__: Moment

Expected result last_date_from is 1/2/2016 why result is 30/1/2016. I know this year. February have 29 days. How to fix this ? Sorry my English is not good


text:
Q: How to print an interval of a 2D Array So i have my 2D array initialized with data from a file and i was wondering if it's possible to System.out.print just this interval.
public static void OptionUn (String[][] TableauLectureFichier) {

    Scanner rDates = new Scanner(System.in);

    System.out.println("ENTER YOUR INTERVAL HERE IN THE FOLLOWING ORDER DAY1 MONTH1 DAY2 MONTH2");

    String Intervale = rDates.nextLine();

    String[] TabChaine = Intervale.split(" ");
    int[] tIntervale = new int[4];

    for (int i = 0; i <TabChaine.length; i++) {
        tIntervale[i] = Integer.parseInt(TabChaine[i]);
    }

    int j1 = tIntervale[0],
        j2 = tIntervale[2],
        m1 = tIntervale[1],
        m2 = tIntervale[3];
}

My array basicly contains Temperature, each row is a temperature of a certain date, its all ordered for january 1st to december 31st. And my question is how can I only System.out.print the temperatures between the dates the USER enters. For exemple between January 1st and February first (1 1 1 2).
So the array looks as follow. It's an irregular 2D array
String[][] TableauLectureFichier = new String[12][];
        TableauLectureFichier[1] = new String[31];
        TableauLectureFichier[2] = new String[LeapYear];
        TableauLectureFichier[3] = new String[31];
        TableauLectureFichier[4] = new String[30];
        TableauLectureFichier[5] = new String[31];
        TableauLectureFichier[6] = new String[30];
        TableauLectureFichier[7] = new String[31];
        TableauLectureFichier[8] = new String[31];
        TableauLectureFichier[9] = new String[30];
        TableauLectureFichier[10] = new String[31];
        TableauLectureFichier[11] = new String[30];
        TableauLectureFichier[12] = new String[31];

Where LeapYear is a method that calculates if february has 28 or 29 days

A: I think you want to print from the two dimensional array passed to the function, and use the input from the user to print a selected range from the passed array?
Your issue must be, that simply doing two nested loops, will not solve this for you. Instead, you want to increment a calendar from the "start month" and "start day" to the "end month" and "end day".
Update
Ok, since you do not want to use a Calendar for this, you can do this by just iterating through the 2d array with a bit of logic. I will assume the the length of the second dimension of the array will vary depending on what month we are in. Meaning, that the code that supplies the data, will only have one entry for each valid day.
So, if the data is recorded on a leap year, the array dimension for February will simply be of the length 29. (TableauLectureFichier[1].length == 29)
Then you can do it with the following:
public static void OptionUn (String[][] TableauLectureFichier) {

    Scanner rDates = new Scanner(System.in);

    System.out.println("ENTER YOUR INTERVAL HERE IN THE FOLLOWING ORDER DAY1 MONTH1 DAY2 MONTH2");

    String Intervale = rDates.nextLine();

    String[] TabChaine = Intervale.split(" ");
    int[] tIntervale = new int[4];

    for (int i = 0; i <TabChaine.length; i++) {
        tIntervale[i] = Integer.parseInt(TabChaine[i]);
    }

    int j1 = tIntervale[0],
        j2 = tIntervale[2],
        m1 = tIntervale[1],
        m2 = tIntervale[3];

    // Loop through all the months specified, taking care to convert from base 1
    // to base 0
    for (int month = m1 - 1; month < m2; month++) {
        // Assume that we will start at the first day of a month
        int day = 0;

        // However, if the current month is the first, start from the day specified as j1
        // instead, and convert to base 0 so that we can use it to index into the array
        if (month == m1) {
            day = j1 - 1;
        }

        // Assume that we will run till the end of this month, or in this case to the end
        // of the array for the current month
        int endDay = TableauLectureFichier[month].length;

        // If the current month is the last month, only run to specified end day
        if (month == m2) {
            endDay = j2;
        }

        // Now run from the start day to the end day in the current month, paying
        // attention to that endDay is still base 1
        for (; day < endDay; day++) {
            System.out.println(String.format("Month: %d, day: %d, value %s",
                month,
                day,
                TableauLectureFichier[month][day]));
        }

        // At this point we will step into the next month
    }
}

I have not added bounds checking to the month or 'day' variables. So if you are handing this in to anyone - please add bounds checking before you use the variables in the array.

A: public static void OptionUn (String[][] TableauLectureFichier) {
Scanner rDates = new Scanner(System.in);

System.out.println("ENTER YOUR INTERVAL HERE IN THE FOLLOWING ORDER DAY1 MONTH1 DAY2 MONTH2");

String Intervale = rDates.nextLine();

String[] TabChaine = Intervale.split(" ");
int[] tIntervale = new int[4];

for (int i = 0; i <TabChaine.length; i++) {
    tIntervale[i] = Integer.parseInt(TabChaine[i]);
}

int j1 = tIntervale[0],
    j2 = tIntervale[2],
    m1 = tIntervale[1],
    m2 = tIntervale[3];

for(int i=m1+1; i < m2; i++) {
    for(int j=j1+1; j < j2; j++) {
         System.out.printf("Temperature on day %d and month %d: %s", j, i,  TableauLectureFichier[i][j]);
    }
}

}