text:
Q: Unable to deploy Minio in kubernetes cluster using Helm I am trying to deploy minio in kubernetes using helm stable charts,
and when I try to check the status of the release

*

*helm status minio

the pod desired capacity is 4, but current is 0
I tried to look the journalctl logs for any logs from kubelet, but found none
I have attached all helm charts can some one please point out what wrong am I doing?
---
# Source: minio/templates/secrets.yaml
apiVersion: v1
kind: Secret
metadata:
  name: RELEASE-NAME-minio
  labels:
    app: minio
    chart: minio-1.7.0
    release: RELEASE-NAME
    heritage: Tiller
type: Opaque
data:
  accesskey: RFJMVEFEQU1DRjNUQTVVTVhOMDY=
  secretkey: bHQwWk9zWmp5MFpvMmxXN3gxeHlFWmF5bXNPUkpLM1VTb3VqeEdrdw==
---
# Source: minio/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: RELEASE-NAME-minio
  labels:
    app: minio
    chart: minio-1.7.0
    release: RELEASE-NAME
    heritage: Tiller
data:
  initialize: |-
    #!/bin/sh
    set -e ; # Have script exit in the event of a failed command.

    # connectToMinio
    # Use a check-sleep-check loop to wait for Minio service to be available
    connectToMinio() {
      ATTEMPTS=0 ; LIMIT=29 ; # Allow 30 attempts
      set -e ; # fail if we can't read the keys.
      ACCESS=$(cat /config/accesskey) ; SECRET=$(cat /config/secretkey) ;
      set +e ; # The connections to minio are allowed to fail.
      echo "Connecting to Minio server: http://$MINIO_ENDPOINT:$MINIO_PORT" ;
      MC_COMMAND="mc config host add myminio http://$MINIO_ENDPOINT:$MINIO_PORT $ACCESS $SECRET" ;
      $MC_COMMAND ;
      STATUS=$? ;
      until [ $STATUS = 0 ]
      do
        ATTEMPTS=`expr $ATTEMPTS + 1` ;
        echo \"Failed attempts: $ATTEMPTS\" ;
        if [ $ATTEMPTS -gt $LIMIT ]; then
          exit 1 ;
        fi ;
        sleep 2 ; # 1 second intervals between attempts
        $MC_COMMAND ;
        STATUS=$? ;
      done ;
      set -e ; # reset `e` as active
      return 0
    }

    # checkBucketExists ($bucket)
    # Check if the bucket exists, by using the exit code of `mc ls`
    checkBucketExists() {
      BUCKET=$1
      CMD=$(/usr/bin/mc ls myminio/$BUCKET > /dev/null 2>&1)
      return $?
    }

    # createBucket ($bucket, $policy, $purge)
    # Ensure bucket exists, purging if asked to
    createBucket() {
      BUCKET=$1
      POLICY=$2
      PURGE=$3

      # Purge the bucket, if set & exists
      # Since PURGE is user input, check explicitly for `true`
      if [ $PURGE = true ]; then
        if checkBucketExists $BUCKET ; then
          echo "Purging bucket '$BUCKET'."
          set +e ; # don't exit if this fails
          /usr/bin/mc rm -r --force myminio/$BUCKET
          set -e ; # reset `e` as active
        else
          echo "Bucket '$BUCKET' does not exist, skipping purge."
        fi
      fi

      # Create the bucket if it does not exist
      if ! checkBucketExists $BUCKET ; then
        echo "Creating bucket '$BUCKET'"
        /usr/bin/mc mb myminio/$BUCKET
      else
        echo "Bucket '$BUCKET' already exists."
      fi

      # At this point, the bucket should exist, skip checking for existence
      # Set policy on the bucket
      echo "Setting policy of bucket '$BUCKET' to '$POLICY'."
      /usr/bin/mc policy $POLICY myminio/$BUCKET
    }

    # Try connecting to Minio instance
    connectToMinio
    # Create the bucket
    createBucket bucket none false

  config.json: |-
    {
      "version": "26",
      "credential": {
        "accessKey": "DR06",
        "secretKey": "lt0ZxGkw"
      },
      "region": "us-east-1",
      "browser": "on",
      "worm": "off",
      "domain": "",
      "storageclass": {
        "standard": "",
        "rrs": ""
      },
      "cache": {
        "drives": [],
        "expiry": 90,
        "maxuse": 80,
        "exclude": []
      },
      "notify": {
        "amqp": {
          "1": {
            "enable": false,
            "url": "",
            "exchange": "",
            "routingKey": "",
            "exchangeType": "",
            "deliveryMode": 0,
            "mandatory": false,
            "immediate": false,
            "durable": false,
            "internal": false,
            "noWait": false,
            "autoDeleted": false
          }
        },
        "nats": {
          "1": {
            "enable": false,
            "address": "",
            "subject": "",
            "username": "",
            "password": "",
            "token": "",
            "secure": false,
            "pingInterval": 0,
            "streaming": {
              "enable": false,
              "clusterID": "",
              "clientID": "",
              "async": false,
              "maxPubAcksInflight": 0
            }
          }
        },
        "elasticsearch": {
          "1": {
            "enable": false,
            "format": "namespace",
            "url": "",
            "index": ""
          }
        },
        "redis": {
          "1": {
            "enable": false,
            "format": "namespace",
            "address": "",
            "password": "",
            "key": ""
          }
        },
        "postgresql": {
          "1": {
            "enable": false,
            "format": "namespace",
            "connectionString": "",
            "table": "",
            "host": "",
            "port": "",
            "user": "",
            "password": "",
            "database": ""
          }
        },
        "kafka": {
          "1": {
            "enable": false,
            "brokers": null,
            "topic": ""
          }
        },
        "webhook": {
          "1": {
            "enable": false,
            "endpoint": ""
          }
        },
        "mysql": {
          "1": {
            "enable": false,
            "format": "namespace",
            "dsnString": "",
            "table": "",
            "host": "",
            "port": "",
            "user": "",
            "password": "",
            "database": ""
          }
        },
        "mqtt": {
          "1": {
            "enable": false,
            "broker": "",
            "topic": "",
            "qos": 0,
            "clientId": "",
            "username": "",
            "password": "",
            "reconnectInterval": 0,
            "keepAliveInterval": 0
          }
        }
      }
    }
---
# Source: minio/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: RELEASE-NAME-minio
  labels:
    app: minio
    chart: minio-1.7.0
    release: RELEASE-NAME
    heritage: Tiller
spec:
  type: ClusterIP
  clusterIP: None

  ports:
    - name: service
      port: 9000
      targetPort: 9000
      protocol: TCP
  selector:
    app: minio
    release: RELEASE-NAME

---
# Source: minio/templates/statefulset.yaml

apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: RELEASE-NAME-minio
  labels:
    app: minio
    chart: minio-1.7.0
    release: RELEASE-NAME
    heritage: Tiller
spec:
  serviceName: RELEASE-NAME-minio
  replicas: 4
  selector:
    matchLabels:
      app: minio
      release: RELEASE-NAME
  template:
    metadata:
      name: RELEASE-NAME-minio
      labels:
        app: minio
        release: RELEASE-NAME
    spec:
      containers:
        - name: minio
          image: node1:5000/minio/minio:RELEASE.2018-09-01T00-38-25Z
          imagePullPolicy: IfNotPresent
          command: [ "/bin/sh",
          "-ce",
          "cp /tmp/config.json  &&
          /usr/bin/docker-entrypoint.sh minio -C  server
          http://RELEASE-NAME-minio-0.RELEASE-NAME-minio.default.svc.cluster.local/export
          http://RELEASE-NAME-minio-1.RELEASE-NAME-minio.default.svc.cluster.local/export
          http://RELEASE-NAME-minio-2.RELEASE-NAME-minio.default.svc.cluster.local/export
          http://RELEASE-NAME-minio-3.RELEASE-NAME-minio.default.svc.cluster.local/export" ]
          volumeMounts:
            - name: export
              mountPath: /export
            - name: minio-server-config
              mountPath: "/tmp/config.json"
              subPath: config.json
            - name: minio-config-dir
              mountPath:
          ports:
            - name: service
              containerPort: 9000
          env:
            - name: MINIO_ACCESS_KEY
              valueFrom:
                secretKeyRef:
                  name: RELEASE-NAME-minio
                  key: accesskey
            - name: MINIO_SECRET_KEY
              valueFrom:
                secretKeyRef:
                  name: RELEASE-NAME-minio
                  key: secretkey
          livenessProbe:
            tcpSocket:
              port: service
            initialDelaySeconds: 5
            periodSeconds: 30
            timeoutSeconds: 1
            successThreshold: 1
            failureThreshold: 3
          readinessProbe:
            tcpSocket:
              port: service
            periodSeconds: 15
            timeoutSeconds: 1
            successThreshold: 1
            failureThreshold: 3
          resources:
            requests:
              cpu: 250m
              memory: 256Mi

      volumes:
        - name: minio-user
          secret:
            secretName: RELEASE-NAME-minio
        - name: minio-server-config
          configMap:
            name: RELEASE-NAME-minio
        - name: minio-config-dir
          emptyDir: {}
  volumeClaimTemplates:
    - metadata:
        name: export
      spec:
        accessModes: [ "ReadWriteOnce" ]
        storageClassName: local-fast
        resources:
          requests:
            storage: 49Gi

---
# Source: minio/templates/ingress.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: RELEASE-NAME-minio
  labels:
    app: minio
    chart: minio-1.7.0
    release: RELEASE-NAME
    heritage: Tiller
  annotations:
    nginx.ingress.kubernetes.io/affinity: cookie
    nginx.ingress.kubernetes.io/session-cookie-hash: sha1
    nginx.ingress.kubernetes.io/session-cookie-name: route

spec:
  tls:
    - hosts:
        - minio.sample.com
      secretName: tls-secret
  rules:
    - host: minio.sample.com
      http:
        paths:
          - path: /
            backend:
              serviceName: RELEASE-NAME-minio
              servicePort: 9000

A: I suspect you are not getting the physical volume. Check your kube-controller-manager logs on your active master. This will vary depending on the cloud you are using: AWS, GCP, Azure, Openstack, etc. The kube-controller-manager is usually running on a docker container on the master. So you can do something like:
docker logs <kube-controller-manager-container>

Also, check:
kubectl get pvc
kubectl get pv

Hope it helps.

A: bit more digging gave me the answer, statefulset was deployed but pods were not created
kubectl describe statefulset -n <namespace> minio

the log said it was looking for mount path which was "" (in previous versions of charts), changing it solved my issue.


text:
Q: Dataframe has subscription purchase history. Trying to show subsequent subscriptions purchased I have a dataframe with subscription term purchase records. For example, individuals (identified by their account numbers) have originally purchased 3, 6, 9, 12, 16, 18 or 24 month subscriptions. I am interested in determining how many purchasers of, e.g, 3 month subscriptions went to purchases another 3 month subscription or 6, 9, 12, 16, 18 or 24 month period subscription.
Here is a simplified version of the dataframe.
user_id     purch date          Product

65587578    2018-03-01 01:21:12     3 month subscription
65587578    2018-06-07 19:39:56     6 month subscription
65587578    2019-03-07 11:39:56     12 month subscription

65785442    2018-03-07 19:39:56     3 month subscription
65785442    2018-09-07 11:39:16     6 month subscription
65785442    2019-09-01 10:21:11     6 month subscription

89808622    2018-03-01 02:19:0      3 month subscription
89808622    2018-06-07 19:39:56     1 month subscription
89808622    2019-07-07 12:31:46     12 month subscription

Here is some code I have to extract, for example, all the 3 month subscriptions:
repurchases.loc[repurchases['product'] == '3 month subscription']
which could produce
user_id     purch date      Product
65587578    2019-03-07 11:39:56 3 month subscription
89808622    2019-07-07 12:31:46 3 month subscription
and so on..

But what I really want to do is group the account numbers that made an initial purchase of e.g., a 3 month subscription (using the purch date), count them, and determine how many other other subscriptions they bought subsequently such as 1 month subscription, 6 month subscription, and so on.
I am struggling with how to approach this. Any suggestions?

A: If I get your query then you may want how many users purchased a specific product
dictionary = {
    'user_id':[65587578,65587578,65587578,65785442,65785442,65785442,89808622,89808622,89808622],
    'purch_date':['2018-03-01 01:21:12','2018-06-07 19:39:56','2019-03-07 11:39:56','2018-03-07 19:39:56'
,'2018-09-07 11:39:16','2019-09-01 10:21:11','2018-03-01 02:19:0','2018-06-07 19:39:56','2019-07-07 12:31:46'],
    'Product': ['3 month subscription','6 month subscription','12 month subscription'
,'3 month subscription'
,'6 month subscription'
,'6 month subscription'
,'3 month subscription'
,'1 month subscription'
,'12 month subscription']
}

df = pd.DataFrame(dictionary)
display(df)

user_id     purch_date           Product
65587578    2018-03-01 01:21:12 3 month subscription
65587578    2018-06-07 19:39:56 6 month subscription
65587578    2019-03-07 11:39:56 12 month subscription
65785442    2018-03-07 19:39:56 3 month subscription
65785442    2018-09-07 11:39:16 6 month subscription
65785442    2019-09-01 10:21:11 6 month subscription
89808622    2018-03-01 02:19:0  3 month subscription
89808622    2018-06-07 19:39:56 1 month subscription
89808622    2019-07-07 12:31:46 12 month subscription

#List of users with a 3-month subscription

df[df['Product']=='3 month subscription']

    user_id     purch_date             Product
0   65587578    2018-03-01 01:21:12 3 month subscription
3   65785442    2018-03-07 19:39:56 3 month subscription
6   89808622    2018-03-01 02:19:00 3 month subscription

#Number of users with a 3-month subscription

(df['Product']=='3 month subscription').sum()
-->3

Now other subscriptions they bought. For this, we can use the string functionality of pandas.
#This will do the work you want
other = (df.groupby('user_id').sum()['Product'].str.split('3 month subscription',expand=True))
#expand=True makes it in DataFrame else you will get Series
display(other)
    0                              1
user_id
65587578        6 month subscription12 month subscription
65785442        6 month subscription6 month subscription
89808622        1 month subscription12 month subscription

#More cleaned
other[1].str.split('subscription',expand=True).drop(2,axis=1)

               0        1
user_id
65587578    6 month 12 month
65785442    6 month 6 month
89808622    1 month 12 month

A: Updating this. I used the following to identify user_ids with multiple purchases (showing up more than once in the dataframe)
#All purchases users whose first purchase is 3 month subscription
df_all = df[df.duplicated(['user_id'], keep=False)]
df_all_sorted = df_all.sort_values(['user_id', 'purch_date'], ascending=True)
df_all_first = df_all_sorted.groupby('user_id'], as_index=False).nth(0)
df_first_xmo = df_all_first[df_all_first['product'] == '3 month subscription']

#Prepare date-sorted dataframes to extract subsequent purchases where first purchase is 3 months subscription."
df_all_withxmosPurchFirst = df_all[df_all.p_paid_user_id.isin(df_first_xmo.user_id)]
df_all_withxmosPurchFirst_sorted = df_all_withxmosPurchFirst.sort_values(['user_id', 'purch_date'])

#Second purchases where first purchase is "3 months subscription"
firstpurch_xmos_and_secpurch = df_all_withxmosPurchFirst_sorted.groupby(
['user_id'], as_index=False).nth(1)
firstpurch_xmos_and_secpurch_frame = firstpurch_xmos_and_secpurch['product'].str.title(    ).value_counts().to_frame(name='second_buy')

And that give me output like this showing subsequent purchases of those who initially purchased a 3 Months Subscription:
                        second_buy
3 Months Subscription   23
6 Months Subscription   18
12 Months Subscription  16
1 Month Firecracker Md  3
24 Months Subscription  3
2 Months Subscription   3
18 Months Subscription  3
36 Months Subscription  2
9 Months Subscription   1
48 Months Subscription  1
2 Month Subscription    0
18 Months Subscription  0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to return the default value for the object attribute in perl I have a module , when I am trying to get the default attribute set in initialization, is giving the following error when subroutine is being called get_name
     Use of uninitialized value

sample code
     package test;
     #....
     #....
     sub new {
         my ($class) =  @_;
         my $self    = {};
         bless $self,$class;
         $self->_initialize();
         return $self;
     }

     sub _initailalize {
        my($self) = @_;
        $self = {
                     _name => 'NA'
        };
     }

     sub get_name {
              return $_[0]->{_name};
     }

valuable inputs required.

A: You are redefining $self in the local scope of _initialize and assigning a new hashref. That way you are not adding the _name key to the blessed object. After _initialize is done, your newly assigned $self (with a plain hashref) is gone. Thus in get_name it cannot access the key _name.
 sub _initailalize { # btw typo here
    my ($self) = @_;
    $self->{_name} = 'NA';
 }

If you do it like this, you will need to assign each member on an individual line.

As a suggestion, this built-in style of OO is very tedious. Try looking at Moose or it's derivatives as they are pretty powerful.


text:
Q: What does Mega-Word (MW) mean? I have a question about data sizes, I came across a question about what is the size of a physical address if the size of the physical memory is 1MW (Mega-Word).
I have never heard about this term (Mega-Word) and I didn't find much on the net.
I hope you can explain me briefly what Mega-Word is.
Thank you.

A: Some systems do not use bytes at all. There was a time not long ago when it was common for systems to use memory organized into 12 and 36-bit "words." Both Sperry (CTS) and DEC (TOPS) had 36-bit systems, for example.
On such systems, there was no such thing as a "megabyte." Instead, memory was measured in megawords where a word was 36-bits.


text:
Q: Plane rotated about line of intersection to another plane? The plane ax+by=0 is rotated about its line of intersection with the plane z=0 through an angle n. What is the equation of the plane in its new position? I saw a question in stack exchange relating to 3d plane rotation but its answers were of a more advanced level. Would someone please help me with an easy visualisation and solving of this problem?

A: Take a unit vector $\bf t$ parallel to the intersection line, e.g. take the difference of two points that satisfy the equations of both planes, and then make it unitary.
Otherwise take the cross product of the unit normals to each plane $ \bf n_1 \times \bf n_2$.
After that $\bf m = \bf n_1 \times \bf t$ is a unit vector that lies on the first plane
 and is normal to the intersection line.
 The set $(\bf t, \bf m, \bf n_1)$ has the same chirality as $(x,y,z)$.
Rotating the plane by an angle $\alpha$ around $t$ according to the right-hand rule, gives a new normal to the plane which is $\bf n_1'= - \sin \alpha\, \bf m + \cos \alpha \, \bf n_1$.
Having the new normal $\bf n_1'$ and a point on the intersection line, you have the equation of the rotated plane.

A: A general plane has the equation
$$px+qy+rz=s.$$
If you plug the condition $z=0$, the equation of all planes by the line $z=0$ are
$$px+qy=s.$$
If you observe that the origin $(0,0,0)$ belongs to the line of intersection, $s=0$ and the equation is
$$px+qy=0.$$
Now we want to express that the angle between the given plane and the unknown one is $\theta$, or that the angle between the unit normal vectors is $\theta$, we have that their dot product is the cosine of $\theta$, and
$$\frac{ap+bq}{\sqrt{(a^2+b^2)(p^2+q^2)}}=\cos\theta.$$
To solve this equation for $p,q$, it is easier to express $(a,b)$ and $(p,q)$ in polar coordinates. After simplification,
$$\cos(\phi_{ab}-\phi_{pq})=\cos\theta.$$


text:
Q: Prove that : $m_{a}m_{b}m_{c}\leq\frac{Rs^{2}}{2}$ Let $m_{a},m_{b},m_{c}$ be the lengths of the medians and $a,b,c$ be the lengths of the sides of a given triangle , Prove the inequality :
$$m_{a}m_{b}m_{c}\leq\frac{Rs^{2}}{2}$$
Where :
$s : \operatorname{Semiperimeter}$
$R : \operatorname{circumradius}$
I know the relation :
$$m_{a}^{2}=\frac{2(b^{2}+c^{2})-a^{2}}{4}$$
But when I multiple together I dont get simple formulas!
So, I need help finding a solution.
Thanks!

A: In the standard notation we need to prove that:
$$\frac{1}{8}\sqrt{\prod_{cyc}(2a^2+2b^2-c^2)}\leq\frac{1}{2}\cdot\frac{abc}{4S}\cdot\frac{(a+b+c)^2}{4}$$ or
$$a^2b^2c^2(a+b+c)^3\geq\prod_{cyc}(2a^2+2b^2-c^2)\prod_{cyc}(a+b-c).$$
Now, let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, $$\prod_{cyc}(2a^2+2b^2-c^2)=\prod_{cyc}(2(a^2+b^2+c^2)-3c^2)=$$
$$=8(9u^2-6v^2)^3-12(9u^2-6v^2)^3+18(9u^2-6v^2)(9v^4-6uw^3)-27w^6=$$
$$=27(-w^6+2(3u^2-2v^2)(9v^4-6uw^3)-4(3u^2-2v^2)^3).$$
Also, $$\prod_{cyc}(a+b-c)=\prod_{cyc}(3u-2c)=27u^3-54u^3+36uv^2-8w^3=$$
$$=-8w^3-27u^3+36uv^2.$$
Thus, we need to prove that $f(w^3)\geq0,$ where
$$f(w^3)=u^3w^6-(-w^6+2(3u^2-2v^2)(9v^4-6uw^3)-4(3u^2-2v^2)^3)(-8w^3-27u^3+36uv^2).$$
But $$f''(w^3)=2u^3-2(-2w^3+2(3u^2-2v^2)(-6u))(-8)+$$
$$-(-8w^3-27u^3+36uv^2)(-2)=-4(157u^3-114uv^2+12w^3)<0,$$ which says that $f$ is a concave function.
Thus, it's enough to prove our inequality for an extreme value of $w^3$, which happens in the following cases.

*

*$w^3\rightarrow0^+$.
in this case the inequality is obvious;

*$\prod\limits_{cyc}(a+b-c)\rightarrow0^+$.
It's obvious again;

*Two variables are equal.

Since our inequality is symmetric and homogeneous, it's enough to assume $b=c=1$.
Thus, $0<a<2$ and we need to prove that
$$a^2(a+2)^3\geq(2a^2+1)^2(4-a^2)a^2(2-a)$$ or
$$(a+2)^2\geq(2a^2+1)^2(2-a)^2$$ or
$$a+2\geq(2a^2+1)(2-a)$$ or
$$a(a-1)^2\geq0$$ and we are done!

A:
Note that the triangles ABD and EDC are similar. Then,
$$\frac{AD}{BD}=\frac{CD}{ED}\implies \frac{m_a}{\frac a2}=\frac{\frac a2}{AE-m_a}
\implies m_a^2 -AE\cdot m_a + \frac {a^2}4=0$$
which, since $AE \le 2R$ and $a=2R\sin A$, leads to
$$m_a =\frac12(AE+\sqrt{AE^2-a^2})\le \frac12\left[2R+\sqrt{(2R)^2-(2R\sin A)^2}\right] =2R\cos^2 \frac A2$$
Likewise, $m_b\le 2R\cos^2 \frac B2$ and $m_c\le 2R\cos^2 \frac C2$. Together, we have
$$\begin{align}
m_a m_bm_c & \le \frac12R^3\left( 4\cos\frac A2\cos \frac B2\cos \frac C2\right)^2  \\
& = \frac12R^3\left( 2 \cos\frac A2 \left(\cos \frac {B+C}2+\cos \frac {B-C}2 \right)\right)^2 \\
& = \frac12R^3\left( 2 \cos\frac A2 \sin\frac A2+2 \sin\frac {B+C}2\cos \frac {B-C}2 \right)^2 \\
& = \frac12R^3\left( \sin A + \sin B + \sin C \right)^2 \\
& = \frac12R^3 \left( \frac a{2R} + \frac b{2R} + \frac c{2R}\right)^2 \\
& = \frac12R \left( \frac{a + b+ c}2 \right)^2 \\
\end{align}$$
Thus,
$$m_a m_bm_c \le \frac12Rs^2$$


text:
Q: ASP.NET Web API 2: Login with external provider via native mobile (iOS) app I have done much searching and have not been able to find an ideal solution for this issue. I know that there is an alleged solution (WebApi ASP.NET Identity Facebook login) however, some elements of the solution are a (in my mind) seriously hacky (e.g. registering the user with a regular account and then adding the external login, rather than registering them with the external login).
I would like to be able to register and authenticate against an ASP.NET Web API 2 application, after already having used the Facebook SDK login on a iOS mobile app, i.e. I have already authenticated against Facebook using their SDK, and now want to seamlessly register/authenticate with the ASP.NET Web API. I do not want to use the process where I have to use the web calls (/api/Account/ExternalLogin) as this, well, is not a great user experience on a native mobile app.
I have tried learning about OWIN, but the .NET framework is complex and I am struggling in how to solve this issue.

A: I needed to do this today for my Ionic app. The Web API Account controller has its own opinion on how to do things and the best way to understand it is reading this pretty amazing 3 part blog post by Dominick Baier. https://leastprivilege.com/2013/11/26/dissecting-the-web-api-individual-accounts-templatepart-3-external-accounts/.
The way I worked around it was to forget the out-of-the-box flow, but instead use the accessToken from the native Facebook login and then call into the following server code to 1) call the Facebook API to validate the access token, 2) from that Facebook call, get the email and id, 3) either get the user or create it (and login) which is already code that's in the Account controller in other places, 4) Create the local authority JWT for subsequent Web API calls.
public class ProviderAndAccessToken {
    public string Token { get; set; }
    public string Provider { get; set; }
}

[AllowAnonymous]
[HttpPost]
[Route("JwtFromProviderAccessToken")]
public async Task<IHttpActionResult> JwtFromProviderAccessToken(ProviderAndAccessToken model) {
    string id = null;
    string userName = null;

    if (model.Provider == "Facebook") {
        var fbclient = new Facebook.FacebookClient(model.Token);
        dynamic fb = fbclient.Get("/me?locale=en_US&fields=name,email");
        id = fb.id;
        userName = fb.email;
    }

    //TODO: Google, LinkedIn

    ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(model.Provider, id));
    bool hasRegistered = user != null;

    string accessToken = null;
    var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
    var props = new AuthenticationProperties() {
        IssuedUtc = DateTime.UtcNow,
        ExpiresUtc = DateTime.UtcNow.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan),
    };

    if (hasRegistered) {
        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
            OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
            CookieAuthenticationDefaults.AuthenticationType);

        AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
        Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
        identity.AddClaim(new Claim("role", "user"));

    }
    else {

        user = new ApplicationUser() { UserName = userName, Email = userName };

        IdentityResult result = await UserManager.CreateAsync(user);
        if (!result.Succeeded) {
            return GetErrorResult(result);
        }

        result = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(model.Provider, id));
        if (!result.Succeeded) {
            return GetErrorResult(result);
        }

        identity.AddClaim(new Claim(ClaimTypes.Name, userName));
    }

    identity.AddClaim(new Claim("role", "user"));
    var ticket = new AuthenticationTicket(identity, props);
    accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

    return Ok(accessToken);
}

The code I'm using in Ionic basically does this to get the access token from Facebook, then call the Web API to get a local authority JWT to use as the Bearer token.
Facebook.login(['public_profile', 'email']).then((result) => {
    return this.http.post("<URL>/api/Account/JwtFromProviderAccessToken", { provider: "Facebook", token: result.authResponse.accessToken })
        .map((res: Response) => res.json())
        .catch(this.handleError)
        .subscribe((res: Response) => {
            // use the result as the Bearer token
        });
})...

Seems pretty safe, but understand that I'm not security expert so this code comes without warranty and please let me know if you see anything glaring and I'll update the code.


text:
Q: How to run mobile joomla on desktop browser? I need to see the output by mobile joomla plugin in my regular browser, to be able to style and tweak things easily.
In older versions of mobile joomla ther was an option ('Mobile Always') that would output mobile views all the time. But I can't find it current version (1.0.3)

A: You can always install User Agent Switcher for Firefox. It gives you the ability to change to a mobile user agent and also a few others things such as IE6 and IE7. You can also add others. Hope this helps. Regards.


text:
Q: Theme displays on localhost and not on domain server, please help! For some odd reason my theme is not displaying on the live server but on the localhost it shows perfectly fine. What could be the cause of this issue?
Thanks in advance!

A: Enter in your database and run this query

SELECT * FROM core_config_data WHERE path LIKE 'web/';

, make sure it is all set up correctly .
What change did you made before the frontend broke ?How do you make deploys in live site ?
Run everything you can :

*

*rm -r pub/static/*

*rm -r generated/*

*rm -r var/cache/*

*php bin/magento setup:upgrade

*php bin/magento setup:di:compile

*php bin/magento setup:static-content:deploy -f

*sudo service varnish restart (if you have varnish in your site)

*Clear CDN (if you have setup cdn)

*run a git status in your repo, to see for any change in root.

*sudo service php-fpm restart.

A: Give the permissions under root folder var/ pub/
sudo chmod 777 -R var/ pub/
After permission clear folder

*

*var/cache, var/generation, var/view_proceed.

*pub/static/frontend.

then refresh your site.


text:
Q: How I can concatenate some bytes read from a stream before hashing them in python3? I try to read a binary file concatenate some bytes ans hash it:
import hashlib
from io import BytesIO
import sys

if __name__ == "__main__":

    in_file = sys.argv[1]
    file_data = open(in_file, 'rb').read()
    stream = BytesIO(file_data)

    digest = hashlib.new('sha256')
    # Concat 32 bytes to inpuit data and then hash it
    digest.update(('\x00' * 32) + stream.read())

What I want is to concatenate 32 bytes initialized with zero to the bytes read through the stream, then hash it alltogether.
But seems the oneliner:
('\x00' * 32) + stream.read()

Not to cut the chase due to the following error:
TypeError: can only concatenate str (not "bytes") to str

DO you know an alternate approach in my case?

A: Use bytes function to create a zero-filled byte sequence of a specified length:
In [1018]: bytes(32)
Out[1018]: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

In your case:
digest.update(bytes(32) + stream.read())

A: You do not need to concatenate in order to get the digested value. You should better call the update method several times to avoid creating a potentially costly copy of the file content. If the file is very large, you should also load it in chunks.
digest.update(32 * b'\x00')
chunk_size = 1024**2
while True:
    chunk = stream.read(chunk_size)
    if not chunk:
        break
    digest.update(chunk)


text:
Q: How to get Gatsby page HTML in graphQL I'm trying to implement site search with elasticlunr and am following the instructions for gatsby-plugin-elasticlunr-search. I'm stuck trying to build a search index since I can't come up with a graphql query that includes any of my content.
Every example I find shows how to edit gatsby-config.js to populate graphql with markdown content:
resolvers: {
      // For any node of type MarkdownRemark, list how to resolve the fields` values
      MarkdownRemark: {
        title: node => node.frontmatter.title,
        tags: node => node.frontmatter.tags,
        path: node => node.frontmatter.path,
      },
    },

I don't have any markdown, my content is entirely in HTML and a few JSON files. Is there any way to pull HTML content into graphql so it can be included in a search index?
Am I going about this the wrong way?

A: You can retrieve the JSON files/content in the same way that the guides does with markdown (as you can see in Gatsby's docs or in this article), however, you may need to create a data structure to populate your HTML since you can't fetch directly the data from an HTML file as it, since it's not inside the Gatsby filesystem, so that Gatsby doesn't know how to create nodes nor GraphQL schema from that content.
The easiest approach is to create a custom data filesystem (JSON, YAML, or markdown files) to populate your HTML and make it dynamic, not "hardcoded" as it is actually (apparently). Once you've set the filesystem and you are able to create queries to gather data and fill your pages/components, you will be able to create queries to use elasticlunr.
Resources:

*

*https://itnext.io/reading-data-from-a-json-file-with-gatsby-graphql-572b18ab98a

*https://github.com/gatsbyjs/gatsby/issues/20734

*GraphQL Query access all transformed json files within a folder located in subdirectories


text:
Q: homomorphism problem The monoids $(S,\min)$ and $(T,\min)$, where $S = \{3,4,5,6\}$ and $T = \{1,2,3,4,5,6\}$ and $\min$ is the minimum function of two integers. Let the function $f:S \to T$ be defined by $f(x) = x-1$; which of the following statements are true?
(A) $f$ is an isomorphism.
(B) $f$ is a one-to-one homomorphism, but $f$ is not onto.
(C) $f$ is an onto homomorphism, but $f$ is not onto.
(D) $f$ is bijective, but $f$ is not a homomorphism.
(E) $f$ is one-to-one, but $f$ is neither a homomorphism nor onto.
(F) $f$ is surjective, but $f$ is neither a homomorphism nor one-to-one.
How would I go about this problem? I also get somewhat confused by the $\min$ function

A: HINT: You should already be familiar with the properties one-to-one and onto for functions in general, so I'll not say anything about them. The function $f$ is a monoid homomorphism if and only if it has the following two properties:

*

*for all $m,n\in S$, $f\big(\min\{m,n\}\big)=\min\big\{f(m),f(n)\big\}$. By the definition of $f$ this means that $\min\{m,n\}-1=\min\{m-1,n-1\}$; is that always true?

*$f(1_S)=1_T$, where $1_S$ is the identity element of $S$, and $1_T$ is the identity element of $T$. Your first step here must be to figure out which element of $S$ is $1_S$, and which element of $T$ is $1_T$. Remember, $1_S$ has the property that $\min\{n,1_S\}=n$ for all $n\in S$, and $1_T$ has a similar property with respect to $T$.
A monoid isomorphism is a homomorphism that is also one-to-one and onto.


text:
Q: Remove or trim zeros 0 at the end only of a float[] samples array I am kind of new with C# and I was wondering if there is a function to remove specific values (0) at the end of an array of float?
For example:
float[] samples = {0.0, 4.0, 2.5, ..., 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

after the call I want my samples to be:
samples == {0.0, 4.0, 2.5, ..., 2.0}

Thank you for your help

A: I'd start by finding the final non-zero index:
int i = samples.Length - 1;
for( ; i >= 0; i--)
    if(samples[i] != 0.0F) break;

then I'd either copy that subset (0-i inclusive), or to avoid allocations I'd use a Span<T> to limit myself to that part without creating a new array:
var span = new Span<float>(samples, 0, i + 1);

A: float[] samples = { 0.0f, 4.0f, 2.5f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };

var clean = new List<float>();
for (int i = 0; i <samples.Length; i++)
{
    if (i == 0)
    {
        if (samples[i] == 0.0f) clean.Add(samples[i]);
        continue;
    }
    if (samples[i] != 0.0f) clean.Add(samples[i]);
}

//clean.ToArray() = float[]

This may be better solution
float[] samples = { 0.0f, 4.0f, 2.5f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };

List<float> clean = samples.ToList();
for(int i=clean.Count-1; i>0; i--)
{
    if (clean[i] == 0.0f) clean.RemoveAt(i);
    else break;
}

//clean.ToArray()

A: For now, I've tried this, it works for what I want but I'm not sure it is the simplest:
                float[] samples = new float[AudioFeedbackList[i].GetComponent<AudioSource>().clip.samples * AudioFeedbackList[i].GetComponent<AudioSource>().clip.channels];

            List<float> sampi = new List<float>();
            sampi.AddRange(samples);
            int j = sampi.Count;

            while (sampi[j - 1] == 0.0f)
            {
                j--;
            }

            List<float> newSampi = new List<float>();
            for (int k = 0; k < j; k++)
            {
                newSampi.Add(sampi[k]);
            }

            samples = newSampi.ToArray();

Thank you for the feedback!


text:
Q: libssh2 C compilation Its my first time working on a project in C. im just trying to make a SSH client.
my code copied from libssh2 site
http://www.libssh2.org/examples/ssh2.html
But when i run this i get the following errors ?
main.o: In function `main':
main.c:(.text+0xbe): undefined reference to `libssh2_init'
main.c:(.text+0x1a7): undefined reference to `libssh2_session_init_ex'
main.c:(.text+0x1bf): undefined reference to `libssh2_session_startup'
main.c:(.text+0x209): undefined reference to `libssh2_hostkey_hash'
main.c:(.text+0x282): undefined reference to `libssh2_userauth_list'
main.c:(.text+0x3e3): undefined reference to `libssh2_userauth_password_ex'
main.c:(.text+0x443): undefined reference to `libssh2_userauth_keyboard_interactive_ex'
main.c:(.text+0x4b9): undefined reference to `libssh2_userauth_publickey_fromfile_ex'
main.c:(.text+0x529): undefined reference to `libssh2_channel_open_ex'
main.c:(.text+0x58d): undefined reference to `libssh2_channel_setenv_ex'
main.c:(.text+0x5d9): undefined reference to `libssh2_channel_request_pty_ex'
main.c:(.text+0x633): undefined reference to `libssh2_channel_process_startup'
main.c:(.text+0x674): undefined reference to `libssh2_channel_free'
main.c:(.text+0x6a0): undefined reference to `libssh2_session_disconnect_ex'
main.c:(.text+0x6ac): undefined reference to `libssh2_session_free'
main.c:(.text+0x6c9): undefined reference to `libssh2_exit'
collect2: ld returned 1 exit status

I know there is some issue with library linking. Im using Netbeans as my IDE and am relatively new to this. Can anyone please guide me. I have searched a lot on the Internet, But mostly replies are related to code compiled on the command using gcc. If someone can help in Netbeans.

A: Got it , in Netbeans goto File -> Project Properties -> Linker -> Additional Commands i wrote -lssh2

A: To compile that code you need to install libssh2 in your system. Those undefined references come from the functions included in the header files (and used in the code) that need to be linked to the library where they are implemented.
#include <libssh2.h>
#include <libssh2_sftp.h>

After installing libssh2 you must add the flag -lssh2 to the compiler. I don't know about Netbeans so I can't help you with that. Browse through the project options and look for something about the compiler parameters/flags.


text:
Q: clearing objects from localstorage with localstorage i have a load of unspecified items saved with dynamic names using a data namespace like so:
localStorage["myAppName.settings.whatever"] = something.whatever;

//and this:
localStorage["myAppName.data."+dynObj.name] = dynObj.data;

I want to keep the settings but not the data. However I won't ever know what all of the names inside of my data object are so I cannot clear them individually. I need to clear these each time my app is loaded but I must keep the settings so
localstorage.clear() is not an option.
I have tried:
localstorage.removeItem("myAppName.data")

but no dice.
Anyone have any thoughts on how to clear dynamically named portions of localstorage?

A: You can loop through the keys in the localStorage and target them with a reg exp:
Object.keys(localStorage)
      .forEach(function(key){
           if (/^(myAppName.data.)/.test(key)) {
               localStorage.removeItem(key);
           }
       });

Here's a similar question: HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word

A: try something like
var i = localStorage.length, key;
while (i--) {
  key = localStorage.key(i);
  if (key.slice(0, 19) !== "myAppName.settings.") {
    localStorage.remove(key);
  }
}

A: Tried something like this?
// Select current settings
var settings = localStorage["myAppName.settings"] || {};
// Clear localStorage
localStorage.clear();
// Add settings to localStorage
localStorage["myAppName.settings"] = settings;

A: Assuming a this.namespace present (in my case 'session') and the underscore library:
_.each(_.keys(localStorage), function(key) {
  if (RegExp("^" + this.namespace + "\\.").test(key)) {
    return localStorage.removeItem(key);
  }
});

And with CoffeeScript:
_.each _.keys(localStorage), (key) ->
  if ///^#{@namespace}\.///.test(key)
    localStorage.removeItem(key)


text:
Q: Transferring data from MS Access to SQL Server I have MS Access tables that are indexed but accept duplicates. Tables have been transferred to SQL Server and linked to Access.
How do you replicate primary keys that accept duplicates?

A: You should consider using SSMA
Sql Server Migration Assistant for Access
It can move up tables.
It will move up related data, setup PK columns for you.
It will maintain, and create relationships for you.
It will maintain and create all indexes you have now.

If you just have a few tables, say 2-5 tables? Then sure, just import them and setup the relatonships and indexs your self.
However, the last few migrations of data from Access to SQL server? There was in excess of 80 tables - and HUGE numbers of reatonships, indexes, and of course PK settings. The migration wizard thus can send up all of the tables - and setup all of the tables correctly on SQL server for you. Including PK values, FK values (Foreign Keys (related tables)),
and even constraints are in most cases correctly move up to sql server.
what is nice, is then you can re-link the tables in your Access application, and you now using SQL server for the back end database.
SSMAA can be found here:
https://www.microsoft.com/en-us/download/details.aspx?id=54255

A: I think you're confusing an "index" with a "primary key".
An "index" is a structure that helps optimise queries. Indexes don't have to be unique. A "primary key" is a logical constraint on a column which requires that all values in the column are unique.
It sounds like what you want to do is import the data into SQL and create an index to help speed up queries, but where that index is not constrained to be unique.
Here's the syntax to do that. Suppose we have some table T:
create table T(i int, j int, k int);

We want to create an index on column i to speed up queries, but i is not unique. To do that we create a regular (non unique) index:
create index MyIndexName on T(i);

As a rule, I tend to name my indexes based on what they are indexing. So in the above case I wouldn't call the index "MyIndexName", I would call it something like ix_T_i.


text:
Q: epsilon delta for limits of complex variables Show that  $$\lim_{z->2i} 2x+iy^2=4i$$
Prove this using epsilon-delta proof.
I've tried like this  but got stuck in middle: $f(z)=2x+iy^2$
$$|f(z)-4i|=|2x+iy^2-4i| \le |2x|+|y^2-4|
                      =2|x|+|y-2||y+2|$$
How to choose delta?


text:
Q: AngularJS Ng-route - Switching to a particular page view when typing an input:text from another url Sorry for the long title. This question is based in the answer provided here
I have a page with two views
app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {

$routeProvider
.when('/content1', {
  templateUrl: 'content1.html',
  controller: 'myCtrl'
})

.when('/content2', {
templateUrl: 'content2.html',
controller: 'myCtrl'
})

.otherwise({
redirectTo: '/content1'
});

}]);

When typing into an input:text it switches to the second view using a ng-change directive that triggers the function searchProduct() and starts searching with an ng-model directive right away.
<div ng-controller="myCtrl" ng-app="myApp">
<input type="text"
       ng-change="searchProduct()"
       ng-model="searchFilter"
       ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }">
<ng-view></ng-view>
</div>

Being the searchProduct() function
$scope.searchProduct = function() {
    $location.path('content2');
    $location.search({
      searchFilter: $scope.searchFilter
    });
};

All this is working properly. But the problem is that I would like to implement the same feature in another page with a different url (this is for SEO purposes), so that when searching in that page it would redirect to content2.html, and it would also preserve what has been typed in the search box.
I've tried to do it by setting an absolute path, but it doesn't seem to work. You can see a working plunker with the code here. Thanks in advance!

A: I would suggest you to use $stateprovider for routing. It is better than route provider. You can read out it's plus points on net over $routeProvider. Route is more of obsolete now. On state provider you just need to redirect to state And your problem will also be resolved. $state.go('content2') or $state.go('home')
 you can have nested states as well.
https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stateprovider-1


text:
Q: How to cast the output of a for loop into a single list of strings in Python? Using BeautifulSoup I have collected the data from a web page weather table. I managed to scrape the text from a specific column by looping trough all 14 rows and indexing by [0].
However by iterating trough the table rows it puts the text in descending order line by line, like:
Maandag 13 mei
Dinsdag 14 mei
Woensdag 15 mei
Donderdag 16 mei
Vrijdag 17 mei
Zaterdag 18 mei
Zondag 19 mei
Maandag 20 mei
Dinsdag 21 mei
Woensdag 22 mei
Donderdag 23 mei
Vrijdag 24 mei
Zaterdag 25 mei
Zondag 26 mei
Maandag 27 mei

print(list(days) doesn't work it just transforms every item into a separate list and still in descending order.
TableRows = table.find_all('tr')

CleanTableRows = TableRows[2:]

for tr in (CleanTableRows):
    td = tr.find_all('td')
    rows = [item.text for item in td]

    days = rows[0]

    print(days)

I want to cast it into a list of strings like:
['Maandag 13 mei', 'Dinsdag 14 mei', 'Woensdag 15 mei', 'Donderdag 16 mei', 'Vrijdag 17 mei', 'Zaterdag 18 mei', 'Zondag 19 mei', 'Maandag 20 mei', 'dinsdag 21 mei', 'Woensdag 22 mei', 'Donderdag 23 mei', 'Vrijdag 24 mei', 'Zaterdag 25 mei', 'Zondag 26 mei', 'Maandag 27 mei']

How can this be accomplished?

A: This should work
data = []
for tr in (CleanTableRows):
    td = tr.find_all('td')
    rows = [item.text for item in td]

    days = rows[0]
    data.append(days)
    print(days)

print(data) # This is a list which contains all your days data


text:
Q: Falha quando acessa uma opção de vetor que não existe Fiz a alguns anos atrás um algoritmo de herança e polimorfismo ele esta funcionando corretamente mas se eu digitar 7 que é uma opção inexistente no menu ele retorna falha de segmentação em vez de me retornar nada imprimindo a frase, qual é o problema?
O menu é este abaixo:

 O ecossistema tem 0 mamífero(s).

    Quer inserir um novo mamífero no ecossistema?
    Digite [s]-Sim ou [n]-Não: s

    Diga qual animal vai se reproduzir:
    0: cachorro
    1: gato
    2: homem
    3: cavalo
    4: cabra
    5: leao
    6: boi
    --> 0

    O ecossistema tem 1 mamífero(s).
    Um cachorro, que emite latido.

#include <vector>
#include <iostream>

class mamifero
{
  public: //Class is private by default then it is necessary to use public so that other classes or structs have access to the members
    mamifero(){}
    ~mamifero(){}
    virtual mamifero *reproduz() = 0; // Pure virtual constructor (and abstract, to enforce reimplementation in each derived class).
    virtual std::string nome() = 0;
    virtual std::string som() = 0;
};

//Class is private by default so it is necessary to use public
class cachorro: public mamifero
{
  public:
    cachorro(){}
    ~cachorro(){}
    cachorro *reproduz(){ return new cachorro; }
    std::string nome(){ return "cachorro"; }
    std::string som() { return "latido"; }
};

class gato: public mamifero
{
  public:
    gato(){}
    ~gato(){}
    gato *reproduz() { return new gato; }
    std::string nome(){ return "gato"; }
    std::string som() { return "miado"; }
};

class homem: public mamifero
{
  public:
    homem(){}
    ~homem(){}
    homem *reproduz() { return new homem; }
    std::string nome(){ return "homem"; }
    std::string som() { return "fala"; }
};

class cavalo: public mamifero
{
  public:
    cavalo(){}
    ~cavalo(){}
    cavalo *reproduz() { return new cavalo; }
    std::string nome(){ return "cavalo"; }
    std::string som() { return "relincho"; }
};

class cabra: public mamifero
{
  public:
    cabra(){}
    ~cabra(){}
    cabra *reproduz() { return new cabra; }
    std::string nome(){ return "cabra"; }
    std::string som() { return "berro"; }
};

class leao: public mamifero
{
  public:
    leao(){}
    ~leao(){}
    leao *reproduz() { return new leao; }
    std::string nome(){ return "leao"; }
    std::string som() { return "rugido"; }
};

class boi: public mamifero
{
  public:
    boi(){}
    ~boi(){}
    boi *reproduz() { return new boi; }
    std::string nome(){ return "boi"; }
    std::string som() { return "sturro"; }
};

std::vector<mamifero *> opcoes
{
  new cachorro,
  new gato,
  new homem,
  new cavalo,
  new cabra,
  new leao,
  new boi
};

std::vector<mamifero *> ecossistema;

mamifero *menu(void)
{
  int n=0;
  std::cout << "\n\tDiga qual animal vai se reproduzir: ";
  for(const auto &animal: opcoes)
  std::cout << "\n\t" << n++ << ": " << animal->nome() << "";
  std::cout << "\n\t--> ";
  std::cin >> n;
  std::cin.ignore(1, '\n');
    if (n >= 0 && n < opcoes.size())return opcoes[n]->reproduz();
else
{
std::cout<<"\n\tEcosistema não encontrado.\n\tDeseja continuar? (s)im ou n(ão): ";
std::cin>>op;
if(op == 's' || op == 'S')
return menu();

else
std::cout << "\n\tGoodbye!\n\n";
}
}

mamifero *getDetails(void)
{
  std::string resposta;

  do
  {
   std::cout << "\n\tO ecossistema tem " << ecossistema.size() << " mamífero(s).\n";
   if(ecossistema.size() > 0)
   for(const auto &animal: ecossistema)
   std::cout << "\tUm " << animal->nome() << ", que emite " << animal->som() << ".\n";
   std::cout << "\n\tQuer inserir um novo mamífero no ecossistema?\n\tDigite [s]-Sim ou [n]-Não: ";
   getline(std::cin, resposta);
   std::cout << std::endl;

   if(resposta == "s" || resposta == "S")
   ecossistema.push_back(menu());
   else
   if(resposta == "n" || resposta == "N")break;
   else
   if(resposta != "s" || resposta != "S")
   std::cout<<"\n\tOpção Inválida\n";

  }while(resposta != "n" || resposta != "N");

  if(ecossistema.size() > opcoes.size()) std::cout<<"\n\tEcosistema nao encontrado.\n";
  else
  if(ecossistema.size() > 0)
   {
    std::cout << "\n\tAo final, o ecossistema tinha " << ecossistema.size() << " mamífero(s).\n";
    for(const auto &animal: ecossistema)
    std::cout << "\tUm " << animal->nome() << ", que emite " << animal->som() << ".\n";
    std::cout << "\n\tGoodbye!\n\n";
   }
  else
  std::cout << "\n\tAo final, o ecossistema tem " << ecossistema.size() << " mamífero.\n\n";
  return 0;
}

int main()
{
  getDetails();
}

A: Obviamente que se só tem opções de 0 a 6 declaradas não é possível usar a 7, portanto verifique se n está na faixa válida antes de usá-la, algo assim:
if (n >= 0 && n < opcoes.size()) return opcoes[n]->reproduz();
return 0;

Coloquei no GitHub para referência futura.
Suspeito que tenha vários outros erros no código, ainda que funcione.


text:
Q: How can I create a .app file to open DMG files with, to run AppleScript with that file as input? What I ultimately want to do is have a .app that I can open DMG files with. When the DMG file is opened the app, it opens the DMG in a new Finder tab and then shows the Toolbar in Finder after half a second. AppleScript for the later would look like this:
delay 0.5
tell application "Finder"
      tell the front window to set toolbar visible to true
end tell

I tried looking up how to open a DMG file in a new Finder Tab with AppleScript but didn't find a solution. If I end up not finding one, then I'll see if I can do so with a Terminal command and then do it in AS with do shell script.  For the file input, I tested this code based off what I found here but it doesn't work, it just creates a copy of the DMG:
on run {input, parameters}
    if input is {} then
        set inputFile1 to ¬
            quoted form of POSIX path of ¬
            (choose file with prompt "Please select a file to process:")
    else
        set inputFile1 to quoted form of ¬
            (POSIX path of first item of input)
    end if
    display dialog inputFile1

end run

I did a bunch of googling as well for how to do so but I found nothing. What I can do to end up with an AppleScript that does everything I described?

A: I would open the dmg with hdiutil which seems to open the image into a standard window:
set runDMG to quoted form of POSIX path of (choose file)
do shell script "/usr/bin/hdiutil attach " & runDMG

Basically, you get the posix path of your dmg file and feed it to hdiutil attach. The disk image will open and —for me at least— consistently opens in a default finder window (i.e. same size as other windows, list view, sidebar visible, toolbar visible).
I should add that typically when I double-click on a dmg, it opens in a 'drag to applications folder' window which is icon view and shows only the app and the applications folder.
Separately, this code seems to work with bringing the disk image's folder to the front window.
tell application "Finder"

    parent of startup disk
    --> computer container of application "Finder"

    open computer container
    set target of window 1 to (last item of window 1 as alias)
    --> disk "Key Codes" of application "Finder"

end tell

There are (at least on my Sierra mac), three items in the 'computer' folder: 'Network', 'Remote Disc', the startup volume. When you open a dmg, the virtual appears here as a 'removable'. I've found that when you get a list of folders in the computer container, the removable is the last item in the list. I don't know if that ever changes, and I haven't played around with multiple disk images simultaneously but it provides a starting point for specifying the desired window if for some reason, it doesn't open automatically.


text:
Q: Missing Push Notification Entitlement, even with aps-environment entitlement set. iOS and Testflight Good morning!
I am working on getting my app to receive push notifications from Firebase cloud messaging. when I add my build to testflight, I get a warning email with the error code: ITMS-90078: Missing Push Notification Entitlement, I am allowing xcode to manage my profile, which has the aps-environment entitlement and the capability for push notifications, and a development signing certificate, as you can see in this screenshot from xcode:

Luckily, this is just a warning, so I can still push this build to my testflight testers, but they do not receive push notifications. I can confirm that firebase cloud messaging is generating the device messaging token, and it is storing in my firebase database just fine, so I assume this is not the issue.
I have also confirmed that I have a Production Apple Push notification SSL cert assigned to this bundle ID, as shown here:

After I took this screenshot, I also tried adding a development SSL cert, but the problem persists.
I have found a number of other posts on apple dev forums and here on Stack exchange, but most are fron over 4 years ago and no longer appear relevant. Example: Missing Push Notification Entitlement warning
What am I missing? Thank you for your time and help in advance!
UPDATE
I have now also attempted the to fix this by using a provisioning profile I set up, rather than allowing xcode to manage it for me. It is an "App Store Distribution" Profile.

Same issue, getting the same email error, and any installed applications do not receive push notifications. Any suggestions? Thanks!

A: After a multi - hour debug session with a friend of mine that is better versed in Apple processes than I am, we managed to figure out the issue. Everything was set up correctly... all my certs were in line, all of the profiles and Bundle IDs matched, everything looked good. The issue was for some reason, xcode was displaying all of my certs from appstoreconnect and developer.apple.com, but it was not including a local entitlements file with the binary that ultimately got uploaded to app store connect, which drew the error, and ultimately prevented push notifications from working. The fix was simple... just click "+ capability" next to "all" in signing and capabilities, search for and add push notifications, and bingo! This adds the proper entitlements to my binary, which then look for the certs in app store connect. This now uploads without the error message and push notifications on any installs from this new build starting working immediately. I hope this helps someone, someday! Apple, please make this more straightforward, or don't let xcode lie about its certs!


text:
Q: How to getTileProperty while using multi-layer map? I'm new to Slick2D, and I'm using Tiled to make .tmx map.
for (int xAxis = 0; xAxis < map.getWidth(); xAxis++) {
    for (int yAxis = 0; yAxis < map.getHeight(); yAxis++) {
        int tileID = map.getTileId(xAxis, yAxis, 0);
        String value = map.getTileProperty(tileID, "blocked", "0");
        int valueInInt = Integer.parseInt(value);
        if (valueInInt == 1) {
            blocked[xAxis][yAxis] = true;
        }
    }
}

This works fine when the blocks are on the same layer with others, however, if I put the blocks on a different Tile layer, I can't get the right TileProperty anymore.
Why did it happen? What can I do with that or any ideals?
Thanks a lot.

A: The third parameter to TiledMap.getTileId() is the layerIndex. You would have to use that to select the layer where you're searching for tiles with the "blocked" property set to "1".


text:
Q: CQWP Renders only in Edit Mode I have customized CQWP (Content Query Web Part) to display items from my sub sites.  The items are filtered based on my custom content type.
I have cusomized the rendering of additional fields in CQWP using ItemStyle.xsl.
I am having a strange issue that my web part is able to render data when the page is in Edit mode,  however when i exit the edit mode, the web part is not showing any data.
Any Help, Pointers,
Sudhir Kesharwani

A: I have figured out the issue,  the CQWP has a property called "UseCache".  By default this property is set to "True",  this conflicts with the web part rendering.
To resolve this,  I exported my web part onto my local machine and updated the "UseCache" property to "False"
<property name="UseCache" type="bool">False</property>

This worked like charm. My sincere thatnks to Michael Nemtsev
Regards,
Sudhir Kesharwani


text:
Q: How would I find the limit for this equaiton? How would you find the limit of this function:

The n value is always even (this is for a problem and it would not make sense for n to be an odd number)
Also, how could I plot this with n as the x value? I've tried to do it with an excel spreadsheet, but I just can't find the way to do it. I've done the first 10 even values for n (2,4,6,8,10,12,14,16,18,20) and the graph looks like it is approaching 0.3, but is there a way to know for sure?


text:
Q: Displaying images is Matlab I want To write a Matlab function that can display one single image, multiple images (i.e. cell arrays, vector, matrices) of images so that I don't need to worry about writing 'plots', 'subplots', and other complicated Matlab mechanisms each time I run my program with new inputs. That is also one of my requirements in my project.
The following source code has several problems:

*

*it can't show only one image

*occasionally it doesn't preserve the original aspect ratio of images

*resizing the window to a smaller size drastically reduces the size of the images on display

How can I fix these issues?

Source Code
function draw_images(image_list)
    d = size(image_list);
    l = length(d);

    figure;
    hold all
    colormap(gray(256));

    % vector or cell-array
    if(l==2)
        N = length(image_list);
        [m, n] = factor_out(N);

        % images may be of differenet dimensions
        if(iscell(image_list))
            for k=1:N
                h = subplot(m,n,k);
                image(image_list{k},'Parent',h);
                set(gca,'xtick',[],'ytick',[])
            end
        % must be of same dimension
        elseif(isvector(image_list))
            for k=1:N
                h = subplot(m,n,k);
                image(image_list(k),'Parent',h);
                set(gca,'xtick',[],'ytick',[])
            end
        end
    % 3D matrix of images (!!!)
    elseif(l==3)
        N = d(3) ;
        [m, n] = factor_out(N);
        for k=1:N
            I = image_list(:,:,k);
            subplot(m,n,k);
            imshow(I);
            set(gca,'xtick',[],'ytick',[])
        end
    end
    hold off

function [m, n] = factor_out(input_number)
    sqrtt = ceil(sqrt(input_number));
    m = sqrtt;
    n = sqrtt;

A: I think there is no a built-in solution similar to pyplot.tight-layout() in python. However, there exist several solutions written by several authors. I would prefer the function called subtightplot
There is also a discussion regarding this question at Stackoverflow called How to reduce the borders around subplots in matlab?


text:
Q: Errors when Upgrading to IdentityServer 4.0.2 Before upgrading, I am successfully able to log in using Azure AD and the local database users (Alice and Bob).
When I upgrade the IdentityServer4 nuget package from 3.1.3 to 4.0.2 and then upgrade the UI components using either the power shell command or "dotnet new is4ui", I am able to compile my application.
When I run it, I get the error "Scope  not found in store.". I then add it to the AddInMemoryApiScopes in the Startup method.
When I then run the application, I get "Invalid username or password" when logging in as Alice or Bob. The demo IdentityServer no longer permits login for Alice or Bob and gives the same error. When I click the External Account "Azure AD" button, it now throws an "System.Exception: External authentication error".
Are there upgrade notes posted that I am missing when upgrading to the latest version?


text:
Q: Does AWS Beanstalk hosting charge for every EC2 instance it creates? I am new to AWS ElasticBeanstalk. As i have started working on AWS ElasticBeanstalk i have some confusion which are as follows.
1.Does Amazon charge for every EC2 instance which is created to run ElasticBeanstalk app under free tier.
2.Is it possible to host multiple app under samne EC2 instance which is created for Elasticbeanstalk i.e ASp.net ,Web Api and angular 4 app under same elasticbeanstalk.
Please help me to clear my issues.
Thanks

A: *

*If the EC2 instances used for Elastic Beanstalk fall under the free tier (i.e. within the first 12 months of account ownership, they're small enough instances, use less than 750 hours/month, etc.), then they'll be free. It doesn't matter if the instances are used for an Elastic Beanstalk application or something else.

*Yes, it is possible to host multiple Elastic Beanstalk applications on the same EC2 instance. See this related StackOverflow question.


text:
Q: How can I pull data out of an Option for independent use? Is there a way to 'pull' data out of an Option? I have an API call that returns Some(HashMap). I want to use the HashMap as if it weren't inside Some and play with the data.
Based on what I've read, it looks like Some(...) is only good for match comparisons and some built-in functions.
Simple API call pulled from crate docs:
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::blocking::get("https://httpbin.org/ip")?
        .json::<HashMap<String, String>>()?;
    println!("{:#?}", resp.get("origin"));
    Ok(())
}

Result:
Some("75.69.138.107")

A: The most common way is with if let:
if let Some(origin) = resp.get("origin") {
    origin.do_stuff()
}

For more fine grained control, you can use pattern matching:
match resp.get("origin") {
    Some(origin) => origin.do_stuff(),
    None => panic!("origin not found!")
}

You could also use unwrap, which will give you the underlying value of the option, or panic if it is None:
let origin = resp.get("origin").unwrap();

You can customize the panic message with expect:
let origin = resp.get("origin").expect("Oops!");

Or compute a default value with unwrap_or:
let origin = resp.get("origin").unwrap_or(&String::from("192.168.0.1"));

You can also return an error instead of panicking:
let origin = resp.get("origin").ok_or(Error::UnknownOrigin)?;

A: Your options are a plenty.
if let Some(origin) = resp.get("origin") {
    // do stuff using origin
}

origin = resp.get("origin").unwrap()
// will panic if None

resp.get("origin").map(|origin| {
    // do stuff using inner value, returning another option
})

resp.get("origin").and_then(|origin| {
    // same as map but short-circuits if there is no inner value
})

A: if let Some(origin) = resp.get("origin") {
    // use origin
}

If you can guarantee that it's impossible for the value to be None, then you can use:
let origin = resp.get("origin").unwrap();

Or:
let origin = resp.get("origin").expect("This shouldn't be possible!");

And, since your function returns a Result:
let origin = resp.get("origin").ok_or("This shouldn't be possible!")?;

Or with a custom error type:
let origin = resp.get("origin").ok_or(MyError::DoesntExist)?;


text:
Q: Can not solve known memory leak when using bitmaps **

DUPLICATE SOLVED THE ISSUE

**
I crawled google quite a while now and I found some answers to this but I can not make it work.
I read that there is a memory leak in .NET when loading/replacing bitmaps. The framework is not autom. releasing the memory from the older bitmaps. The GC can not collect the old bitmap due to an "internal?" reference that is not autom. removed by the framework.
Everything works fine, so you really don't have to read all the code.
I just don't understand where to release that annoying pice of memory.
Any help is very welcome. Thank you in advance.
What I do:
imageTif.Source = _imageManager.getBitmapSource();

public BitmapSource getBitmapSource(){
   //Create Bitmap from Tif
   //Create **NEW** BitmapSource using HBitmap
   //returning BitmapSource
}

This is how I create the Bitmap:
    private Bitmap tiffToBitmap()
    {
        FieldValue[] imageHeight = _tif.GetField(TiffTag.IMAGELENGTH);
        int height = imageHeight[0].ToInt();

        FieldValue[] imageWidth = _tif.GetField(TiffTag.IMAGEWIDTH);
        int width = imageWidth[0].ToInt();

        FieldValue[] bitsPerSample = _tif.GetField(TiffTag.BITSPERSAMPLE);
        short bpp = bitsPerSample[0].ToShort();
        if (bpp != 1)
            return null;

        FieldValue[] samplesPerPixel = _tif.GetField(TiffTag.SAMPLESPERPIXEL);
        short spp = samplesPerPixel[0].ToShort();
        if (spp != 1)
            return null;

        FieldValue[] photoMetric = _tif.GetField(TiffTag.PHOTOMETRIC);
        Photometric photo = (Photometric)photoMetric[0].ToInt();
        if (photo != Photometric.MINISBLACK && photo != Photometric.MINISWHITE)
            return null;

        int stride = _tif.ScanlineSize();
        Bitmap result = new Bitmap(width, height, PixelFormat.Format1bppIndexed);

        // update bitmap palette according to Photometric value
        bool minIsWhite = (photo == Photometric.MINISWHITE);
        ColorPalette palette = result.Palette;
        palette.Entries[0] = (minIsWhite ? Color.White : Color.Black);
        palette.Entries[1] = (minIsWhite ? Color.Black : Color.White);
        result.Palette = palette;

        for (int i = 0; i < height; i++)
        {
            Rectangle imgRect = new Rectangle(0, i, width, 1);
            BitmapData imgData = result.LockBits(imgRect, ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);

            byte[] buffer = new byte[stride];
            _tif.ReadScanline(buffer, i);

            Marshal.Copy(buffer, 0, imgData.Scan0, buffer.Length);
            result.UnlockBits(imgData);
        }

        return result;
    }

This is how I create the BitmapSource using HBitmap:
private BitmapSource getBitmapSourceFromBitmap(Bitmap bitmap){
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bitmap.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }


text:
Q: Compilation error when including eigen library I'm currently using eigen library, and this is the only file that I include eigen:
Kraftwerk2.cpp:
#include "Kraftwerk2.h"

Kraftwerk2::Kraftwerk2(int n){ //n: num instances
    Connectivity_mat.resize(n,n);
}

int Kraftwerk2::Parse_Inst_Name(string s){ //input: String("M12"), output: int 12
    return stoi(s.substr(1));
}

void Kraftwerk2::Generate_Connectivity_matrix(unordered_map<string, net> map){
    for(auto& it : map){
        int n =it.second.net_pin.size();
        for(int i=0; i<n; i++){
            for(int j=i+1; j<n; j++){
                Connectivity_mat(i,j) = Connectivity_mat(i,j) +1;
            }
        }
    }
}

void Kraftwerk2::Print_Mat(){
    IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");
    cout << Connectivity_mat.format(CleanFmt);
}

Kraftwerk2.h:
#include <iostream>
#include <Eigen/Core>
#include "module.h"
using namespace std;
//    unordered_map<string, instance> instances;
//    unordered_map<string, net> nets;
using namespace Eigen;

class Kraftwerk2{
    public:
        Kraftwerk2(int);
        MatrixXd Connectivity_mat;
        int Parse_Inst_Name(string);
        void Generate_Connectivity_matrix(unordered_map<string, net>);
        void Print_Mat();
};

And I use makefile for compiling:
(I'm pretty new to makefile, so if there's something I can improve, please tell me)
(Eigen is installed in the working directory ./eigen)
# CC and CFLAGS are varilables
CC = g++
CFLAGS = -c
OPTFLAGS = -O2

DBGFLAGS = -g -D_DEBUG_ON_
# make all
all : bin/partition
    @echo -n "make complete!"

# optimized version
bin/partition: main_opt.o FM.o partition.o module.o Kraftwerk2.o
    $(CC) $(OPTFLAGS) main_opt.o FM.o partition.o module.o Kraftwerk2.o -o bin/partition
main_opt.o: src/main.cpp  src/FM_alg.h src/partition.h src/module.h src/Kraftwerk2.h
    $(CC) -I ./eigen $< -o $@

FM.o: src/FM_alg.cpp src/FM_alg.h
    $(CC) $(CFLAGS) $(OPTFLAGS) $< -o $@
partition.o: src/partition.cpp src/partition.h
    $(CC) $(CFLAGS) $(OPTFLAGS) $< -o $@
Kraftwerk2.o: src/Kraftwerk2.cpp src/Kraftwerk2.h
    $(CC) ./eigen $(CFLAGS) $(OPTFLAGS) $< -o $@
module.o: src/module.cpp src/module.h
    $(CC) $(CFLAGS) $(OPTFLAGS) $< -o $@

# clean all the .o and executable files
clean:
        rm -rf *.o lib/*.a lib/*.o bin/*

However, when I make, the terminal seems to output some error that comes form the library itself(???
g++  -I ./eigen src/main.cpp -o main_opt.o
In file included from ./eigen/Eigen/Core:269,
                 from src/Kraftwerk2.h:2,
                 from src/main.cpp:4:
./eigen/Eigen/src/Core/util/IndexedViewHelper.h:69:23: error: declaration of 'template<class first> constexpr Eigen::Index Eigen::internal::first(const first&)' shadows template parameter
   69 | EIGEN_CONSTEXPR Index first(const T& x) EIGEN_NOEXCEPT { return x.first(); }
      |                       ^~~~~
./eigen/Eigen/src/Core/util/IndexedViewHelper.h:68:10: note: template parameter 'first' declared here
   68 | template<typename T>
      |          ^~~~~~~~
make: *** [makefile:15: main_opt.o] Error 1

I would be so appreciated if anybody can tell me what's wrong with this.


text:
Q: useState does not re-render const [searchText, setSearchText] = useState('')

  const searchHandler = async (searchTextInput) => {
    console.log('search is:::', searchTextInput)
    setSearchText(() => searchTextInput)
  }

  const searchOnSubmitHandler = async () => {
    await loadShopsCount()
    await loadShops()
  }

  const searchClearHandler = async () => {
    setSearchText(() => "")
    console.log('onClear-----------search is:::', searchText)
    await loadShopsCount()
  }

On calling searchClearHandler after searching for something, searchText returns the previous state value instead of empty string. Hence, my component is not able to re-render.
How can I set searchText to empty string and re-render the component on calling searchClearHandler?

A: Use useEffect.
useEffect(() => {
    Here your function which you want to call.
  }, [searchText]);


text:
Q: An idiomatic word meaning "very good" in this context The country's ranking in global output has been _____ for quite some time now.
What is an idiomatic adjective, or adjectival phrase, meaning "very positive" or "very good" or "very high", to put in the above sentence. Or are each of these three options idiomatic when we talk of ranking?
Thesaurus give a lot of options, among which "outstanding" sounds not a bad option to me, but I still don't know which one is idiomatic when we are talking about rankings.
I am not looking for words that add other meanings. For example, "promising" seems to me to add a sense about future and consequences, and that is why it is not what I am looking for.

A: phenomenal serves the purpose.
Here are three links which show synonyms for phenomenal.You can use any of them for your  sentence.
https://thesaurus.yourdictionary.com/wondrous
https://thesaurus.yourdictionary.com/remarkable
https://thesaurus.yourdictionary.com/phenomenal

A: I would suggest "on the rise" if you prefer an idiom.
There are virtually an indefinite number of expressions that can satisfy the requirement-astonishing, phenomenal, spectacular, impressive, remarkable and so on and so forth.


text: Q: Android minSdkVersion confusion I have an App which has minSdkVersion defined to 19. I am still able to install an exported APK to a device which has Android 4.0 or 4.1. Is this behavior correct and the minSdkVersion will only be used by the play store to filter out irrelevant devices?


text:
Q: getting Clean Sources Plus written by Jeff Atwood, this program cleans the project folders from bin, obj and Resharper files ... BUT its downlaod link is broken , does anybody know where can I get it from ?
http://www.codinghorror.com/blog/2005/08/clean-sources-plus.html

A: Update: This comment was left by Christian Junk

https://github.com/coding-horror/CleanSourcesPlus

Which seems to be exactly what you're looking for.

Old answer:
I can't find Clean Source Plus, but I did find Tree Trim, which seems to do the same thing

A: You can download from this link

A: TreeTrim is very cool but it will report an exception when i try to clean svn work copy. the exception message just like " no privilege to delete all-wcprops...".
i got the source code and fixed the issue, so if someone like TreeTrim, you can download the setup file on http://db.tt/hFdwQWId
Hi, Everyone,  i just found a good alternative---CleanPoject from http://wf.codeplex.com/wikipage?title=Thank%20you%20for%20installing%20CleanProject, Maybe we can replace CleanSourcePlus with CleanProject.


text:
Q: Keycloak token not active with angularjs I have spring boot backend app with Angular js app. The login process and initial backend communication are successful. After some idle time, the front end will show 403 forbidden with token not active on the backend console.
The code below contains refresh token, But it seems not working.
// use bearer token when calling backend
themesApp.config(['$httpProvider', function($httpProvider) {
  var isExpired = keycloak.isTokenExpired();
  var token = keycloak.token;

  if (isExpired) {
    keycloak.updateToken(5)
    .success(function() {
      $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
    })
    .error(function() {
      console.error('Failed to refresh token');
    });
  }

  $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
}]);

Error on the backend
2017-05-29 10:08:23.715 ERROR 5072 --- [nio-8080-exec-3] o.k.a.BearerTokenRequestAuthenticator    : Failed to verify token

org.keycloak.common.VerificationException: Token is not active

A: Something must be wrong on the Keycloak Server, Token not active means token being is expired or is used before it gets valid. Could it be that the time/date is wrong on your KC server ?

A: you can config the 'Session Idle Time' here:

I had the same issue and handle it with an automatical logout. So the user has to login again.

A: In your code:
var token = keycloak.token;

you define the value of token once. After the update you have to set it again:
// use bearer token when calling backend
themesApp.config(['$httpProvider', function($httpProvider) {
  var isExpired = keycloak.isTokenExpired();
  var token = keycloak.token;

  if (isExpired) {
    keycloak.updateToken(5)
    .success(function() {

     // UPDATE THE TOKEN
     token = keycloak.token;

     $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' +     token;
    })
.error(function() {
  console.error('Failed to refresh token');
});
}

 $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
}]);


text:
Q: Create a simple ListView Cascades I want to create a simple ListView in Cascades (either in C++ or QML).
The data of the ListView is simple, just strings that I want to pass to it (no XML or SQL etc.);
Also the ListView may have sections, e.g.,
 - Green
        - Cucumber
        - Peas
        - Salad
 - Red
        - Tomato
        - Red Radish
        - Carrot

Also, I want to be able to customize the appearance of items of the list view and possibly the ListView itself (e.g., set background color, set list item text color etc.).
Any tutorial or simple sample app which achieves what I wrote above would be greatly appreciated!!
Thank you.

A: The simplest way, if you're going to use just a static list (I mean, you don't want to change it in runtime) is to load it from a XML file (ex: a model.xml in your assets folder), like this:
<model>
    <header title="Green"/>
    <item title="Cucumber"/>
    <item title="Peas"/>
    <item title="Salad"/>
    <header title="Red"/>
    <item title="Tomato"/>
    <item title="Red Radish"/>
    <item title="Carrot"/>
</model>

Your ListView just needs to load it:
ListView {
    dataModel: XmlDataModel {
        source: "model.xml"
    }
}

Now, if you want to customize the appearence, you just have to put in the listItemComponents how you want them to be shown:
ListView {
    dataModel: XmlDataModel {
        source: "model.xml"
    }
    listItemComponents: [
        ListItemComponent {
            type: "header"
            Container {
                // your personal code
            }
        },
        ListItemComponent {
            type: "item"
            Container {
                // your personal code
            }
        }
    ]
}

These containers allow you to define your own layout. For example, supposing you want to just show the header with a matching background color, you could just do:
ListView {
    dataModel: XmlDataModel {
        source: "model.xml"
    }
    listItemComponents: [
        ListItemComponent {
            type: "header"
            Container {
                background: {
                    if (ListItemData.title == "Green") {
                        return Color.Green
                    } else {
                        return Color.Red
                    }
                }
                Header {
                    title: ListItemData.title
                }
            }
        },
        ListItemComponent {
            type: "item"
            Container {
                preferredHeight: 100
                Label {
                    text: ListItemData.title
                    verticalAlignment: VerticalAlignment.Center
                }
                Divider {}
            }
        }
    ]
}

Hope this gave you an idea of how this works.

A: if i understand correctly you want like ExpandableListView in android  you can achieve it using implementing bb::cascades::DataModel example is here


text:
Q: SQLDependency Caching not working I am trying to use SQLDependency Caching with Query Notifications in my ASP.NET application.
I followed these steps to set up SQLDependency Caching.I was able to set up the db successfully.
However,when I run my application I am getting the following error.
Cannot find the specified user 'owner'.
Cannot find the queue
SqlQueryNotificationService-6c3ae823-a678-4ed2-8b97-561b5f2561ee',
because it does not exist or you do not have permission.
Invalid object name
SqlQueryNotificationService-6c3ae823-a678-4ed2-8b97-561b5f2561ee'.

Code Global.asax
void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        System.Data.SqlClient.SqlDependency.Start(ConfigurationManager.ConnectionStrings["McdConn"].ToString());

    }

I tried to Google the solution but I could not get any help.
Can anyone help me with this?
Am I missing something?

A: Either you can give the User sysadmin rights
OR
provide alter permission to the dbo schema.
In order to create a procedure, a function, schema scoped objects etc.., you need at least ALTER permission on the target schema. Here is the TSQL syntax,
grant alter on schema :: schema_name to  user_name

The user should also have the permissions on the Notification Service , Queues.
To grant the permission to user 'John' on the Service and queue use:
GRANT SEND on service::SqlQueryNotificationService to John
GRAND RECEIVE on SqlQueryNotificationService_DefaultQueue to John

Also the user needs permission to subscribe to notification.( This is done already by you I guess) To do this use:
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO John

One last point so far i can guess to help is that in case you have setup SqlDependency on a command, then make sure you execute it.Query subscriptions on the server happen only on command execution.
SqlDataReader reader = command.ExecuteReader();

This post may prove more helpful.


text:
Q: Css3 Animation looping in webkit-animation I have a problem with css3 animation effect.I want to know how to continue looping without go to start place.
As a example. when clouds are moving, the webkit-animation time over, it come to first step and start animate again.So it not nice  because cloud go to back and again start moving (watch 7 seconds), i want to continue animation without cloud goes to start.
DEMO Here
CSS3
.sky {
        height:638px;
        background:#007fd5;
        position:relative;
        overflow:hidden;
        -webkit-animation:sky_background 50s ease-out infinite;
        -moz-animation:sky_background 50s ease-out infinite;
        -o-animation:sky_background 50s ease-out infinite;
        -webkit-transform:translate3d(0,0,0);
        -moz-transform:translate3d(0,0,0);
        -o-transform:translate3d(0,0,0)
    }

    .moon {
        background:url("http://montanaflynn.me/lab/css-clouds/images/moon.png");
        position:absolute;
        left:0;
        height:85%;
        width:300%;
        -webkit-animation:moon 50s linear infinite;
        -moz-animation:moon 50s linear infinite;
        -o-animation:moon 50s linear infinite;
        -webkit-transform:translate3d(0,0,0);
        -moz-transform:translate3d(0,0,0);
        -o-transform:translate3d(0,0,0)
    }

    .clouds_one {
          margin-top: -55px;
        background:url("http://montanaflynn.me/lab/css-clouds/images/cloud_one.png");
        position:absolute;
        left:0;
        top:0;
        height:80%;
        width:400%;
        -webkit-animation:cloud_one 5s linear infinite;
        -moz-animation:cloud_one 5s linear infinite;
        -o-animation:cloud_one 5s linear infinite;
        -webkit-transform:translate3d(0,0,0);
        -moz-transform:translate3d(0,0,0);
        -o-transform:translate3d(0,0,0)
    }

    .clouds_two {
        background:url("http://montanaflynn.me/lab/css-clouds/images/cloud_two.png");
        position:absolute;
        left:0;
        top:0;
        height:80%;
        width:400%;
        -webkit-animation:cloud_two 7s linear infinite;
        -moz-animation:cloud_two 7s linear infinite;
        -o-animation:cloud_two 7s linear infinite;
        -webkit-transform:translate3d(0,0,0);
        -moz-transform:translate3d(0,0,0);
        -o-transform:translate3d(0,0,0)
    }

    .clouds_three {

        background:url("http://montanaflynn.me/lab/css-clouds/images/cloud_three.png");
        position:absolute;
        left:0;
        top:0;
        height:75%;
        width:400%;
        -webkit-animation:cloud_three 10s linear infinite;
        -moz-animation:cloud_three 10s linear infinite;
        -o-animation:cloud_three 10s linear infinite;
        -webkit-transform:translate3d(0,0,0);
        -moz-transform:translate3d(0,0,0);
        -o-transform:translate3d(0,0,0)
    }

    @-webkit-keyframes sky_background {
        0% {
            background:#007fd5;
            color:#007fd5
        }

        50% {
            background:#007fd5;
            color:#007fd5
        }

        100% {
            background:#007fd5;
            color:#007fd5
        }
    }

    @-webkit-keyframes moon {
        0% {
            opacity: 0;
            left:-200%
            -moz-transform: scale(0.5);
            -webkit-transform: scale(0.5);
        }

        50% {
            opacity: 1;
            -moz-transform: scale(1);
            left:0%
            bottom:250px;
            -webkit-transform: scale(1);
        }

        100% {
            opacity: 0;
            bottom:500px;
            -moz-transform: scale(0.5);
            -webkit-transform: scale(0.5);
        }
    }

    @-webkit-keyframes cloud_one {
        0% {
            left:0
        }

        100% {
            left:-200%
        }
    }

    @-webkit-keyframes cloud_two {
        0% {
            left:0
        }

        100% {
            left:-200%
        }
    }

    @-webkit-keyframes cloud_three {
        0% {
            left:0
        }

        100% {
            left:-200%
        }
    }

    @-moz-keyframes sky_background {
        0% {
            background:#007fd5;
            color:#007fd5
        }

        50% {
            background:#000;
            color:#a3d9ff
        }

        100% {
            background:#007fd5;
            color:#007fd5
        }
    }

    @-moz-keyframes moon {
        0% {
            opacity: 0;
            left:-200%
            -moz-transform: scale(0.5);
            -webkit-transform: scale(0.5);
        }

        50% {
            opacity: 1;
            -moz-transform: scale(1);
            left:0%
            bottom:250px;
            -webkit-transform: scale(1);
        }

        100% {
            opacity: 0;
            bottom:500px;
            -moz-transform: scale(0.5);
            -webkit-transform: scale(0.5);
        }
    }

    @-moz-keyframes cloud_one {
        0% {
            left:0
        }

        100% {
            left:-200%
        }
    }

    @-moz-keyframes cloud_two {
        0% {
            left:0
        }

        100% {
            left:-200%
        }
    }

    @-moz-keyframes cloud_three {
        0% {
            left:0
        }

        100% {
            left:-200%
        }
    }

HTML