text:
Q: How to get an Istio VirtualService to vary routes by header along with uri I'm still experimenting with Istio in a dev cluster, along with a couple of other people.  We have a sample virtualservice, deployment, and destinationrule, and requests to the specified uri are going to the pod associated with the deployment.  This is working fine.
I am attempting a variation of this that goes to an alternate deployment if a particular header and value are present.  If the header is not set, or the specified header value is not present, it will go to the original deployment, otherwise to the alternate deployment.  I eventually intend for it to check for several different values of the specified header, each going to different deployments.
I've created a deployment and destination rule that are copies of the original, with consistent variations.  I attempted to modify the virtualservice with this alternate routing.  Thus far, it isn't working properly.  I determine which deployment a request goes to by tailing the container log of the container associated with each deployment.  When I sent a request with the specified header and value, it does go to the alternate deployment.  However, when I send the request without the specified header, or without the matching value, it ALSO goes to the alternate deployment. In fact, I can't get it to reach the main deployment at all.
Note that I understand that another way to do this is to have one virtualservice for the "default" route, and an additional virtualservice for each alternate route, specifying a different header value.  I've seen something basically like that working.  However, that seems like a lot of duplication to get something that should be simpler to set up in a single VirtualService.
The following is the current state of the virtualservice, with some elisions:
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  annotations: {}
  name: fooms-vs-ingress
  namespace: com-example
spec:
  gateways:
  - ingress-gateway
  hosts:
  - '*'
  http:
  - match:
    - uri:
        prefix: /msapi/foo
    - headers:
        ctx-debug-route-fooms:
          exact: myuid-1
    route:
    - destination:
        host: fooms.com-example.svc.cluster.local
        port:
          number: 80
        subset: myuid-1
  - route:
    - destination:
        host: fooms.com-example.svc.cluster.local
        port:
          number: 80
        subset: blue

I could show the deployments and destinationrules, but I don't know if that will be helpful.
Update:
Since I wrote this, I discovered that in order to make two conditions AND in a route match, I have to have both conditions in a single match rule. I'm still getting used to how YAML works.  I'm going to provide here an updated version of the virtualservice, along with the gateway, destination rule, and much of the deployment.  There's a lot of stuff in the deployment that probably isn't helpful.
When I sent a request to the service from Postman, with or without the routing header, I get a 503 back.  Before I made these changes to check for the routing header, it was properly routing requests to the "blue" instance (I am tailing the logs for both pods).  When I first tried making these changes, I inadvertently defined two match blocks, one with the uri condition, and one with the header match condition.  When I did that, all of the requests were going to the alternate pod.
Here are elided versions of the objects that might be relevant, with some transient properties removed.
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  annotations: {}
  name: fooms-vs-ingress
  namespace: com-example
spec:
  gateways:
  - comp-ingress-gateway
  hosts:
  - '*'
  http:
  - match:
    - headers:
        compctx-debug-route-fooms:
          exact: myuid-1
      name: match-myuid-1
      uri:
        prefix: /msapi/foo
    route:
    - destination:
        host: fooms.com-example.svc.cluster.local
        port:
          number: 80
        subset: myuid-1
  - name: default
    route:
    - destination:
        host: fooms.com-example.svc.cluster.local
        port:
          number: 80
        subset: blue

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  annotations: {}
  name: comp-ingress-gateway
  namespace: com-example
spec:
  selector:
    istio: ingressgateway
  servers:
  - hosts:
    - '*'
    port:
      name: http
      number: 80
      protocol: HTTP
  - hosts:
    - '*'
    port:
      name: https
      number: 443
      protocol: HTTPS
    tls:
      mode: SIMPLE
      privateKey: /etc/istio/ingressgateway-certs/tls.key
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  labels:
    app: FooMS
    role: blue
    routeoffer: DEFAULT
    seed: COMPv2.2.0
    version: 2.2.0-myuid-1
  name: fooms-myuid-1
  namespace: com-example
spec:
  replicas: 1
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      app: FooMS
      role: blue
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      annotations:
        sidecar.istio.io/inject: "true"
      creationTimestamp: null
      labels:
        app: FooMS
        role: blue
        routeoffer: DEFAULT
        seed: COMPv2.2.0
        version: 2.2.0-myuid-1
    spec:
      containers:
      - env:
        - name: SERVICE_NAME
          value: fooms
        - name: NODE_NAME
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: spec.nodeName
        envFrom:
        - configMapRef:
            name: global-config
        - secretRef:
            name: global-secrets
        image: dockercentral.it....
        imagePullPolicy: Always
        name: fooms
        ports:
        - containerPort: 8080
          name: http
          protocol: TCP
      - image: ...
        imagePullPolicy: IfNotPresent
        name: info
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      serviceAccount: default
      serviceAccountName: default
      terminationGracePeriodSeconds: 30

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  annotations: {}
  name: fooms-destination-myuid-1
  namespace: com-example
spec:
  host: fooms.com-example.svc.cluster.local
  subsets:
  - labels:
      version: 2.2.0-myuid-1
    name: myuid-1
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL

A: Since I don't have all  informations from this command kubectl get pods,ep,svc -o wide i'm not sure that's destination rule error because i don't know everything about your pods,ep,svc and your destination rule applies to same deployment with only 1 replica.
Probably the problem there is destination rule with only 1 subset
Based on your virtual service i think that's how your destination rule should look
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: fooms-destination-myuid-1
  namespace: com-example
spec:
  host: fooms.com-example.svc.cluster.local
  subsets:
  - labels:
      version: 2.2.0-myuid-1
    name: myuid-1
  subsets:
  - labels:
       role: blue
    name: blue
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL

I made some example, everything needed to make this below
Kubernetes version 1.13.11-gke.14
Istio version 1.4.1
kubectl label namespace default istio-injection=enabled

Deployment 1
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx1
spec:
  selector:
    matchLabels:
      run: nginx1
  replicas: 1
  template:
    metadata:
      labels:
        run: nginx1
        app: frontend
    spec:
      containers:
      - name: nginx1
        image: nginx
        ports:
        - containerPort: 80
        lifecycle:
          postStart:
            exec:
              command: ["/bin/sh", "-c", "echo Hello nginx1 > /usr/share/nginx/html/index.html"]

Deployment 2
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx2
spec:
  selector:
    matchLabels:
      run: nginx2
  replicas: 1
  template:
    metadata:
      labels:
        run: nginx2
        app: frontend
    spec:
      containers:
      - name: nginx2
        image: nginx
        ports:
        - containerPort: 80
        lifecycle:
          postStart:
            exec:
              command: ["/bin/sh", "-c", "echo Hello nginx2 > /usr/share/nginx/html/index.html"]

Service
apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: frontend
spec:
  ports:
  - port: 80
    protocol: TCP
  selector:
    app: frontend

Gateway
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: comp-ingress-gateway
  namespace: default
spec:
  selector:
    istio: ingressgateway
  servers:
  - hosts:
    - '*'
    port:
      name: http
      number: 80
      protocol: HTTP
  - hosts:
    - '*'
    port:
      name: https
      number: 443
      protocol: HTTPS
    tls:
      mode: SIMPLE
      privateKey: /etc/istio/ingressgateway-certs/tls.key
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt

Virtual Service
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: nginxvirt
spec:
  gateways:
  - comp-ingress-gateway #outside cluster
  - mesh #inside cluster
  hosts:
  - nginx.default.svc.cluster.local #inside cluster
  - nginx.com #outside cluster
  http:
  - name: match-myuid
    match:
    - uri:
        prefix: /msapi
      headers:
        compctx:
          exact: myuid
    rewrite:
      uri: /
    route:
    - destination:
        host: nginx.default.svc.cluster.local
        port:
          number: 80
        subset: v1
  - name: default
    route:
    - destination:
        host: nginx.default.svc.cluster.local
        port:
          number: 80
        subset: v2

Destination Rule
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: nginxdest
spec:
  host: nginx.default.svc.cluster.local
  subsets:
  - name: v1
    labels:
      run: nginx1
  - name: v2
    labels:
      run: nginx2
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL

Pod for testing
apiVersion: v1
kind: Pod
metadata:
  name: ubu1
spec:
  containers:
  - name: ubu1
    image: ubuntu
    command: ["/bin/sh"]
    args: ["-c", "sleep 3000"]

And results from curl:
Outside:
curl -H "host: nginx.com" -H "compctx: myuid" ingress_gateway_ip/msapi
Hello nginx1
curl -H "host: nginx.com" -H "compctx: myuid" ingress_gateway_ip/msapi
Hello nginx1
curl -H "host: nginx.com" -H "compctx: myuid" ingress_gateway_ip/msapi
Hello nginx1

curl -H "host: nginx.com" ingress_gateway_ip
Hello nginx2
curl -H "host: nginx.com" ingress_gateway_ip
Hello nginx2
curl -H "host: nginx.com" ingress_gateway_ip
Hello nginx2

Inside:
kubectl exec -ti ubu1 -- /bin/bash

root@ubu1:/# curl -H "compctx: myuid " nginx/msapi
Hello nginx1
root@ubu1:/# curl -H "compctx: myuid " nginx/msapi
Hello nginx1
root@ubu1:/# curl -H "compctx: myuid " nginx/msapi
Hello nginx1


text:
Q: How to convert from plain text to URL Encoded html I need to know how to convert a text message to URL Encoded html. (I mean the HTML code that's actually being sent to the web server)
Example of the conversation:
Text: Hello, Brother!
HTML: Hello%2C+Brother%21
Would be very thankful if anyone helped me.

A: You can URL encode client-side with JavaScript's encodeURIComponent method. If you are using a JavaScript library such as jQuery, they will handle it for you when you encapsulate your data in an object, e.g., jQuery.get() using the data parameter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting Between DateTime Objects & Strings in Python I am trying to take a variable (String), convert it to a DateTime object to increment the day and then convert back to a string again.
The reason for this converting is that the string variables I'm starting with are being read from an SQLite database table. As far as I'm aware SQLite does not support DateTime?
See below for example.
Original String Format:
temp_data = 'May 28 2015'

I then convert it to a dateTime obeject:
temp_data = datetime.datetime.strptime(temp_date, '%d %b %Y')

Then increment the date by one day:
temp_data += datetime.timedelta(days=1)

Which results in temp_data having the following value:
2015-05-29 00:00:00

However, I now want to convert my new temp_data variable back to a string in the format:
'May 29 2015'

I thought I could make use of the strftime function but not completely sure. Would appreciate any help I could get with this.
Thanks.


text:
Q: Magento 2: address custom attribute, from Order entity to Account entity I've added a custom attribute to checkout:

*

*added column in 'quote' and 'sales_oreder' tables

*plugin for Magento\Checkout\Block\Checkout\LayoutProcessor

*plugin for Magento\Checkout\Model\ShippingInformationManagement

*RequireJS + Magento_Checkout/js/model/shipping-save-processor/default override js file

*observer on 'sales_model_service_quote_submit_before' event

All works fine.
The field value is stored in the two tables correctly.
Then, I've added the same custom attribute to customer_address entity:

*

*$this->eavSetup->addAttribute(
AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
self::CUSTOM_ATTRIBUTE_CODE,
[]) .. etc

*plugin for Magento\Sales\Model\Order\CustomerManagement

*observer (adminhtml) on 'core_layout_render_element' event

All works fine. The field value is stored linked to 'customer_address_entity' in EAV mode.
Now,
what I'm trying to do is to save the field into customer_address entity during Checkout Onepage Success Page, when the customer want to create his/her account.
How can I do this?


text:
Q: How to get input text value using Jquery I have the following code, in mydata.jsp value of q is empty. What is the correct way to pass value of inputId to mydata.jsp?
<input type="text" size="25" name="inputId" id="inputId" />

and Jquery script as
 <script type="text/javascript">
$(function() {
    $("#inputId").autocomplete({

        source: "mydata.jsp?q="+$( "#inputId" ).val(),
        select:function(event,ui) {
            $("#hid").val(ui.item.email)
        }
    });
});

</script>

A: When you pass $( "#inputId" ).val() as an argument to .autocomplete(), you're getting the initial value from that field before anything has been typed.  That would explain why it is empty.
If you use the string version of autocomplete, it can automatically add the typed value to the URL.  See the doc for the string version of source here.
If you want the URL for the source to be a dynamically generated URL, then you can also pass a function as the source and the code in that function can generate the URL/alternatives.  See the doc for the source option here.

A:  $('#inputId').keyup(function()
{
var str=$(this).val();
if(str!='')
{
  $.ajax({
      type:"GET",
      url:"mydata.jsp",
      data:"str="+str,
      success: function(data){
          alert(data);
     }

  });
}
});

Try like this. hope it will give you some solution.


text:
Q: python argparse: my help, not auto-generated, but short help for single options Is there a way in argparse
to print
my help, not auto-generated, for --help,
but only the short help= for single options ?
An example:
    # my help, not auto-generated --
if len(sys.argv) >= 1  and sys.argv[1].startswith(( "-h", "--h" )):
    print __doc__
    sys.exit()

p = argparse.ArgumentParser( usage="" )

    # want to print only this short help= for e.g. `-help -col`
p.add_argument( "-col", default=1, type=int,
                        help="the column to look at and color, 1 2 3 ..." )

    # and only this help= for e.g. `-help -color`
p.add_argument( "-color", "-colour", default="red",
                        help="one of: r g b red green blue " )

~


text:
Q: How can I code my program to look at index 7 of my program for only one of two letter How can I code my program to look at index 7 of my program for only one of two letter for the last part of this code. I'm new and been working on this for awhile. This has been given me  a hard time and I keep reading the book and download some video but I just seem to not be getting this.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{

string string;

    // get character
cout << "\nEnter Email address ID: ";
getline(cin,  string );
cout << endl;
{
if (!isalpha(string[0]))
    cout << "first charactor needs to be a Letter"<< endl;

 if (!isalpha(string[1]))
     cout << "Second charactor needs to be a letter"<< endl;

 if (!isdigit(string[2]))
    cout << "Third charactor needs to be a number"<< endl;

 if (!isdigit(string[3]))
    cout << "Fourth charactor needs to be a number"<< endl;

 if (!isdigit(string[4]))
    cout << "Fifth charactor needs to be a number"<< endl;

 if (!isdigit(string[5]))
    cout << "Sixth charactor needs to be a number"<< endl;

if (!isdigit(string[6]))
    cout << "Seventh charactor needs to be a number"<< endl;

if(!isalpha(string[7]))

 if(string != "n" || string !="p")
    cout << "Eight charactor needs to be a N or P"<< endl;
{
}

cout << endl;
system("pause");
return 0;
}
 }

A: -->IsAlpha Determines whether an integer represents an alphabetic character.
                Output:
            Enter Email address ID: abcdef1@kmail.com

            Third charactor needs to be a number
            Fourth charactor needs to be a number
            Fifth charactor needs to be a number
            Sixth charactor needs to be a number
            Eight charactor needs to be a N or P

            Press any key to continue . . .

//-----------------------Make changes in braces as below------
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{

    string string;

    // get character
    cout << "\nEnter Email address ID: ";
    getline(cin,  string );
    cout << endl;
    {
        if (!isalpha(string[0]))
            cout << "first charactor needs to be a Letter"<< endl;

        if (!isalpha(string[1]))
            cout << "Second charactor needs to be a letter"<< endl;

        if (!isdigit(string[2]))
            cout << "Third charactor needs to be a number"<< endl;

        if (!isdigit(string[3]))
            cout << "Fourth charactor needs to be a number"<< endl;

        if (!isdigit(string[4]))
            cout << "Fifth charactor needs to be a number"<< endl;

        if (!isdigit(string[5]))
            cout << "Sixth charactor needs to be a number"<< endl;

        if (!isdigit(string[6]))
            cout << "Seventh charactor needs to be a number"<< endl;

        if(!isalpha(string[7]))
        {
            if(string != "n" || string !="p")
                {cout << "Eight charactor needs to be a N or P"<< endl;

                 }
        }

        cout << endl;
        system("pause");
        return 0;
    }
}


text:
Q: Ubuntu драйвера сетевого адаптера T2U plus Установил ubuntu на пк, нету wifi, полез в интернет, понял, что нужен драйвер, установил по вот такому методу:
1) Скачал с windows10 пакет dkms в формате .deb, установил на ubuntu при помощи утилиты dgpk -i <file.deb>
2) на windows10 ввел комманду: git clone https://github.com/aircrack-ng/rtl8812au.git, перекинул на флешку
3) на убунту зашел на флешку с rtl8812au, ввел комманду sudo ./dkms-install.sh Пишет нету данного файла(он есть). Погуглил, ввел комманду make подождал минут 10, ввел комманду sudo make install, все прошло успешно!
Перезагрузил пк... Ии... НИЧЕГО!
Помогите пожалуйста, где скачать эти драйвера и как установить??? Если что у меня есть ubuntu на ноутбуке(с интернетом).
upd: Пробовал https://askubuntu.com/questions/991643/rtl8812au-usb-adapter-driver-issues способ не работает


text:
Q: Restrict access for Cognito user to their resources? I have a application which uses

*

*Cognito User Pool/Identity Pool to authenticate user and provide access to aws Console using Custom URL

I want those user should see their resources only, I have researched a lot but can't find any solution
For S3, I tried this policy but it still says access denied. What actual value "${cognito-identity.amazonaws.com:sub}" this will give.
 {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": ["s3:ListBucket"],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::mybucket"],
      "Condition": {"StringLike": {"s3:prefix": ["${cognito-identity.amazonaws.com:sub}/*"]}}
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::mybucket/${cognito-identity.amazonaws.com:sub}/*"]
    }
  ]
   }

For EC2, I am using below policy, If i hard code some value in  It works but I want this to be dynamic for Cognito Users. I tried placing  but not working.
      {
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "ec2:DescribeInstances"
        ],
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": "ec2:RunInstances",
        "Resource": [
            "arn:aws:ec2:*:*:volume/*",
            "arn:aws:ec2:*:*:instance/*"
        ],
        "Condition": {
            "StringEquals": {
                "aws:RequestTag/owner": "<KeyValue>"
            }
        }
    },
    {
        "Effect": "Allow",
        "Action": "ec2:RunInstances",
        "NotResource": [
            "arn:aws:ec2:*:*:volume/*",
            "arn:aws:ec2:*:*:instance/*"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "ec2:CreateVolume",
        "Resource": "*",
        "Condition": {
            "StringEquals": {
                "aws:RequestTag/owner": "<KeyValue>"
            }
        }
    },
    {
        "Effect": "Allow",
        "Action": [
            "ec2:CreateTags"
        ],
        "Resource": "*",
        "Condition": {
            "StringEquals": {
                "ec2:CreateAction": [
                    "CreateVolume",
                    "RunInstances",
                    "CreateSnapshot"
                ]
            }
        }
    },
    {
        "Effect": "Allow",
        "Action": [
            "ec2:StartInstances",
            "ec2:StopInstances",
            "ec2:RebootInstances",
            "ec2:TerminateInstances",
            "ec2:CreateTags",
            "ec2:DeleteTags",
            "ec2:AttachVolume",
            "ec2:DetachVolume",
            "ec2:DeleteVolume",
            "ec2:DeleteSnapshot"
        ],
        "Resource": "*",
        "Condition": {
            "StringEquals": {
                "ec2:ResourceTag/owner": "<KeyValue>"
            }
        }
    },
    {
        "Effect": "Allow",
        "Action": "ec2:CreateSnapshot",
        "Resource": [
            "arn:aws:ec2:*:*:snapshot/*"
        ],
        "Condition": {
            "StringEquals": {
                "aws:RequestTag/owner": "<KeyValue>"
            }
        }
    },
    {
        "Effect": "Allow",
        "Action": "ec2:CreateSnapshot",
        "Resource": [
            "arn:aws:ec2:*:*:volume/*"
        ],
        "Condition": {
            "StringEquals": {
                "ec2:ResourceTag/owner": "<KeyValue>"
            }
        }
    }
          ]
          }

To refer my application, Here is the link for my Code. Any leads would be appreciated.


text:
Q: Variable iterates twice (only supposed to once) in a single loop in bash I have an issue where a number is printing twice when it should only be printing once before some output. I'll be highlighting the most relevant content, but to give context, I'll provide the entirety of my script.
#!/bin/bash

I load the out put of a ps aux into an array.
N=0
for i in $(ps aux | awk '{print $11,$4}' | grep -v 0.0 | grep -v MEM | sort) ; do

array[$N]="$i"

let "N= $N + 1"
done

Here I split the array into two arrays
N=0

for i in `seq 0 ${#array[@]}`; do

if [ $(( $i % 2 )) -eq 0 ]; then arrayb[$N]=${array[$i]} ; else arrayc[$N]=${array[$i]} ;fi

let "N= $N + 1"

done

Now I look to combine duplicate entries (please pardon some of the convoluted variable naming; I was taking shots in the dark trying to trouble shoot).
N=0
c=0

for i in `seq 0 ${#arrayb[@]}`; do

let "B= $N - 1"

A=`echo ${arrayb[$B]} | tr -d '\n'`
B=`echo ${arrayb[$N]} | tr -d '\n'`

#A=${arrayb[$B]}
#B=${arrayb[$N]}

Here is where I check to see if the former array element is equal to the latter. If so combine and remove.
#if [ "$A" = "$B" ]; then
#arrayc[$N]=$(bc <<< ${arrayc[$N]}+${arrayc[$B]}); unset arrayb[$B];unset arrayc[$B]; echo trololo
#echo derp
#fi

The important part though is this. echo $c then I echo $A $B. My output however shows the following:
0
 awk
1
awk
2
 -bash
3
-bash
4
 -bash

When it should be something like:
0
 awk
awk
2
 -bash
-bash
3

echo $c
echo -n "$A" "$B"

echo ""
let "c=$c+1"

let "N= $N + 1"
done

What I can't wrap my head around is how it prints a then c then b then c when it's all the same loop. Any assistance would be greatly appreciated.

A: The first for loop can be simplified to:
array=( $(ps aux | awk '$4 != 0.0 && $4 !~ /MEM/ {print $11,$4}' | sort) )

When written as a single fragment, the second loop is:
N=0
for i in `seq 0 ${#array[@]}`
do
    if [ $(( $i % 2 )) -eq 0 ]
    then arrayb[$N]=${array[$i]}
    else arrayc[$N]=${array[$i]}
    fi
    ((N++))
done

You are incrementing N every iteration, so you have arrayb[0] containing a name and arrayc[1] containing the corresponding memory usage. You should probably be using:
for i in `seq 0 ${#array[@]}`
do
    if [ $(( $i % 2 )) -eq 0 ]
    then arrayb[$((i/2))]=${array[$i]}
    else arrayc[$((i/2))]=${array[$i]}
    fi
done

However, you'd probably do better again to combine the first assignment with the second loop:
ps aux | awk '$4 != 0.0 && $4 !~ /MEM/ {print $11,$4}' | sort |
while read name memory
do
     arrayb+=($name)
     arrayc+=($memory)
done

The only snag here is that the arrays are set in a sub-shell which exits.  Fortunately, bash provides Process Substitution to evade that problem:
arrayb=()
arrayc=()
while read name memory
do
     arrayb+=($name)
     arrayc+=($memory)
done < <(ps aux | awk '$4 != 0.0 && $4 !~ /MEM/ {print $11,$4}' | sort)

Then your code currently is written as:
N=0
c=0

for i in `seq 0 ${#arrayb[@]}`; do

    let "B= $N - 1"

    A=`echo ${arrayb[$B]} | tr -d '\n'`
    B=`echo ${arrayb[$N]} | tr -d '\n'`
    echo $c
    echo -n "$A" "$B"
    echo ""
    let "c=$c+1"
    let "N= $N + 1"

done

And you've got a problem because you access arrayb twice and ignore arrayc.  You also seem to be going through contortions to undo the unwanted incrementing in the original code for the second loop.
The use of back-ticks is generally a bad idea; use $(...) instead. The tr -d '\n' should be unnecessary. The use of echo -n "$A" "$B" followed immediately by echo "" is odd: echo "$A" "$B" would suffice?
for i in $(seq 0 ${#arrayb[@]})
do
    echo "${arrayb[$i]}" "${arrayc[$i]}"
done

So, we can reduce the script provided so far to:
arrayb=()
arrayc=()
while read name memory
do
     arrayb+=($name)
     arrayc+=($memory)
done < <(ps aux | awk '$4 != 0.0 && $4 !~ /MEM/ {print $11,$4}' | sort)

for i in $(seq 0 ${#arrayb[@]})
do
    echo "${arrayb[$i]}" "${arrayc[$i]}"
done

From here, you can continue with the two arrays, arrayb and arrayc, organized so that matching indexes contain comparable values.


text:
Q: Convert date to GMT time of Day Date Month Year Swift I'm struct on how to get/convert current time to  GMT time in format "Wed, 08 Apr 2015 21:27:30 GMT"
Currently I'm using below code to convert but that gives me "Wednesday" instead of "Wed" , "April" instead of "Apr" and most importantly in current local time.
Please advice how to get current GMT time in below format "Wed, 08 Apr 2015 21:27:30 GMT"
func convertDateToDayDateMonthYear(from inputFormat: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = inputFormat
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")

    if let dateInLocal = dateFormatter.date(from: self) {
        dateFormatter.dateFormat = "EEEE, dd MMMM yyyy"
        dateFormatter.locale = Locale.current
        return dateFormatter.string(from: dateInLocal)
    }

    return "NA"
}

A: Use date formatter as
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
print(dateFormatter.string(from: date))

Console o/p

Tue, 10 Sep 2019 16:01:13 GMT

Follow this link to learn more about date formatting styles

A: Your dateFormatter.dateFormat is incorrect. Check this site to structure it the way you like: https://nsdateformatter.com/
This site will let you test out different formats without actually having to run code. This way, you'll be able to experiment and find the dateFormat that is best for your code.


text:
Q: AWS WAF XSS check blocking form with "ON" keyword in form field value Posting a form with " on" or any word starting with "on" as last word in a form field resulting in an XSS block from aws waf
blocked by this rule
Body contains a cross-site scripting threat after decoding as URL
e.g. "twenty only" or " online" or "check on" all results in XSS block
These seems to be normal words, why it's getting blocked for xss?
but with whitespace at the end it doesn't block
e.g. "twenty only " or " online " or "check on " these works

A: Just flagging up we got started with WAF last night, and overnight a few dozen legitimate requests were blocked.
Surely enough, each XSS rule had the string "on" in the request body, followed by other characters.
I wonder if it was trying to detect the hundred or so onerror, onload and other javascript events? Feels like it could have been a lot more specific than matching on followed by "some stuff"...
Only solution here seems to be disable this rule for us - it's going to be a constant source of false positives for us otherwise, which makes it worthless.

A: This is a known problem with the "CrossSiteScripting_BODY" WAFv2 rule provided by AWS as part of the AWSManagedRulesCommonRuleSet ruleset. The rule will block any input that matches on*=*
In a form with multiple inputs, any text that has " on" in it will likely trigger this rule with false positive, e.g. a=three two one&b=something else
In Sept 2021, I complained to AWS Enterprise Support about this clearly broken rule and they replied "Its better to block the request when in doubt than to allow a malicious one", which I strongly disagree with. The support engineer also suggested that I could attempt to whitelist inputs which have triggered this rule, which is totally impractical for any non-trivial web app.
I believe the rule is attempting to block XSS attacks containing scripts like onerror=eval(src), see https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filter_Evasion_Cheat_Sheet.html#waf-bypass-strings-for-xss
I would recommend excluding all the black box CrossSiteScripting rules from your WAF, as they are not fit for purpose.

A: You can try upgrading to WAFv2, however certain combination with characters "on" +"&" may still cause a false positive. The rule that is causing the problem is XSS on body with URL decoding. So if your formdata is submitted using url-encoding, you could hit a problem. If you submit your form as JSON data or using MIME multipart/form-data it should work. I have 2 application, one with formdata submission with a javascript XHR using fetch api, it uses multipart/form-data and another with JSON data wasn't getting blocked.
Otherwise, you have to tune your XSS rules or set that specific rule to count. I will not post how to tune lest someone lurking here and try to be funny.
What your suggestion of adding a whitespace works as well, the backend can remove the whitespace or leave as it is. A little annoying but it works.


text:
Q: How to get date from datetime in crystal report? I have the datetime format in my sqldatabase was "2012-07-21 00:00:00.000". I need the date(21) only. Am trying to convert but it was showing database error for this particular field.
My Code is:
DatePart('d',CDate({tblFiles.Filed_Date}));

A: It's a problem with the connection of your report to the database. Make sure to set the data source correctly. You may start by verifying the report.

A: Okay I had this problem in the past, which is dealt with some bits of conversions, here is an example to how I dealt with this issue, here I did not have date but I had time in my database, you need to convert it to text and replace the number of zeros you see and display x as Date(x); and then right click the field and format it to just get the data, by right clicking it. hope this helps.
LOCAL STRINGVAR x := REPLACE(totext({DETAILED_FOR_EMPLOYEE.LOGIN_TIME}), '.0000000', '')


text:
Q: Selenium - Navigation gets stuck after clicking a drop down (prior to an iframe switch) The code clicks and pops up an overlay (successful). I am able to switch to iframe (using the driver.switchTo().frame(2)). Once selecting an element and clicking the Accept button, the overlay closes. Now I switch back to the main page using driver.switchTo().defaultContent(). The problem occurs soon after the code clicks a dropdown in the main page. This dropdown is not the typical Select or Option type (Select() or <option>). The elements are listed in a
.
There is no error displayed in the console but the program hangs. It stops the navigation after clicking the drop down and then no response.
Please find the html portion:
<input type="hidden" name="ctl00$cph$ctl02$TEST$FORM$ctl06$ctl32$ctl01$ctl03"
    id="ctl00_cph_ctl02_TEST_FORM_ctl06_ctl32_ctl01_ctl03" />
<input type="hidden" name="ctl00$cph$ctl02$TEST$FORM$ctl06$ctl32$ctl01$ctl04"
    id="ctl00_cph_ctl02_TEST_FORM_ctl06_ctl32_ctl01_ctl04" value="-1" />
<input type="hidden" name="ctl00$cph$ctl02$TEST$FORM$ctl06$ctl32$ctl01$ctl05" />
<input type="hidden" name="ctl00$cph$ctl02$TEST$FORM$ctl06$ctl32$ctl01$ctl06" />

                Act1

                Act2

                Act3

                Act4

In the code I am trying to select an option 'Act1' using the below statements. Note that only the first line executes, i.e, it clicks the drop down but then it doesn't move forward to the next step, where the selection happens.
driver.findElement(By.xpath(".//*[@id='ctl00_cph_ctl02_TEST$FORM_ctl06_ctl32_ctl01']")).click();

driver.findElement(By.xpath(".//*[@id='ctl00_cph_ctl02_TEST$FORM_ctl06_ctl32_ctl01_tbl']/tbody/tr/td[1][contains(text(),'Act1')]")).click();


text:
Q: How to Render Binary Data in Image in React Native? Help!!! I am currently struggling to render binary data as an image in react native. I am receiving an array of numbers from the backend, and I have no clue what to do with it in order to render it. I'm not sure if I need to convert it into base64, and if so, how to do it, or if I can simply display the raw binary data without base64 processing.
Any help would be much appreciated.

A: In order to use the binary data for image you should append this at the beginning of the data received: 'data:image/png;base64,'
So basically,
<Image style={{width: 100, height: 50}} source={{uri: `data:image/png;base64,${image.data}`}}/>

Please replace image.data with the binary data you are receiving.


text:
Q: NV12 to YUV444 speed up I have a code that converts image from nv12 to yuv444
for h in range(self.img_shape[0]):
    # centralize yuv 444 data for inference framework
    for w in range(self.img_shape[1]):
        yuv444_res[h][w][0] = (nv12_y_data[h * self.img_shape[1] +w]).astype(np.int8)
        yuv444_res[h][w][1] = (nv12_u_data[int(h / 2) * int(self.img_shape[1] / 2) +int(w / 2)]).astype(np.int8)
        yuv444_res[h][w][2] = (nv12_v_data[int(h / 2) * int(self.img_shape[1] / 2) +int(w / 2)]).astype(np.int8)

Since for loop is very slow in python, much slower than numpy. I was wondering if this conversion can be done in NumPy calculation.
Update on 06/15/2021:
I was able to get this piece of code with fancy indexing from this page External Link:
    yuv444 = np.empty([self.height, self.width, 3], dtype=np.uint8)
    yuv444[:, :, 0] = nv12_data[:self.width * self.height].reshape(
        self.height, self.width)
    u = nv12_data[self.width * self.height::2].reshape(
        self.height // 2, self.width // 2)
    yuv444[:, :, 1] = Image.fromarray(u).resize((self.width, self.height))
    v = nv12_data[self.width * self.height + 1::2].reshape(
        self.height // 2, self.width // 2)
    yuv444[:, :, 2] = Image.fromarray(v).resize((self.width, self.height))

    data[0] = yuv444.astype(np.int8)

If the PIL is used to replace the deprecated imresize, then the code match the old code 100%
Update on 06/19/2021:
After a closer look at the answer Rotem given, I realize that his way is quicker.
    #nv12_data is reshaped to one dimension
    y = nv12_data[:self.width * self.height].reshape(
        self.height, self.width)
    shrunk_u = nv12_data[self.width * self.height::2].reshape(
        self.height // 2, self.width // 2)
    shrunk_v = nv12_data[self.width * self.height + 1::2].reshape(
        self.height // 2, self.width // 2)
    u = cv2.resize(shrunk_u, (self.width, self.height),
                   interpolation=cv2.INTER_NEAREST)
    v = cv2.resize(shrunk_v, (self.width, self.height),
                   interpolation=cv2.INTER_NEAREST)
    yuv444 = np.dstack((y, u, v))

Also, I did a time comparison for processing 1000 pics. Turns out the cv reshape is quicker and guarantees the same result.
cv time: 4.417593002319336, pil time: 5.395732164382935

Update on 06/25/2021:
Pillow resize has different default resample param values in different versions.
5.1.0:
def resize(self, size, resample=NEAREST, box=None):

8.1.0:
def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):

It would be a good idea to specify the resample strategy used.

A: You may use the process described in my following post, in reverse order (without the RGB part).
Illustration:

Start by creating a synthetic sample image in NV12 format, using FFmpeg (command line tool).
The sample image is used for testing.
Executing from Python using subprocess module:
import subprocess as sp
import shlex

sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=1 -vcodec rawvideo -pix_fmt nv12 nv12.yuv'))
sp.run(shlex.split('ffmpeg -y -f rawvideo -video_size 192x162 -pixel_format gray -i nv12.yuv -pix_fmt gray nv12_gray.png'))

Read the sample image, and executing the code from your post (used as reference):
import numpy as np
import cv2

nv12 = cv2.imread('nv12_gray.png', cv2.IMREAD_GRAYSCALE)
cols, rows = nv12.shape[1], nv12.shape[0]*2//3

# Reference implementation - using for-loops (the solution is in the part below):
################################################################################
nv12_y_data = nv12[0:rows, :].flatten()
nv12_u_data = nv12[rows:, 0::2].flatten()
nv12_v_data = nv12[rows:, 1::2].flatten()

yuv444_res = np.zeros((rows, cols, 3), np.uint8)

for h in range(rows):
    # centralize yuv 444 data for inference framework
    for w in range(cols):
        yuv444_res[h][w][0] = (nv12_y_data[h * cols + w]).astype(np.int8)
        yuv444_res[h][w][1] = (nv12_u_data[int(h / 2) * int(cols / 2) + int(w / 2)]).astype(np.int8)
        yuv444_res[h][w][2] = (nv12_v_data[int(h / 2) * int(cols / 2) + int(w / 2)]).astype(np.int8)

################################################################################

My suggested solution applies the following stages:

*

*Separate U and V into two "half size" matrices shrunk_u and shrunk_v.

*Resize shrunk_u and shrunk_v to full image size matrices using cv2.resize.
In my code sample I used nearest neighbor interpolation for getting the same result as your result.
It is recommended to replace it with linear interpolation for better quality.

*Use np.dstack for merging Y, U and V into YUV (3 color channels) image.

Here is the complete code sample:
import numpy as np
import subprocess as sp
import shlex
import cv2

sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=1 -vcodec rawvideo -pix_fmt nv12 nv12.yuv'))
sp.run(shlex.split('ffmpeg -y -f rawvideo -video_size 192x162 -pixel_format gray -i nv12.yuv -pix_fmt gray nv12_gray.png'))
#sp.run(shlex.split('ffmpeg -y -f rawvideo -video_size 192x108 -pixel_format nv12 -i nv12.yuv -vcodec rawvideo -pix_fmt yuv444p yuv444.yuv'))
#sp.run(shlex.split('ffmpeg -y -f rawvideo -video_size 192x324 -pixel_format gray -i yuv444.yuv -pix_fmt gray yuv444_gray.png'))
#sp.run(shlex.split('ffmpeg -y -f rawvideo -video_size 192x108 -pixel_format yuv444p -i yuv444.yuv -pix_fmt rgb24 rgb.png'))
#sp.run(shlex.split('ffmpeg -y -f rawvideo -video_size 192x108 -pixel_format gbrp -i yuv444.yuv -filter_complex "extractplanes=g+b+r[g][b][r],[r][g][b]mergeplanes=0x001020:gbrp[v]" -map "[v]" -vcodec rawvideo -pix_fmt rgb24 yuvyuv.yuv'))
#sp.run(shlex.split('ffmpeg -y -f rawvideo -video#_size 576x108 -pixel_format gray -i yuvyuv.yuv -pix_fmt gray yuvyuv_gray.png'))

nv12 = cv2.imread('nv12_gray.png', cv2.IMREAD_GRAYSCALE)
cols, rows = nv12.shape[1], nv12.shape[0]*2//3

nv12_y_data = nv12[0:rows, :].flatten()
nv12_u_data = nv12[rows:, 0::2].flatten()
nv12_v_data = nv12[rows:, 1::2].flatten()

yuv444_res = np.zeros((rows, cols, 3), np.uint8)

for h in range(rows):
    # centralize yuv 444 data for inference framework
    for w in range(cols):
        yuv444_res[h][w][0] = (nv12_y_data[h * cols + w]).astype(np.int8)
        yuv444_res[h][w][1] = (nv12_u_data[int(h / 2) * int(cols / 2) + int(w / 2)]).astype(np.int8)
        yuv444_res[h][w][2] = (nv12_v_data[int(h / 2) * int(cols / 2) + int(w / 2)]).astype(np.int8)

y = nv12[0:rows, :]
shrunk_u = nv12[rows:, 0::2].copy()
shrunk_v = nv12[rows:, 1::2].copy()

u = cv2.resize(shrunk_u, (cols, rows), interpolation=cv2.INTER_NEAREST)  # Resize U channel (use NEAREST interpolation - fastest, but lowest quality).
v = cv2.resize(shrunk_v, (cols, rows), interpolation=cv2.INTER_NEAREST)  # Resize V channel

yuv444 = np.dstack((y, u, v))

is_eqaul = np.all(yuv444 == yuv444_res)
print('is_eqaul = ' + str(is_eqaul))  # is_eqaul = True

# Convert to RGB for display
yvu = np.dstack((y, v, u))  # Use COLOR_YCrCb2BGR, because it's uses the corrected conversion coefficients.
rgb = cv2.cvtColor(yvu, cv2.COLOR_YCrCb2BGR)

# Show results:
cv2.imshow('nv12', nv12)
cv2.imshow('yuv444_res', yuv444_res)
cv2.imshow('yuv444', yuv444)
cv2.imshow('rgb', rgb)
cv2.waitKey()
cv2.destroyAllWindows()

Input (NV12 displayed as Grayscale):

Output (after converting to RGB):

A: Seems to be a prime case for fancy indexing (advanced indexing).
Something like this should do the trick, though I didn't verify it on an actual image. I've added a section to reconstruct the image in the beginning, because it is easier to work with the array as a whole than broken into parts. Likely, you can refactor this and avoid splitting it to begin with.
# reconstruct image array
y = nv12_y_data.reshape(self.image_shape[0], self.image_shape[1])
u = nv12_u_data.reshape(self.image_shape[0], self.image_shape[1])
v = nv12_v_data.reshape(self.image_shape[0], self.image_shape[1])
img = np.stack((y,u,v), axis=-1)

# take every index twice until half the range
idx_h = np.repeat(np.arange(img.shape[0] // 2), 2)[:, None]
idx_w = np.repeat(np.arange(img.shape[1] // 2), 2)[None, :]

# convert
yuv444 = np.empty_like(img, dtype=np.uint8)
yuv444[..., 0] = img[..., 0]
yuv444[..., 1] = img[idx_h, idx_w, 1]
yuv444[..., 2] = img[idx_h, idx_w, 2]

If this is along your critical path, and you want to tease out a little more performance, you could consider processing the image channel first, which will be faster on modern CPUs (but not GPUs).

A: This answer is just another way to do it, and is not the quickest way to get the job done, but definitely should be easy to understand. I have checked the generated files with yuvplayer application as well to confirm it works.
#height mentioned is height of nv12 file and so is the case with width
def convert_nv12toyuv444(filename= 'input.nv12',height=2358,width=2040):

    nv12_data = np.fromfile(filename, dtype=np.uint8)
    imageSize = (height, width)
    npimg = nv12_data.reshape(imageSize)
    y_height = npimg.shape[0] * (2/3)
    y_wid = npimg.shape[1]
    y_height = int(y_height)
    y_wid = int(y_wid)
    y_data= npimg[:y_height,:y_wid]
    uv_data=npimg[y_height:,:y_wid]
    shrunkU= uv_data[:, 0 : :2]
    shrunkV= uv_data[:, 1 : :2]
    u = cv2.resize(shrunkU, (y_wid, y_height),
                   interpolation=cv2.INTER_NEAREST)
    v = cv2.resize(shrunkV, (y_wid, y_height),
                   interpolation=cv2.INTER_NEAREST)
    yuv444 = np.dstack((y_data, u, v))


text:
Q: In angular is $pending only set on the form for $asyncValidators? I have an ng-submit function that is called when submitting a form.
I want to perform some action after any pending $asyncValidators are called.
if (myForm.$pending) {
    var pendingWatch = scope.$watch(function() {
         return myForm.$pending; }, function(pending) {
               if (!pending) {
                   pendingWatch();
                   performSubmit();
               }
         });
} else {
    performSubmit();
}

The problem I am having is that myForm.$pending is always returning an object. Even with values that aren't $asyncValidators but rather custom $validators I added. This is not happening for all inputs.
How is is possible for the form to have pending validations that aren't even $asyncValidators? These "pending" validations never gets completed.

A: No, actually, in my experience, $pending is also set on form, if any of your custom validators returns 'undefined' (even if there are not any asyncValidators present)
So to solve this issue, make sure all of your validators return true / false


text:
Q: Get coordinates upon mapview gesture How do I get the latitude and longitude on the point where the user do a longhold(eg 2s)on the mapView.
I chanced upon a similar question : get coordinates on tap in iphone application
But I don't understand how do I go about handling the touch event on the mapView.
What I intent to achieve it to drop a pin annotation to the location, do nesscary reverse geocoding via Google API and display it on the subtitle. So firstly, I would need to get the required coordinates.
Examples would be very much appreciated.
Thanks.

A: You can convert the coordinates of the touch in the view retrieved from the gesture to gps coordinates like this...
- (void)mapLongPress:(UILongPressGestureRecognizer *)gestureRecognizer{
    if(gestureRecognizer.state == UIGestureRecognizerStateBegan){
        CGPoint touchLocation = [gestureRecognizer locationInView:mapView];

        CLLocationCoordinate2D coordinate;
        coordinate = [mapView convertPoint:touchLocation toCoordinateFromView:mapView];
    }
}

Note that in my example, I had the gesture applied to the mapView itself. You would have to pass the view to which you applied the gesture to toCoordinateFromView:mapView


text:
Q: message not display in UITextView in iOS? message display in console window but not display in uitextview when i run the program what the problem in that.
-(void)getSmsData
{
    array = [[NSMutableArray alloc] init];

    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                            NSUserDomainMask, YES);
    NSString *documentDir = [docPaths objectAtIndex:0];
    self.databasePath = [documentDir stringByAppendingPathComponent:@"SMS.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:self.databasePath];
    [database setLogsErrors:TRUE];
    [database open];

    NSString *anQuery = [[NSString alloc]initWithFormat:@"SELECT * FROM SMSnJokes where
    Id=%@",self.Id ];

    FMResultSet *results = [database executeQuery:anQuery];

    while([results next])
    {
        SmsTitle *title=[[SmsTitle alloc]init];
        title.Id = [results stringForColumn:@"Id"];
        title.Data=[results stringForColumn:@"Data"];
        title.CategoryId = [results stringForColumn:@"CategoryId"];
        title.Title = [results stringForColumn:@"Title"];
        [array addObject:title];
        NSLog(@"SMS LIST %@",title.Data);
    }

    [database close];
}

-(void)getSmsdisplay
{
    smsdisplay=[[UITextView alloc]init];

    for (SmsTitle *title in array)
    {
        NSString *tempStr = title.Data;
        smsdisplay.text=tempStr;
        smsdisplay.editable = NO;
        [smsdisplay setTextColor:[UIColor blackColor]];
        smsdisplay.font = [UIFont systemFontOfSize:15];
    }

    [self.view addSubview:smsdisplay];
}

message display in console window but not display in uitextview when i run the program what the problem in that.

A: You have to set the UITextView frame.
If you create the TextView from the XIB, don't call the alloc-init methods.
UITextView *smsdisplay = [[UITextView alloc] initWithFrame: YOUR_FRAME];
// some stuff...
[self.view addSubview: smsdiplay];

A: After NSLog(@"SMS LIST %@",title.Data); add the next code to update your textfield :
_myTextfield.text = [NSString stringWithFormat:@"%@\n%@", _myTextfield.text, title.data];

A: You didn't set frame of the textview.


text:
Q: How to make countdown timer with RxJS Observables? I'm struggling to create a countdown timer using Observables, the examples at http://reactivex.io/documentation/operators/timer.html do not seem to work.  In this specific example the error related to timerInterval not being a function of the Observable returned from timer.
I have also been experimenting with other approaches and the best I've come up with is:
Observable.interval(1000).take(10).subscribe(x => console.log(x));

The problem here is it counts up from 0 to 10 and I want a countdown timer e.g. 10,9,8...0.
I've also tried this but the timer does not exist for type Observable
Observable.range(10, 0).timer(1000).subscribe(x => console.log(x));

As well as, which produces no output at all.
Observable.range(10, 0).debounceTime(1000).subscribe(x => console.log(x));

To clarify I need help with ReactiveX's RxJS implementation, not the MircoSoft version.

A: With interval, allows you to specify how long a second is
const time = 5 // 5 seconds
var timer$ = Rx.Observable.interval(1000) // 1000 = 1 second
timer$
  .take(time)
  .map((v)=>(time-1)-v) // to reach zero
  .subscribe((v)=>console.log('Countdown', v))

A: You were on the right track - your problem was that timer does not exist on the prototype (and thereby on Observable.range())but on Observable (see the RxJS docs). I.e. jsbin
const start = 10;
Rx.Observable
  .timer(100, 100) // timer(firstValueDelay, intervalBetweenValues)
  .map(i => start - i)
  .take(start + 1)
  .subscribe(i => console.log(i));

// or
Rx.Observable
  .range(0, start + 1)
  .map(i => start - i)
  .subscribe(i => console.log(i));

A: I am the take...() lover, so I am using takeWhile() as follow ( RxJS 6.x.x, in ES6 way )
import {timer} from 'rxjs';
import {takeWhile, tap} from 'rxjs/operators';

let counter = 10;
timer(1000, 1000) //Initial delay 1 seconds and interval countdown also 1 second
  .pipe(
    takeWhile( () => counter > 0 ),
    tap(() => counter--)
  )
  .subscribe( () => {
    console.log(counter);
  } );

A: This example worked for me :)
By the way, using takeWhile(val => val >= 0) instead of take(someNumber) might make sense but it will check -1 and only then complete.. 1 second too late.
The example below will emit 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0. Starting at 10 and ending at 0 immediately seems trivial but it was rather tricky for me.
const counter$ = interval(1000); // rxjs creation operator - will fire every second
const numberOfSeconds = 10;

counter$.pipe(
    scan((accumulator, _current) =>  accumulator - 1, numberOfSeconds + 1),
    take(numberOfSeconds + 1),

    // optional
    finalize(() => console.log(
      'something to do, if you want to, when 0 is emitted and the observable completes'
    ))
)

This will do the same:

counter$.pipe(
    scan((accumulator, current) => accumulator - 1, numberOfSeconds),
    startWith(numberOfSeconds), // scan will not run the first time!
    take(numberOfSeconds + 1),

    // optional
    finalize(() => console.log(
      'something to do, if you want to, when 0 is emitted and the observable completes'
    ))
  )

You could, of course, make many changes.. you can mapTo(-1) before the scan for example, and then write accumulator + current and the current will be -1.

A: Using timer, scan and takeWhile if you don't want to depend on a variable for your starting time, the 3rd argument in scan is the starting number
timer$ = timer(0, 1000).pipe(
  scan(acc => --acc, 120),
  takeWhile(x => x >= 0)
);

Check it out on Stackblitz

A: My counterdown function with display time:
import { Observable, timer, of, interval } from "rxjs";
import { map, takeWhile, take } from "rxjs/operators";

function countdown(minutes: number, delay: number = 0) {
   return new Observable<{ display: string; minutes: number; seconds: number }>(
      subscriber => {
        timer(delay, 1000)
          .pipe(take(minutes * 60))
          .pipe(map(v => minutes * 60 - 1 - v))
          .pipe(takeWhile(x => x >= 0))
          .subscribe(countdown => { // countdown => seconds
            const minutes = Math.floor(countdown / 60);
            const seconds = countdown - minutes * 60;

            subscriber.next({
              display: `${("0" + minutes.toString()).slice(-2)}:${("0" + seconds.toString()).slice(-2)}`,
              minutes,
              seconds
            });

            if (seconds <= 0 && minutes <= 0) {
              subscriber.complete();
            }
       });
   });
}

countdown(2).subscribe(next => {
  document.body.innerHTML = `<pre><code>${JSON.stringify(next, null, 4)}</code></pre>`;
});

Output i.e:
{
   "display": "01:56",
   "minutes": 1,
   "seconds": 56
}

A: As if there were not enough proposed solutions, I will add one more.
It is a re-usable function with parameters to configure your countdown options, and it's written in TypeScript:
import { filter, interval, map, Observable, startWith, take } from "rxjs";

interface CountdownOptions {
    tickDuration?: number;
    emitZero?: boolean;
    emitInitial?: boolean;
}

/**
 * Creates an observable which emits a decremented value on every tick until it reaches zero.
 * @param ticks - the amount of ticks to count down
 * @param options (object):
 *          tickDuration - the duration of one tick in milliseconds (1000 by default)
 *          emitZero - whether to emit 0 at the end of the countdown, immediately before the observable completes (true by default)
 *          emitInitial - whether to emit initial countdown value immediately after the observable is created (true by default)
 */
function countdown(ticks: number, options: CountdownOptions = {}): Observable<number> {
    const tickDuration = options.tickDuration ?? 1000;
    const emitZero = options.emitZero ?? true;
    const emitInitial = options.emitInitial ?? true;

    const countdown$ = interval(tickDuration).pipe(
        take(ticks),
        map(n => ticks - 1 - n),
        filter(value => emitZero || value !== 0)
    );

    if (emitInitial)
        return countdown$.pipe(startWith(ticks));
    else
        return countdown$;
}

// SAMPLE USAGE

// starts immediately, logs values from 10 to 0, and completes immediately on 0
countdown(10).subscribe({
    next: x => console.log(`Launching in ${x} seconds...`),
    complete: () => console.log(`Launched!`)
});

// starts after 1 second, logs values from 9 to 1, and completes on 0 without emitting it
countdown(10, { emitZero: false, emitInitial: false}).subscribe({
    next: x => console.log(`Please wait ${x} seconds...`),
    complete: () => console.log(`Ready!`)
});

A: I also needed an interval that counts backward, so I tried this solution:

const { interval, take } = rxjs

const countDownEl = document.querySelector("#countdown");

/**
 * Coundown with RxJs
 * @param startPoint {number} Value of timer continuing to go down
 */
function countDown(startPoint) {
  // * Fire Every Second
  const intervalObs = interval(1000);

  // * Shrink intervalObs subscription
  const disposeInterval = intervalObs.pipe(take(startPoint));

  // * Fire incremental number on every second

  disposeInterval.subscribe((second) => {
    console.log("Second: ", second);
    countDownEl.innerHTML = startPoint - second;
  })
}

countDown(10);

Countdown:

A: This is the simplest approach imho:
import { interval } from 'rxjs'
import { map, take } from 'rxjs/operators'

const durationInSeconds = 1 * 60 // 1 minute

interval(1000).pipe(take(durationInSeconds), map(count => durationInSeconds - count)).subscribe(countdown => {
  const hrs  = (~~(countdown / 3600)).toString()
  const mins = (~~((countdown % 3600) / 60)).toString()
  const secs = (~~countdown % 60).toString()
  console.log(`${hrs.padStart(2, '0')}:${mins.padStart(2, '0')}:${secs.padStart(2, '0')}`);
})

A: Or this way :)
 interval(1000)
      .take(10)
      .map((t) => Math.abs(t - 10))
      .subscribe((t) => {
        console.log(t);
      });

A: Easy Appraoch
private countDown: Subscription = new Subscription();
public counter = 300; // seconds
private tick = 1000;

resetTimer() {
    this.canResendOTP = false;
    this.counter = 300;
    this.countDown.unsubscribe();
}

timer() {
    this.resetTimer();
    this.countDown = timer(0, this.tick)
    .subscribe(() => {
        --this.counter;
    });
}

A: const rxjs = require("rxjs");
function customTimer(seconds){
return rxjs
.range(0, seconds + 1)
.pipe(
  rxjs.concatMap((t) => rxjs.of(t).pipe(rxjs.delay(1000))),
  rxjs.map((sec) => ({
    hours: Math.trunc(sec / (60 * 60)),
    minutes: Math.trunc(sec / 60) - Math.trunc(sec / (60 * 60)) * 60,
    seconds: sec - Math.trunc(sec / 60) * 60,
  })),
  rxjs.map(time=>{
    return {
        hours:time.hours>9?`${time.hours}`:`0${time.hours}`,
        minutes:time.minutes>9?`${time.minutes}`:`0${time.minutes}`,
        seconds:time.seconds>9?`${time.seconds}`:`0${time.seconds}`
    }
  })
 );
}

function countDownTimer(startDate, endDate) {
 const seconds = (endDate - startDate) / 1000;
 return rxjs.range(0, seconds + 1).pipe(
        rxjs.concatMap((t) => rxjs.of(t).pipe(rxjs.delay(1000))),
        rxjs.map((sec) => seconds - sec),
        rxjs.takeWhile((sec)=>sec>=0),
        rxjs.map((sec) => ({
          hours: Math.trunc(sec / (60 * 60)),
          minutes: Math.trunc(sec / 60) - Math.trunc(sec / (60 * 60)) * 60,
          seconds: sec - Math.trunc(sec / 60) * 60,
    })),
    rxjs.map((time) => {
      return {
        hours: time.hours > 9 ? `${time.hours}` : `0${time.hours}`,
        minutes: time.minutes > 9 ? `${time.minutes}` : `0${time.minutes}`,
        seconds: time.seconds > 9 ? `${time.seconds}` : `0${time.seconds}`,
     };
   })
  );
 }

// Normal Countdown timer
customTimer(3600).subscribe(time=>console.log(time));

// Reverse  Countdown timer
const startDate = new Date();
const endDate = new Date();
endDate.setMinutes(startDate.getMinutes() + 1);
countDownTimer(startDate, endDate).subscribe((time) => console.log(time));


text:
Q: NFT Collections and Supply - ERC721 vs ERC 1155 I'm building an NFT marketplace, say a copycat of OpenSea.
I need to make my users able to mint their own tokens. That's ok, that would be an ERC721 contract. But I want to allow my users to mint different collections (as OpenSea does) with different supplies as follows:

*

*(1) Have a single collection

*(2) Have multiple collections

*(A) Mint 1/1 NFTs

*(B) Mint 1/N NFTs (say, for instance, 100 in total of the same NFT)
That makes a set of combinations:

*

*Single collections (1) of 1/1 NFTs (A)

*Single collections (1) of 1/N NFTs (B)

*Multiple collections (2) of 1/1 NFTs (A)

*Multiple collections (2) of 1/N NFTs (B)

*Single or multiple collections (1 or 2) of both 1/1 and 1/N NFTS (A and B)
When using ERC721 I would be able to make (A) and (B), yet for every collection I would have to deploy a new contract. I want to avoid this.
Is this covered by ERC1155?

A:
(A) Mint 1/1 NFTs
(B) Mint 1/N NFTs (say, for instance, 100 in total of the same NFT)

Both options are in accordance with the ERC-1155 standard.
The ERC-1155 defines a collection of tokens, where each token has an ID and an amount (specified as a value in the standard). Which means, you can have for example:

*

*Token ID 1 that has amount of 1. At any point in time, it's always owned by just one address. (Case A)

*Token ID 2 that has amount of 10. Five of these tokens ID 2 is owned by Alice, and other five tokens ID 2 is owned by Bob. (Case B)


text:
Q: How to add/append string to blob in Google Apps Script (Google Drive API) This code does work, except this part Drive.Files.update(thefile, theFileID, updatedBlob);
var folder = DriveApp.getFolderById("0B0RcUNcUERU5MGpIaEXXXXXXXX");
var file = DriveApp.getFileById("NcUERXXXXXXXXERU5UWQUTZKY2X2");
var file2 = DriveApp.getFileById("NcUERXXXXXXXXERU5UWDDDDDDD2");

var myString = "sometext";
var updatedBlob = file.getBlob() + myString;

var myFileName = "StringAddedFile.mp4";
var thefile = {
  title: myFileName,
  mimeType: 'video/mp4'
};

var allFilesByName = folder.getFilesByName(myFileName);
while (allFilesByName.hasNext()) {
  var thisFile = allFilesByName.next();
  var theFileID = thisFile.getId();
  var myVar = Drive.Files.update(thefile, theFileID, updatedBlob);
};

I have tried:
file.getBlob() + myString;
file.getBlob().getDataAsString() + myString;
file.getBlob().getDataAsString() + file2.getBlob().getDataAsString();
file.getAs() + file2.getAs();
file.getBlob() + file2.getBlob();

...
Getting this error message: "The mediaData parameter only supports Blob types for upload."
How can I add/append myString to file?

A: It looks like you are trying to add something to a mimeType: 'video/mp4' file.  It looks like you need to create a blob from the string.  You can use the Utilities service to do that.
For String

*

*Create a base 64 encoded string

*encoded string as a byte array

For file

*

*Get file as blob

*Convert blob to bytes

Combine

*

*Combine bytes of both files

*Update file as blob with another blob

The code:
var myString = "sometext";
var encoded = Utilities.base64Encode(myString);
var byteDataArray = Utilities.base64Decode(encoded);

var file = DriveApp.getFileById("File ID here");
var fileAsBlob = file.getBlob();
var fileAsBytes = fileAsBlob.getBytes();

var combinedBytes = byteDataArray.concat(fileAsBytes);
var allBytesAsBlob = Utilities.newBlob(combinedBytes);

var updatedBlob = Drive.Files.update(thefile, theFileID, allBytesAsBlob);

This is a suggestion to try.  Haven't tested it.  Don't know if it will work, but no-one else has answered, so can't hurt to try.  I'll leave it up to you to try, and let me know if it works or not.


text:
Q: MongoDB Aggregation - match documents with array of objects, by another array of objects filter I have documents that consist of an array of objects, and each object in this array consists of another array of objects.
For simplicity, irrelevant fields of the documents were omitted.
It looks like this (2 documents):
{
  title: 'abc',
  parts: [
    {
      part: "verse",
      progressions: [
        {
          progression: "62a4a87da7fdbdabf787e47f",
          key: "Ab",
          _id: "62b5aaa0c9e9fe8a7d7240d3"
        },
        {
          progression: "62adf477ed11cbbe156d5769",
          key: "C",
          _id: "62b5aaa0c9e9fe8a7d7240d3"
        },
      ],
      _id: "62b5aaa0c9e9fe8a7d7240d2"
    },
    {
      part: "chorus",
      progressions: [
        {
          progression: "62a4a51b4693c43dce9be09c",
          key: "E",
          _id: "62b5aaa0c9e9fe8a7d7240d9"
        }
      ],
      _id: "62b5aaa0c9e9fe8a7d7240d8"
    }
  ],
}

{
  title: 'def',
  parts: [
    {
      part: "verse",
      progressions: [
        {
          progression: "33a4a87da7fopvvbf787erwe",
          key: "E",
          _id: "62b5aaa0c9e9fe8a7d7240d3"
        },
        {
          progression: "98opf477ewfscbbe156d5442",
          key: "Bb",
          _id: "62b5aaa0c9e9fe8a7d7240d3"
        },
      ],
      _id: "12r3aaa0c4r5me8a7d72oi8u"
    },
    {
      part: "bridge",
      progressions: [
        {
          progression: "62a4a51b4693c43dce9be09c",
          key: "C#",
          _id: "62b5aaa0c9e9fe8a7d7240d9"
        }
      ],
      _id: "62b5aaa0rwfvse8a7d7240d8"
    }
  ],
}

The parameters that the client sends with a request are an array of objects:
[
  { part: 'verse', progressions: ['62a4a87da7fdbdabf787e47f', '62a4a51b4693c43dce9be09c'] },
  { part: 'chorus', progressions: ['62adf477ed11cbbe156d5769'] }
]

I want to retrieve, through mongodb aggregation, the documents that at least one of objects in the input array above is matching them:
In this example, documents that have in their parts array field, an object that has the value 'verse' in the part property and one of the progressions id's ['62a4a87da7fdbdabf787e47f', '62a4a51b4693c43dce9be09c'] in the progression property in one of the objects in the progressions property, or documents that have in their parts array field, an object that has the value 'chorus' in the part property and one of the progressions id's ['62adf477ed11cbbe156d5769'] in the progression property in one of the objects in the progressions property.
In this example, the matching document is the first one (with the title 'abc'), but in actual use, there might be many matching documents.
I tried to create an aggregation pipeline myself (using the mongoose 'aggregate' method):
// parsedProgressions = [
//   { part: 'verse', progressions: ['62a4a87da7fdbdabf787e47f', '62a4a51b4693c43dce9be09c'] },
//   { part: 'chorus', progressions: ['62adf477ed11cbbe156d5769'] }
// ]
songs.aggregate([
  {
    $addFields: {
      "tempMapResults": {
        $map: {
          input: parsedProgressions,
          as: "parsedProgression",
          in: {
            $cond: {
              if: { parts: { $elemMatch: { part: "$$parsedProgression.part", "progressions.progression": mongoose.Types.ObjectId("$$parsedProgression.progression") } } },
              then: true, else: false
            }
          }
        }
      }
    }
  },
  {
    $addFields: {
      "isMatched": { $anyElementTrue: ["$tempMapResults"] }
    }
  },
  { $match: { isMatched: true } },
  { $project: { title: 1, "parts.part": 1, "parts.progressions.progression": 1 } }
]);

But it didn't work - as I understand it, because the $elemMatch can be used only in the $match stage.
Anyway, I guess I overcomplicated the aggregation pipeline, so I will be glad if you can fix my aggregation pipeline/offer a better working one.

A: This is not a simple case as these are both nested arrays and we need to match both the part and the progressions, which are not on the same level
One option looks complicated a bit, but keeps your data small:

*

*In order to make things easier, $set a new array field called matchCond which includes an array called progs containing the parts.progressions. To each sub-object inside it insert the matching progressions input array. We do need to be careful here and handle the case where there is no matching progressions input arrayprogressions input array, as this is the case for the "bridge" part on the second document.

*Now we just need to check if for any of these progs items, the progression field is matching one option in input array. This is done using $filter, and $rediceing the number of results.

*Just match document which have results and format the answer

db.collection.aggregate([
  {
    $set: {
      matchCond: {
        $map: {
          input: "$parts",
          as: "parts",
          in: {progs: {
              $map: {
                input: "$$parts.progressions",
                in: {$mergeObjects: [
                    "$$this",
                    {input: {progressions: []}},
                    {input: {$first: {
                          $filter: {
                            input: inputData,
                            as: "inputPart",
                            cond: {$eq: ["$$inputPart.part", "$$parts.part"]}
                          }
                     }}}
                ]}
              }
          }}
        }
      }
    }
  },
  {$set: {
      matchCond: {
        $reduce: {
          input: "$matchCond",
          initialValue: 0,
          in: {$add: [
              "$$value",
              {$size: {
                  $filter: {
                    input: "$$this.progs",
                    as: "part",
                    cond: {$in: ["$$part.progression", "$$part.input.progressions"]}
                  }
                }
              }
            ]
          }
        }
      }
    }
  },
  {$match: {matchCond: {$gt: 0}}},
  {$project: {title: 1, parts: 1}}
])

See how it works on the playground example
Another option is to use $unwind, which looks simple, but will duplicate your data, thus, likely to be slower:
db.collection.aggregate([
  {$addFields: {inputData: inputData, cond: "$parts"}},
  {$unwind: "$cond"},
  {$unwind: "$cond.progressions"},
  {$unwind: "$inputData"},
  {$match: {
      $expr: {
        $and: [
          {$eq: ["$cond.part", "$inputData.part"]},
          {$in: ["$cond.progressions.progression", "$inputData.progressions"]}
        ]
      }
    }
  },
  {$project: {title: 1, parts: 1}}
])

See how it works on the playground example - unwind
There are several options between these two...


text:
Q: Android - Unable to view image saved in new directory when I try to upload it again I am uploading a image from gallery and saving it into new directory after cropping it (using Android-image-cropper library).
The directory is getting created and image is getting saved successfully.
It can be found in File Explorer, but when I try upload the same image in the app it is not showing up.
I also tried saving the image in existing directory, the directory is visible in the search and not the image in it, but it can be found in File Explorer.
EditActivity
save_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveImage();
                }
        });
    }

public void saveImage(){
        try {
            InputStream inputStream = getContentResolver().openInputStream(resultUri);
            bitmap = BitmapFactory.decodeStream(inputStream);;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        File file = Environment.getExternalStorageDirectory();
        File dir = new File(file.getAbsolutePath()+"/Pictures/");
        if(!dir.exists()){
            dir.mkdirs();
        }
        File f = new File(dir,System.currentTimeMillis()+".jpg");
        try {
            outputStream = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
        Toast.makeText(getApplicationContext(),f.toString(),Toast.LENGTH_SHORT).show();
        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

MainActivity

    private void cam_permission() {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
        } else{
            dispatchTakePictureIntent();
        }
    }

    private  void storage_permission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
        } else{
            Intent gallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(gallery, GALLERY_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == CAMERA_PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                Toast.makeText(this, "Camera Permission is required", Toast.LENGTH_SHORT).show();
            }
        }
        else if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            }
            else {
                Toast.makeText(MainActivity.this, "Storage Permission is required", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                File file = new File(currentPhotoPath);
                Uri contentUri = Uri.fromFile(file);

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent .setClass(MainActivity.this,  EditActivity.class);
                intent .putExtra("imageUri", contentUri.toString());
                startActivity(intent);
            }
        }
        if (requestCode == GALLERY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Uri contentUri = data.getData();
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent .setClass(MainActivity.this,  EditActivity.class);
                intent .putExtra("imageUri", contentUri.toString());
                startActivity(intent);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File

            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

AndroidManifest.xml
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: perl LWP: connection timeout different from request timeout I'm using LWP::UserAgent to communicate with webservices on several servers; the servers are contacted one at a time. Each response might take up to 30 minutes to finish, so I set the LWP timeout to 30 minutes.
Unfortunately the same timeout also applies, if the server is not reachable at all (e.g. the webserver is down). So my application waits 30 minutes for a server, which is not running.
Is it feasable to set two seperate timeouts?

*

*a short one, which waits for the connection to be established.

*a longer one, which waits for the response, once the connection has been established.

A: The same timeout doesn't "also apply" if the server is not reachable. The timeout option works in a very specific way:

The request is aborted if no activity on the connection to the server is
     observed for timeout seconds. This means that the time it takes for the
     complete transaction and the request() method to actually return might be
     longer.

As long as data is being passed, the timeout won't be triggered. You can use callback functions (see the REQUEST METHODS section of the docs) to check how long data transfer has been going on, and to exit entirely if desired.


text:
Q: How do I append a colon zero, :0 onto the end of an IP address string? I have a simple Linux shell script that parses a file generated in windows that is shared with a Linux VM. I would like to obtain an IP address from this file and append a colon 0 (:0) on the end, so as to set the DISPLAY environment variable. When I try to do so, I get strange results.
Here is the script:
#!/bin/bash
LOCAL_HOST=`grep IPv4 /mnt/hgfs/share/localip | awk 'NR ==1 {printf "%s\n", $14 }'`

# for some reason, it overwrites the string from the beginning
COLON_ZERO=':0'
export DISPLAY=${LOCAL_HOST}${COLON_ZERO}
echo $DISPLAY

# This obviously works, but doesnt have the COLON_ZERO on the end
echo "export DISPLAY="$LOCAL_HOST

And here is the output of running this script:
# ./display.sh
:09.107.26.25
export DISPLAY=159.107.26.25

# bash --version
GNU bash, version 3.2.48(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.

And just in case its necessary, here is the result of the grep from the file used in the script:
# grep IPv4 /mnt/hgfs/share/localip
   IPv4 Address. . . . . . . . . . . : 159.107.26.25
   IPv4 Address. . . . . . . . . . . : 192.168.223.1
   IPv4 Address. . . . . . . . . . . : 192.168.132.1

Why do I get this strange result when I append the colon zero onto the end of the IP address string? How can I change the script to get the correct result?

A: Your input file contains Windows line endings (\r\n). Remove the \r character from the ip address.


text:
Q: xrandr lists 5 providers only, card5 is always disconnected I have 3 DisplayLink USB3 adapters connected to my PC (yes, it's a notebook so I can't use any PCIe graphics cards). Every adapter has 2 output ports (1x HDMI, 1x DVI). These adapters are i-tec U3DUALADA, but I think it doesn't matter because the problem will be somewhere in the X environment.
System: Debian Buster, Xfce
When I connect 6 monitors to these adapters, the system acts like this:

*

*first 4 connected monitors are working, other 2 don't

*no mather in which ports these are connected in

In the DisplayLink log file, I see DisplayLink knows about all of the connected monitors (when I disconnect/connect any monitor, DisplayLink adds some output to the log file).
But there are two strange things in xrandr:
1/ When I start connecting DisplayLink adapters, xrandr --listproviders outputs:
After 1st connected adapter:
root@fix-x270:/etc/X11# xrandr --listproviders
Providers: number : 3
Provider 0: id: 0x4a cap: 0xf, Source Output, Sink Output, Source
Offload, Sink Offload crtcs: 3 outputs: 8 associated providers: 0 name:modesetting
Provider 1: id: 0x283 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 2: id: 0x261 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting

After 2nd connected adapter:
root@fix-x270:/etc/X11# xrandr --listproviders
Providers: number : 5
Provider 0: id: 0x4a cap: 0xf, Source Output, Sink Output, Source
Offload, Sink Offload crtcs: 3 outputs: 8 associated providers: 0 name:modesetting
Provider 1: id: 0x283 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 2: id: 0x261 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 3: id: 0x23e cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 4: id: 0x21c cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting

After 3rd connected adapter:
root@fix-x270:/etc/X11# xrandr --listproviders
Providers: number : 6
Provider 0: id: 0x4a cap: 0xf, Source Output, Sink Output, Source Offload, Sink Offload crtcs: 3 outputs: 8 associated providers: 0 name:modesetting
Provider 1: id: 0x283 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 2: id: 0x261 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 3: id: 0x23e cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 4: id: 0x21c cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting
Provider 5: id: 0x1f5 cap: 0x2, Sink Output crtcs: 1 outputs: 1 associated providers: 0 name:modesetting

As you can see, Provider 6 is missing, which is the first problem.
2/ When I use these providers by:
xrandr --setprovideroutputsource 1 0
xrandr --setprovideroutputsource 2 0
xrandr --setprovideroutputsource 3 0
xrandr --setprovideroutputsource 4 0
xrandr --setprovideroutputsource 5 0

When I would run xrandr --setprovideroutputsource 6 0, ofcourse it says Could not find provider with index 6.
When I run ls /sys/class/drm/*/status | xargs -I {} -i bash -c "echo -n {}: ; cat {}", it outputs:
/sys/class/drm/card0-DP-1/status:disconnected
/sys/class/drm/card0-DP-2/status:disconnected
/sys/class/drm/card0-DP-3/status:disconnected
/sys/class/drm/card0-DP-4/status:connected
/sys/class/drm/card0-DP-5/status:connected
/sys/class/drm/card0-eDP-1/status:connected
/sys/class/drm/card0-HDMI-A-1/status:disconnected
/sys/class/drm/card0-HDMI-A-2/status:disconnected
/sys/class/drm/card1-DVI-I-1/status:connected
/sys/class/drm/card2-DVI-I-2/status:connected
/sys/class/drm/card3-DVI-I-3/status:connected
/sys/class/drm/card4-DVI-I-4/status:connected
/sys/class/drm/card5-DVI-I-5/status:disconnected

First three monitors are connected directly to the PC, they are not interesting for us, because they work as they should.
Strange thing is that card5-DVI-I-5 is always disconnected, which is the second problem.
9 monitor setup is something not as common, so I was unable to find any similar problem.
Thank you for your advice.
fix


text:
Q: How to remove android permissions when wrapping html5 app using Cocoonjs Every time when I use Cocoonjs Cloud services to convert a HTML5 app to Android app, it automatically adds all the unnecessary android permissions. It makes users confused when downloading app. In fact, all unnecessary permissions such as access to phone book, access the internet, wifi access, location, etc. will be added to the manifest file.
Is there any way I can remove those permissions. Actually, I am using Construct 2 to build the application, then wrap it using ludei cloud services. After that, I received an unsigned apk file.
Thanks in advance.

A: This may not be a proper answer but the official doc recommends crosswalk instead of Cocoonjs and it seems that crosswalk will let you choose which permissions to use.


text:
Q: ParseInt elements in array to int Suppose you have an array of the following element basically three numbers: 2,000 3,000, and 1,000
In order to say multiply each by 1,000 you would have to parse it to be set as an int:

var i = 0;
var array_nums[3,000, 2,000, 1,000];
for(i = 0; i < array_nums.length; i++){
  array_nums[i] = parseInt(array_nums[i]);
}
arraytd_dth_1[i]*1000;
//arraytd_dth_1[i].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Once parsed I would want to multiply by them by 1,000 and display them so that it has commas for every three digits. This is just a general solution I came up with for Javascript and JQuery.

A: 2,000 is not a number. It's a String.
You should first remove the commas and then parse it to a number.

var i = 0;
var array_nums = ["3,000", "2,000", "1,000"];
for (i = 0; i < array_nums.length; i++) {
  array_nums[i] = parseInt(array_nums[i].replace(new RegExp(",", 'g'), "")) * 1000;
}
console.log(array_nums);

A: You can do it in a forEach and use toLocaleString() to format with commas.  Straight Javascript ... no JQuery necessary.
var array_output=[];
var array_nums = [3000, 2000, 1000];

array_nums.forEach(x => {
  array_output.push((x*1000).toLocaleString());
})

A: if you are using ES6 try let newArr = array_nums.map(data => data*1000)


text:
Q: .net mvc codefirst multiple SiteDataContextInitializer one database I'm trying to create modules to reuse. For example, a Membership project that creates and handles user operations (login, register, etc), then build it, and use the dll inside other projects.
So, in the Membership project I create my POCO classes and the DataContext using its own Namespace:
namespace CloudOne.Membership.Models
{
    public class SiteDataContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }
        public DbSet<UserRoleJoin> UserRoleJoins { get; set; }

        // Twist our database
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }
    }

    public class SiteDataContextInitializer : DropCreateDatabaseAlways<SiteDataContext>
    {
        protected override void Seed(SiteDataContext context)
        {
            // users

            var user = new User { UserID = "UserA", Password = "D33177D41FD48F0027BD10D2689E8599", DateCreated=DateTime.Now, DateLastLogin = DateTime.Now };

            context.Users.Add(user);

            var roles = new List<UserRole>
            {
                new UserRole { RoleID = "Admin" },
                new UserRole { RoleID = "Editor" },
                new UserRole { RoleID = "Customer" },
                new UserRole { RoleID = "Guest" }
            };

            roles.ForEach(m => context.UserRoles.Add(m));

            var userRoleJoin = new UserRoleJoin { UserID = "UserA", RoleID = "Admin" };

            context.UserRoleJoins.Add(userRoleJoin);
        }
    }
}

Then I use in a main project, using the CloudOne.Membership.dll as reference, the main project has its own Namespace, DataContext and seed again:
namespace CloudOne.Models
{
    public class SiteDataContext : DbContext
    {
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductPrice> ProductPrices { get; set; }
        public DbSet<ProductPicture> ProductPictures { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }
    }

    public class SiteDataContextInitializer : DropCreateDatabaseAlways<SiteDataContext>
    {
        protected override void Seed(SiteDataContext context)
        {
            // data seeding here

            context.SaveChanges();
        }
    }
}

Then I call both Initializers from global.asax
protected void Application_Start()
        {
            Database.SetInitializer<SiteDataContext>(new SiteDataContextInitializer());
            Database.SetInitializer<CloudOne.Membership.Models.SiteDataContext>(new CloudOne.Membership.Models.SiteDataContextInitializer());

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

Now the problem is, when I access a page that uses main project classes, it creates the database (ModelFirst) for the POCO defined in main class, and seeds the data as defined in the main project datacontext, but it doesnt create POCO or seed for Membership ones. And, when access a page that uses Membership data... it recreates the database for Membership only.
So, how I can use Membership (and other modules) together with a main project, without having to add tables, relationships and seeding manually for all is not in the main project?
For example, the main project is about Shopping Cart, in order to user Membership module, I have to copy all POCO classes inside ShoppingCart DataContext and also the seeding part to create users, roles, etc. But that code already is inside the Membership. Initializer, so how to encapsulate that, so that no need copy code from all module to the main app just to have the database with all tables and data?

A: There is a good chance this is a connection string issue and the DB is actually getting created just not in the place you're expecting.
My guess is that you have defined the SiteDataContext connection string in your web.config but you have not defined the CloudOne.Membership.Models.SiteDataContext connection string explicitly.
EF is going to consider these two separate DbContexts -- it's not like you can merge them simply by making the classes the same name.  So it's looking for separate connection strings to go along with the separate initialization instructions you are assigning.
I have not tried this with EF 4.1 but I believe model change tracking will prevent having two contexts share the same physical database (as described here).
In short, I believe your immediate problem is that you're not initializing your Membership context with a connection string so it is defaulting to local.  EF will try to find a connection string with the name of your context in the active App Domain (your Shopping Cart website) so it needs to be in the web.config of that site.


text:
Q: Restricting access to AWS S3 objects I am using AWS S3 to store photos in conversations between users in my chat application (backend is written in Java / Spring Boot). At the moment, access to the bucket is public, which means that every user who would guesses the url will be able to see the picture.
What I would like to achieve is to restrict access to the resource only to interlocutors who belong to the given conversation so that they can see the photos sent between them.
I don't want to run all the traffic through my backend, I just want to delegate authorization to the S3. Is it possible to set some kind of "auth token" to restrict access to the given object on s3? I would generate this token on my backend and possibly refresh it from time to time. Are there any other recommended options for this task?

A: As indicated, you can presign the URL.  In Java (API V1) the basics are something like:
String bucketName = "the-bucket-name";
String objectKey = "/your/object/keyname.jpg";

AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build();

// Set the presigned URL to expire after one hour.
Date expiration = new Date();
long expTimeMillis = expiration.getTime() + 1000 * 60 * 60;
expiration.setTime(expTimeMillis);

// Generate the presigned URL.
GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(bucketName, objectKey)
                .withMethod(HttpMethod.GET)
                .withExpiration(expiration);

URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

System.out.println("Pre-Signed URL: " + url.toString());

This allows anyone to access the image for one hour if they have the URL.  Presumably you could generate the URL to include on a web page and the likelihood of sharing the link is low.
If you must have a guarantee that only the correct person can access the image then you'll need some sort of server side component.  You can route it through your server or possibly a API Gateway/Lambda component.

A: You can create presigned URLs for S3 objects. This generates a temporary link that grants access to an S3 object, even if the bucket is not public.
As an example/test, you could run the aws s3 presign command in the AWS CLI:
aws s3 presign s3://BucketName/SomePhoto.png --expires-in 86400

This command will return an address that can be used to access SomePhoto.png. The URL will be valid for 86400 seconds, which is one day. --expires-in is optional.
More details on the command lind reference can be found here.


text:
Q: How to save associated models in cakePHP I have five models and their respective tables are
Member:id,fname,lname
Student:id,member_id(foreign key references member table id),order_id (references order table id)
Contact:id,member_contact_id(foreign key references Member id)
Address:id,city,state
Order:id,student_id(foreign key references student id),contact_id( foreign references contact id),address_id(foreign key references address id

and i established relation in models also.

when i do
$this->Order->saveAll($this->session->read())

only contact and address and in order contact_id and address_id is saving but the member and student is not saving.
please give me the solution to save all the models at on shot.

A: cake only does 2 level deep association saves with saveAll (or multi rows of the same model)
you will need to roll your own save with a few foreach loops or just saving the various parts of the data.
eg: you use saveAll to save the contact and address and then get the id's. manually set the ids of the fk in the other data and then call a bunch of saves for the remaining data.


text:
Q: $\mathbb{P}$ divisible into infinitely many subsets $S_i$ of consecutive primes where $\sum S_i = \text{prime}$? Let $\mathbb{P}$ be the set of all primes, $p_n$ the $n^{\text{th}}$ prime and $S_i$ a subset of $\mathbb{P}$, consisting of the smallest amount of consecutive primes for which $\sum S_i = \text{prime}$.
Rule 1: if the last prime of $S_i$ is $p_n$, then the first prime of $S_{i+1}$  must be $p_{n+1}$.
Rule 2: $|S_i| \ge 2 $
If we start with the first primes we get
$$S_1 = \{ 2,3 \} \quad \to \quad \sum S_1 = 5$$
followed by
$$S_2 = \{ 5,7,11 \} \quad \to \quad \sum S_2 = 23$$
$$S_3 = \{ 13,17,19, 23, 29 \} \quad \to \quad \sum S_3 = 101$$
$$S_4 = \{ 31,37,41 \} \quad \to \quad \sum S_4 = 109$$
$$\dots$$
After calculating the subsets for the first $10^4$ primes, I'm inclined to say that there are infinitely many of these subsets. Is there any way we can prove this?

A: This PARI/GP-program shows the sums having more summands than every earlier sum.
? maxi=0;s=0;p=1;while(p<10^9,s=0;p=nextprime(p+1);s=s+p;p=nextprime(p+1);s=s+p;
l=2;while(isprime(s)==0,p=nextprime(p+1);s=s+p;l=l+1);if(l>maxi,maxi=l;print(p,"
  ",s,"  ",l)))
3  5  2
11  23  3
29  101  5
127  757  7
173  1367  9
983  44843  57
15641  936697  61
77069  5747459  75
102329  12913867  127
848273  119470049  141
2090071  323789369  155
2501357  422521873  169
4053473  765829241  189
9145921  1801447657  197
17298467  3615013973  209
30961577  6594416419  213
39716671  9015231847  227
45057613  11849608241  263
72835471  24981493099  343
491344573  178356736889  363
?

The last sum has only $11$ summands.
? print(p," ",s,"  ",l)
1000000009 10999998463  11
?

The following conjectur would imply your conjecture.

The sequence of partial
   sums of consecutive primes, starting with an arbitary prime $p$, contains a prime greater than $p$ itself.


text:
Q: What is the difference between 'remove' and 'removeChild' method in JavaScript? I have created an HTML page to understand how removing an element works.
Code:

    <button onclick="rem()">remove</button>
    <button onclick="remChild()">removeChild</button>
    <button onclick="ins()">insert</button>

Here I try to remove the 'child' div in two ways:

*

*By calling 'remove' method on 'child' div

*By calling 'removeChild' method on 'parent1' node
But in both the cases, the node is not actually removed. I can always insert 'child' div to 'parent2'.
I can understand that in second case, the 'child' is unbound from 'parent1' and not actually deleted. But in first case, is the 'child' not removed permanently?
Shouldn't I get an error while trying to insert an element which does not exist?
Please explain.
And if the element does exist even after calling 'remove' on element:

*

*How is 'remove' different from 'removeChild'? As I see, both these methods just unbound child from parent, but element still occupies the memory.

*Is there any way to ensure that element is actually removed from memory?

A:
the node is not actually removed

The confusion might be because you might think removing an element means something like killing or destroying it.

But in fact, the concept of removal basically means breaking the relationship between a child and its parent. It's just a detachment.

Shouldn't I get an error while trying to insert an element which does not exist?

No, because it still exists.

How is remove different from removeChild?

remove only needs a reference to the child. removeChild needs a reference both to the parent and the child. The result is identical.

Is there any way to ensure that element is actually removed from memory?

No. You can only unreference it and hope that there is a garbage collector which will detect the object is not referenced and then will remove it.

A: remove is a new function. It's a shortcut, making it simpler to remove an element without having to look for the parent node. It's unfortunately not available on old versions of Internet Explorer so, unless you don't want to support this browser, you'll have to use removeChild or use a polyfill.
The reason the child element is kept in memory is your code keeps a reference to it.
If you do
childDiv = null;

then there's no reference pointing to it and the browser can free the memory.