text:
Q: Proving that $\Phi_{t*}[\mathbb{Y},\mathbb{Z}]=[\Phi_{t*}\mathbb{Y},\Phi_{t*}\mathbb{Z}]$
Let $\mathbb{X},\mathbb{Y}$ be vector fields on $\mathbb{R}^n$. Let $\Phi_t$ denote the flow of $\mathbb{X}$. Define $L_{\mathbb{X}}\mathbb{Y}=[\mathbb{X},\mathbb{Y}]$. You are given that
$\displaystyle L^j_{\mathbb{X}}[\mathbb{Y},\mathbb{Z}]=\sum_{k=0}^{j} \binom jk [L^k_\mathbb{X}\mathbb{Y},L^{j-k}_\mathbb{X}\mathbb{Z}]$
and that $\displaystyle \Phi_{t*}\mathbb{Y} = \sum_{j=0}^{\infty}\frac{(-t)^j}{j!}L^j_{\mathbb{X}}\mathbb{Y}$
Show that $\displaystyle \Phi_{t*}[\mathbb{Y},\mathbb{Z}]=[\Phi_{t*}\mathbb{Y},\Phi_{t*}\mathbb{Z}]$
Let $F$ be a diffeomorphism on $\mathbb{R}^n$, define
  $$ \mathbb{X}^i(x)=\frac{\partial F^i}{\partial x^1}(F^{-1}(x)), \mathbb{Y}^i(x)=\frac{\partial F^i}{\partial x^2}(F^{-1}(x))$$
  Show that $[\mathbb{X},\mathbb{Y}]=0$.

$\begin{align}
\displaystyle \Phi_{t*}[\mathbb{Y},\mathbb{Z}] &= \sum_{j=0}^{\infty}\frac{(-t)^j}{j!}L^j_{\mathbb{X}}[\mathbb{Y},\mathbb{Z}] \\
&= \sum_{j=0}^{\infty}\frac{(-t)^j}{j!} \left(\sum_{k=0}^{j} \binom jk [L^k_\mathbb{X}\mathbb{Y},L^{j-k}_\mathbb{X}\mathbb{Z}]\right) \\
&= \sum_{l,k=0}^{\infty} \frac{(-t)^{k+l}}{(l+k)!} \binom{l+k}{k}[L^k_\mathbb{X}\mathbb{Y},L^{l}_\mathbb{X}\mathbb{Z}] \\
&= \sum_{l,k=0}^{\infty} \frac{(-t)^{k}(-t)^{l}}{l!k!} [L^k_\mathbb{X}\mathbb{Y},L^{l}_\mathbb{X}\mathbb{Z}] \\
&= [\Phi_{t*}\mathbb{Y},\Phi_{t*}\mathbb{Z}]
\end{align}$
I cannot see how to proceed now. For the last part I assume somehow the first part has been used as I just cannot see how.
Please that $[\cdot,\cdot]$ denotes the Jacobi bracket, not the Poisson bracket. So
$$ [\mathbb{X},\mathbb{Y}]=\left( \mathbb{X}\cdot \nabla \right) \mathbb{Y} - \left( \mathbb{Y}\cdot \nabla \right) \mathbb{X} $$

A: By definition, $X=F_* \frac{\partial}{\partial x^1}$ and $Y=F_* \frac{\partial}{\partial x^2}$. If $F$ is a diffeomorphism, then $y^1:=F^1,\ldots, y^n:=F^n$ is a coordinate frame on $\mathbb{R}^n$ and $\frac{\partial}{\partial y^j}$ are commuting vector fields. But $\frac{\partial}{\partial y^i}=\sum_j \frac{\partial F^j}{\partial x^i}\frac{\partial}{\partial x^j}=F_*(\frac{\partial }{\partial x^i})$, so $X=\frac{\partial}{\partial y^1}$ and $Y=\frac{\partial}{\partial y^2}$ commute.
I don't see how to use the previous result, as it is not obvious how to express $F_*$ as $\phi_{t*}$ for some flow.

Edit: If you want to avoid the "manifold"-notation and stay in $\mathbb{R}^n$, then define $e_1=(1,0,\ldots, 0)$ and $e_2=(0,1,\ldots,0)$ to be the Cartesian coordinate vector fields. You can easily verify that $X=F_* e_1$ and $Y=F_* e_2$. If $F=(F^1,\ldots, F^n)$ is a diffeomorphism, you can consider the components $F^1,\ldots, F^n$ to be new coordinates on $\mathbb{R}^n$ (think of polar coordinates $(r,\phi)$ on a suitable subset of $\mathbb{R}^2$ for an analogy). Then $X$ and $Y$ are the vector fields generated by first and second of these new coordinates. That means, $X$ is the field generated by keeping $F^2,\ldots, F^n$ fixed and increasing $F^1$ with unit velocity. It is a standard fact that is written in most textbook on differential geometry that such coordinate vector fields always commute.
But now I see that this is probably the core that should be proved. If you accept the notation $Xf:=df(X)$ referring to a function that in each $x$ is the derivative of $f$ in $x$ in the direction of $X(x)$, then $[X,Y]f=X(Y(f))-Y(X(f))$ and the rest follows from the simple and nice computation given by @kobe. The identity
$Xf=(\frac{\partial}{\partial x^1}(f\circ F))\circ F^{-1}$ that he uses follows from
\begin{align}
(Xf)(x)&=(df(x))(X(x))=((\nabla f)(x))((F_* e_1)(F^{-1}(x)))=
\sum_i {\frac{\partial f(x)}{\partial x^i}} \frac{\partial F^i}{\partial x^1}(F^{-1}(x))\\
&=(\ldots \text{use the chain rule})
=(\frac{\partial}{\partial x^1} (f\circ F))(F^{-1}(x))
\end{align}
and similarly for $Y$.
Final remark: You have probably no problem accepting $\frac{\partial^2}{\partial x^1 \partial x^2}=\frac{\partial^2}{\partial x^2 \partial x^1}$. But similarly, $\frac{\partial^2}{\partial r\,\partial\phi}=\frac{\partial^2}{\partial \phi\,\partial r}$ in polar coordinates (or any other coordinates). That's all what this is about.

A: To me, the problem does not indicate to use the first part in order to prove the second part. For the second part, note that since $X = F_{*}\frac{\partial}{\partial x^1}$ and $Y = F_{*}\frac{\partial}{\partial x^2}$, for every smooth real-valued function $f$ on $\Bbb R^n$,
\begin{align}[X,Y]f &= X(Yf) - Y(Xf)\\
&= \left(\frac{\partial}{\partial x^1}(Yf \circ F)\right) \circ F^{-1} - \left(\frac{\partial}{\partial x^2}(Xf \circ F)\right) \circ F^{-1}\\
&=\left(\frac{\partial}{\partial x^1} \frac{\partial}{\partial x^2}(f \circ F)\right) \circ F^{-1} - \left(\frac{\partial}{\partial x^2}\frac{\partial}{\partial x^1}(f\circ F)\right)\circ F^{-1}\\
&= 0
\end{align}
Therefore, $[X,Y] = 0$.


text:
Q: $\mathbb{R}\to\mathbb{R}$ Diffeomorphism with special property $\phi:\mathbb{R}\to\mathbb{R}$ be a diffeomorphism with the following property
$a\in\mathbb{R},|a|<\frac{1}{10}$
(i)$\phi(a)=0$
(ii) $\phi(x)=x$ when $|x|>1$
and how to generalize that in $\mathbb{R}^n$
please help.

A: First let's generalize: Suppose $a\in B_{\frac{1}{10}}(0)$; the idea is to construct a vector field in $\mathbb{R}^n$, such that in a neighbourhood which contains $0$, $a$ and is contained in $B_1(0)$, the field points in the "direction" of the vector $-a$ with positive velocity, and in the complement, the field is zero.
If we construct this field in such a way that it is Lipschitz, then we know that there exist a flow associated to the field, i.e. if the field is given by $x'(t)=f(x(t))$ with $x(0)=a$, where $f$ is Lipschitz, then there exist a function $F$ depending on $t$ and $a$, satisfying $$\frac{\partial F(a,t)}{\partial t}=f(F(a,t))$$
Moreover, this functions has some good properties:
I- It is $C^1$,
II- $F(a,0)=a$,
III- $F(a,s+t)=F(F(a,t),s)$
IV- For each fixed $t$, $F(a,t):\mathbb{R}^n\rightarrow\mathbb{R}^n$ is an diffeomorphism
Case 1: $\mathbb{R}$
Let $\epsilon>0$ be a small number and construct an $C^1$ function $g:\mathbb{R}\rightarrow [0,1]$, such that $g(t)=1$ if $t\in [0,a]$; $0\leq g(t)\leq 1$ if $t\in (-\epsilon,0)\cup (a,a+\epsilon)$ and $g(t)=0$ on the rest. Consider the vector field $$x'(t)=-g(t),\ x(0)=b$$
Let $F(b,t)$ be the flow associated with this vector field. Note that for $b\in [0,a]$ and $t\in [0,b]$ your flow is defined by $F(b,t)=b-t$. This implies that if $b=a$, then $F(a,a)=0$. Because $F(b,a)$ (b varying) is an diffeomorphism and $F(b,a)=b$ for $b$ in the set where $g$ is zero, you can conclude.
Case 2: $\mathbb{R}^n$
Try to do this case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Email Setup to Prevent Identity Theft My father-in-law asked me for ideas to improve his email security. He read an article about how some hackers, having gained access to a Gmail account, were able to reset the account holder's passwords for other services, such as Amazon.
This is what I've come up with so far, but more brainpower would really help as I've never thought of this before, so all critique and suggestions will be warmly welcome.
Starting Point:
He has a website hosted on a LAMP / cPanel system, and his current email goes through the website's domain. The email account is set up in cPanel. He retrieves his email via pop3, deleting it from the server. I'm thinking this might be a decent starting point? No need for iMap as he only has one computer (no iPhone) and he deletes it as he goes?
Next Steps:

*

*I am thinking to get him to set up several address forwarders on his cPanel: one for his bank, one for Amazon---basically one for each of the few accounts that are linked to a bank or a credit card. These forwarders would all forward to one central address, also set up in cPanel, which would be "private", in the sense that he would not use it to send emails. He would only use it to retrieve email via pop3.

*Also thinking of getting him to can store his email on his computer on an encrypted virtual drive using TrueCrypt.
With this set-up it seems to me the messages are vulnerable in a few places:

*

*in transit from Amazon to his server, than from his server to his computer. Not much we can do about that as his bank or Amazon are not going to send him encrypted email.

*while stored on his cPanel LAMP set-up. I wonder how safe (unsafe) that is. If it was a shared host I'd be very worried. Being a VPS it might be a little safer. But still... Someone could hack in... How likely is that?

*on his computer, if someone gains access while he is logged in and the virtual drive is mounted.

Big thanks in advance, looking forward to your thoughts.
UPDATE: SUMMARY OF REPLIES SO FAR
How lucky, several thoughtful and detailed replies came in so far.
Summarizing the replies so far.
Using the Web

*

*His router should be hardened, for example disallowing the Internet remote management console. Be mindful of the fact that a hack could reveal his IP address and ISP login password.

*Use long and complex passwords that are unique to each on-line account that he uses. Strong passwords (16 characters or more)

*Creating different email accounts off one domain for different services: Pros: prevents the "Epic Wired hacking". Cons: increases the number of vulnerable nodes
Use a secure browser. For Firefox, see Top 10 Best Firefox Security Add-ons, esp. noscript

Retrieving Messages (Thunderbird)

*

*Use SSL

*PGP encryption for sensitive correspondence (requires the counterpart to have a key)

Local Machine

*

*Firewall

*A good anti-virus suite is also a must.

*Disable unused network services

*Encryption => Applications leak an unbelievable amount of data throughout the whole system in caches and logs, rendering a solely encrypted local mailbox somewhat irrelevant. If you encrypt, Truecrypt the whole drive.

Hardening the Server

*

*Uninstall every unessential service or product that may listen or access the Internet and more.

*Grsecurity or a similar system to prevent buffer overflow attacks

*He should login to his webserver using its IP address and not the domain-name which can redirect him elsewhere: If a DNS server is hacked, then when browsing he could find himself confronted with a login page to any website or even his own server that is an exact duplicate of the real page.

Fischer's Set-up
(Special category as Fischer's workflow is different system from the other replies)

*

*If you don't know how secure your lamp server is, host it on outlook.com instead (free)

*Forward all email accounts to GmailAC#1 and delete from server

*After reading, PGP-encrypt messages and forward to GmailAC#2

*Retrieve via Thunderbird

A: This is a complex question, but putting together a simple system to protect your father-in-law's confidential information should not be that difficult.
Your first suggestion of using separate addresses for separate services probably won't make much of a difference. If someone (say, Mallory) is intercepting email in the network, then they can probably intercept any forwards you make; therefore all services are vulnerable to attack if you are using only one domain for all accounts. Mallory can simply search for any emails containing *@example.com in the To field and assume they're all being forwarded to the hidden address. Just knowing what the email address for a given account on a given service is gives Mallory an advantage, as that's what is authenticated to the service and that's what she will use to compromise it. Even creating email accounts off your domain simply increases the number of vulnerable nodes.
One way that you can considerably improve security is by enabling SSL for all protocols on the mail client used to fetch from the server. That way you eliminate at least one vulnerable hop where Mallory can intercept the plaintext of the emails. Also, contrary to what you've stated, it is very likely that sensitive services are using SSL to send you mail via SMTP, or that you can enable that somehow.
That's the most you can do on the network end. If the service refuses to use SSL-SMTP, it's probably not going to be very secure at all. There's a lot you can do to improve security on the local end, however. You should take standard precautions such as creating a firewall and disabling unused network services, as well as making sure that all your passwords are strong (16 characters or more). The LAMP server can be hardened with Grsecurity or a similar system to prevent buffer overflow attacks. Creating a virtual encrypted drive is of dubious utility, seeing as that unless you want your email to be undeliverable 90% of the time, the drive must be unlocked for you to receive it. Picture a physical mailbox with a padlock!
The local system presumably being used to retrieve email from the server using (SSL-)POP3 can be hardened as well if it's Linux. If you're serious about local security, the whole drive should be TrueCrypted (it's not actually on standby waiting for mail all the time) because applications leak an unbelievable amount of data throughout the whole system in caches and logs, rendering a solely encrypted local mailbox somewhat irrelevant.
So there's a little you can do for the network, a lot you can do for the server, and more you can do for the local system. Remember that the weakest part of your whole security system is the passwords.

A: I'm not a security expert, nor a bounty hunter, but this question is open for 2 days and no answer, i'll see if i can help.
Lets starts with the basics, the first thing that comes to mind when securing an email account is using gpg. Before i start, I assume that your lamp server is secured and you have ssh and all, you just need an architecture to keep your mails safe. I strongly recommend using outlook free mail hosting if you don't know how secure your lamp server is.
So that's my idea:

*

*you create different email account for each service: amazon@example.com, ebay@example.com

*you create a gmail account, lets call it negitoro@gmail.com, we will use it later (you really have to use gmail not another service).

*all the mails that he receives will be forwarded to the the gmail we created, and you set a cron job his other mail accounts (amazon@example.com and others) to delete mail. I believe you don't need a cron job, when adding amazon@example.com to gmail accounts in the settings, just uncheck "leave a copy on the server"

*what we have so far is amazon@example sends to gmail and the message isn't left on the server, it's stored in gmail only. This step is we go to gmail settings and we configure it to send as amazon@example.com, so now it receive from that account and sends also. Do that for all the other accounts, we want to send and receive from gmail to all the other accounts.

*Step 5 is easy, create another gmail account, lets call it fischer@gmail.com

*step 6, configure gpg between fischer@gmail.com and negitoro@gmail.com, but don't connect them, like we did in step 4.

*link fischer@gmail.com with thunderbird or any email client that you like, link the other gmail too.

*Now all the mails arrive at negitoro@gmail.com, after reading the mails and replying, encrypt the message using gpg and send it to fischer, and delete it from gmail (this isn't an automated process, because you can't encrypt a message and send it to amazon).

*now all your messages are encrypted and stored in fischer's mailbox, download them using thunderbird or whatever and encrypt the hard drive.
Bonus steps
I insisted on using gmail, because you can secure it using sms
Change passwords regularly, if you can't remember them use lastpass + yubikey

A: The security breaches your father has read about have used two vulnerabilities :

*

*Using the same password on gmail and on other less-secure on-line services,
so once having breached the other service the hacker gained access also to gmail.

*A phishing or DNS attack succeeded in either convincing the target to hand over his password or install a virus/trojan on his computer.

In your father's case, he has four weak points :

*

*Himself

*His web server

*His ISP (or ISPs if his web server uses a different one)

*The DNS servers used by himself and his web server

The first point can be strengthened by using long and complex passwords that are unique
to each on-line account that he uses, as well as changing them periodically
(something like every few months). The subject of secure passwords has been extensively
treated on the Internet. His router should also be hardened, for example disallowing
the Internet remote management console.
Your father should also use a secure browser (which doesn't include Internet Explorer)
and install in it several security extensions while being careful about Java.
For Firefox, see Top 10 Best Firefox Security Add-ons of which I absolutely
recommend NoScript (WOT is not as good as is described).
A good anti-virus suite is also a must.
His server should also be hardened as regarding passwords, uninstalling every unessential
service or product that may listen or access the Internet and more.
Again, the subject of hardening a Linux server has been extensively treated on the Internet.
For his ISP, he should be mindful of the fact that a hack could reveal his IP address
and login password, although the damage there will only be minimal
since he doesn't use the email server of his ISP.
If a DNS server is hacked, then when browsing he could find himself confronted with a login
page to any website or even his own server that is an exact duplicate of the real page.
His password will then be recorded and control will pass seamlessly to the real page.
He should login to his webserver using its IP address and not the domain-name which
can redirect him elsewhere, and in general be alert to any glitches that may arrive.
Final word: The best protection for your father is in being unimportant enough,
so as to not attract attention from the real hackers.
This is because there are too many attack vectors and no way of protecting against
them all. However, being careful he at least can protect himself against script-kiddos
and the occasional random attack.


text:
Q: select a date 15 days before today in datepicker using robot framework Iam using robot framework to test my web application.  I need to select a date that is 15 days before current date. The application uses ng-model datepicker implement.
so far  I have tried to get the current date and prvious date and also tried to remove the readonly attribute for the input filed for dateselected. but the problem is Iam not able to select the previous date.
     ${date}=        Get Current Date   result_format=datetime
 ${monthyear}=  Convert Date    ${date} result_format=%m%Y
 ${my_date_to_select}=    Get Current Date    UTC    -15 days   %Y-%m-%dT%H:%M:%S.%f
 ${expectedMonthYear}=  Convert Date    ${my_date_to_select}    result_format=%m%Y
 ${day}=    Convert Date    ${my_date_to_select}    result_format=%d
  Execute Javascript                         document.getElementById("datepickerLMP").removeAttribute("readonly");
  Execute Javascript          document.getElementById("datepickerLMP").removeAttribute("onchange");

A: Use the "Get Current Date" keyword from the DateTime library to get the current date in a desired format. For example:
${current_date}=  Get Current Date  result_format=%Y-%m-%d

This will give you the current date in the format "yyyy-mm-dd".
Use the "Convert Date" keyword from the DateTime library to convert the current date to a datetime object. For example:
${current_datetime}=  Convert Date  ${current_date}  result_format=datetime

This will give you a datetime object for the current date.
Subtract 15 days from the current date using the "Subtract Time From Date" keyword from the DateTime library. For example:
${previous_datetime}=  Subtract Time From Date  ${current_datetime}  15 days

This will give you a datetime object for the date 15 days before the current date.
Use the "Format Date" keyword from the DateTime library to format the previous date in the format expected by the ng-model datepicker. For example:
   ${previous_date}=  Format Date  ${previous_datetime}  result_format=%Y-%m-%d

This will give you the previous date in the format "yyyy-mm-dd".
Use the "Input Text" keyword from the SeleniumLibrary to set the value of the datepicker input field to the previous date. For example:
Input Text  ${date_picker_locator}  ${previous_date}

Replace ${date_picker_locator} with the locator for the datepicker input field on your web application.
Hope this helps!


text:
Q: how can I get country name by coordinates without external API? What I am looking for?
I am looking for a python library with a method/module that gets coordinates and return country name without connect to external API
Why?
I have a pandas df with a lot of rows (much more 10000) and I don't want to send a request for each row.
this want I am doing now:
from geopy.geocoders import ArcGIS
...
...
...

geolocator = ArcGIS(scheme='http')

    for index, row in df.iterrows():

        if math.isnan(row['latitude']) or math.isnan(row['longitude']):
            continue
        else:
            try:
                location = geolocator.reverse((row['latitude'], row['longitude']), timeout=30)
                # takes the country
                location = str(location)
                if len(location.split(",")) == 4:
                    country = location.split(",")[3][1:]
                    df.at[index, 'country'] = country

if it possible to send one request for all the rows it still fine

A: There seem to be no off-the-shelf libraries, but one possible solution to do this without external APIs would be to:

*

*download natural earth boundary data as a shapefile - https://www.naturalearthdata.com/downloads/10m-cultural-vectors/

*load the boundaries shapefile into your script using geopandas - https://geopandas.org/io.html

*do point in polygon tests for each latlng point to get the country relevant for the point - https://automating-gis-processes.github.io/CSC18/lessons/L4/point-in-polygon.html

A:
if it possible to send one request for all the rows it still fine

I think this is API dependant, and I don't think anyone would allow somthing like that (nevertheless, the last word relies on the documentation of each API).
Having said that, I don't see how you could escape from making a request per entry.
One possibility is to evaluate how fine grained the information you're looking for needs to be, and then decide if you can use one same result to fill more than one row, but then again, that requires some extra work.
I once had to do the exact same, and although it was a bit tedious, the best solution I could find was to make all the requests. Here are some ideas which may help:

*

*You can split the data in chunks so it's all more managable in case something goes wrong.

*periodically save the results to disk

*you may consider running the code on Google Colab or Kaggle, so you don't depend on your own pc running and not interrupting the connection during the time the task is being complete (I find this a huge plus - I don't want to rely on my pc or connection with time consuming tasks ;) ).


text:
Q: Is it true that all elements of $U(\mathbb{Z}_n)$ are the elements which are relatively prime to n? I feel like I heard my professor say this today, but I'm not entirely sure.

A: Yes true since
$$\overline a\in U(\mathbb Z_n)\iff \exists \overline b\in U(\mathbb Z_n)\;|\; \overline a \overline b=\overline1\iff ab\equiv 1(\mod n)\iff\exists k\in \mathbb Z\;\; ab+kn=1\iff n\wedge a=1\;\text{by Bézout's identity}$$

A: Yes. $\ \ \ \ \ \ \ \ \ \ \ \ \ $


text:
Q: Asp.Net token authentication redirect to login Aiming to use best and modern practices I decied to implement token authentication in my web application and I was able to make it to work but the fact is I'm not being able to redirect to login page on unauthorized access, instead it throws a 401.0 blank page with error.
I was googling and found this next piece of code to be put on Configure method on Startup.cs to redirect depending of Http status error code but Visual Studio is complaining with IAppBuilder does not contain a definition for UseStatusCodePages.
First of all I'd like to know which specific package should I add so method UseStatusCodePages is found but I'd also like to know if this is the best approach to redirect to login page on unauthorized access using token authentication or if not what do you suggest.
app.UseStatusCodePages(async context =>
{
    var request = context.HttpContext.Request;
    var response = context.HttpContext.Response;
    var path = request.Path.Value ?? "";

    if (response.StatusCode == (int)HttpStatusCode.Unauthorized && path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase))
    {
        response.Redirect("~/Account/Login");
    }
});

This is my ConfigureOAuth method:
public static void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new ADAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }

Another option is to use a custom authorize class like so:
public class CustomAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            //filterContext.Result = new HttpUnauthorizedResult();
            filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new { controller = "Login" }));
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new { controller = "Employee" }));
        }
    }
}

And with this second approach replacing [Authorize] with [CustomAuthorize] is working fine but the fact is I wouldn't like to be in the need to use a CustomAuthorize instead of the default one so what do you think? Is this second one a good approach? Should I keep the first? What about UseStatusCodePages not being found? In the end, is it a good idea to use token auth on an app which most likely won't use web api?
FYI, I'm using MVC with Asp.Net Framework 4.6.1
Thanks.


text:
Q: Creating upgradable C# .net windows application I create an windows application and give the user the installation pack for it. So now I need to fix some bugs and give a revised version to the user but I don't want them to reinstall it. So how can I create a fix and distribute it?

A: ClickOnce will greatly simplify this process of installation/upgrade. You may have to reinstall the application once through ClickOnce, but after that, upgrades will be easily provided. Explanations here.

A: Create a new installer that will overwrite old files with the new files.
or consider using click once deployment

A: I haven't used clickonce, but a couple of years ago I had to write something that would auto update.  I can't find the code or else I would post, but this is what it did:
1) Main exe would look at an assembly and find the version.
2) IF the exe could connect to a public server, it would check and see if a different assembly was available.
3) If the assembly was available, it would download it and run the new assembly
4) If the assembly wasn't available or didn't have an internet connection, it would just run the local one.
Doing this requires no user interaction.


text:
Q: i want to write forms like this is this the correct way to approach..?

search form
<form action="category.php?type=search" method="post">
select all delete form
<form name="frmMain" method="post">

</form>
</form>

A: If you are using to send form using php then below is right way:
 //search form
    <form action="category.php?type=search" method="post">

    </form>

//select all delete form

    <form name="frmMain" method="post">

    </form>

if you want to send form using ajax and jquery then you can use this way:
//search form
<form action="category.php?type=search" method="post">

  //select all delete form
   <form name="frmMain" method="post">

  </form>
</form>

Example of HTML:5 new form element (from an answer by ilevent):

<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>

 <input type="text" name="foo" form="saveForm" />
 <input type="hidden" value="some_id" form="deleteForm" />
 <input type="text" name="foo2" id="foo2" form="saveForm" value="success" />

    <input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
    <input type="submit" name="delete" value="Delete" form="deleteForm" />
    Cancel


text:
Q: Extract a part from a file between specific lines I would like to know, how can I extract some data from a specific range in a big data file? Is there a way to read the content beginning and ending with "buzzwords".
I would like to read line per line between *NODE and **
*NODE
13021145,       2637.6073002472617,       55.011929824413045,        206.0394346892517
13021146,       2637.6051226039867,        55.21115693303926,       206.05686503802065
13021147,        2634.226986419154,        54.98263035830583,        205.9520084547658
13021148,        2634.224808775879,       55.181857466932044,       205.96943880353476
**

Before *NODE and after ** there are thousand of lines...
I know it should look something similar like:
a = []

with open('file.txt') as file:
   for line in file:
      if line.startswith('*NODE'):

      # NOW THERE SHOULD FOLLOW SOMETHING LIKE:
      #   Go to next line and "a.append" till there comes the "magical"
      #   "**"

Any idea? I am totally new to python. Thanks for help!
I hope u know what i mean.

A: You pretty much did it - the only thing missing is that once you find the beginning, you search for the sequence end and until that happens append every line you're iterating over to your list. i.e.:
data = None  # a placeholder to store your lines
with open("file.txt", "r") as f:  # do not shadow the built-in `file`
    for line in f:  # iterate over the lines
        if data is None:  # we haven't found `NODE*` yet
            if line[:5] == "NODE*":  # search for `NODE*` at the line beginning
                data = []  # make `data` an empty list to begin collecting
        elif line[:2] == "**":  # data initialized, we look for the sequence's end
            break  # no need to iterate over the file anymore
        else:  # data initialized but not at the end...
            data.append(line)  # append the line to our data

Now data will contain either a list of lines between NODE* and **, or None if the sequence was not found.

A: Try this:
 with open('file.txt') as file:
    a = []
    running = False  # avoid NameError when 'if' statement below isn't reached
    for line in file:
        if line.startswith('*NODE'):
            running = True  # show that we are starting to add values
            continue  # make sure we don't add '*NODE'
        if line.startswith('**'):
            running = False  # show that we're done adding values
            continue  # make sure we don't add '**'
        if running:  # only add the values if 'running' is True
            a.extend([i.strip() for i in line.split(',')])

The output is a list containing the following as strings:
(I used print('\n'.join(a)))

13021145
2637.6073002472617
55.011929824413045
206.0394346892517
13021146
2637.6051226039867
55.21115693303926
206.05686503802065
13021147
2634.226986419154
54.98263035830583
205.9520084547658
13021148
2634.224808775879
55.181857466932044
205.96943880353476

A: We can iterate over lines until there is no any left or we've reached end of block like
a = []

with open('file.txt') as file:
    for line in file:
        if line.startswith('*NODE'):
            # collect block-related lines
            while True:
                try:
                    line = next(file)
                except StopIteration:
                    # there is no lines left
                    break
                if line.startswith('**'):
                    # we've reached the end of block
                    break
                a.append(line)
            # stop iterating over file
            break

will give us
print(a)
['13021145,       2637.6073002472617,       55.011929824413045,        206.0394346892517\n',
 '13021146,       2637.6051226039867,        55.21115693303926,       206.05686503802065\n',
 '13021147,        2634.226986419154,        54.98263035830583,        205.9520084547658\n',
 '13021148,        2634.224808775879,       55.181857466932044,       205.96943880353476\n']

Alternatively we can write helper predicates like
def not_a_block_start(line):
    return not line.startswith('*NODE')

def not_a_block_end(line):
    return not line.startswith('**')

and then use brilliance of itertools module like
from itertools import (dropwhile,
                       takewhile)

with open('file.txt') as file:
    block_start = dropwhile(not_a_block_start, file)
    # skip block start line
    next(block_start)
    a = list(takewhile(not_a_block_end, block_start))

this will give us the same value for a.


text:
Q: Table scaling with partitions or with separate databases? Let's say I have a table (let's call it BigTable) which could experience 5,000,000 INSERTS per day (with possibly just as many SELECTs).  Each row inserted is about 50kb.
These daily INSERTs are split across 5 clients equally (the table has a FK called ClientID).  There is never a need to SELECT or JOIN data across multiple clients.
I am worried about the database performance as this table grows, so I have come up with two solutions.
SOLUTION 1:

*

*Partition BigTable by ClientID

*Store each partition on a separate hard disk on the server (using Azure blog storage).

*Partition all data which is 1 month old (archive data, yet still need to be queryable) into another set of READONLY partitions.

Essentially this means the following partitions on their own storage devices:

*

*Primary (all data excluding BigTable)

*ClientA's BigTable (5,000,000 rows per day / 5 clients x 30 days = 30,000,000 rows)

*ClientB's BigTable (30,000,000 rows)

*ClientC's BigTable (30,000,000 rows)

*ClientD's BigTable (30,000,000 rows)

*ClientE's BigTable (30,000,000 rows)

*ClientA's BigTable archive

*ClientB's BigTable archive

*ClientC's BigTable archive

*ClientD's BigTable archive

*ClientE's BigTable archive

The number of rows in the archive tables will be (5,000,000) x (age of DB in days) - (30,000,000).  This is still a huge table, but will only be used to drawing up the odd report.
SQL Server will be hosted on a 14GB, 8core Azure VM.
SOLUTION 2:
The other option is to host separate databases for each client.  This means each will have it's own dedicated SQL Server machine.  Partitioning will still happen for archive data.
This option is not optimal because of the physical separation of the data.  Having to manage updates to multiple databases could be very problematic.  Having separate database connections for each client will also be a consideration for the developers.
Could anyone perhaps advise on these options?

A: Since you have tagged this with [azure] and [sql-server], I assume that you are trying to do this in Windows Azure. If that is the case then a) partitioning by client is not necessarily a good idea, and b) SQL may not be the best (complete) fit for your problem.
When building scalable architectures, the partitioning strategy shouldn't be based on something specific like 'client', but rather something more arbitrary. The reason is simple — unless clients have a reason to be separate, such as not wanting their data mixed with others, or different SLAs per client, then the choice of 'client' as a partition may not render the optimal result. If 80% of your business is generated by a single client, you have not solved your problem, and still have to maintain n separate databases for marginal load.
5 mil database inserts per day is not a big number, but may be a big number for SQL Server hosted in Azure IaaS, or Azure SQL Database — due to the performance of the underlying commodity hardware. Before determining how to partition SQL, ask yourself two questions. First, what are the usages and performance characteristics that you want from the data? (Does it have to be immediately consistent? Can you process data asynchronously?) Secondly, have you mapped those characteristics against other data store technologies? Have you considered Table Storage (or non-MS solutions like Redis)?
You may find, after trying out a few options that:

*

*SQL is a good store for some of the data, some of the time.

*Much of the processing can be done asynchronously, so the peak performance of inserts is of little concern (and doing 5 mil inserts over a 24-hour period is not a problem).

*SQL may not be suited to long-term storage.

*Querying of older data can be done effectively using map-reduce, rather than SQL queries.

For example, I have an app that tracks vehicles at one-second intervals. It is targeted for 100,000 vehicles but architected in such a way as to be able to scale up to millions without changing any code or databases. But in the medium term, it has to cope with 72 mil inserts per day. All of this runs on a single Windows Azure SQL database that is less than 10GB, and a whole bunch of table storage. The reason why this works is because although I want to archive all data (72 mil rows), I don't need complex SQL query access to it, so it sits happily in table storage. What I store in SQL is a summary of the data. So in my example, I am only interested in a vehicle's journey (start and end position, distance travelled etc), which means that I only have two or three rows per vehicle per day that I need in SQL — greatly reducing the load on the database. Also, my bottleneck is in the collection of data, so I add the data immediately to a (Windows Azure) queue — and worry about the summarising of data in a separate workload.
This answer may be a bit long, but is intended for you to think about your data model more carefully, rather than just trying to think about how to solve the problem with SQL. For more detail, have a look at the data model in CALM.

A: A few ideas for you:
1) Use Azure Tables instead of SQL.  Have PartitionKey = ClientID.  Each table can be 200TB & support 20k IOPS.  Each partition is 2k IOPS, since the clients would be logically separated you would get a natural load balance (Azure load balances by Partition).  This would also save you from having to run/manage a XL VM 24x7 (i.e. much cheaper).  The storage costs would be the same since the data drive for the VM is backed by Azure storage anyway.  5M inserts per day is only ~60/sec, so there would be a lot of headroom for growth.  This is especially true b/c you are doing fairly simplistic Insert/Select and would not cross Client boundaries.
2) If you want to do a per client DB, I would go with SQL Azure.  The provisioning is much faster and each DB is a separate scale unit (this would prevent one client from creating an issue for others).  You can also dynamically change the DB based on the client changes.
3) If you want a single monolithic DB, I would go with SQL Server on a VM.  Create multiple Data drives and mount them as a striped set.  For an XL VM, you can have up to 16 drives mapped.  This will limit the maximum size of the DB to 16TB, so you would need to have some mechanism for aging out/archiving/garbage collecting.

A: You do not only need to think about access performance but also about disaster recovery performance. At 6TB for each client in the active month alone, I strongly recommend to keep the clients in separate databases.
If you have a decent Continuos Integration and an automated deploy process, keeping the database schema in synch should not be that big of a problem.


text:
Q: While transferring local server work to live server in Odoo/OpenERP using postgreSql as a database? It is showing error I had made many modifications like creating new views, models, menu items. I was working on the local server and I shifted newly created views, models, etc. on the server.
I took backup through pgAdminIII and when I transferred,

*

*Record data does not exist in odoo.

*Uncaught TypeError: Cannot read property 'off' of undefined.


text:
Q: ASP.NET MVC List of attachments (from binary data) Using ASP.NET MVC and SQL Server 2016. I have attachments which stored as binary data in SQL Server.
Table with data looks like:
 attachment_ID  | attachment_GUID  | attachment_data | attachment_name|
  --------------|------------------|-----------------|----------------|
       211      |   A893C2Z1-4C0   |  0x255044462... |    file1.doc   |
       212      |   A893C2R5-4F0   |  0x255044455... |    file5.pdf   |

I need to display list of this attachments (names), as hyperlinks in html page. So if I click on attachment name it should start the downloading process.
Need help with an ASP.NET MVC controller.
I have controller which downloads a file directly:
using System;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;

namespace Project.SERVER.Controllers
{
    public class AttachmenttoHTMLController : Controller
    {
        #region View attachments
        [HttpGet]
        public ActionResult Get()
        {
            SqlConnection connection = Project.SERVER.Classes.INT_DataBase.getConnection();
            SqlCommand command = new SqlCommand("SELECT * FROM AllAttachments WHERE document_GUID='F3A2AC32-D98D'", connection);
            command.Dispose();

            SqlDataAdapter sqlDtAdptr = new SqlDataAdapter(command);
            System.Data.DataTable result = new System.Data.DataTable();
            result.Dispose();
            sqlDtAdptr.Fill(result);
            sqlDtAdptr.Dispose();
            connection.Dispose();
            connection.Close();

            if (result.Rows.Count > 0 && !System.Convert.IsDBNull(result.Rows[0]["attachment_data"]))
            {
                byte[] file = (byte[])result.Rows[0]["attachment_data"];
                Response.ContentType = result.Rows[0]["attachment_contentType"].ToString();

                return File(file, Response.ContentType, result.Rows[0]["attachment_fileName"].ToString());
            }
            else return new EmptyResult();
        }
        #endregion
    }
}

What should I add to the code to achieve controller for attachment list with option to download when clicked?

A: You have to save first the binary data into Image Format into your directory project.
Use FileResult
HTML:

    @Html.ActionLink("Download", "Download", "Home");

HomeController:
 public FileResult Download()
    {
        String path = HostingEnvironment.ApplicationPhysicalPath + "Image\\Capture.PNG";
        string fname= Path.GetFileName(path);
        byte[] fileBytes = System.IO.File.ReadAllBytes(path);
        string fileName = fname;
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

    }

Assuming that you have a list in your model
 List<Attachment> lst = new List<Attachment>();

This list is the content of your data from your Database and saved the byte to imageformat into you project folder.
Your code from above should fall  in here saved the byte with a filename even id.PNG or any. Adding  lst.id and lst.filename for html purpose.
 public class Attachment
        {
            public int id { get; set; }
            public string filename { get; set; }
        }

Your HTML looks like:

@{
            if (Models.GetAttachment.lst.Count > 0)
            {
                  for (int m = 0; m < Models.GetAttachment.lst.Count; m++)
                {

                        @Html.ActionLink("Download", "Download", new { id = Models.GetAttachment.lst.Coun[m].id })

                }
            }

  }

HomeController With id:
 public FileResult Download(int?id)
        {
            String path = HostingEnvironment.ApplicationPhysicalPath + "Image\\Capture.PNG";
            string fname= Path.GetFileName(path);
            byte[] fileBytes = System.IO.File.ReadAllBytes(path);
            string fileName = fname;
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

        }

the purpose of id to locate the file in your project directory for every user click.


text:
Q: Using CSS to change the brightness of one of the background images in a multiple image background? I tried the following code and it is not helping.
.information{
    background-image:url(../images/needle_img.png),url(../images/broken_noise.png);
    background-size: auto 60%, auto auto;
    background-position:left bottom,top left;
    -webkit-filter: brightness(0.8),brightness(1);
    -moz-filter: brightness(0.7),brightness(1);
    -o-filter: brightness(0.8),brightness(1);
    -ms-filter: brightness(0.8),brightness(1);
    filter: brightness(0.8),brightness(1);
    background-repeat: no-repeat,repeat;

}


text:
Q: Wrap domain roles around aggregate root operations to represent the ubiquitous language In a BC I have the following rules:
A project can be defined by an employer.
An approver should approve the project.
Then an employee can bid that project.
A project can be directed by a member (= an employer or an employee) to another member.

The project is an independent aggregate from employer, employee, and approver.
And employer, employee, and approver are all users and all I need to know from users in this BC is their Identities.
I designed the project including methods :
static Define(){...}
ApprovedBy(approderId){...}
Bid(bidderId){...}
Direct(directorId,directeeId){...}

How should I apply the rest of ubiquitous language to the context?
Should I skip Users in this context or create classes for employee, employer, and approver and make for example the the Approve method internal so that limit the app layer only be able to approve a project through an Approver class like the following?
class Approver{
    approverId _id
    public Approver(approverId id){
        _id = id
    }
    public Approve(project){
       project.ApprovedBy(_id);
    }
}

Update:
Here are some comments Iv'e written on answers that may make the question clearer:
Approver is a role that defined in Identity and Access BC, and the only thing should match is it's role name.Bidder should had filled out some additional data than a regular member to be able to bid a project. I wanted to use a saga and listen to events to check if the bidder is satisfied the rule, then the saga sends AddRole() or RemoveRole() to I&A BC. I thought this way I have a more cohesive I&A concern which is separated from the rest of the system but when I was designing the Project BC I thought why do not call something like factories.Employer(employerId).DefineProject(..)
BUT
I'm worrying about is future features that would grow after the initial release.They may expect more rules for the Employer for example,and as I started add them to the BC,I'll have to break my tests to avoid the Project from leaking the responsibilities of the Employer,for example I should no more be able to call DefineProject() as a static factory (or constructor),and the only way of defining a project should be calling Employer.DefineProject();and I feel the natural place that the Approvement should be concerned is the Approver class.Do you think I'm over engineering?
One of reasons that we encapsulate everything even identities in another object in ddd is taking care of the change of requirements independently by defining explicit contracts between objects and letting them change their internal implementations in another context.The PO doesn't care much about identities but he explicitly talks about roles and their rules.That can affect my tests and service layer codes later. Shouldn't I take care of roles at least as much as identities? Or I misunderstood something about boundaries and contracts?
Can explicit abstract role contracts act as a potential anti corruption layer interface which can keep me away from breaking the OCP?

A: I wouldn't model the operations on the actors because the natural home for operations are aggregates. However, you could get role security checks for free and have a strong alignment with your Ubiquitous Language if you model the roles explicitely. The explicit roles would become part of the anti-curruption layer and the classes could be instantiated by a service that abstracts away the integration with your Idendity & Access BC.
E.g.
Approver approver = actorService.approverOfId(userId);
project.markAsApprovedBy(approver);

This approach is discussed in Vaughn Vernon's IDDD book and blog post.

A: Unless there is business logic that would be better represented by having separate classes, I wouldn't bother creating Approver, Director and Bidder classes. It sounds like this context doesn't need to know anything other than the ids associated with them. So just keep it simple with the model you currently have.
This advice would probably change if you had a situation, say where an Approver or a Director had other details that determined their permission to do certain actions. For example, take StackOverflow - maybe a User needs a certain amount of reputation to be an Approver, or maybe Directing between two members needed other business rules applying to make to a valid transfer. These sort of scenarios might be better modelled as classes.

A: I don't know how you have defined your contexts but I'll try to give a reasonable answer regardless.

*

*All your requirements have the <ROLE> being able to do something.

*That tells me that you need a <ROLE> aggregate for your code to match the language in your requirements (for you to create a proper ubiquitous language)

*My answers assume an aggregate for the roles.

*You can ofcourse redesign a little and make things cleaner by using inheritance or other patterns that augment your code but I am not tackling any of those here

Let's take your requirements one at a time:
A project can be defined by an employer
It sounds like a project can ONLY be defined by an employer. In which case, you do need to be able to tell whether your current user is an employer or not.
There are a few questions here but one of hte bigger ones is:
Where do you validate to make sure the user is an employer?
Your factory method.
So:
ProjectFactory.Create(User: Employer)
I generally prefer to use a factory method that's part of an aggregate.
Something like:
Employer.createProject(someProject: Project) This lends itself well to the Ubiquitous language because an employer is Creating a project.
class Employer{
    Project[] projects{get; private set;}
    //you can also pass primitives as parameters so the consumer doesn't
    //need to bother with knowing how to create a project.
    //furthermore, you could use a factory to get just the project
    Project createProject(someProject: Project)
}

An approver should approve the project
Approver.approve(someProject: Project) This also lends itself well to the ubiquitous language. The interesting thing is how will you save this state? In the previous example about creating projects, it's easy to come to the conclusion that Employer will have a collection of projects and createProject will add to that collection. In this case, What will your method actually be doing? I think it makes sense to have your method modifying state in the specific project. Approver will serve as an aggregate and Projects are value members.
Then an employee can bid that project.
This could be done as a bid service or as a method in the User Aggregates like the ones above. Which one makes sense depends on your specific requirements and your specific usecase. If the bid is supposed to be persisted to a datastore as soon as it's made then you want to consider a service. If the bid can be persisted at the same time as the aggregate, then a method in your aggregate is fine.
A project can be directed by a member (= an employer or an employee) to another member.
This sounds like a service to me.
TransferService(proj: Project, User1: User, User2: User) This fits better because in a lot of cases there are complex rules governing things like transfer that the user aggregates don't know or care about.

A: My opinion:
Remember that your model is only a representation that is useful for your context (set of requirements). If your requirements change it's only natural that your model will evolve. So, a test breaking is a good thing. I understand that you want to anticipate change but do not overthink it too much. Maybe the business will just be happy with Role Based Access control.
How about instead of using "Approver" in your "IAM BC" you introduce the "Project Member" or "Team Member" concept in your "Project BC". The member is a role that a Party (employer, employee, and approver) plays within the project context:
ApprovedBy(memberId){...}
Bid(memberId){...}
Direct(directorId,directeeId){...}

Like this your project only needs to know about members. Or the other way around. your parties only need to know about the roles they play. So Project and your parties are decoupled. Also, one Employee can play multiple roles on projects (as a team member).
You might need to integrate (anti-corruption layer?) between "Identity and Access BC" and "Project BC" in case your roles change which might impact your project/project members.


text:
Q: How to get the Base Url in Twig I am using twig in Node+express. How can I get the base url in twig file ?
I've tried the following 2 snippets:
{{ app.request.schemeAndHttpHost ~ app.request.requestUri }}

{{path()}}

A: You could use the baseUrl attribute
{{ app.request.baseUrl }}

usually used with the scheme and host:
{{ app.request.schemeAndHttpHost ~ app.request.baseUrl }}

Hope this help

A: I think npm twig package haven't any base URL common method(I have checked) so you need to pass it from your controller or route as per the following.
Route(route.js)
router.get('/twig', function (req, res) {
    res.render('index.twig', {
        message: "Hello World",
        baseUrl: req.protocol + '://' + req.get('host') + req.originalUrl
    });
});

views/index.twig
Base URL : <b>{{ baseUrl }}</b>


text:
Q: PHP Find All (somewhat) Unique Combinations of an Array I've been looking at PHP array permutation / combination questions all day.. and still can't figure it out :/
If I have an array like:
20 //key being 0
20 //key being 1
22 //key being 2
24 //key being 3

I need combinations like:
20, 20, 22 //keys being 0 1 2
20, 20, 24 //keys being 0 1 3
20, 22, 24 //keys being 0 2 3
20, 22, 24 //keys being 1 2 3

The code I currently have gives me:
20, 22, 24

because it doesn't want to repeat 20... but that's what I need!
Here is the code I have. it is directly from Php recursion to get all possibilities of strings
function getCombinations($base,$n){

$baselen = count($base);
if($baselen == 0){
    return;
}
    if($n == 1){
        $return = array();
        foreach($base as $b){
            $return[] = array($b);
        }
        return $return;
    }else{
        //get one level lower combinations
        $oneLevelLower = getCombinations($base,$n-1);

        //for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add
        $newCombs = array();

        foreach($oneLevelLower as $oll){

            $lastEl = $oll[$n-2];
            $found = false;
            foreach($base as  $key => $b){
                if($b == $lastEl){
                    $found = true;
                    continue;
                    //last element found

                }
                if($found == true){
                        //add to combinations with last element
                        if($key < $baselen){

                            $tmp = $oll;
                            $newCombination = array_slice($tmp,0);
                            $newCombination[]=$b;
                            $newCombs[] = array_slice($newCombination,0);
                        }

                }
            }

        }

    }

    return $newCombs;

}

I've been playing around with the ($b == $lastEl) line, with no luck
===============
Questions I've already looked at, and are not the same OR that created an out of memory error!:

*

*How can I get all permutations in PHP without sequential duplicates?

*Permutations - all possible sets of numbers

*Combinations, Dispositions and Permutations in PHP

*PHP array combinations

*Get all permutations of a PHP array?

*PHP: How to get all possible combinations of 1D array?

*Select only unique array values from this array

*Get all permutations of a PHP array?

*PHP: How to get all possible combinations of 1D array?

*Select only unique array values from this array

*How can I get all permutations in PHP without sequential duplicates?

*Algorithm to return all combinations of k elements from n

*Find combination(s) sum of element(s) in array whose sum equal to a given number

*Combinations, Dispositions and Permutations in PHP

*PHP array combinations

*Php recursion to get all possibilities of strings

*How to return permutations of an array in PHP?

*Permutations - all possible sets of numbers

*Subset-sum problem in PHP with MySQL

*Find unique combinations of values from arrays filtering out any duplicate pairs

*Finding all the unique permutations of a string without generating duplicates

*Generate all unique permutations

*Subset sum for exactly k integers?
I've tried some of these algorithms with an array of 12 items, and end up running out of memory. However the algorithm that I'm currently using doesn't give me an out of memory error.... BUT.. I need those duplicates!

A: The pear package Math_Combinatorics makes this kind of problem fairly easy. It takes relatively little code, it's simple and straightforward, and it's pretty easy to read.
$ cat code/php/test.php
<?php
$input = array(20, 20, 22, 24);

require_once 'Math/Combinatorics.php';

$c = new Math_Combinatorics;
$combinations = $c->combinations($input, 3);
for ($i = 0; $i < count($combinations); $i++) {
  $vals = array_values($combinations[$i]);
  $s = implode($vals, ", ");
  print $s . "\n";
}
?>

$ php code/php/test.php
20, 20, 22
20, 20, 24
20, 22, 24
20, 22, 24

If I had to package this as a function, I'd do something like this.
function combinations($arr, $num_at_a_time)
{
    include_once 'Math/Combinatorics.php';

    if (count($arr) < $num_at_a_time) {
        $arr_count = count($arr);
        trigger_error(
            "Cannot take $arr_count elements $num_at_a_time "
            ."at a time.", E_USER_ERROR
        );
    }

    $c = new Math_Combinatorics;
    $combinations = $c->combinations($arr, $num_at_a_time);

    $return = array();
    for ($i = 0; $i < count($combinations); $i++) {
        $values = array_values($combinations[$i]);
        $return[$i] = $values;
    }
    return $return;
}

That will return an array of arrays. To get the text . . .
<?php
  include_once('combinations.php');

  $input = array(20, 20, 22, 24);
  $output = combinations($input, 3);

  foreach ($output as $row) {
      print implode($row, ", ").PHP_EOL;
  }
?>
20, 20, 22
20, 20, 24
20, 22, 24
20, 22, 24

A: Why not just use binary? At least then its simple and very easy to understand what each line of code does like this? Here's a function i wrote for myself in a project which i think is pretty neat!
function search_get_combos($array){
$bits = count($array); //bits of binary number equal to number of words in query;
//Convert decimal number to binary with set number of bits, and split into array
$dec = 1;
$binary = str_split(str_pad(decbin($dec), $bits, '0', STR_PAD_LEFT));
while($dec < pow(2, $bits)) {
    //Each 'word' is linked to a bit of the binary number.
    //Whenever the bit is '1' its added to the current term.
    $curterm = "";
    $i = 0;
    while($i < ($bits)){
        if($binary[$i] == 1) {
            $curterm[] = $array[$i]." ";
        }
        $i++;
    }
    $terms[] = $curterm;
    //Count up by 1
    $dec++;
    $binary = str_split(str_pad(decbin($dec), $bits, '0', STR_PAD_LEFT));
}
return $terms;
}

For your example, this outputs:
Array
(
    [0] => Array
        (
            [0] => 24
        )
    [1] => Array
        (
            [0] => 22
        )
    [2] => Array
        (
            [0] => 22
            [1] => 24
        )
    [3] => Array
        (
            [0] => 20
        )
    [4] => Array
        (
            [0] => 20
            [1] => 24
        )
    [5] => Array
        (
            [0] => 20
            [1] => 22
        )
    [6] => Array
        (
            [0] => 20
            [1] => 22
            [2] => 24
        )
    [7] => Array
        (
            [0] => 20
        )
    [8] => Array
        (
            [0] => 20
            [1] => 24
        )
    [9] => Array
        (
            [0] => 20
            [1] => 22
        )
    [10] => Array
        (
            [0] => 20
            [1] => 22
            [2] => 24
        )
    [11] => Array
        (
            [0] => 20
            [1] => 20
        )
    [12] => Array
        (
            [0] => 20
            [1] => 20
            [2] => 24
        )
    [13] => Array
        (
            [0] => 20
            [1] => 20
            [2] => 22
        )
    [14] => Array
        (
            [0] => 20
            [1] => 20
            [2] => 22
            [3] => 24
        )
)

A: If you don't mind using a couple of global variables, you could do this in PHP (translated from a version in JavaScript):
<?PHP
$result = array();
$combination = array();

function combinations(array $myArray, $choose) {
  global $result, $combination;

  $n = count($myArray);

  function inner ($start, $choose_, $arr, $n) {
    global $result, $combination;

    if ($choose_ == 0) array_push($result,$combination);
    else for ($i = $start; $i <= $n - $choose_; ++$i) {
           array_push($combination, $arr[$i]);
           inner($i + 1, $choose_ - 1, $arr, $n);
           array_pop($combination);
         }
  }
  inner(0, $choose, $myArray, $n);
  return $result;
}

print_r(combinations(array(20,20,22,24), 3));
?>

OUTPUT:
Array ( [0] => Array ( [0] => 20
                       [1] => 20
                       [2] => 22 )
        [1] => Array ( [0] => 20
                       [1] => 20
                       [2] => 24 )
        [2] => Array ( [0] => 20
                       [1] => 22
                       [2] => 24 )
        [3] => Array ( [0] => 20
                       [1] => 22
                       [2] => 24 ) )

A: Had the same problem and found a different and bitwise, faster solution:
function bitprint($u) {
    $s = array();
    for ($n=0; $u; $n++, $u >>= 1){
        if ($u&1){
            $s [] = $n;
        }
    }
    return $s;
}
function bitcount($u) {
    for ($n=0; $u; $n++, $u = $u&($u-1));
    return $n;
}
function comb($c,$n) {
    $s = array();
    for ($u=0; $u<1<<$n; $u++){
        if (bitcount($u) == $c){
            $s [] = bitprint($u);
        }
    }
    return $s;
}

This one generates all size m combinations of the integers from 0 to n-1, so for example
m = 2, n = 3 and calling comb(2, 3) will produce:
0 1
0 2
1 2

It gives you index positions, so it's easy to point to array elements by index.
Edit: Fails with input comb(30, 5). Have no idea why, anyone any idea?

A: Cleaned up Adi Bradfield's sugestion using strrev and for/foreach loops, and only get unique results.
function search_get_combos($array = array()) {
sort($array);
$terms = array();

for ($dec = 1; $dec < pow(2, count($array)); $dec++) {
    $curterm = array();
    foreach (str_split(strrev(decbin($dec))) as $i => $bit) {
        if ($bit) {
            $curterm[] = $array[$i];
        }
    }
    if (!in_array($curterm, $terms)) {
        $terms[] = $curterm;
    }
}

return $terms;
}

A: The Idea is simple. Suppose you know how to permute, then if you save these permutations in a set it becomes a combinations. Set by definition takes care of the duplicate values. The Php euqivalent of Set or HashSet is SplObjectStorage and ArrayList is Array. It should not be hard to rewrite. I have an implementation in Java:
public static HashSet<ArrayList<Integer>> permuteWithoutDuplicate(ArrayList<Integer> input){
          if(input.size()==1){
              HashSet<ArrayList<Integer>> b=new HashSet<ArrayList<Integer>>();
              b.add(input);
              return b;
          }
          HashSet<ArrayList<Integer>>ret= new HashSet<ArrayList<Integer>>();
          int len=input.size();
          for(int i=0;i<len;i++){
              Integer a = input.remove(i);
              HashSet<ArrayList<Integer>>temp=permuteWithoutDuplicate(new ArrayList<Integer>(input));
              for(ArrayList<Integer> t:temp)
                  t.add(a);
              ret.addAll(temp);
              input.add(i, a);
          }
          return ret;
      }


text:
Q: Android Gradle running task before building I've got this task into build.gradle
apply plugin: 'checkstyle'

task checkstyle(type: Checkstyle) {
    // Cleaning the old log because of the creation for the new ones
    delete fileTree(dir: "${project.rootDir}/app/build/reports")
    source 'src'
    include '**/*.java'
    exclude '**/gen/**'
    // empty classpath
    classpath = files()
    //Do not fail build
    ignoreFailures = false
}

I want this to run automatically when i try to build the app and if finds  errors to fail the build. I'm not sure how and where to call the task.

A: project.afterEvaluate{
    assembleAcceptanceDebug.dependsOn("checkstyle")
}

This is what's finally worked. I found the task name when i click to run the app then the problem was that this task does not exists before Evaluate so that was the problem. Now it's working. Thank you and thanks to this https://discuss.gradle.org/t/how-to-define-a-preprocessing-task-for-android-build/6147


text:
Q: ADF Pipeline to Split an a JSON File with array of objects into seperate items in cosmos db I am creating a pipeline for the first time. The requirement is to fetch a JSON file with an array of objects. Split the array and save each object as a separate item in the cosmos DB.
In pipeline I am using CopyData Activity. And providing the source as JSON File and using cosmos db dataset in Sink.
I am stuck with mapping the data. Since I have given the [0] array. All the values in db gets saved with same value. I am not sure how to map the value dynamically. Can someone assist if I there is a way to map dynamically based on the number of objects in the array. Or if I can use any other Activities.
Below is the JSON Data format.
{
"d": {
    "results": [
        {
            "OrderDescription": "abc",
            "SalesManager": "abc",
            "ProjectCoordinator": "",
            "CustomerNumber": "",
            "CustomerName": "",
            "CustomerStreetAddress": "",
            "CustomerCity": "",
            "CustomerState": "",
            "CustomerZiip": "",
            "FacilityName": "",
            "ShipToNumber": "",
            "ShipToName": ""
        },
        {
            "OrderDescription": "abc",
            "SalesManager": "abc",
            "ProjectCoordinator": "",
            "CustomerNumber": "",
            "CustomerName": "",
            "CustomerStreetAddress": "",
            "CustomerCity": "",
            "CustomerState": "",
            "CustomerZiip": "",
            "FacilityName": "",
            "ShipToNumber": "",
            "ShipToName": ""
        },
        {
            "OrderDescription": "abc",
            "SalesManager": "abc",
            "ProjectCoordinator": "",
            "CustomerNumber": "",
            "CustomerName": "",
            "CustomerStreetAddress": "",
            "CustomerCity": "",
            "CustomerState": "",
            "CustomerZiip": "",
            "FacilityName": "",
            "ShipToNumber": "",
            "ShipToName": ""
        }
    ]
}

}

A: I found solution for the above question. Hope it helps someone.
Made few changes in the way of mapping.


text:
Q: Group by Hour for Epoch time I need to group by Hour for converted epoch time, here is what I have done but it is still grouping by the day. Can anyone support?
 select count (*) as "Total",to_char(trunc(to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME),'DD/MM/YYYY HH24') as "Day"
from Records
where ID=35 and (INSERTION_TIME/86400)+ to_date('01-01-1970 00:00:00','dd-mm-yyyy HH24:MI:SS') >=sysdate - 4
group by trunc(to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME)
order by trunc(to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME)

A: You can get rid of most of the arithmetic and just use:
SELECT COUNT(*) as "Total",
       TO_CHAR(
         TRUNC(DATE '1970-01-01' + INTERVAL '1' SECOND * INSERTION_TIME, 'HH'),
         'DD/MM/YYYY HH24'
       ) as "Day"
FROM   Records
WHERE  ID=35
AND    DATE '1970-01-01' + INTERVAL '1' SECOND * INSERTION_TIME >=sysdate - 4
GROUP BY
       TRUNC(DATE '1970-01-01' + INTERVAL '1' SECOND * INSERTION_TIME, 'HH')
ORDER BY
       TRUNC(DATE '1970-01-01' + INTERVAL '1' SECOND * INSERTION_TIME, 'HH')

Note: Epoch time is usually 1970-01-01 00:00:00 UTC. If your session time zone is not UTC then you may be calculating the epoch time incorrectly and would want to use timestamps instead:
SELECT COUNT(*) as "Total",
       TO_CHAR(
         TRUNC(
           TIMESTAMP '1970-01-01 00:00:00 UTC' + INTERVAL '1' SECOND * INSERTION_TIME,
           'HH'
         ),
         'DD/MM/YYYY HH24'
       ) as "Day"
FROM   Records
WHERE  ID=35
AND    TIMESTAMP '1970-01-01 00:00:00 UTC' + INTERVAL '1' SECOND * INSERTION_TIME
         >=SYSTIMESTAMP - INTERVAL '4' DAY
GROUP BY
       TRUNC(
         TIMESTAMP '1970-01-01 00:00:00 UTC' + INTERVAL '1' SECOND * INSERTION_TIME,
         'HH'
       )
ORDER BY
       TRUNC(
         TIMESTAMP '1970-01-01 00:00:00 UTC' + INTERVAL '1' SECOND * INSERTION_TIME,
         'HH'
       )

A: Notice the behavior of trunc on your expression.  It removes the hour component.
Test case with dbfiddle.uk:
Test case
The ungrouped SQL, with extra expression in select list:
select to_char(trunc(to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME),'DD/MM/YYYY HH24') as "Day"
     , to_char(     (to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME),'DD/MM/YYYY HH24') as "Day"
  from Records
 where ID = 35 and (INSERTION_TIME/86400) + to_date('01-01-1970 00:00:00','dd-mm-yyyy HH24:MI:SS') >= sysdate - 4
   AND rownum < 6
 order by      (to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME)
;

The ungrouped result:

Now add the GROUP BY:
select COUNT(*) AS n
     , to_char(trunc(to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME),'DD/MM/YYYY HH24') as "Day"
     , to_char(     (to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME),'DD/MM/YYYY HH24') as "Day"
  from Records
 where ID = 35 and (INSERTION_TIME/86400) + to_date('01-01-1970 00:00:00','dd-mm-yyyy HH24:MI:SS') >= sysdate - 4
 group by      (to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME)
 order by      (to_date('19700101 00', 'YYYYMMDD HH24') + ( 1 / 24 / 60 / 60 ) * INSERTION_TIME)
;

The grouped result:

To create a test case:
CREATE TABLE Records (
    id              int
  , insertion_time  int
);

INSERT INTO Records VALUES (35, 4011134567);
INSERT INTO Records VALUES (35, 4011134567);
INSERT INTO Records VALUES (35, 4011134567);
INSERT INTO Records VALUES (35, 4011134567);


text:
Q: How can I get the corret date using the function strtotime in php? I have this function in php:
private function setInfoTareasDiarias($aDataTarea,$idUsu,$seccion){

        print_r($aDataTarea['fecha']);
        $date=date("Y/m/d 00:00:00", strtotime($aDataTarea['fecha']));
        $aData['porcentaje']=$aDataTarea['porcentaje'];
        $aData['fecha_termino']=$date;
        $aData['descripcion']=$aDataTarea['descripcion'];
        $aData['id_tarea']=$aDataTarea["idTarea"];
        $aData['id_seccion']=$seccion;

        $this->aDatosInfoTareasDiarias[]=$aData;

        print_r($this->aDatosInfoTareasDiarias);
    }

print_r($aDataTarea['fecha']); print this format:
example: 2015/06/9
With $date=date("Y/m/d 00:00:00", strtotime($aDataTarea['fecha']));
and
$aData['fecha_termino']=$date;

I need print :

[fecha_termino] => 2015/06/09 00:00:00

But print:

[fecha_termino] => 1969/12/31 00:00:00

(I need always 00:00:00)
How can I fix this?

A: You need to specify hours, minutes and seconds as H:i:s, like this:
$date = date("Y/m/d H:i:s", strtotime($aDataTarea['fecha'], mktime(0, 0, 0)));

The reason you are getting 1969/12/31 00:00:00 as the result is because this is the default unix timestamp, which basically means there is an error when you try to generate a date from your given timestamp. Try the H:i:s format shown above and this should work for you now.


text:
Q: Why am I getting this ElasticSearch error on startup? Sometimes when I spool up my machine with ES 8.0.1 installed, the ES service fails to start and there is an error from Java about a missing classname with the name of the current date. Eg "2022-05-01". What could be happening here?
This is the only information from journalctl:
Starting Elasticsearch...
Apr 27 00:15:05 systemd-entrypoint[2791]: Error: Could not find or load main class 2022-04-27
Apr 27 00:15:05 systemd[1]: elasticsearch.service: main process exited, code=exited, status=1/FAILURE
Apr 27 00:15:05 systemd[1]: Failed to start Elasticsearch.
Apr 27 00:15:05 systemd[1]: Unit elasticsearch.service entered failed state.
Apr 27 00:15:05 systemd[1]: elasticsearch.service failed.


text:
Q: How may I bind more than one path value to a label's text property? Working in Visual Studio 2017 with C# on an Xamarin.Forms application, I have the following line within the creation of a ListView. Each item in the ListView is represented by one Label. I set each label's text property to that item's 'Number' value. It is working as when viewing the list while running.
label.SetBinding(Label.TextProperty, "Number");

Along with the 'Number' value, each item in the list has a 'SecondNumber' value. How may I bind the 'Number' value, a hyphen, and the 'SecondNumber' value to the each label's text property?
I've tried the following without success:
label.SetBinding(Label.TextProperty, "Number" + "-" + "SecondNumber");

A: You can add a combined value property to your object. This way, you can use it anywhere in your application.
public string Numbers{
    get {return this.Number + "-" + this.SecondNumber;}
}


text:
Q: How to open folder in new vs code instance by right clicking on the folder in the existing vs code instance? I have open two folders inside a VS Code instance.
For example (folder name): A and B
I want to open the folder B in a new instance of VS Code, but there is no option to open by right-clicking on the folder.

Even Atom has the option to open the folder in a new instance.

A: Let's make it very simple

*

*In vscode , Go to Files --> New Window, as shown in the image below. This will open a blank vscode window, where we will open new project.

*Drag the project folder and drop it into the vscode. as shown in the below image

That's it. New blank window has the new project opened.
Another way is discussed below

*

*Go to Folder URL which you want to open in the vscode. On the file location, type in the URL  cmd

*cmd prompt will open with the folder URL.

*In the cmd prompt, type code .

*Your folder will open in the new vscode window.

A: This extension allows you to open a folder in a new vscode window.
Open Folder Context Menus for VS Code

A: You can go via File > New window or ctrl+shift+n for a new window, and open the second folder there.
Or the "window.openFoldersInNewWindow" setting:
// Controls if folders should open in a new window or replace the last active window.
// - default: folders will open in a new window unless a folder is picked from within the application (e.g. via the File menu)
// - on: folders will open in a new window
// - off: folders will replace the last active window
// Note that there can still be cases where this setting is ignored (e.g. when using the -new-window or -reuse-window command line option).
"window.openFoldersInNewWindow": "default",

A: Create a registry File e.g. OpenOnRightClick.reg
Add these lines to the file:
Windows Registry Editor Version 5.00
; Open files
[HKEY_CLASSES_ROOT\*\shell\Open with VS Code]
@="Edit with VS Code"
"Icon"="C:\\Users\\xx\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe,0"
[HKEY_CLASSES_ROOT\*\shell\Open with VS Code\command]
@="\"C:\\Users\\xx\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe\" \"%1\""
; This will make it appear when you right click ON a folder
; The "Icon" line can be removed if you don't want the icon to appear
[HKEY_CLASSES_ROOT\Directory\shell\vscode]
@="Open Folder as VS Code Project"
"Icon"="\"C:\\Users\\xx\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe\",0"
[HKEY_CLASSES_ROOT\Directory\shell\vscode\command]
@="\"C:\\Users\\xx\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe\" \"%1\""
; This will make it appear when you right click INSIDE a folder
; The "Icon" line can be removed if you don't want the icon to appear
[HKEY_CLASSES_ROOT\Directory\Background\shell\vscode]
@="Open Folder as VS Code Project"
"Icon"="\"C:\\Users\\xx\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe\",0"
[HKEY_CLASSES_ROOT\Directory\Background\shell\vscode\command]
@="\"C:\\Users\\xx\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe\" \"%V\""

Change the location of visual studio code as per your installation directory
Now just double click on the OpenOnRightClick.reg file, confirm if asked !
All done ! on you right click you will have a open with Code option.

A: I also wanted that feature in my editor so I saved my settings and preferences and then I reinstalled VS Code in order to check the box that adds "Open with Code" as action in the context menu:
example

A: This is not the way it is asked in the question, but doing the same things in another way.
In windows, there is a simple way to open the folder in visual studio.
If you are in any folder just type cmd on top and press enter key, It will open the command prompt.

Then type code . and press enter. It will open the visual studio code with the current folder.


text:
Q: External HDD accidentally unlocked from launcher In Ubuntu 14.04 I accidentally unlocked from launcher my external HDD.
How can I have it back there?
Thank you in advance

A: when you connect your external hard drive open dash and type the drives names(partitions names of your external harddrive) then drag that drive to launcher


text:
Q: QT Unit Testing moc "unresolved external symbol" for QMetaObject I'm trying to add unit tests to a project of mine for the first time.
I can run mock tests alright (without using my project's classes) and run the application alright. But if I instantiate objects from the project I get an unresolved external symbol of the QMetaObject. If I recall correctly, this means the moc of the object isn't being included on the project.
How do I fix this? I have the same issue using googletests. The guide also doesn't help on this. I've tried installing the qt unit testing plugin, same result.
I've uploaded a mock project that follows the same structure that I'm using in the aforementioned project, fetch it here: https://github.com/quimnuss/QtUnitTestingTest
I'm using a static build of qt on windows, but I guess that's irrellevant. Using QtCreator as IDE and NMAke build.
I've also tried add the HelloWorld.lib, but taking a look at the Makefile.release it isn't used.
Somebody has an idea of what I'm doing wrong?
Here's the unit testing .pro:
QT       += widgets network testlib

TARGET = tst_someunittesttest
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

INCLUDEPATH += $$PWD/../HelloWorld

include($$PWD/../HelloWorld/helloworldCommon.pri)

LIBS += -L"$$OUT_PWD/../HelloWorld/release"
LIBS += -lHelloWorld

message("Searching libs here $$LIBS")

SOURCES += tst_someunittesttest.cpp
DEFINES += SRCDIR=\\\"$$PWD/\\\"

The first error's complete message:
tst_someunittesttest.obj : error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __cdecl HelloWorld::metaObject(void)const " (?metaObject@HelloWorld@@UEBAPEBUQMetaObject@@XZ)

A: When you use the following flags:
LIBS += -L"$$OUT_PWD/../HelloWorld/release"
LIBS += -lHelloWorld

You must have the compiled dynamic or static library. Therefore you must create a project generating a library. In the next part I show you how to create a dynamic library.
HelloWorldLib.pro
#-------------------------------------------------
#
# Project created by QtCreator 2017-01-06T12:37:49
#
#-------------------------------------------------

QT       -= gui

TARGET = HelloWorldLib
TEMPLATE = lib

DEFINES += HELLOWORLDLIB_LIBRARY

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

INCLUDEPATH += $$PWD/include

SOURCES += src/helloworldlib.cpp

HEADERS += include/helloworldlib.h\
        include/helloworldlib_global.h

unix {
    target.path = /usr/lib
    INSTALLS += target
}

DESTDIR = $$PWD/lib

include/helloworldlib.h
#ifndef HELLOWORLDLIB_H
#define HELLOWORLDLIB_H

#include "helloworldlib_global.h"

#include <QDebug>

class HELLOWORLDLIBSHARED_EXPORT HelloWorldLib: public QObject
{
    Q_OBJECT

public:
    HelloWorldLib(){

    }
    static bool returnTrue()
    {
        return true;
    }

public slots:
    void someSlot()
    {
        qDebug() << "test";
    }
};

#endif // HELLOWORLDLIB_H

include/helloworldlib_global.h
#ifndef HELLOWORLDLIB_GLOBAL_H
#define HELLOWORLDLIB_GLOBAL_H

#include <QtCore/qglobal.h>

#if defined(HELLOWORLDLIB_LIBRARY)
#  define HELLOWORLDLIBSHARED_EXPORT Q_DECL_EXPORT
#else
#  define HELLOWORLDLIBSHARED_EXPORT Q_DECL_IMPORT
#endif

#endif // HELLOWORLDLIB_GLOBAL_H

src/helloworldlib.cpp
#include "helloworldlib.h"

Here I show the test project.
HelloWorldTest.pro
#-------------------------------------------------
#
# Project created by QtCreator 2017-01-06T12:42:42
#
#-------------------------------------------------

QT += testlib
QT -= gui

# greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = tst_helloworldtesttest
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += tst_helloworldtesttest.cpp
DEFINES += SRCDIR=\\\"$$PWD/\\\"

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../HelloWorldLib/lib/release/ -lHelloWorldLib
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../HelloWorldLib/lib/debug/ -lHelloWorldLib
else:unix: LIBS += -L$$PWD/../HelloWorldLib/lib/ -lHelloWorldLib

INCLUDEPATH += $$PWD/../HelloWorldLib/include
DEPENDPATH += $$PWD/../HelloWorldLib/include

tst_helloworldtesttest.cpp
#include <QString>
#include <QtTest>

#include <helloworldlib.h>

#include <QDebug>

class HelloWorldTestTest : public QObject
{
    Q_OBJECT

public:
    HelloWorldTestTest();

private Q_SLOTS:
    void testCase1_data();
    void testCase1();
};

HelloWorldTestTest::HelloWorldTestTest()
{
}

void HelloWorldTestTest::testCase1_data()
{
    QTest::addColumn<QString>("data");
    QTest::newRow("0") << QString();
}

void HelloWorldTestTest::testCase1()
{
    QFETCH(QString, data);
    QVERIFY2(true, "Failure");

    HelloWorldLib hw;
    QVERIFY(hw.returnTrue());

}

QTEST_APPLESS_MAIN(HelloWorldTestTest)

#include "tst_helloworldtesttest.moc"

Output:
********* Start testing of HelloWorldTestTest *********
Config: Using QtTest library 5.7.1, Qt 5.7.1 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 6.2.1 20160830)
PASS   : HelloWorldTestTest::initTestCase()
PASS   : HelloWorldTestTest::testCase1(0)
PASS   : HelloWorldTestTest::cleanupTestCase()
Totals: 3 passed, 0 failed, 0 skipped, 0 blacklisted, 0ms
********* Finished testing of HelloWorldTestTest *********

In the following link is the complete project: https://github.com/eyllanesc/stackoverflow/tree/master/QtUnitTestingTest


text:
Q: Lazy initialized objects are always created In some case my broadcast receiver is not required and so need to check if the receiver is null or not but somehow this object is not null even if not using it and causing crash.

private val myBroadCastReceiver by lazy {
   MyBroadcastReceiver()
}
if(myBroadCastReceiver != null) unregisterReceiver(myBroadCastReceiver)

A: when you are trying null check, its initialised and thus it not null. Try this this instead of lazy.
private var myBroadCastReceiver : MyBroadcastReceiver? = null

or try this answer
Kotlin: Check if lazy val has been initialised

A: Because you declare myBroadcastReceiver as Lazy, that means that you won't use it until you call MyBroadcastReceiver(). Which you do in your if statement.
So if you check it that way, it won't be null, because you actually execute MyBroadcastReceiver() here if(myBroadCastReceiver...)


text:
Q: iPhone Sdk: Is it possible to add an UIImageView as a file? i was just wondering wether it is possible to add an uiimageview as a .m and .h class file because you can just choose a subclass from uiview or uitableviewcell in apple's templates and it than automatically creates the .m and .h files.
Is there a way to do the same for an UIImageView or is it possible to somehow "turn" the UIView into an imageview?
thanks in advance!

A: You could create you own subclass of UIImageView, yes. And if you're very brave, you could also create your own subclass of UIView as well, that would take a UIImage and paint that in it's -(void)drawRect: method. Then it would be much like a UIImageView.
But, why would you?
edit subclassing UIImageView is easiest by starting with the UIView subclass template, and then just replacing the word UIView with UIImageView, so you get:
@interface UIImageViewPlus : UIImageView {
    // ...
}

That's all there is to it, now just use UIImageViewPlus wherever you would use UIImageView.

A: UIImageView is a UIView since it inherits directly from UIView so I'm not sure what you are asking about.....you can easily create a subclass of the UIImageView to do whatever customization you require....


text:
Q: Why Are Some Closures 'Friendlier' Than Others? Let me apologize in advance - I'm probably butchering the terminology.  I have a vague understanding of what a closure is, but can't explain the behaviour I'm seeing.  At least, I think it's a closure issue.  I've searched online, but haven't found the right keywords to get what I want.
Specifically - I have two blocks of code that are REALLY SIMILAR (at least to my eyes).  First:
static void Main(string[] args)
{
    Action x1 = GetWorker(0);
    Action x2 = GetWorker(1);
}

static Action GetWorker(int k)
{
    int count = 0;

    // Each Action delegate has it's own 'captured' count variable
    return k == 0 ? (Action)(() => Console.WriteLine("Working 1 - {0}",count++))
                  : (Action)(() => Console.WriteLine("Working 2 - {0}",count++));
}

If you run this code and invoke x1() and x2() you'll see that they maintain a separate 'count' value.
    foreach(var i in Enumerable.Range(0,4))
    {
        x1(); x2();
    }

Outputs:
Working 1 - 0
Working 2 - 0
Working 1 - 1
Working 2 - 1
Working 1 - 2
Working 2 - 2
Working 1 - 3
Working 2 - 3

That makes sense to me and matches the explanations I've read.  Behind the scenes a class is created for each delegate/action and the class is given a field to hold the value of 'count'.  I went to bed feeling smart!
BUT THEN - I tried this very similar code:
    // x3 and x4 *share* the same 'captured' count variable
    Action x3 = () => Console.WriteLine("Working 3 - {0}", count++);
    Action x4 = () => Console.WriteLine("Working 4 - {0}", count++);

And (like the comment says) the behavior is completely different here.  x3() and x4() seem to have the SAME count value!
Working 3 - 0
Working 4 - 1
Working 3 - 2
Working 4 - 3
Working 3 - 4
Working 4 - 5
Working 3 - 6
Working 4 - 7

I can see what's happening - but I don't really get why they are treated differently.  In my head - I liked that original behaviour I was seeing, but the later example confuses me.  I hope that makes sense.  Thanks

A: The difference is that in one example you have one delegate, the other you have two.
Since the count variable is local, it is regenerated each time you make the call. Since only one delegate is used (due to the ternary) each delegate gets a different copy of the variable. In the other example, both delegates get the same variable.
A ternary operator only returns one of its two arguments, so the closure works as you expect. In the second example, you create two closures that share the same "parent" count variable, giving the different result.
It might be a bit clearer if you look at it this way (this is equivalent code to your first sample):
static Action GetWorker(int k)
{
    int count = 0;
    Action returnDelegate

    // Each Action delegate has it's own 'captured' count variable
    if (k == 0)
         returnDelegate = (Action)(() => Console.WriteLine("Working 1 - {0}",count++));
    else
         returnDelegate = (Action)(() => Console.WriteLine("Working 2 - {0}",count++));

    return returnDelegate
}

Clearly there is only one closure generated here, and your other sample obviously has two.

A: Your first example had two different int count variable declarations (from the separate method calls). Your second example is sharing the same variable declaration.
Your first example would behave the same as the second example had int count been a field of your main program:
static int count = 0;

static Action GetWorker(int k)
{
    return k == 0 ? (Action)(() => Console.WriteLine("Working 1 - {0}",count++))
                  : (Action)(() => Console.WriteLine("Working 2 - {0}",count++));
}

This outputs:
Working 1 - 0
Working 2 - 1
Working 1 - 2
Working 2 - 3
Working 1 - 4
Working 2 - 5
Working 1 - 6
Working 2 - 7

You can simplify it without the ternary operator as well:
static Action GetWorker(int k)
{
    int count = 0;

    return (Action)(() => Console.WriteLine("Working {0} - {1}",k,count++));
}

Which outputs:
Working 1 - 0
Working 2 - 0
Working 1 - 1
Working 2 - 1
Working 1 - 2
Working 2 - 2
Working 1 - 3
Working 2 - 3

The main issue is that a local variable declared in a method (in your case int count = 0;) is unique for that invocation of the method, then when the lambda delegate is created, each one is applying closure around its own unique count variable:
Action x1 = GetWorker(0); //gets a count
Action x2 = GetWorker(1); //gets a new, different count

A: A closure captures a variable.
A local variable is created when a method is activated by being called. (There are other things that create local variables but let's ignore that for now.)
In your first example you have two activations of GetWorker and therefore two completely independent variables named count are created. Each is captured independently.
In your second example, which unfortunately you do not show all of, you have a single activation and two closures. The closures share the variable.
Here's a way to think about it that might help:
class Counter { public int count; }
...
Counter Example1()
{
    return new Counter();
}
...
Counter c1 = Example1();
Counter c2 = Example1();
c1.count += 1;
c2.count += 2;
// c1.count and c2.count are different.

Vs
void Example2()
{
    Counter c = new Counter();
    Counter x3 = c;
    Counter x4 = c;
    x3.count += 1;
    x4.count += 2;
    // x3.count and x4.count are the same.
}

Does it make sense to you why in the first example there are two variables called count that are not shared by multiple objects, and in the second there is only one, shared by multiple objects?

A: Another alternative (of what perhaps you were looking for):
static Action<int> GetWorker()
{
    int count = 0;

    return k => k == 0 ?
             Console.WriteLine("Working 1 - {0}",count++) :
             Console.WriteLine("Working 2 - {0}",count++);
}

Then:
var x = GetWorker();

foreach(var i in Enumerable.Range(0,4))
{
    x(0); x(1);
}

Or maybe:
var y = GetWorker();
// and now we refer to the same closure
Action x1 = () => y(0);
Action x2 = () => y(1);

foreach(var i in Enumerable.Range(0,4))
{
    x1(); x2();
}

Or maybe with some curry:
var f = GetWorker();
Func<int, Action> GetSameWorker = k => () => f(k);

//  k => () => GetWorker(k) will not work

Action z1 = GetSameWorker(0);
Action z2 = GetSameWorker(1);

foreach(var i in Enumerable.Range(0,4))
{
    z1(); z2();
}


text:
Q: add when article in another table I have table article:
arrtno     descr         unit   sales
  1        beer            1     10
  2        coke            1     12
  3        beer ct        12      5
  4        coke ct        12      7

and a table mutations
artno   mutation
  1         3
  2         4

I need to query sales for beer so it would be 1*10 + 12*5. So how to get mutation par from other table and add it to basic item.

A: try this
SELECT SUM(unit * sales) FROM article WHERE arrtno IN (
    SELECT mutation from mutations WHERE artno IN (
        SELECT arrtno FROM article WHERE descr = 'beer'
    )
    UNION
    SELECT arrtno FROM article WHERE descr = 'beer'
)

A: try this
SELECT b1.unit * b1.sales + b2.unit*b2.sales
 FROM beer b1, beer b2, mutation
 WHERE b1.artno = mutation.artno
 AND b2.artno = mutation.mutation


text:
Q: How to get 2 random rows per user_id from a mySQL table? I have a table that has many products from different user_id's. Like this:
product_id | user_id
01           20
02           20
03           20
04           20
05           32
06           32
07           53
08           53
09           53
10           84
11           84
etc.

I'm trying to get exactly 2 rows for each different user_id, sorted randomly.
The closest I got is with this query:
SELECT * FROM db_products ORDER BY user_id, RAND()

But that gives me every row sorted randomly, instead of 2 rows for each user_id sorted randomly.
I tried a LIMIT 2 but that shows only 2 rows total. What's the easiest way to achieve this?
Thank you so much for any help :)

A: The easiest way is probably to use variables:
select p.*
from (select p.*,
             (@rn := if(@u = user_id, @rn + 1,
                        if(@u := user_id, 1, 1)
                       )
             ) as rn
      from db_products p cross join
           (select @u := 0, @rn := 0) params
      order by user_id, rand()
     ) p
where rn <= 2;

There are other possibilities.  If your strings are unlikely to overflow and you want the products on a single row:
select user_id,
       substring_index(group_concat(product_id order by rand(), ',', 2)
from db_products
group by user_id;


text:
Q: jQuery UI Sortable: dragged element disappears I set the <div class="container"> .sortable(), and there are some elements in the container.
When I drag the inner element, intend to sort the element with the others, once the dragged one out the container, it can not be seen.
But when I drop it into place holder, it could be seen again. Online case is here.
Anyone have met the problem before? Or anyone can help me with the problem?
Thank you

A: My dragged items were disappearing in a vertical list and I found that using overflow-y: hidden instead of overflow:hidden worked for me. i.e. only target the y axis.

A: most probably the problem is due to this: .container{ margin:0 20px; position:absolute;top:0;height:100%;width:280px;overflow:hidden;}.
If you set overflow:auto it shows the wrapper div with scrollbar and you can view your portlet.

A: Drop the overflow: hidden; on .container and it will work. The problem is that during the drag you're moving a child of .container outside of the .container element, you've told the browser to hide any overflow while you're forcing an overflow during the drag and the browser is doing what you told it to do.
General advice: leave overflow alone unless you know what it does and why you need to use it.

A: the trick is to set helper to 'clone' and use a temporary swaplist for the drag.. modified version of your code here
$( ".selector" ).sortable({
    helper: "clone"
});