text:
Q: Clarification of definitions of function being a contraction in $L_{p}$ space This question arose from Durrett Theorem 4.1.4, as follows:

Conditional expectation is a contraction in $L^{p}$ space for $p\geq 1$.

This question has been addressed here: Contraction Property of Conditional Expectation, and it seems that a conditional expectation being a contraction in $L_{p}$ means that it satisfies $$\|\mathbb{E}(X|\mathcal{F}))\|_{p}\leq\|X\|_{p}.$$ but this definition seems not working in other cases. For instance, what it means by a random variable being a contraction in $L_{p}$?
From https://en.wikipedia.org/wiki/Contraction_(operator_theory), a bounded operator $T:X\longrightarrow Y$ between normed linear spaces $X$ and $Y$ means it satisfies $\|T\|_{Y}\leq 1$. So a random variable $X\in L_{p}(\Omega,\mathcal{F},\mathbb{P})$ being a contraction means it satisfies $\|X\|_{p}\leq 1$?
But from here:https://en.wikipedia.org/wiki/Contraction_mapping it seems that a map being contraction has another meaning.
Are these definitions equivalent or sort of related to each other or they are totally independent among each other?
The word contraction appears only once in Durrett, which is in this theorem. So I do need a general clarification of the definition of "contraction"
Please point it out if my question is not clear. Thank you so much!
Edit 1:
Thanks to "kimchi lover", now it is really clear. I edit this post to simply prove this statement and clarify everything for further readers.

[Contraction]. Given two normed linear space $V$ and $W$, a linear map $T:V\longrightarrow W$ is continuous if and only if there exists a real number $c$ such that $$\|T(v)\|_{W}\leq c\|v\|_{V},\ \text{for all}v\ \in V.$$
Then we define the operator norm of $T$ as $$\|T\|_{op}:=\inf\{c\geq 0:\|T(v)\|_{W}\leq c\|v\|_{V}\ \text{for all}v\ \in V\}.$$
An operator is said to be a contraction if $\|T\|_{op}\leq 1$.

[Refined Statement]. The operator of obtaining conditional expectation is a contraction in $L_{p}$ for $p\geq 1$

Proof: Let $(\Omega,\mathcal{F}_{0},\mathbb{P})$ be a probability space, $\mathcal{F}\subset\mathcal{F}_{0}$ a $\sigma-$algebra, we show that the operator $$T:L_{p}(\Omega,\mathcal{F},\mathbb{P})\longrightarrow L_{p}(\Omega,\mathcal{F},\mathbb{P})\ \text{defined by}$$ $$X\mapsto\mathbb{E}(X|\mathcal{F}),$$ is a contraction.
Firstly, the absolute value function $|\ \cdot\ |^{p}$ is convex for $p\geq 1$. Therefore, by Jensen we have $$\Big|\mathbb{E}(X|\mathcal{F})\Big|^{p}\leq\mathbb{E}(|X|^{p}|\mathcal{F}),$$ so taking expectation we have $$\mathbb{E}\Big|\mathbb{E}(X|\mathcal{F})\Big|^{p}\leq\mathbb{E}\Big(\mathbb{E}(|X|^{p}|\mathcal{F})\Big).$$
Now, $\mathcal{F}$ is a $\sigma-$algebra (in fact a sub-$\sigma-$algebra), so $\Omega\in\mathcal{F}$, then by the second criterion of conditional probability, we have $$\mathbb{E}\Big(\mathbb{E}(|X|^{p}|\mathcal{F})\Big)=\mathbb{E}|X|^{p}.$$
These together imply that $$\|\mathbb{E}(X|\mathcal{F})\|_{p}\leq\|X\|_{p},$$ which is saying that for all $X\in L_{p}(\Omega,\mathcal{F},\mathbb{P})$, $$\|T(X)\|_{p}\leq\|X\|_{p}.$$
Therefore, the operator norm of $T$, being the infimum, must be $\leq 1$. Thus, $T$ is a contraction.

A: Suppose $\mathcal F$ is a sub-algebra of $\sigma$.  Then the operator  $c_{\mathcal F}:L^p(\Omega,\sigma,P)\to L^p(\Omega,\sigma,P)$ given by $c_{\mathcal F}:X\mapsto E[X|\mathcal F]$ is a contraction in the usual sense.
Jensen's inequality shows $\|X\|_p \le \|c_{\mathcal F} X\|_p$, so the operator norm of $c_{\mathcal F}$ is $\le1$.  But for $\mathcal F$-measurable rvs $X$ (including constant rvs) one has $c_{\mathcal F} X=X$, so the operator norm of $c_{\mathcal F}$is $1$.


text:
Q: Type mismatch when passing a query parameter to a controller from a template I'm trying to set up a url that allows optional query params. e.g.
myurl?number=1

I'm getting a compile error when I try to pass a value to my controller from inside of a template.
e.g.

Where the routes.conf is configured as follows:
GET    /myurl/            controllers.Application.myurl(number: Option[Int])

The specific error is:
Type mismatch. Expected Nothing, actual: Option[Int]

It works a OK if I hit the URLs directly in the browser. However, if I try to supply the query param in the template, it fails.

The above I got from this question, which is why I set up my route using option.
GET  /foo    controllers.MyController.foo(name: Option[String], age: Option[Int])

And...
def foo(name: Option[String], age: Option[Int]) = Action { implicit request =>
    Ok(s"Name is: $name, age is $age")

How do I pass a query param to the controller?

A: I you have read Reverse Routing in Play framework then it would be easy for you to understand this.
When you are trying to use optional query parameter then, you define your end point as
GET    /myurl/            controllers.Application.myurl(number: Option[Int])

and you can use it from your template as

The code will be compiled but your IDE may show you an error ignore the error by IDE and just move on from there.
So, whenever you are calling your action from template using reverse routing then you can use the above calling method and it will be treated by play as /myrul?number=1 and if you paste this url in your browser then your myurl action will be called and number parameter will be treated as option to it.
Like, i am using in one of my application as follows:
My EndPoint
GET         /file/:id                                        @controllers.FileController.getFile(id:String,w:Option[Int],h:Option[Int])

My Template

End point seen on terminal
 GET /file/1ecf481b-9fb3-4d9d-93f5-16b10a6cefa3?w=150 took 134ms and returned 200

Does that make it clear?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse Plugin-Development Debugger out of Sync for some internal development I currently customize a Eclipse Plug in. The Plug in I use is deployed as .jar File. Now I extracted the Content and imported it as Eclipse Plug in project. Everything works fine until is start to add some Code.
For testing the new functionality I like to debug my code. Therefore I run the Eclipse Plug in project in Debug mode. I've got a Debugging connection but the line of code highlighted in the editor doesn't match with the code.
1 private void a(){
2   doSomething();
3 }
4
5 private void b(){
6   doSomethingElse();
7 }

For example the Debug view says I am in the Method b(). But the Highlighter, in the Text-Editor, point to line 3.
I tried several things like Cleaning and searched nearly everywhere in the Debug-Configurations but nothing helped me.

A: The debugger highlights the code that is just about to be executed. When the debugger says you are in method b() it is simply telling you that it is about to debug method b()

A: If the displayed code doesn't fit what the debugger tells you it is executing, then you are simply not debugging the code that you see in the editor (but probably still the version without your modifications).
There are a lot of potential reasons for this. For the most easy failure please check your debug configuration. On the plugins page of the debug configuration there are plugins shown as living in your workspace and being provided by the Eclipse installation. Make sure that for your plugin the checkbox is at the workspace version, like the first checkbox in this image:


text:
Q: Why the img will be invisible after click the color change js function? I have a django project including the change color function with js, but the img will be invisible after I use those function. Btw this img has been uploaded to cloudinary. something I need to re-config?
Below is my js function for the changing color, I have already set the img.crossOrigin = ' ' to prevent from the Error of 'getImageData' :
var mug = document.getElementById("mug");
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;

function getPixels(img) {
    img.crossOrigin = '';
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}

function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
    R: (long >>> 16) & 0xff,
    G: (long >>> 8) & 0xff,
    B: long & 0xff
  };
 }

function changeColor()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementById("color").value);

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

function changeColor1()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementById("color1").value);
        {

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

function changeColor2()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementById("color2").value);
        {

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

function changeColor3()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementById("color3").value);
        {

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

Below is my template file:
{% extends 'base.html' %}
{% load static %}

{% block content %}

{{ details.name }}

     <button id="color1" value="#33FFBD" type="button" onclick="changeColor1();" style="background-color: #33FFBD;width: 50px;height: 50px;"></button>
    <button id="color2" value="#FFA500" type="button" onclick="changeColor2();" style="background-color: orange;width: 50px;height: 50px;"></button>
    <button id="color3" value="#b22222" type="button" onclick="changeColor3();" style="background-color: firebrick;width: 50px;height: 50px;"></button>

{{ details.desc }}

{% endblock %}


text:
Q: Inter docker communication (mqtt and python) I am having two docker containers in IBM Bluemix. One is MQTT and other php-python.
The PHP application executes a python script that should connect to the MQTT docker container and subscribe to a topic.
However, the php-python docker fails to connect. It also fails to ping to the MQTT docker container.
The MQTT container is working perfect as I am able to connect to it from my local machine.
I have tried linking the two containers using the following command:
cf ic run -p 443 -p 80 --name connector --link moscacontainer:source
registry.ng.bluemix.net/fortspace/php-mqtt

I have exposed the ports 1883 and 80 for the MQTT container.
I have used the following link as reference:
https://github.com/dceejay/nrdock/blob/master/README.md#linking-containers

Can someone guide on this?
EDIT: The output for cf ic inspect
[
    {
        "BluemixApp": null,
        "BluemixServices": null,
        "Config": {
            "AttachStderr": false,
            "AttachStdin": false,
            "AttachStdout": false,
            "Cmd": [],
            "Dns": "",
            "Env": [
                "logging_password=",
                "space_id=f874124c-cea6-460e-9bf2-b633eeeefcdf",
                "logstash_target=logmet.opvis.bluemix.net:9091",
                "metrics_target=logmet.opvis.bluemix.net:9095"
            ],
            "Hostname": "instance-0018c601",
            "Image": "registry.ng.bluemix.net/fortspace/php-mqtt:latest",
            "ImageArchitecture": "amd64",
            "Labels": {},
            "Memory": 256,
            "MemorySwap": "",
            "OpenStdin": true,
            "PortSpecs": "",
            "StdinOnce": false,
            "Tty": true,
            "User": "",
            "VCPU": 1,
            "VolumesFrom": "",
            "WorkingDir": ""
        },
        "ContainerState": "Running",
        "Created": "2017-01-11T06:21:38.000000000Z",
        "Group": {},
        "HostConfig": {
            "Binds": [],
            "CapAdd": [],
            "CapDrop": [],
            "ContainerIDFile": "",
            "Links": [
                "moscacontainer:source"
            ],
            "LogConfig": {
                "Config": {},
                "Type": "json-file"
            },
            "LxcConf": [],
            "PortBindings": {
                "443/tcp": [
                    {
                        "HostPort": "443"
                    }
                ],
                "80/tcp": [
                    {
                        "HostPort": "80"
                    }
                ]
            },
            "Privileged": false,
            "PublishAllPorts": false
        },
        "HostId": "46f8e5e8739f205e67ec852485095e953f079ff5c8f95b9e7c16f331",
        "Human_id": "connector",
        "Id": "4920a824-66bf-49bd-be71-549d0adeeffc",
        "Image": "sha256:080893a1e47927b2fdf3f24a8b0b803fab035c236551e32df9527654c8af698c",
        "Mounts": [],
        "Name": "connector",
        "NetworkSettings": {
            "Bridge": "",
            "Gateway": "",
            "IPAddress": "172.29.0.53",
            "IPPrefixLen": 0,
            "MacAddress": "fa:16:3e:3a:2e:04",
            "Networks": {
                "default": {
                    "Aliases": null,
                    "EndpointID": "4920a824-66bf-49bd-be71-549d0adeeffc",
                    "Gateway": "172.29.0.1",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "IPAMConfig": null,
                    "IPAddress": "172.29.0.53",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "Links": null,
                    "MacAddress": "fa:16:3e:3a:2e:04",
                    "NetworkID": "bd84d27c-8909-4dcc-a9cf-7dca5453f55c"
                }
            },
            "PortMapping": null,
            "Ports": {
                "443/tcp": [
                    {
                        "HostIp": "169.46.22.55",
                        "HostPort": "443"
                    }
                ],
                "80/tcp": [
                    {
                        "HostIp": "169.46.22.55",
                        "HostPort": "80"
                    }
                ]
            },
            "PublicIpAddress": "169.46.22.55"
        },
        "Path": "date",
        "ResolvConfPath": "/etc/resolv.conf",
        "State": {
            "Error": "",
            "ExitCode": 0,
            "FinishedAt": "0001-01-01T00:00:00Z",
            "Ghost": "",
            "Pid": 1,
            "Running": true,
            "StartedAt": "2017-01-11T06:22:54.000000000Z",
            "Status": "Running"
        },
        "Volumes": {},
        "VolumesRW": {}
    }
]

A: You can review information in this page:
https://console.ng.bluemix.net/docs/containers/container_linking.html
I am afraid the the --link is incorrect and you will may have to ensure alias and name are correct.
This command output should help you:
cf ic inspect recipient_container_name


text:
Q: The disk drive for /media/My_Passport is not ready yet or not present I have a dual boot with Mint MATE and Xubuntu on ONE hard drive.  I NOW have a problem when booting into Xubuntu with a notice of the following:
The disk drive for /media/My_Passport is not ready yet or not present. Continue to wait, or Press S to skip mounting or M for manual recovery.  I would like to eliminate the warning completely!
I recently had connected my USB hard drive but also installed the NTFS configuration tool.  Not sure if the new app caused the problem.  I also brought the USB hard drive to a friends home who copied some files to his MAC computer.  Any HELP would be much appreciated!
GNU nano 2.2.6              File: /etc/fstab

# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>

#Entry for /dev/sda6 :
UUID=e15dec6a-4ed3-4267-a88b-aef98e4ce8f0       /       ext4    errors=remount-$
#Entry for /dev/sdb1 :
UUID=4E1AEA7B1AEA6007   /media/My_Passport      ntfs    defaults,nls=utf8,umask$
#Entry for /dev/sda5 :
UUID=faf77a5c-fff8-49fd-9b83-e73451432379       none    swap    sw      0      $

A: You should add nobootwait to your /etc/fstab. So that it looks like the following:
UUID=4E1AEA7B1AEA6007 /media/My_Passport ntfs defaults,nobootwait,nls=utf8,umask$

Below is from the fstab man page:
The  mountall(8) program that mounts filesystem during boot also recognises additional options that the ordinary  mount(8) tool does not. These are:  bootwait which can be applied to remote filesystems mounted outside of /usr or /var, without which mountall(8) would not hold up the boot for these; nobootwait which can be applied to non-remote filesystems to explicitly instruct mountall(8) not to hold up the boot for them;


text:
Q: Method to update the html file without refreshing the page every time In my angular project have to code a shop-website. There is a Function where a product must first be accepted by a admin before showing in the shop itself. I have now implemented a component called "production authorization" where the admin can accept or reject a product. For that I get the products to be accepted with a get method with the link: "environment.endpointURL + 'products/authorized/no". after accepting it I update the project from authorized: 'no' to 'yes' so it won't be in the get method anymore (because the link changed to 'yes' at the end. But I have to refresh the page every time so it really doesn't show anymore in the 'product authorization' component. How can I implement it without having to refresh the page?
this is my .ts file:
import {Component, OnInit} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {environment} from "../../environments/environment";
import { Product } from '../models/product.model';

@Component({
  selector: 'app-product-authorization',
  templateUrl: './product-authorization.component.html',
  styleUrls: ['./product-authorization.component.css']
})
export class ProductAuthorizationComponent implements OnInit {

  isAdmin: boolean;

  products: Product[];

  displayedColumns: string[] = ['title', 'location', 'delivarable', 'description', 'price', 'acceptorreject'];

  constructor(private httpClient: HttpClient) { }

  ngOnInit(): void {

    this.getProducts()
  }

  getProducts(){
    return this.httpClient.get(environment.endpointURL + 'products/authorized/no').subscribe((res: any) =>
    {
      console.log(res);
      this.products = res;
    })
  }

  authorizeProduct(product: Product){
    product.authorized = "yes"
    product.status = "available"

    return this.httpClient.put(environment.endpointURL + 'products/' + product.productId, product ).subscribe((res: any) =>
    {
      console.log("Update:");
      console.log(res);

      //refresh page to update table
      this.refresh()

    })

  }

  rejectProduct(productId: number){
    return this.httpClient.delete(environment.endpointURL + 'products/' + productId).subscribe((res: any) =>
    {
      console.log("Delete:");

      //refresh page to update table
      this.refresh()
    })
  }

  refresh(): void {
    window.location.reload();
  }

}

and this is my .html file

Products to be authorized:

  <ng-container matColumnDef="title">
     Title
     {{element.title}}
  </ng-container>

  <ng-container matColumnDef="location">
     Location
     {{element.location}}
  </ng-container>

  <ng-container matColumnDef="delivarable">
     Delivarable
     {{element.delivarable}}
  </ng-container>

  <ng-container matColumnDef="description">
     Description
     {{element.description}}
  </ng-container>

  <ng-container matColumnDef="price">
     Price
     {{element.price}}
  </ng-container>

  <ng-container matColumnDef="acceptorreject">
     Authorize

      <button mat-raised-button color="primary" (click)="authorizeProduct(element)">Accept</button>
      <button mat-raised-button color="warn" (click)="rejectProduct(element.productId)">Reject</button>

  </ng-container>

A: You have to remove the accepted object from your local products array in your authorizeProduct method and maybe in your rejectProduct method. With the Angular refresh cycle your ui should be updated afterwards.


text:
Q: Mapping custom domain to Windows Azure CDN does not working I've created an Windows Azure Blob Storage and associated a Windows Azure CDN service.I map custom domain to Azure CDN. After veryfication is completed for my custom domain, I've created CNAME record that map static.codeinstinct.pro to az412526.vo.msecnd.net.
As a result, I have 3 links:
codeinstinct.blob.core.windows.net/test/trouble.gif
az412526.vo.msecnd.net/test/trouble.gif
static.codeinstinct.pro/test/trouble.gif
First 2 links is work, but the last one doesn't (returns a 400 'Bad request' error).
I try to get details DNS name of custom domain. It's look like:
;; QUESTION SECTION:
;static.codeinstinct.pro.   IN  CNAME
;; ANSWER SECTION:
static.codeinstinct.pro. 600    IN  CNAME   az412526.vo.msecnd.net.

;; AUTHORITY SECTION:
codeinstinct.pro.   86399   IN  NS  ns01.parking.ru.
codeinstinct.pro.   86399   IN  NS  ns11.parking.ru.
Why it is not working?

A: You need to enable the custom domain in the Azure portal - see How to Map CDN Content to a Custom Domain

A: I removed all what I had created: custom domain (with CNAME records), then Azure CDN enpoint. Then I recreated what I had removed and... all work!


text:
Q: Conditions for the existence of a limit If $\lim_{x \to a}f(x)$ and $\lim_{x \to a} (f(x)g(x))$ exist, must $\lim_{x \to b} g(x)$ exist?
Let $f,g$ be two functions defined in some open interval $I$ containing a point $a$. Let us suppose that $a=b$.
Let $\epsilon>0$. We know that $\lim_{x \to a}f(x)$ and $\lim_{x \to a}(f(x)g(x))$ exist.
Therefore, let $\lim_{x \to a}f(x)=l$ and $\lim_{x \to a}(f(x)g(x))=l'$.
Since $\lim_{x \to a}f(x)=l$ and $\lim_{x \to a}(f(x)g(x))=l'$, there exists $\eta_1>0$ and $\eta_2>0$ such that:
$\forall x \in I $
\begin{array}{lcl}
\mid x-a \mid \leq \eta_1 \Rightarrow \mid f(x)-l \mid \leq \\
\mid x-a \mid \leq \eta_2 \Rightarrow \mid f(x)g(x)-l' \mid \leq \epsilon\\
\end{array}
I didn't find the first line has to be smaller that and how to I reveal the $g(x)$?
Thank you in advance.

A: $\lim\limits_{x \to b} g(x)$ not necessarily exist. If $\lim\limits_{x \to a} f(x)=0$, for example, $f(x)=\sin{x}$,  $a=0$, $g(x)=\dfrac{1}{\sqrt{x}}$.

A: You have
$$
\lim_{x\to a}g(x)=\lim_{x\to a}\frac{f(x)g(x)}{f(x)}
$$
and applying the theorem on the limit of the ratio, if the two limits are finite and the limit of $f$ is not $0$, this becomes
$$
\frac{\lim_{x\to a}f(x)g(x)}{\lim_{x\to a}f(x)}
$$
so in these hypotheses it exists.
This does not exclude that the limit could exist also if the hypotheses are not satisfied.


text:
Q: How I can create post like system using jquery

function get_posts2()
{

    global $conn;
    $user=$_SESSION['user_email'];
    $get_user="SELECT * FROM users WHERE user_email='$user'";
    $run_user=mysqli_query($conn,$get_user);
    $row=mysqli_fetch_array($run_user);
    $user_id=$row['user_id'];
    $friendn=1;
   $friend_select="SELECT  * from friends where user_1_id='$user_id' AND friends_status='$friendn'";
    $run_select_friends=mysqli_query($conn,$friend_select);
    while ($row_friends=mysqli_fetch_array($run_select_friends)){
        $id_2=$row_friends['user_2_id'];

        $post_selcet="select * from posts WHERE user_id='$id_2'";
        $run_post_select=mysqli_query($conn,$post_selcet);

        while($row_posts=mysqli_fetch_array($run_post_select))
        {

            $post_id=$row_posts['post_id'];
            $u_id=$row_posts['user_id'];
            $post_title=$row_posts['post_title'];
            $content=$row_posts['post_content'];
            $post_date=$row_posts['post_date'];
            $post_image=$row_posts['post_image'];

            $user="select * from users where user_id='$u_id'";
            $run_user=mysqli_query($conn,$user);
            $row_user=mysqli_fetch_array($run_user);
            $user_name=$row_user['user_name'];
            $user_image=$row_user['user_image'];

            echo "

 $post_title

 $user_name$post_date

$content

       ";

        }

    }

}

I want to create a post like system as like as facebook or Instagram
any one can help me ?
My code is show that I get my post information then I use them to show in my page  but I now I want to create a system for like and dislike

A: first u must create "likeCount" or "dislikeCount" fields in u'r posts table then make ajax request for increase or decrease counts.
sample jQuery code.

$(document).on('click','.vote',function(){

 var $this = $(this);
 var $postID = $this.data('post_id');
 var $action = $this.data('vote_type'); //example 'up' or 'down'

 $.ajax({

 url:'url/to/process/ajax',
 type:'POST',
 data:{
   action:$action,
   postID : $postID
  },
 dataType:'json',
 success:function(response){

  //do success action

  },
 error:function(){}
});

});


text:
Q: What do you call these types of words? I just noticed something in a rather innocuous text that I was sending a friend. The word "Left", for instance, could mean, "Hey, have you left already?" or "Is anyone left here?". Both these meanings are completely different from each other even if they are using the same word(in this case, "left").
My question is, "Does anyone know more of such words? And if so, is there a specific term for them?"


text:
Q: Only display 1 article in RSS feed YUI I only want to display one article but when I change the (0,2) to (0,1) nothing appears. Is there a quick solution?

YUI().use('yql', function(Y){
    var query = 'select * from rss(0,2) where url = "http://rss.cnn.com/rss/money_latest.rss"'
    var q = Y.YQL(query, function(r){
        //r now contains the result of the YQL Query as a JSON
        var feedmarkup = '
'
        var feed = r.query.results.item // get feed as array of entries
        for (var i=0; i<feed.length; i++){
            feedmarkup += '
'
            feedmarkup += feed[i].title + '
'
            feedmarkup += '
' + feed[i].description + '
'
   feedmarkup += '
'
            feedmarkup += 'Read more' + '
'
        }
        document.getElementById('uknews').innerHTML = feedmarkup
    })
})

A: I found the answer and hope this helps someone else:

YUI().use('yql', function(Y) {

  var query = 'select * from rss(0,1) where url = "http://rss.cnn.com/rss/cnn_world.rss"'
  var q = Y.YQL(query, function(r) {
    //r now contains the result of the YQL Query as a JSON
    var feedmarkup = '
'
    var feed = r.query.count > 1 ? r.query.results.item : [r.query.results.item]; // get feed as array of entries
    for (var i = 0; i < feed.length; i++) {
      feedmarkup += '
'
      feedmarkup += feed[i].title + '
'
      feedmarkup += '
' + feed[i].description + '
'
      feedmarkup += '
'
      feedmarkup += 'Learn more' + '
'
    }

    document.getElementById('uknews').innerHTML = feedmarkup
  })
})
.feedflare {
  display: none;
}

div.feed-description {
  display: block;
  max-width: 400px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}


text:
Q: Can constant objects with static storage duration and equal, constant initializers be coalesced? Consider two objects with static storage duration and equal, constant initializers:
static const int a = 50;
static const int b = 50;

Is it valid for a compiler to combine these such that &a == &b?
(For context, I was thinking of using static constant objects to get unique addresses to use as sentinel pointer values. If it is legal for a compiler to combine such objects and I use the same constant value for two such objects, then the addresses could be equal and I cannot use them as sentinel values.)

A: The pointers must compare not-equal. See C99 6.5.9 paragraph 6:

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

A: No, the standard forbids that.  Distinct objects must have distinct addresses.   In const char a[]="abc", b[]="abc";, a and b are allocated at different addresses.  This is also true if they're pointers: in const char *a="abc", *b="abc",aandb` are also allocated at different addresses; the string constant they point to can be a single constant array, just as if it was a named object.


text:
Q: Matrix manipulation in tikzpicture I have this code:
    \documentclass[tikz, border=3mm]{standalone}
    \usetikzlibrary{matrix}

    \begin{document}

    \begin{tikzpicture}
    \matrix[matrix of nodes,
    inner sep=0pt,
    anchor=south west,
    row sep=-\pgflinewidth,
    column sep=-\pgflinewidth,
    nodes={draw=black!30,
            anchor=center,
            align=center,
            minimum size=1cm,
            outer sep=0pt,
         }
    ]{
       -t & 1 & 1 & 1 & 0 \\
        0 & 1-t & 0 & 0 & 0 \\
        0 & 1 & 1-t & 0 & 0 \\
        0 & -1 & 0 & 1-t & 1 \\
        0 & 0 & -1 & -1 & -t-1 \\
       };
    \end{tikzpicture}
    \end{document}

There is a way in order to:

*

*have the nodes of the matrix in mathmode

*circle some specific node and bar the other on the same column and row like in this picture.

*numerate automatically rows and columns?

A: For math nodes, use matrix of math nodes instead of matrix of nodes, but it appears you need to remove align=center for that to work.
If you give a name to the matrix, e.g. m as in the code below, you can access the individual nodes with m-<rownum>-<colnum>, so you can use that to draw the lines and add the labels. A couple of loops lets you automate this.

\documentclass[tikz, border=3mm]{standalone}
\usetikzlibrary{matrix}

\begin{document}

\begin{tikzpicture}
\matrix (m) [matrix of math nodes,
inner sep=0pt,
anchor=south west,
row sep=-\pgflinewidth,
column sep=-\pgflinewidth,
nodes={draw=black!30,
        anchor=center,
        minimum size=1.1cm,
        outer sep=0pt,
     }
]{
   -t & 1 & 1 & 1 & 0 \\
    0 & 1-t & 0 & 0 & 0 \\
    0 & 1 & 1-t & 0 & 0 \\
    0 & -1 & 0 & 1-t & 1 \\
    0 & 0 & -1 & -1 & -t-1 \\
   };

% for a single row/column
%\node [draw,circle,minimum size=9mm] (a) at (m-1-1.center) {};
%\draw [thick] ([xshift=-1mm]m-1-5.east) -- (a) -- ([yshift=1mm]m-5-1.south);

% or use a loop to do all three at once
\foreach \i in {1,...,3}
{
\node [draw,circle,minimum size=9mm] (a) at (m-\i-\i.center) {};
\draw [thick] ([xshift=-1mm]m-\i-5.east) -- (a) -- ([yshift=1mm]m-5-\i.south);
}

\foreach \i in {1,...,5}
{
\node [above] at (m-1-\i.north) {\i};
\node [left] at (m-\i-1.west) {\i};
}
\end{tikzpicture}
\end{document}


text:
Q: Zip two folders in one folder using java I am trying to zip two folder with each having some text file. Now I want that 2 folders should zip as one folder with their respective files.
I tried to code, but there is some issue with the zip.

The Zip contains multiple folders.

Here is the code:
package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolders
{
    public static void main(String[] args) throws IOException
    {
        List<String> listOfDir = new ArrayList<String>();

        String dirpath1 = "/home/administrator/Documents/ZipTest/folder1";
        String dirpath2 = "/home/administrator/Documents/ZipTest/folder2";

        String ZipName = "/home/administrator/Documents/ZipTest/output.zip";
        listOfDir.add(dirpath1);
        listOfDir.add(dirpath2);

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZipName));
        zipDirectories(listOfDir,zos);
        zos.close();
        System.out.println("Zip Created Successfully");
    }

    private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
        for(String dirPath:listOfDir){
            try {
                zipdirectory(dirPath, zos);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void zipdirectory(String dirpath, ZipOutputStream zos) throws IOException
    {
        File f = new File(dirpath);
        String[] flist = f.list();
        for(int i=0; i<flist.length; i++)
        {
            File ff = new File(f,flist[i]);
            if(ff.isDirectory())
            {
                zipdirectory(ff.getPath(),zos);
                continue;
            }
            String filepath = ff.getPath();
            ZipEntry entries = new ZipEntry(filepath);
            zos.putNextEntry(entries);
            FileInputStream fis = new FileInputStream(ff);
            int buffersize = 1024;
            byte[] buffer = new byte[buffersize];
            int count;
            while((count = fis.read(buffer)) != -1)
            {
                zos.write(buffer,0,count);
            }
            fis.close();
        }
    }
}

But the output I am getting is not as expected I am getting folder 1 & folder 2
like
output.zip//home/administrator/Documents/ZipTest/ then here we are having our folder1 & folder2.
My expected output was :- inside the zip only the two folders should exist with there files.

A: Your zipdirectory method is used recursive here:
if(ff.isDirectory())
{
     zipdirectory(ff.getPath(),zos);
     continue;
}

That is creating all the folders you see.

A: You need to distiquish between the path of each file/dir and the path of the zip entry:
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
    for(String dirPath:listOfDir){
        try {
            File dir = new File(dirPath);
            zipdirectory(dir, dir.getName(), zos);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
public static void zipdirectory(File dir, String dirpath,
        ZipOutputStream zos) throws IOException
{
    String[] flist = dir.list();
    for(int i=0; i<flist.length; i++)
    {
        String fn = flist[i];
        String fp = dirpath == null || dirpath.isEmpty()
                ? fn : dirpath + "/" + fn;
        File ff = new File(dir, fn);
        if(ff.isDirectory())
        {
            zipdirectory(ff, fp,zos);
            continue;
        }
        ZipEntry entries = new ZipEntry(fp);
        zos.putNextEntry(entries);
        FileInputStream fis = new FileInputStream(ff);
        int buffersize = 1024;
        byte[] buffer = new byte[buffersize];
        int count;
        while((count = fis.read(buffer)) != -1)
        {
            zos.write(buffer,0,count);
        }
        fis.close();
    }
}

A: Copy , Paste the Code and Run it for the result :-
   package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolders
{
    public static void main(String[] args) throws IOException
    {
        List<String> listOfDir = new ArrayList<String>();

        String dirpath1 = "/home/administrator/Documents/ZipTest/folder1";
        String dirpath2 = "/home/administrator/Documents/ZipTest/folder2";

        String ZipName = "/home/administrator/Documents/ZipTest/output.zip";
        listOfDir.add(dirpath1);
        listOfDir.add(dirpath2);

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZipName));
        zipDirectories(listOfDir,zos);
        zos.close();
        System.out.println("Zip Created Successfully");
    }

    private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
        for(String dirPath:listOfDir){
            try {
                zipdirectory(dirPath, zos);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void zipdirectory(String dirpath, ZipOutputStream zos) throws IOException
    {
        File f = new File(dirpath);
        String[] flist = f.list();
        for(int i=0; i<flist.length; i++)
        {
            File ff = new File(f,flist[i]);
            if(ff.isDirectory())
            {
                zipdirectory(ff.getPath(),zos);
                continue;
            }
            String fileName = ff.getPath().substring(ff.getPath().lastIndexOf('/'));

            String folder = dirpath.substring(dirpath.lastIndexOf('/')+1);

            ZipEntry entries = new ZipEntry(folder+fileName);
            zos.putNextEntry(entries);
            FileInputStream fis = new FileInputStream(ff);
            int buffersize = 1024;
            byte[] buffer = new byte[buffersize];
            int count;
            while((count = fis.read(buffer)) != -1)
            {
                zos.write(buffer,0,count);
            }
            fis.close();
        }
    }
}


text:
Q: How to parse a tuple of "x=y" strings into a dictionary in python? I have a tuple of strings that I would like to convert into a dictionary by splitting each element using a separator. Is this possible with dictionary comprehension?
>>> x = ('var1=abc', 'var2=xyz', 'var3=10')
>>> y = {k: v for (k, v) in ???}  # this is where I need your help
>>> print y
{ "var1": "abc", "var2": "xyz", "var3": "10" }

This is as much an learning exercise as anything - so please don't answer with an alternative way of doing it (I have plenty of those) - I want to know if it's possible with a dictionary comprehension.
[UPDATE]
There is a slight modification that I didn't write down first - I need to strip an extraneous linefeed character from the end of each value.
>>> x = ('var1=abc\n', 'var2=xyz\n', 'var3=10')
>>> d = {k: v.strip('\n') for (k, v) in [e.split('=') for e in x]}
>>> d
{'var1': 'abc', 'var3': '10', 'var2': 'xyz'}

(Of course, now it's not in the same order - but I can live with that. Grrr.)

A: You'd have to split each string twice, but yes, it can be done:
{elem.split('=', 1)[0]: elem.split('=', 1)[1].strip() for elem in x}

Result:
>>> x = ('var1=abc\n', 'var2=xyz\n', 'var3=10')
>>> {elem.split('=', 1)[0]: elem.split('=', 1)[1].strip() for elem in x}
{'var1': 'abc', 'var3': '10', 'var2': 'xyz'}

To avoid splitting twice, use a generator expression and the dict() constructor instead:
dict(elem.strip().split('=', 1) for elem in x)

since it takes a sequence of two-value tuples.

A: Using dict() constructor
dict(elem.split('=', 1) for elem in x)

In action:
>>> x = ('var1=abc', 'var2=xyz', 'var3=10')
>>> dict(elem.split('=', 1) for elem in x)
{'var1': 'abc', 'var3': '10', 'var2': 'xyz'}

note: dictionaries are unsorted, and so you will not get the exact result you wanted.

A: >>> x = ('var1=abc', 'var2=xyz', 'var3=10')
>>> dict([element.split('=') for element in x])
{'var1': 'abc', 'var3': '10', 'var2': 'xyz'}


text:
Q: Send PUT, DELETE HTTP request in HttpURLConnection I have created web service call using java below code. Now I need to make delete and put operations to be perform.
URL url = new URL("http://example.com/questions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/json");

OutputStream os = conn.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();

When I add below code to perform DELETE action it gives errors saying:

java.net.ProtocolException: HTTP method DELETE doesn't support output.

conn.setRequestMethod( "DELETE" );

So how to perform delete and put requests?

A: PUT example using HttpURLConnection:
URL url = null;
try {
   url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
    exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpURLConnection.setRequestMethod("PUT");
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);
    dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
    dataOutputStream.write("hello");
} catch (IOException exception) {
    exception.printStackTrace();
}  finally {
    if (dataOutputStream != null) {
        try {
            dataOutputStream.flush();
            dataOutputStream.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
    if (httpsURLConnection != null) {
        httpsURLConnection.disconnect();
    }
}

DELETE example using HttpURLConnection:
URL url = null;
try {
    url = new URL("http://localhost:8080/deleteservice");
} catch (MalformedURLException exception) {
    exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
    httpURLConnection.setRequestMethod("DELETE");
    System.out.println(httpURLConnection.getResponseCode());
} catch (IOException exception) {
    exception.printStackTrace();
} finally {
    if (httpURLConnection != null) {
        httpURLConnection.disconnect();
    }
}

A: FOR PUT
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
    httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();

FOR DELETE
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
    "Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();

Actually got it from the link here:
Send PUT, DELETE HTTP request in HttpURLConnection

A: i suggest you to use restlet client for  web service request .please refer the bellow sample code ,it may help you
 Client client = new Client(new Context(), Protocol.HTTP);
   clientResource = new ClientResource(url);
        ResponseRepresentation responseRep = null;
         try {
            clientResource.setNext(client);
            clientResource.delete();

       } catch (Exception e) {
           e.printStackTrace();

       }


text:
Q: How to getting current Email that be used for login in Myth/Auth library Code Igniter 4 I wanted to make a program that able to store a data and every the data that i send to the Database must contain the Email from user used to login to my Web. In here i'm using Myth Auth library as authenticator and login security. But i can't find the method to call the current Email so i can fetch it and push to my Database. i'm using MySql as my DB.

A: You have to create an Entity extending Mith's one.
So create app/Entities/User.php
Then... to use:
echo user()->getEmail();
See Documentation:
https://github.com/lonnieezell/myth-auth/blob/develop/docs/extending.md
<?php namespace App\Entities;

use Myth\Auth\Entities\User as MythUser;

class User extends MythUser
{
    /**
     * Returns Email
     *
     * @return string
     */
    public function getEmail()
    {
        return trim(trim($this->attributes['email']));
    }
}

A: add the following method to myth-auth\src\Entities\User.php
public function getEmail()
    {
        return trim(trim($this->attributes['email']));
    }

then, anywhere in your app, you can call it with user()->getUsername()
You can do the same for username or any of the other user attributes.

A: A!
Now that we have our new entity, we need to update our UserModel to return it instead of the default Myth:Auth version:
class UserModel extends MythModel
{
    protected $returnType = 'App\Entities\User';
    ...


text:
Q: A User can be a Teacher or a Admin, or a Parent, or a Student. How to achieve this using Django models? I have a table called User. And there are other tables Admin, Teacher, Parent and Student. Now, a User can be a Teacher or a Admin, or a Parent, or a Student. How to implement this using Django models?

A: You should use Django's generic relations and content types. Assuming the relation of User to Teacher/Admin/Parent/Student is called "role", below is pseudocode of what that should look like:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

class User(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="role")
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

A: *

*Something like this would be preferable:

Situation 1:

*

*If the user can only handle one role, you can employ the below:

models.py
class User(AbstractUser):
    USER_ROLES = (
        ('A', 'Administrator'),
        ('T', 'Teacher'),
        ('S', 'Student'),
        ('P', 'Parent'),
    )

    role = models.CharField(max_length=1, blank=False, choices=USER_ROLES )
    # ... other fields here...

    def __str__(self):
        return '{}'.format(self.get_full_name())

class Administrator(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )
    # ... other fields here...

class Student(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )
    # ... other fields here...

class Teacher(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )
    # ... other fields here...

class Parent(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )
    # ... other fields here...

Situation 2:

*

*If the user needs more than one role, you can employ the below:

models.py
class User(AbstractUser):

    is_administrator = models.BooleanField(default=False)
    is_teacher       = models.BooleanField(default=False)
    is_student       = models.BooleanField(default=False)
    is_parent        = models.BooleanField(default=False)
    # ... other fields here...

    def __str__(self):
        return '{}'.format(self.get_full_name())


text:
Q: jQuery Mobile grid space gap I'm using jQuery Mobile layout grids with 2 columns but there's a space gap when the cell's height is different.
Example:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>jQueryMobile Demos</title>
        <link type="text/css" rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />

Name

Diogo
Cardoso

A: In the documentation (in the example) they use a inline-style tag for the height.
Documentation: http://jquerymobile.com/demos/1.0a4.1/docs/content/content-grids.html
inline-style tag: style="height:120px"
Here is a working example: http://jsfiddle.net/V4uqN/5/
http://api.jquery.com/css/
Something like:
$('#element').css('height','120px');


text:
Q: Efficient way to load big heterogeneous dataset in a numpy array? I have to load a dataset into a big array with p instances where each instance has 2 dimensions (n_i, m). The length of the first dimension n_i is variable.
My first approach was to pad all the instances to the max_len over the first dimension, initialize an array of size (p, max_len, m) and then broadcast each instance into the big array as follows big_array[i*max_len:i*max_len+max_len] = padded_i_instance. This is fast and works well, the problem is that I only have 8Gb of RAM and I get  (interrupted by signal 9: SIGKILL) error when I try to load the whole dataset. It also feels very wasteful since the shortest instance is almost 10 times shorter than the max_len so some instances are 90% padding.
My second approach was to use np.vstack and then build the big_array iteratively. Something like this:
big_array = np.zeros([1,l])
for i in range(1,n):
    big_array = np.vstack([big_array, np.full([i,l], i)])

this feels less "wasteful" but it actually takes 100x longer to execute for only 10000 instances, it is unfeasible to use for 100k+.
So I was wondering if there was a method that is both more memory efficient than approach 1 and more computationally efficient than approach 2. I read about np.append and np.insert but they seem to be other versions of np.vstack so I assume the would take roughly as much time.

A: The slow repeated vstack:
In [200]: n=5; l=2
     ...: big_array = np.zeros([1,l])
     ...: for i in range(1,n):
     ...:     big_array = np.vstack([big_array, np.full([i,l], i)])
     ...:
In [201]: big_array
Out[201]:
array([[0., 0.],
       [1., 1.],
       [2., 2.],
       [2., 2.],
       [3., 3.],
       [3., 3.],
       [3., 3.],
       [4., 4.],
       [4., 4.],
       [4., 4.],
       [4., 4.]])

list append is faster:
In [202]: alist = []
In [203]: for i in range(1,n):
     ...:     alist.append(np.full([i,l], i))
     ...:
     ...:
In [204]: alist
Out[204]:
[array([[1, 1]]),
 array([[2, 2],
        [2, 2]]),
 array([[3, 3],
        [3, 3],
        [3, 3]]),
 array([[4, 4],
        [4, 4],
        [4, 4],
        [4, 4]])]
In [205]: np.vstack(alist)
Out[205]:
array([[1, 1],
       [2, 2],
       [2, 2],
       [3, 3],
       [3, 3],
       [3, 3],
       [4, 4],
       [4, 4],
       [4, 4],
       [4, 4]])

filling a preallocated array:
In [210]: arr = np.zeros((10,2),int)
     ...: cnt=0
     ...: for i in range(0,n):
     ...:     arr[cnt:cnt+i,:] = np.full([i,l],i)
     ...:     cnt += i
     ...:
In [211]: arr
Out[211]:
array([[1, 1],
       [2, 2],
       [2, 2],
       [3, 3],
       [3, 3],
       [3, 3],
       [4, 4],
       [4, 4],
       [4, 4],
       [4, 4]])


text:
Q: How to make a bash copy of an awk variable? Here is a simplified version of my problem.
if (echo "AA BB CC" | awk '{ print $1 $2 }' | grep -q "B"); then
   echo $2
fi

I would like to make $2 available in bash, so I can use it elsewhere in the script.
Can that be done?
Update
I realized that I had simplified the problem too much. The awk expression should have been awk '{ print $1 $2 }' instead of just awk '{ print $2 }' which I originally posted.

A: You can use set:
set -- `echo "AA BB CC" | awk '{print $2}'`
case $1 in *B*) echo $1;; esac

... or if you used the awk just to split the output, let set do that part as well:
set -- `echo "AA BB CC"`
case $2 in *B*) echo $2;; esac

A: Remember the output of awk, test it for the regular expression and print it:
output=$( echo "AA BB CC" | awk '{ print $2 }' )
if grep -q B <<< "$output" ; then echo "$output" ; fi

A: You can capture stdout into a variable by using the backtick operator, e.g.
a=`echo foo`
echo $a

For your example, it would be something like:
a=`echo "AA BB CC" | awk '{ print $2 }' | grep -q "B"`
echo $a


text:
Q: How to solve Reflected XSS error in query referenced in my Visualforce Component When I sent my code to security scan I got Reflected XSS error. How to solve this issue? I wrapped the variable with Jsencode. Visualforce component is not saving. Below is the code where I got that error.
if('{!sfield}' !=''){
 $elem.select2("data", {id: "{!new}", text: "{!sfield}"})
}

A: Lets first understand what is XSS and see what are the possible ways to prevent this

Cross-site scripting(XSS) is a vulnerability that occurs when an
  attacker can insert unauthorized JavaScript, VBScript, HTML, or other
  active content into a web page viewed by other users. A malicious
  script inserted into a page in this manner can hijack the user's
  session, submit unauthorized transactions as the user, steal
  confidential information

Mechanism provided in VF to Overcome this issue
1)Built in Auto Encoding
All merge-fields are always auto HTML encoded provided they
i)do not occur within a or tag
ii)do not occur within an apex tag with the escape='false' attribute
2)Built in VisualForce encoding functions
The platform provides the following VisualForce encoding functions:

JSENCODE -- performs string encoding within a Javascript String
  context
HTMLENCODE -- encodes all characters with the appropriate HTML
  character references so as to avoid interpretation of characters as
  markup.
URLENCODE -- performs URI encoding (% style encoding) within a URL
  component context
JSINHTMLENCODE -- a convenience method that is equivalent to the
  composition of HTMLENCODE(JSENCODE(x))

There is a detailed article in below link
https://developer.salesforce.com/page/Secure_Coding_Cross_Site_Scripting
Sample example

Click me!

The above is vulnerable
Lets see how we use Encode functions to rectify this

Click me!

The above is safe since we have use HTMLENCODE AND JSENCODE to encode and hence its hard for attacker to inject script or insert iframe
Edit
For your code try like below
if('{!JSENCODE(sfield)}' !=''){
 $elem.select2("data", {id: "{!JSENCODE(new)}", text: "{!JSENCODE(sfield)}"})
}

Edit 2

Use the String function to wrap the sfiled because JSENCODE only accepts
  TEXT

if('{!JSENCODE(String(sfield))}' !=''){
     $elem.select2("data", {id: "{!JSENCODE(new)}", text: "{!JSENCODE(String(sfield))}"})
    }

Here is the answer that I did refer: -
Source


text:
Q: ошибка при запуске "куча была повреждена" Имею код:
#include <iostream>
#include <vector>
#include <ctime>
#include <cmath>
#include "methods.h"
#include "functions.h"
#include <boost/multiprecision/cpp_bin_float.hpp>

using namespace std;
namespace mp = boost::multiprecision;
using int128_t = boost::multiprecision::int128_t;

typedef int128_t matrix[2][2];

void mul(matrix a, matrix b, matrix c, int128_t mod)
{
    int n = 2;
    matrix d;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
        {
            int128_t s = 0;
            for (int k = 0; k < n; ++k)
                s = (s + a[i][k] * b[k][j]) % mod;
            ((c == a || c == b) ? d[i][j] : c[i][j]) = s;
        }
    if (c == a || c == b)
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < n; ++j)
                c[i][j] = d[i][j];
}

void power(matrix i, int128_t p, matrix&r, int128_t mod)
{
    int n = 2;
    if (p % 2)
    {
        for (int j = 0; j < n; ++j)
            for (int k = 0; k < n; ++k)
                r[j][k] = i[j][k];
    }
    else
    {
        for (int j = 0; j < n; ++j)
            for (int k = 0; k < n; ++k)
                r[j][k] = (j == k) ? 1 : 0;
    }
    while (p /= 2)
    {
        mul(i, i, i, mod);
        if (p % 2) mul(i, r, r, mod);
    }
}

vector<int128_t> Schirokauer_Maps(int128_t a, int128_t b, int128_t h, int128_t q)
{
    int128_t q1 = pow(q, 2);
    vector<int128_t> s(2);
    matrix ax, r;
    ax[0][0] = a;
    ax[0][1] = h;
    ax[1][0] = b;
    ax[1][1] = a - b;

    power(ax, q - 1, r, q1);

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            if (r[i][j] < 0)
                r[i][j] += q1;

    s[0] = (r[0][0] - 1) / q;
    s[1] = r[1][0] / q;

    return s;
}

int64_t number(uint64_t h, uint64_t g, uint64_t p, uint64_t m1)  //p-модуль, g-основание, h-ответ, d-степень для взятия корня
{
    int d = 2;
    vector<int> prime{ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019 };
    int128_t q = p, ts = p;
    int128_t qs = (p - 1) / 2;
    mp::cpp_bin_float_quad N = 0;
    int i = 0;
    int128_t quantity_prime = 0;
    int128_t t = 0;
    int128_t w = 0; // счетчик коэффицентов
                    //int128_t m = mp::pow(p, 1.0 / d);
    int128_t m = mp::sqrt(p);
    vector<int128_t> equation(d + 1);
    //построение уравнения
    for (i = d; i > 0; i--)
    {
        do {
            q = q - mp::pow(m, int(i));
            w++;
        } while (q - pow(m, int(i)) > 0);
        equation[int(i)] = w;
        w = 0;
    }
    equation[0] = q;

    //выделение памяти под базисы
    int128_t b = 8;
    do
    {
        i++;
        t = prime[int(i)];
    } while (t < b);

    vector <pair<int128_t, int128_t> > rational_factor;
    vector <pair<int128_t, int128_t> > algebraic_factor;
    i = 0;
    t = 0;

    //расчет рационального базиса:
    q = prime[0];
    ts = prime[0];
    do {
        do
        {
            rational_factor.push_back(make_pair(m%q, q));
            i++;
            q = prime[int(i)];
        } while (b > q);
        //расчет алгебраического базиса:
        w = 0; //для расчета уравнения
        int128_t y = 0;
        do
        {
            for (int128_t iw = 0; iw < ts; iw++)
            {
                for (int j = 0; j < equation.size(); j++)
                    w += equation[j] * pow(iw, j);
                if (w%ts == 0)
                {
                    algebraic_factor.push_back(make_pair(iw, ts));
                    y++;
                }
                w = 0;
            }
            t++;
            ts = prime[int(t)];
        } while (b > ts);
        if ((i == prime.size() - 1) || t == prime.size() - 1)
            return -1;
    } while (algebraic_factor.size() != rational_factor.size());

    b = 2 * algebraic_factor.size() + 3;

    //построение матрицы
    int128_t ij = 1;
    vector<vector<int128_t>> mas(b.convert_to<size_t>(), vector<int128_t>(b.convert_to<size_t>(), 0));
    pair<int128_t, int128_t> ab;
    int o = 0;
    vector <pair<int128_t, int128_t> > pairs(m.convert_to<size_t>());
    bool a = true;

    srand(time(0)); // автоматическая рандомизация
    int128_t d0 = 0, d1 = 0, d2 = 0, d3 = 0;

    do {

        //генерация a и b проверка на нод и вхождения
        do {
            ab.first = rand() % (2 * m1) + 1; // диапазон равен от 1 до 3 включительно
            ab.second = rand() % (2 * m1 + 1) + (-m1);
            int128_t i = 0;

            if (NOD(ab.first, ab.second) != 1)
                a = false;
            else if (find(pairs.begin(), pairs.end(), ab) == pairs.end())
            {
                a = true;
                pairs[o] = ab;
                o++;
            }
            else a = false;
            if (a == true)
            {
                for (int i = 0; i < rational_factor.size(); i++)
                {
                    d0 = -rational_factor[i].first*ab.second%rational_factor[i].second;
                    d3 = ab.first%rational_factor[i].second;
                    if (d0 < 0)
                        d0 += rational_factor[i].second;
                    if (d3 < 0)
                        d3 += rational_factor[i].second;
                    if (d3 == d0)
                        d1++;
                }

                for (int i = 0; i < algebraic_factor.size(); i++)
                {
                    d0 = -algebraic_factor[i].first*ab.second%algebraic_factor[i].second;
                    d3 = ab.first%algebraic_factor[i].second;

                    if (d0 < 0)
                        d0 += algebraic_factor[i].second;

                    if (d3 < 0)
                        d3 += algebraic_factor[i].second;

                    if (d3 == d0)
                        d2++;
                }
                if ((d1 == 0) || (d2 == 0))
                {
                    pairs[o].first = 0;
                    pairs[o].second = 0;
                    o--;
                }
            }
        } while ((a == false) || (d1 == 0) || (d2 == 0));

        //процесс заполнения матрицы
        int128_t summa = 0;
        int128_t yup = 0;

        summa = ab.first + ab.second*m;

        if (summa == 0)
            yup = rational_factor.size();

        if (summa < 0)
        {
            mas[0][ij.convert_to<size_t>()] = 1;
            summa *= -1;
        }
        while (yup != rational_factor.size())
        {
            if (summa % rational_factor[yup.convert_to<size_t>()].second == 0)
            {
                summa /= rational_factor[yup.convert_to<size_t>()].second;
                mas[(yup + 1).convert_to<size_t>()][ij.convert_to<size_t>()]++;
            }
            else
                yup++;
        }
        int128_t i = 0;
        //yup++;
        mp::cpp_bin_float_quad as = (mp::cpp_bin_float_quad) - ab.first / ab.second.convert_to<mp::cpp_bin_float_quad>();
        for (int j = 0; j <= 2; j++)
            N += equation[j].convert_to<mp::cpp_bin_float_quad>() * pow(as, j);
        N = N * mp::pow(-ab.second, d).convert_to<mp::cpp_bin_float_quad>();

        if (N == 0 || summa == 0)
            i = algebraic_factor.size();
        while (i < algebraic_factor.size())
        {
            d0 = -algebraic_factor[int(i)].first*ab.second%algebraic_factor[int(i)].second;
            d3 = ab.first%algebraic_factor[int(i)].second;

            if (d0 < 0)
                d0 += algebraic_factor[int(i)].second;

            if (d3 < 0)
                d3 += algebraic_factor[int(i)].second;

            if (d3 == d0)
                do {
                    if ((int128_t)N % algebraic_factor[int(i)].second == 0)
                    {
                        N /= algebraic_factor[int(i)].second.convert_to<mp::cpp_bin_float_quad>();
                        mas[(yup + 1).convert_to<size_t>()][ij.convert_to<size_t>()]++;
                    }
                } while ((int128_t)N % algebraic_factor[int(i)].second == 0);
                i++;
                yup++;
        }
        if (N == 1 && summa == 1)
        {
            vector<int128_t> mapk = Schirokauer_Maps(ab.first, ab.second, -equation[0] * ab.second, qs);
            int128_t y = 0;
            for (int u = algebraic_factor.size() * 2 + 1; u < b; u++, y++)
                mas[u][ij.convert_to<size_t>()] = mapk[y.convert_to<size_t>()];
            ij++;
        }
        else
        {
            pairs[o].first = 0;
            pairs[o].second = 0;
            o--;
            for (int k = 0; k<b; k++)
                mas[k][ij.convert_to<size_t>()] = 0;
        }
        N = 0;
    } while (ij != b);

    //добавляем 1 строку в начало и ответ системы
    vector<int128_t> rezult(b.convert_to<size_t>());
    int128_t G = 0;
    int128_t H = 0;
    int128_t S = 0;
    int128_t R = 0;
    int128_t yup = 0;
    do {
        S = rand() % qs + 10;
        G = int128_t(powmod(g, S, p));
        while (yup != rational_factor.size())
        {
            if (G % rational_factor[yup.convert_to<size_t>()].second == 0)
            {
                G /= rational_factor[yup.convert_to<size_t>()].second;
                mas[(yup + 1).convert_to<size_t>()][0]++;
            }
            else
                yup++;
        }
        if (G != 1)
        {
            for (int i = 0; i<b; i++)
                mas[i][0] = 0;
        }
        yup = 0;
    } while (G != 1);
    yup = 0;
    do {
        R = rand() % qs + 10;
        H = int128_t(powmod(g, R, p)*h) % p;
        while (yup != rational_factor.size())
        {
            if (H % rational_factor[yup.convert_to<size_t>()].second == 0)
            {
                H /= rational_factor[yup.convert_to<size_t>()].second;
                rezult[(yup + 1).convert_to<size_t>()]++;
            }
            else
                yup++;
        }
        yup = 0;
        if (H != 1)
        {
            for (int i = 0; i<b; i++)
                rezult[i] = 0;
        }
    } while (H != 1);

    for (int i = 0; i < b; i++)
    {
        if (rezult[i] != 0)
            rezult[i] = -rezult[i] + qs;
    }

    auto resh = gauss(mas, rezult, b, qs);
    int128_t k = 0;
    int128_t k1 = 0;
    int64_t x = 0;
    /*do {
    if (k == resh.size())
    return -1;
    x = (-resh[k][0] * S - R) % qs;
    if (x < 0)
    x += qs;
    k++;
    } while (powmod(g, x, p) != h);*/
    k1 = (-resh[k.convert_to<size_t>()][0] * S - R) % qs;
    x = k1.convert_to<int64_t>();
    if (x < 0)
        x += uint64_t(qs);
    return x;
}

Когда собираю ошибок нет, но как только начинаеться запуск выдает ошибку:

Необработанное исключение по адресу 0x00007FFDB2D4879B (ntdll.dll) в
  all_metods.exe: 0xC0000374: Куча была повреждена (параметры:
  0x00007FFDB2DAC6E0).

update
в debug выдает ошибку:

Вызвано исключение по адресу 0x00007FFDB2CC7670 (ntdll.dll) в
  all_metods.exe: 0xC0000005: нарушение прав доступа при чтении по
  адресу 0xFFFFFFFFFFFFFFFF.


text:
Q: fix ionic cordova google-services/firebase build error Hi I have a ionic cordova project and it build ok on ios, but when i invoke
ionic cordova build android (or "ionic cordova run android" either) it return the following error:

Failed to notify dependency resolution listener.
The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[15.0.2,15.0.2], [16.0.0,16.0.0]], but resolves to 15.0.4. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.
The library com.google.firebase:firebase-analytics-impl is being requested by various other libraries at [[15.0.2,15.0.2], [16.1.1,16.1.1]], but resolves to 16.1.1. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

My root level build.gradle looks like this:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.android.tools.build:gradle:3.0.0'
    } }

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="25.0.2" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=26 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=26 //Integer - We ALWAYS compile with the latest by default
    } }

task clean(type: Delete) {
    delete rootProject.buildDir }

inside the app/ folder the build.gradle is:
apply plugin: 'com.android.application'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
    repositories {
        mavenCentral();
        jcenter()
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '4.1.0'
}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: '../CordovaLib/cordova.gradle'
    // The value for android.compileSdkVersion.
    if (!project.hasProperty('cdvCompileSdkVersion')) {
        cdvCompileSdkVersion = null;
    }
    // The value for android.buildToolsVersion.
    if (!project.hasProperty('cdvBuildToolsVersion')) {
        cdvBuildToolsVersion = null;
    }
    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Sets the minSdkVersion to the given value.
    if (!project.hasProperty('cdvMinSdkVersion')) {
        cdvMinSdkVersion = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // Whether to append a 0 "abi digit" to versionCode when only a single APK is build
    if (!project.hasProperty('cdvVersionCodeForceAbiDigit')) {
        cdvVersionCodeForceAbiDigit = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
apply from: "../cordova-plugin-firebase/myapp-build.gradle"
apply from: "../cordova-plugin-googlemaps/myapp-tbxml-android.gradle"
apply from: "../card.io.cordova.mobilesdk/myapp-build.gradle"
apply from: "../com.paypal.cordova.mobilesdk/myapp-build.gradle"
apply from: "../cordova-android-play-services-gradle-release/myapp-cordova-android-play-services-gradle-release.gradle"
apply from: "../cordova-plugin-browsertab/myapp-BrowserTab.gradle"
apply from: "../cordova-plugin-buildinfo/myapp-BuildInfo.gradle"
apply from: "../cordova-support-google-services/myapp-build.gradle"
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
    apply from: 'build-extras.gradle'
}

// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
    ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
    //ext.cdvCompileSdkVersion = project.ext.defaultCompileSdkVersion
}
if (ext.cdvBuildToolsVersion == null) {
    ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
    //ext.cdvBuildToolsVersion = project.ext.defaultBuildToolsVersion
}
if (ext.cdvDebugSigningPropertiesFile == null && file('../debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = '../debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('../release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = '../release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvVersionCodeForceAbiDigit = cdvVersionCodeForceAbiDigit == null ? false : cdvVersionCodeForceAbiDigit.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : defaultMinSdkVersion
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps << {
    println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
    println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
    println('cdvVersionCode=' + cdvVersionCode)
    println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)
    println('cdvMinSdkVersion=' + cdvMinSdkVersion)
    println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
    println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
    println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
    println('cdvBuildArch=' + cdvBuildArch)
    println('computedVersionCode=' + android.defaultConfig.versionCode)
    android.productFlavors.each { flavor ->
        println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
    }
}

android {

    defaultConfig {
        versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))
        applicationId privateHelpers.extractStringFromManifest("package")

        if (cdvMinSdkVersion != null) {
            minSdkVersion cdvMinSdkVersion
        }
    }

    lintOptions {
      abortOnError false;
    }

    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion

    //This code exists for Crosswalk and other Native APIs.
    //By default, we multiply the existing version code in the Android Manifest by 10 and
    //add a number for each architecture.  If you are not using Crosswalk or SQLite, you can
    //ignore this chunk of code, and your version codes will be respected.

    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        flavorDimensions "default"

        productFlavors {
            armeabi {
                versionCode defaultConfig.versionCode*10 + 1
                ndk {
                    abiFilters = ["armeabi"]
                }
            }
            armv7 {
                versionCode defaultConfig.versionCode*10 + 2
                ndk {
                    abiFilters = ["armeabi-v7a"]
                }
            }
            arm64 {
                versionCode defaultConfig.versionCode*10 + 3
                ndk {
                    abiFilters = ["arm64-v8a"]
                }
            }
            x86 {
                versionCode defaultConfig.versionCode*10 + 4
                ndk {
                    abiFilters = ["x86"]
                }
            }
            x86_64 {
                versionCode defaultConfig.versionCode*10 + 5
                ndk {
                    abiFilters = ["x86_64"]
                }
            }
        }
    } else if (Boolean.valueOf(cdvVersionCodeForceAbiDigit)) {
        // This provides compatibility to the default logic for versionCode before cordova-android 5.2.0
        defaultConfig {
            versionCode defaultConfig.versionCode*10
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.
                storeFile = null
                storePassword = "__unset"
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }
    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }
}

/*
 * WARNING: Cordova Lib and platform scripts do management inside of this code here,
 * if you are adding the dependencies manually, do so outside the comments, otherwise
 * the Cordova tools will overwrite them
 */

dependencies {
    implementation fileTree(dir: 'libs', include: '*.jar')
    // SUB-PROJECT DEPENDENCIES START
    implementation(project(path: ":CordovaLib"))
    compile "com.google.gms:google-services:11.8.0"
    compile "com.google.android.gms:play-services-tagmanager:11.8.0"
    compile "com.google.firebase:firebase-core:11.8.0"
    compile "com.google.firebase:firebase-messaging:11.8.0"
    compile "com.google.firebase:firebase-crash:11.8.0"
    compile "com.google.firebase:firebase-config:11.8.0"
    compile "com.google.firebase:firebase-perf:11.8.0"
    compile "com.google.android.gms:play-services-maps:11.8.0"
    compile "com.google.android.gms:play-services-location:11.8.0"
    compile "com.android.support:support-core-utils:24.1.0"
    compile "com.android.support:customtabs:23.3.0"
    compile "com.android.support:support-v4:24.1.1+"
    // SUB-PROJECT DEPENDENCIES END
}

def promptForReleaseKeyPassword() {
    if (!cdvReleaseSigningPropertiesFile) {
        return;
    }
    if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
        android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
    }
    if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
        android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
    }
}

gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each() { task ->
      if(['validateReleaseSigning', 'validateSigningRelease', 'validateSigningArmv7Release', 'validateSigningX76Release'].contains(task.name)) {
         promptForReleaseKeyPassword()
      }
    }
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase();
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}

I tried to follow the instructions at:
[How to fix google play service error
but with no luck.
What I don't understand is this part of the error
"is being requested by various other libraries at [[15.0.2,15.0.2], [16.0.0,16.0.0]], but resolves to 15.0.4"
which version should i use ? Where do I specify this? I looked in both my gradle files (even with webstorm's search in path) but I didn't find any declaration
Thanks in advance,
Luca


text:
Q: T-SQL: Is there a way to check if the value of one variable is present in another variable Code:
Declare @a VARCHAR(100) = ';2;9;12;13;14;16;17;21;'
Declare @b VARCHAR(100) = ';2;12;13;'
Declare @c VARCHAR(100)
While len(@a) > 1
Begin
    Set @c = substring(@a,1,charindex(';',@a,2))
    Set @b += @c Where @c Not In @b  ----This statement gives a problem and shows a syntax error
    Set @a = substring(@a,charindex(';',@a,2),len(@a))
    Select @a, @b, @c
End

What I'm trying to accomplish here is that I have declared 2 variables of VARCHAR type and assigned them some value. A third variable I've declared is a sub-string derived from the 1st variable. The value of the 3rd variable I'm trying to find it's presence in the 2nd variable and if it's not I'm trying to concatenate it with the 2nd one.
So the first value that @c would get is: ';2;' and it should compare with @b and if not present in @b it should concatenate with @b.
So basically the result should look something like this in the end.
@b = ';2;12;13;9;14;16;17;21;'
Kindly help. Thanks.

A: If I understand your problem correctly, I believe you would want to use sets (tables) instead of strings.  You could do this with strings if absolutely necessary using a split function (exists in SQL Server 2016 but will have to write your own for prior versions.  There are tons of examples on S.O.)
To use sets, Try this:
DECLARE @a TABLE (id INT identity(1, 1), val INT)
DECLARE @b TABLE (Val INT)
DECLARE @c INT
DECLARE @aSetStr VARCHAR(max)
DECLARE @bSetStr VARCHAR(max)

INSERT INTO @a
VALUES (2), (9), (12), (13), (14), (16), (17), (21)

INSERT INTO @b
VALUES (2), (12), (13)

DECLARE @i INT = 0

WHILE EXISTS (
        SELECT A.id
        FROM @a A
        LEFT JOIN @b B
            ON A.Val = B.Val
        WHERE A.id > @i AND B.Val IS NULL
        )
BEGIN
    SELECT TOP 1 @i = A.id, @c = A.Val
    FROM @a A
    LEFT JOIN @b B
        ON A.Val = B.Val
    WHERE A.id > @i AND B.Val IS NULL
    ORDER BY A.id ASC

    IF NOT EXISTS (
            SELECT 1
            FROM @b B
            WHERE B.Val = @c
            )
        INSERT INTO @b (Val)
        SELECT @c

    SELECT @aSetStr = STUFF((
                SELECT ';' + CAST(val AS VARCHAR(max))
                FROM @a
                FOR XML PATH('')
                ), 1, 0, '') + ';'

    SELECT @bSetStr = STUFF((
                SELECT ';' + CAST(val AS VARCHAR(max))
                FROM @b
                FOR XML PATH('')
                ), 1, 0, '') + ';'

    SELECT @aSetStr AS [Set A], @bSetStr AS [Set B], cast(@C AS VARCHAR(255)) AS [Value of C]
END

This will Yield
Set A                      Set B                     Value of C
-------------------------- ------------------------- ------------
;2;9;12;13;14;16;17;21;    ;2;12;13;9;               9

Set A                      Set B                     Value of C
-------------------------- ------------------------- ------------
;2;9;12;13;14;16;17;21;    ;2;12;13;9;14;            14

Set A                      Set B                     Value of C
-------------------------- ------------------------- ------------
;2;9;12;13;14;16;17;21;    ;2;12;13;9;14;16;         16

Set A                      Set B                     Value of C
-------------------------- ------------------------- ------------
;2;9;12;13;14;16;17;21;    ;2;12;13;9;14;16;17;      17

Set A                      Set B                     Value of C
-------------------------- ------------------------- ------------
;2;9;12;13;14;16;17;21;    ;2;12;13;9;14;16;17;21;   21

A: TRY THIS CODE
    Declare @a VARCHAR(100) = ';2;9;12;13;14;16;17;21;'
    Declare @b VARCHAR(100) = ';2;12;13;'
    Declare @c VARCHAR(100)
    While len(@a) > 1
    Begin
        Set @c = substring(@a,1,charindex(';',@a,2))
            IF (@c) NOT IN (@b) begin
                Set @b += @c
            end

         Set @a = substring(@a,charindex(';',@a,2),len(@a))
        Select @a, @b, replace(@c,';','')
    End

A: Another way of getting expected Result
Declare @a VARCHAR(100) = ';2;9;12;13;14;16;17;21;'
Declare @b VARCHAR(100) = ';2;12;13;'

DECLARE @Tempa TABLE (Value nvarchar(1000))
INSERT INTO @Tempa VALUES(@a)
DECLARE @Tempb TABLE (Value nvarchar(1000))
INSERT INTO @Tempb VALUES(@b)

;WITH cte
     AS (SELECT Cast(dataa AS INT) AS DataA
         FROM   (SELECT split.a.value('.', 'nvarchar(1000)') AS DataA
                 FROM   (SELECT Cast('<S>' + Replace(value, ';', '</S><S>') +
                                     '</S>'
                                     AS
                                     XML) AS
                                Data
                         FROM   @Tempa)AS A
                        CROSS apply data.nodes('S') AS Split(a)) dt
         WHERE  dt.dataa <> ''
         UNION
         SELECT Cast(dataa AS INT) AS DataA
         FROM   (SELECT split.a.value('.', 'nvarchar(1000)') AS DataA
                 FROM   (SELECT Cast('<S>' + Replace(value, ';', '</S><S>') +
                                     '</S>'
                                     AS
                                     XML) AS
                                Data
                         FROM   @Tempb)AS A
                        CROSS apply data.nodes('S') AS Split(a))dt
         WHERE  dt.dataa <> '')
SELECT ''';' + Stuff((SELECT '; '+Cast(dataa AS VARCHAR(10)) FROM cte ORDER BY
       dataa
       FOR xml path ('')), 1, 1, '') + ' ;''' AS ExpectedCResult

Result
ExpectedCResult
---------------------------------
'; 2; 9; 12; 13; 14; 16; 17; 21 ;'

A: If your values are unique, you can use UNION to merge your strings:
    Declare @a VARCHAR(100) = ';2;9;12;13;14;16;17;21;'
    Declare @b VARCHAR(100) = ';2;7;12;13;'
    Declare @c VARCHAR(100)

    ;WITH
    a AS
    (
        SELECT @a AS FIELD, SUBSTRING(@a, 1, CHARINDEX(';', @a)) AS num
        UNION ALL
        SELECT RIGHT(FIELD, LEN(FIELD)-LEN(num)), SUBSTRING(RIGHT(FIELD, LEN(FIELD)-LEN(num)), 1, CHARINDEX(';', RIGHT(FIELD, LEN(FIELD)-LEN(num))))
        FROM a
        WHERE FIELD != num
    ),
    b AS
    (
        SELECT @b AS FIELD, SUBSTRING(@b, 1, CHARINDEX(';', @b)) AS num
        UNION ALL
        SELECT RIGHT(FIELD, LEN(FIELD)-LEN(num)), SUBSTRING(RIGHT(FIELD, LEN(FIELD)-LEN(num)), 1, CHARINDEX(';', RIGHT(FIELD, LEN(FIELD)-LEN(num))))
        FROM b
        WHERE FIELD != num
    )
    SELECT @c =
        (
        SELECT ';' + CAST(v.num AS VARCHAR)
        FROM (
            SELECT CAST(REPLACE(a.num, ';', '') AS INT) num
            FROM a
            WHERE a.num != ';'
            UNION
            SELECT CAST(REPLACE(b.num, ';', '') AS INT)
            FROM b
            WHERE b.num != ';'
        ) v
        FOR XML PATH('')
        ) + ';'

SELECT @c

A: To solve your problem straightforwardly, change:
Set @b += @c Where @c Not In @b

To:
SET @b += CASE WHEN CHARINDEX(@c, @b) > 0 THEN '' ELSE @c END


text:
Q: Search inside a range of fields MongoDB I have a DB on MongoDB, with a collection like this:
{
    "_id" : ObjectId("59a64b4cfb80146432aff6ac"),
    "name": "Mid Range",
    "end" : NumberLong("50000"),
    "start" : NumberLong("10000"),
},
{
    "_id" : ObjectId("59a64b4cfb80146432aff6ac"),
    "name": "Hi Range",
    "end" : NumberLong("100000"),
    "start" : NumberLong("150000"),
}

The user enters a number to validate: 125000, i need a query to get: "Hi Range" document.
How can i do that? I'm trying to avoid code side, but if there is no choice it's ok.
Thanks!

A: You could even make do without the $and. You just need to set the query to find a result such that your number is less than or equal to its end and greater than or equal to its start. For example:
db.collection.find({start: {$lte: 125000}, end: {$gte: 125000}})

Note: Careful, if you want that range to include the start and end number, use $lte, $gte. Using $lt or $gt will not include it.

A: You can do it like this -
db.find({name:/Hi Range/}) // regular Expression.

A: To avoid logic that determine that 12500 is Hi Range you could do something like this
db.collection.find( { $and: [ { start: { $lte: 125000 } }, { end: { $gt: 12500 } } ] } )


text:
Q: Merge sort using inplace merging A[]  ->  1 3 5 7 2 4 6 8      //
lb=0,mid-1=3,mid+1=4,ub=7;
a=3,b=7,ab=7;
1st iteration
a=3,b=6,ab=6;

2nd iteration
swap(A[ab],A[a])  // int t; t i'll using for temporary storage
1 3 5 6 2 4 7 8
b=5,ab=5;
 sort(A,lb,mid-1);  // using bubble sort

3rd iteration
swap(A[ab],A[a])
1 3 5 4  2 6 7 8
b=5,ab=4
sort(A,lb,mid-1) // using bubble sort

Is this correct approach for Merge sort using inplace merging. This is my first attempt about inplace merging.If it is not correct approach  someone can suggest me.

A: Not sure that you have Mergesort algorithm.
Using Mergesort at first phase you need to split you array into subarrays.
A = [1, 3, 5, 7, 2, 4, 6, 8]

A1 = [1, 3, 5, 7], A2 = [2, 4, 6, 8]

A11 = [1,3], A12 = [5,7], A21 = [2,4], A22 = [6,8]
... // till you have an arrays looks like this:
A1 = [1], A2 = [3], A3 = [5], A4 = [7], A5 = [2], A6 = [4], A7 = [6], A8 = [8]

Then you merging in reverse order, and compare only first elements in both arrays (put lowest element in new array).
[1,3], [5,7], [2,4], [6,8]
  [1,3,5,7],   [2,4,6,8]
     [1,2,3,4,5,6,7,8]


text:
Q: Nginx is outputting logs to my terminal (stdout). How can I stop it? My laptop is ArchLinux, with Nginx 1.6.2 installed. I've never touched Nginx's log configuration, but out of blue, when I try to access the local website, the logs will be printed to the opening Terminal (if more than one is opening, there's only one will have it).
I just cant't figure out why, and how can I locate the problem.
Any answers would be appreciated.
# nginx.conf file content
user http;
worker_processes  8;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #$status $body_bytes_sent "$http_referer" '
    #'"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;
    include servers/*.conf;
}
#below is one of the server config file content
server {
listen       80;
server_name  www.laravel.com;

#charset koi8-r;

#access_log  logs/host.access.log  main;

root   /srv/http/blog/public;

location / {
    index  index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$query_string;
}

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
       # fastcgi_pass   127.0.0.1:9000;
       fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
       include        fastcgi_params;
    }

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
    #    deny  all;
    #}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
    #listen       8000;
    #listen       somename:8080;
    #server_name  somename  alias  another.alias;

    #location / {
    #root   html;
    #index  index.html index.htm;
    #}
#}

A: As far as I can say, and I'm not sure, cause of the "formating": There is not a single line sayig something like error_log  /where/should/nging/save/the/error.log; that is not comment out.
The vhost config should look somewhat like:
server {
    listen       80;
    server_name  www.laravel.com;
    charset koi8-r;
    access_log  /where/to/put/the/logs/host.access.log  main;
    error_log   /where/to/put/the/logs/host.error.log; # <- LOOK AT THIS LINE
    root   /srv/http/blog/public;
    location / {
        # ...
    }
}


text:
Q: MySQL counting occurrence of values in a field I've got a MySQL table containing 115 fields like these:
v1q1  v1q2  v2q1  v2q2  v3q1  v3q3 (...)

The records all contain one of the value 0, 1, 2, 3 or 4.
Now I need to count for every field the number of records containing a 0, the number of records containing a 1, the number of records containing a 2,... (until 4).
How I can accomplish this in a rather efficient way?

A: You can use the IF statement and doing a sum like this:
SELECT
 SUM(IF(v1q1=0, 1, 0)) as cnt0,
 SUM(IF(v1q1=1, 1, 0)) as cnt1,
 SUM(IF(v1q1=2, 1, 0)) as cnt2,
 SUM(IF(v1q1=3, 1, 0)) as cnt3,
 SUM(IF(v1q1=4, 1, 0)) as cnt4
FROM `myTable`

A: You can't do that in any efficient way. The layout of the database itself is inefficient, and you can't overcome that with any kind of query.
Patrick showed you how to do it for one single field in the table. Now make a query that contains that 115 times... As you see, that is not efficient.
You should have the values in the table where the data that you now have in the field names is where data belongs; in the fields:
id v q value
-------------
1  1 1 2
1  1 2 4
1  2 1 0
1  2 2 1
1  3 1 3
1  3 3 2
2  1 1 0
2  1 2 1
2  1 2 0
2  2 1 4
...

Now that you have all the data as actual data, you can get the information efficiently:
select v, q, value, count(*)
from TheTable
group by v, q, value


text:
Q: android - How to tell what resources are still loading? I have a webview in my Android app and sometimes it loads up perfectly but other times window.load() just never gets called and I have to refresh the webview a few times to get it to work.
Is there a way I can see what's still trying to load?

A: Check WebViewClient:
http://developer.android.com/reference/android/webkit/WebViewClient.html
webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        //get the url being loaded
    }

    public void onLoadResource (WebView view, String url) {
       //get the url of the resource being loaded
    }
}


text:
Q: Titanium app running on titanium sdk 3.4.0 but not on titanium sdk 3.5.0 Titanium app is running fine on titanium sdk 3.4.0 but when I updated titanium sdk to 3.5.0,the app is installing on device but application does not starts.I have not used any module,so I do not converted any module to 64 bit.
What should I do? I have created adhoc provisioning profile to test the app on device,but after updating to 3.5.0 titanium sdk,the app is not working..
Thanks...


text:
Q: Build color scale from numeric values in python I need a method to build a color scale from a numeric variable, for example from blue through black to red, for further use on geo heat maps and other things. How can I do this?

A: You may want to consider using matplotlib and its built in colormaps - see https://matplotlib.org/3.1.0/gallery/color/colormap_reference.html


text:
Q: How to make jenkins job wait for other job triggered by same event? job_A and job_B gets triggered for gerrit_change_x - this works.
I want job_A to do a Verified+ on gerrit_change_x only after job_B finishes successfully, I cannot use "Trigger build on other projects" on job_A to trigger job_B because I need it to get triggered by a gerrit event so I can use all GERRIT_XXX env variables in job_B as well. job_A can start after job_B or at the same time, but will have to wait for job_B's result before the last "execute shell" step which does Verified+.

A: Actually you do not need to have a second job triggered by gerrit. You do the trigger parametrized down stream job with the same params you have in gerrit triggered job only if the original job build is successful. I do this way. The 1st build once succeed set the verify label and trigger down stream. If failed ,set verify as minus and do not trigger down stream.  It's enough to see there is something wrong at what exactly step of verification.