问:
Running MongoDB on Kubernetes Minikube with local persistent storage
I am currently trying to reproduce this tutorial on Minikube:

```<code>http://blog.kubernetes.io/2017/01/running-mongodb-on-kubernetes-with-statefulsets.html
</code>```

I updated the configuration files to use a hostpath as a persistent storage on minikube node.

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv0001
  labels:
    type: local
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/tmp"

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: myclaim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

---
apiVersion: v1
kind: Service
metadata:
  name: mongo
  labels:
    name: mongo
spec:
  ports:
  - port: 27017
    targetPort: 27017
  clusterIP: None
  selector:
    role: mongo
---
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: mongo
spec:
  serviceName: "mongo"
  replicas: 3
  template:
    metadata:
      labels:
        role: mongo
        environment: test
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: mongo
          image: mongo
          command:
            - mongod
            - "--replSet"
            - rs0
            - "--smallfiles"
            - "--noprealloc"
          ports:
            - containerPort: 27017
          volumeMounts:
            - name: myclaim
              mountPath: /data/db
        - name: mongo-sidecar
          image: cvallance/mongo-k8s-sidecar
          env:
            - name: MONGO_SIDECAR_POD_LABELS
              value: "role=mongo,environment=test"
  volumeClaimTemplates:
    - metadata:
        name: myclaim
</code>```

Which result in the following:

```<code>kubectl get pv
NAME                                       CAPACITY   ACCESSMODES   RECLAIMPOLICY   STATUS      CLAIM             REASON    AGE
pv0001                                     1Gi        RWO           Retain          Available                               17s
pvc-134a6c0f-1565-11e7-9cf1-080027f4d8c3   1Gi        RWO           Delete          Bound       default/myclaim             11s

kubectl get pvc
NAME      STATUS    VOLUME                                     CAPACITY   ACCESSMODES   AGE
myclaim   Bound     pvc-134a6c0f-1565-11e7-9cf1-080027f4d8c3   1Gi        RWO           14s

kubectl get svc
NAME         CLUSTER-IP   EXTERNAL-IP   PORT(S)     AGE
kubernetes   10.0.0.1     <none>        443/TCP     3d
mongo        None         <none>        27017/TCP   53s

kubectl get pod
No resources found.

kubectl describe service mongo
Name:           mongo
Namespace:      default
Labels:         name=mongo
Selector:       role=mongo
Type:           ClusterIP
IP:         None
Port:           <unset> 27017/TCP
Endpoints:      <none>
Session Affinity:   None
No events.

kubectl get statefulsets
NAME      DESIRED   CURRENT   AGE
mongo     3         0         4h

kubectl describe statefulsets mongo
Name:           mongo
Namespace:      default
Image(s):       mongo,cvallance/mongo-k8s-sidecar
Selector:       environment=test,role=mongo
Labels:         environment=test,role=mongo
Replicas:       0 current / 3 desired
Annotations:        <none>
CreationTimestamp:  Thu, 30 Mar 2017 18:23:56 +0200
Pods Status:        0 Running / 0 Waiting / 0 Succeeded / 0 Failed
No volumes.
Events:
  FirstSeen LastSeen    Count   From        SubObjectPath   Type    Reason      Message
  --------- --------    -----   ----        -------------   --------------      -------
  1s        1s      4   {statefulset }          WarningFailedCreate pvc: myclaim-mongo-0, error: PersistentVolumeClaim "myclaim-mongo-0" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
  1s        1s      4   {statefulset }          WarningFailedCreate pvc: myclaim-mongo-1, error: PersistentVolumeClaim "myclaim-mongo-1" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
  1s        0s      4   {statefulset }          WarningFailedCreate pvc: myclaim-mongo-2, error: PersistentVolumeClaim "myclaim-mongo-2" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]

kubectl get ev | grep mongo
29s        1m          15        mongo      StatefulSet               Warning   FailedCreate              {statefulset }          pvc: myclaim-mongo-0, error: PersistentVolumeClaim "myclaim-mongo-0" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
29s        1m          15        mongo      StatefulSet               Warning   FailedCreate              {statefulset }          pvc: myclaim-mongo-1, error: PersistentVolumeClaim "myclaim-mongo-1" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
29s        1m          15        mongo      StatefulSet               Warning   FailedCreate              {statefulset }          pvc: myclaim-mongo-2, error: PersistentVolumeClaim "myclaim-mongo-2" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]

kubectl describe pvc myclaim
Name:       myclaim
Namespace:  default
StorageClass:   standard
Status:     Bound
Volume:     pvc-134a6c0f-1565-11e7-9cf1-080027f4d8c3
Labels:     <none>
Capacity:   1Gi
Access Modes:   RWO
No events.

minikube version: v0.17.1
</code>```

It seems that the service is not able to load pods, which makes it complicated to debug with kubectl logs.
Is there something wrong with the way I am creating a persistent volume on my node ?

Thanks a lot

答:
TL; DR

In the situation described in the question the problem was that the Pods for the StatefulSet did not start up at all therefore the Service had no targets. The reason for not starting up was:

WarningFailedCreate pvc: myclaim-mongo-0, error: PersistentVolumeClaim "myclaim-mongo-0" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]`

And since the volume by default is defined as required the Pod won't start without it. So edit the StatefulSet's volumeClaimTemplate to have:

```<code>volumeClaimTemplates:
- metadata:
    name: myclaim
  spec:
    accessModes: [ "ReadWriteOnce" ]
    resources:
      requests:
        storage: 1Gi
</code>```

(There is no need to create the PersistentVolumeClaim manually.)

More general solution

If can't connect a Service try this command:

```<code>kubectl describe service myservicename
</code>```

And if you see something like this in the output:

```<code>Endpoints:      <none>
</code>```

That means there are no targets (usually Pods) running or the targets are not ready. To find out which one is the case do:

```<code>kubectl describe endpoint myservicename
</code>```

It will list all endpoints, ready or not. If not ready, investigate the readinessProbe in the Pod. If doesn't exist then try to find out why by looking at the StatefulSet (Deployment, ReplicaSet, ReplicationController, etc) itself for messages (the Events section):

```<code>kubectl describe statefulset mystatefulsetname
</code>```

This information is available if you do:

```<code>kubectl get ev | grep something
</code>```

If you are sure they are running and ready then the labels on the Pods and the Service do not match up.

Body:
I am currently trying to reproduce this tutorial on Minikube:

http://blog.kubernetes.io/2017/01/running-mongodb-on-kubernetes-with-statefulsets.html

I updated the configuration files to use a hostpath as a persistent storage on minikube node.

kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv0001
  labels:
    type: local
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/tmp"

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: myclaim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

---
apiVersion: v1
kind: Service
metadata:
  name: mongo
  labels:
    name: mongo
spec:
  ports:
  - port: 27017
    targetPort: 27017
  clusterIP: None
  selector:
    role: mongo
---
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: mongo
spec:
  serviceName: "mongo"
  replicas: 3
  template:
    metadata:
      labels:
        role: mongo
        environment: test
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: mongo
          image: mongo
          command:
            - mongod
            - "--replSet"
            - rs0
            - "--smallfiles"
            - "--noprealloc"
          ports:
            - containerPort: 27017
          volumeMounts:
            - name: myclaim
              mountPath: /data/db
        - name: mongo-sidecar
          image: cvallance/mongo-k8s-sidecar
          env:
            - name: MONGO_SIDECAR_POD_LABELS
              value: "role=mongo,environment=test"
  volumeClaimTemplates:
    - metadata:
        name: myclaim

Which result in the following:

kubectl get pv
NAME                                       CAPACITY   ACCESSMODES   RECLAIMPOLICY   STATUS      CLAIM             REASON    AGE
pv0001                                     1Gi        RWO           Retain          Available                               17s
pvc-134a6c0f-1565-11e7-9cf1-080027f4d8c3   1Gi        RWO           Delete          Bound       default/myclaim             11s

kubectl get pvc
NAME      STATUS    VOLUME                                     CAPACITY   ACCESSMODES   AGE
myclaim   Bound     pvc-134a6c0f-1565-11e7-9cf1-080027f4d8c3   1Gi        RWO           14s

kubectl get svc
NAME         CLUSTER-IP   EXTERNAL-IP   PORT(S)     AGE
kubernetes   10.0.0.1     <none>        443/TCP     3d
mongo        None         <none>        27017/TCP   53s

kubectl get pod
No resources found.

kubectl describe service mongo
Name:           mongo
Namespace:      default
Labels:         name=mongo
Selector:       role=mongo
Type:           ClusterIP
IP:         None
Port:           <unset> 27017/TCP
Endpoints:      <none>
Session Affinity:   None
No events.

kubectl get statefulsets
NAME      DESIRED   CURRENT   AGE
mongo     3         0         4h

kubectl describe statefulsets mongo
Name:           mongo
Namespace:      default
Image(s):       mongo,cvallance/mongo-k8s-sidecar
Selector:       environment=test,role=mongo
Labels:         environment=test,role=mongo
Replicas:       0 current / 3 desired
Annotations:        <none>
CreationTimestamp:  Thu, 30 Mar 2017 18:23:56 +0200
Pods Status:        0 Running / 0 Waiting / 0 Succeeded / 0 Failed
No volumes.
Events:
  FirstSeen LastSeen    Count   From        SubObjectPath   Type    Reason      Message
  --------- --------    -----   ----        -------------   --------------      -------
  1s        1s      4   {statefulset }          WarningFailedCreate pvc: myclaim-mongo-0, error: PersistentVolumeClaim "myclaim-mongo-0" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
  1s        1s      4   {statefulset }          WarningFailedCreate pvc: myclaim-mongo-1, error: PersistentVolumeClaim "myclaim-mongo-1" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
  1s        0s      4   {statefulset }          WarningFailedCreate pvc: myclaim-mongo-2, error: PersistentVolumeClaim "myclaim-mongo-2" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]

kubectl get ev | grep mongo
29s        1m          15        mongo      StatefulSet               Warning   FailedCreate              {statefulset }          pvc: myclaim-mongo-0, error: PersistentVolumeClaim "myclaim-mongo-0" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
29s        1m          15        mongo      StatefulSet               Warning   FailedCreate              {statefulset }          pvc: myclaim-mongo-1, error: PersistentVolumeClaim "myclaim-mongo-1" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]
29s        1m          15        mongo      StatefulSet               Warning   FailedCreate              {statefulset }          pvc: myclaim-mongo-2, error: PersistentVolumeClaim "myclaim-mongo-2" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]

kubectl describe pvc myclaim
Name:       myclaim
Namespace:  default
StorageClass:   standard
Status:     Bound
Volume:     pvc-134a6c0f-1565-11e7-9cf1-080027f4d8c3
Labels:     <none>
Capacity:   1Gi
Access Modes:   RWO
No events.

minikube version: v0.17.1

It seems that the service is not able to load pods, which makes it complicated to debug with kubectl logs.
Is there something wrong with the way I am creating a persistent volume on my node ?

Thanks a lot

Body:
TL; DR

In the situation described in the question the problem was that the Pods for the StatefulSet did not start up at all therefore the Service had no targets. The reason for not starting up was:

WarningFailedCreate pvc: myclaim-mongo-0, error: PersistentVolumeClaim "myclaim-mongo-0" is invalid: [spec.accessModes: Required value: at least 1 access mode is required, spec.resources[storage]: Required value]`

And since the volume by default is defined as required the Pod won't start without it. So edit the StatefulSet's volumeClaimTemplate to have:

volumeClaimTemplates:
- metadata:
    name: myclaim
  spec:
    accessModes: [ "ReadWriteOnce" ]
    resources:
      requests:
        storage: 1Gi

(There is no need to create the PersistentVolumeClaim manually.)

More general solution

If can't connect a Service try this command:

kubectl describe service myservicename

And if you see something like this in the output:

Endpoints:      <none>

That means there are no targets (usually Pods) running or the targets are not ready. To find out which one is the case do:

kubectl describe endpoint myservicename

It will list all endpoints, ready or not. If not ready, investigate the readinessProbe in the Pod. If doesn't exist then try to find out why by looking at the StatefulSet (Deployment, ReplicaSet, ReplicationController, etc) itself for messages (the Events section):

kubectl describe statefulset mystatefulsetname

This information is available if you do:

kubectl get ev | grep something

If you are sure they are running and ready then the labels on the Pods and the Service do not match up.


来源: stackexchange

问:
Design pattern to build one or more side-by-side views
I am attempting to build a dynamic control in Android that uses the builder pattern to construct a view that looks like:

[** Text][** Text]

Essentially, I am looking to create a view with an image and some text and group multiple such views together.

```<code>public static class DualBuilder {
        private final Context mContext;
        protected Drawable mFirstButtonIcon;
        protected Drawable mSecondButtonIcon;
        protected String mFirstButtonText;
        protected String mSecondButtonText;

        private DualBuilder(@NonNull final Context context) {
            mContext = context;
        }

        public DualBuilder firstButtonIcon(@Nullable final Drawable firstButtonIcon) {
            super.buttonIcon(firstButtonIcon);
            return this;
        }

        public DualBuilder firstButtonText(@NonNull final String firstButtonText) {
            super.buttonPrimaryText(firstButtonText);
            return this;
        }

        public DualBuilder secondButtonIcon(@Nullable final Drawable secondButtonIcon) {
            mSecondButtonIcon = secondButtonIcon;
            return this;
        }

        public DualBuilder secondButtonText(@NonNull final String secondButtonText) {
            mSecondButtonText = secondButtonText;
            return this;
        }

        public MultiViewControl build() {
            return new MultiViewControl(this);
        }
}
</code>```

The above would be a builder if i were to have two of these views. The constructor would take the builder variables and use them to construct a layout for each first/second view. The details of how that happens are not the issue, I just want to learn how to build something like this in a flexible way so it can accept 1...n number of views. What kind of a pattern can i use to achieve this? Any code sample would be very much appreciated.

答:
My two pence here...I just came up with this on the fly based on my experience.
So as I see it, your basic view content is an image and a string. If we consider this as an object structure called ViewContent then we can imagine that the Builder takes a composite of ViewContent objects and therefore we can pass 1..n such objects as a composite as input to the Builder object which will then proceed to act upon all these objects and create a layout for you...Hope this helps.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to build a dynamic control in Android that uses the builder pattern to construct a view that looks like:

[** Text][** Text]

Essentially, I am looking to create a view with an image and some text and group multiple such views together.

public static class DualBuilder {
        private final Context mContext;
        protected Drawable mFirstButtonIcon;
        protected Drawable mSecondButtonIcon;
        protected String mFirstButtonText;
        protected String mSecondButtonText;

        private DualBuilder(@NonNull final Context context) {
            mContext = context;
        }

        public DualBuilder firstButtonIcon(@Nullable final Drawable firstButtonIcon) {
            super.buttonIcon(firstButtonIcon);
            return this;
        }

        public DualBuilder firstButtonText(@NonNull final String firstButtonText) {
            super.buttonPrimaryText(firstButtonText);
            return this;
        }

        public DualBuilder secondButtonIcon(@Nullable final Drawable secondButtonIcon) {
            mSecondButtonIcon = secondButtonIcon;
            return this;
        }

        public DualBuilder secondButtonText(@NonNull final String secondButtonText) {
            mSecondButtonText = secondButtonText;
            return this;
        }

        public MultiViewControl build() {
            return new MultiViewControl(this);
        }
}

The above would be a builder if i were to have two of these views. The constructor would take the builder variables and use them to construct a layout for each first/second view. The details of how that happens are not the issue, I just want to learn how to build something like this in a flexible way so it can accept 1...n number of views. What kind of a pattern can i use to achieve this? Any code sample would be very much appreciated.


问:
how to change the font of the EditText hint in android?
As I have mentioned in the Question I am trying to change the font of hint in EditText. But I can't seem to make it happen!

this is my code for the the EditText getting the username:

```<code><!-- Email Label -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:id="@+id/input_username_id"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="20dp">

            <EditText
                android:id="@+id/input_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textColorHint="@color/white"
                android:hint="@string/hint_username"
                android:layout_marginRight="10dp"
                android:gravity="right" />
        </android.support.design.widget.TextInputLayout>
</code>```

and here is my java code:

```<code>_usernameText = (EditText) (findViewById(R.id.input_username));
font = Typeface.createFromAsset(getAssets(), "fonts/ir.ttf");
_usernameText.setTypeface(font);
</code>```

this didn't change the font of the hint of the EditText.
I have tried other solutions and nothing changed.
http://chintanrathod.com/customizing-textinputlayout-part-2/

答: since your EditText is wrapped in TextInputLayout you will have to setTypeface on TextInputLayout object reference

Body:
As I have mentioned in the Question I am trying to change the font of hint in EditText. But I can't seem to make it happen!

this is my code for the the EditText getting the username:

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:id="@+id/input_username_id"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="20dp">

            <EditText
                android:id="@+id/input_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textColorHint="@color/white"
                android:hint="@string/hint_username"
                android:layout_marginRight="10dp"
                android:gravity="right" />
        </android.support.design.widget.TextInputLayout>

and here is my java code:

_usernameText = (EditText) (findViewById(R.id.input_username));
font = Typeface.createFromAsset(getAssets(), "fonts/ir.ttf");
_usernameText.setTypeface(font);

this didn't change the font of the hint of the EditText.
I have tried other solutions and nothing changed.
http://chintanrathod.com/customizing-textinputlayout-part-2/


问:
-[__NSCFString objectForKey:]: unrecognized selector sent to instance in Objective C
I am new in iOS and I am facing problem regarding to show data from web service to calendar.

My code is like this

```<code>-(void)funAddEvents:(NSArray *)arrDate
{
    _eventsByDate = [NSMutableDictionary new];

    for(int i=0;i<arrDate.count;i++)
    {

        NSString *datefromweb= [NSString stringWithFormat: @"%@",[[arrDate objectAtIndex:i] objectForKey:@"Date"]]; //Showing error on this like..
        NSDateFormatter* df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
        NSDate *randomDate = [[NSDate alloc] init];
        randomDate = [df dateFromString:datefromweb];

        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        //  NSLog(@"event date =%@",randomDate);

        if(!_eventsByDate[key])
        {
            _eventsByDate[key] = [NSMutableArray new];
        }

        [_eventsByDate[key] addObject:randomDate];
        // NSLog(@"afte event date %@",eventsByDate);
    }

}
</code>```

Thanks in Advance!

答:
arrDate is Array of String not Array of Dictionary also you are getting nil because of wrong dateFormat. Correct dateFormat for your string is yyyy/MM/dd and currently you are setting dateFormat to MM/dd/yyyy hh:mm:ss a which is wrong, so changing dateFormat will solved your problem.

```<code>for(int i=0;i<arrDate.count;i++)
{

    NSString *datefromweb= [NSString stringWithFormat: @"%@",[[arrDate objectAtIndex:i] objectForKey:@"Date"]]; //Showing error on this like..
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy/MM/dd"];
    NSDate *randomDate = [[NSDate alloc] init];
    randomDate = [df dateFromString:datefromweb];

    NSString *key = [[self dateFormatter] stringFromDate:randomDate];
    //  NSLog(@"event date =%@",randomDate);

    if(!_eventsByDate[key])
    {
        _eventsByDate[key] = [NSMutableArray new];
    }

    [_eventsByDate[key] addObject:randomDate];
    // NSLog(@"afte event date %@",eventsByDate);
}
</code>```

Body:
I am new in iOS and I am facing problem regarding to show data from web service to calendar.

My code is like this

-(void)funAddEvents:(NSArray *)arrDate
{
    _eventsByDate = [NSMutableDictionary new];

    for(int i=0;i<arrDate.count;i++)
    {

        NSString *datefromweb= [NSString stringWithFormat: @"%@",[[arrDate objectAtIndex:i] objectForKey:@"Date"]]; //Showing error on this like..
        NSDateFormatter* df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
        NSDate *randomDate = [[NSDate alloc] init];
        randomDate = [df dateFromString:datefromweb];

        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        //  NSLog(@"event date =%@",randomDate);

        if(!_eventsByDate[key])
        {
            _eventsByDate[key] = [NSMutableArray new];
        }

        [_eventsByDate[key] addObject:randomDate];
        // NSLog(@"afte event date %@",eventsByDate);
    }

}

Thanks in Advance!

Body:
arrDate is Array of String not Array of Dictionary also you are getting nil because of wrong dateFormat. Correct dateFormat for your string is yyyy/MM/dd and currently you are setting dateFormat to MM/dd/yyyy hh:mm:ss a which is wrong, so changing dateFormat will solved your problem.

for(int i=0;i<arrDate.count;i++)
{

    NSString *datefromweb= [NSString stringWithFormat: @"%@",[[arrDate objectAtIndex:i] objectForKey:@"Date"]]; //Showing error on this like..
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy/MM/dd"];
    NSDate *randomDate = [[NSDate alloc] init];
    randomDate = [df dateFromString:datefromweb];

    NSString *key = [[self dateFormatter] stringFromDate:randomDate];
    //  NSLog(@"event date =%@",randomDate);

    if(!_eventsByDate[key])
    {
        _eventsByDate[key] = [NSMutableArray new];
    }

    [_eventsByDate[key] addObject:randomDate];
    // NSLog(@"afte event date %@",eventsByDate);
}


问:
FragmentManager is already executing transactions Android
I used the google developers example in order to make a slider of Views
screen-slide

Everything was working fine, at the moment I implemented the onclick listener to change to the next fragment, the activity was working fine, at the moment I hit the back btn or go back and press another answer, the app shows:

FragmentManager is already executing transactions

It shows that the process is being called from pager.java and fragment2.java

Here are the samples:

ThaTransfomer.java

```<code>package name of the package

import android.support.v4.view.ViewPager;
import android.view.View;

public class ThaTransformer implements ViewPager.PageTransformer{
private static final float MIN_SCALE =0.85f;
private static final float MIN_ALPHA = 0.5f;

public void transformPage(View view, float position){
    int pageWidth = view.getWidth();
    int pageHeight = view.getHeight();
    if(position < -1){
        view.setAlpha(0);
    }else if(position <=1){
        float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
        float vertMargin = pageHeight * (1 - scaleFactor) / 2;
        float horzMargin = pageWidth * (1 - scaleFactor) / 2;
        float ThaResult0 = horzMargin - vertMargin / 2;
        float ThaResultNon0 = horzMargin + vertMargin / 2;
        if(position < 0){
            view.setTranslationX(ThaResult0);
        }else{
            view.setTranslationX(ThaResultNon0);
        }
        view.setScaleX(scaleFactor);
        view.setScaleY(scaleFactor);

        view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA));
    }else{
        view.setAlpha(0);
    }
}
}
</code>```

Pager.java

```<code>public class Pager extends FragmentActivity {

/*Number of Pages*/
private static final int NUM_PAGES = 5;

private ViewPager mPager;

private PagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_slide);
    Button prevBtn = (Button) findViewById(R.id.previous);
    Button nextBtn = (Button) findViewById(R.id.next);

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    mPager.setPageTransformer(true, new ThaTransformer());
    mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);

    prevBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            prevItem();
        }
    });
    nextBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nextItem();
        }
    });
}

@Override
public void onBackPressed(){

    if(mPager.getCurrentItem()==0){
        /*Prevent bug if user is on first step*/
        super.onBackPressed();
    }else{
        /*Previous item*/
        mPager.setCurrentItem(mPager.getCurrentItem()-1);
    }
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        switch(position)
        {
            case 0: return new SurveyFragment1();
            case 1: return new SurveyFragment2();
            case 2: return new SurveyFragment3();
            case 3: return new SurveyFragment4();
            case 4: return new SurveyFragment5();
            default : return new SurveyFragment1();
        }
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}
public boolean nextItem(){
    int nextItemVar = mPager.getCurrentItem();
    if(nextItemVar<=3){
        Log.d("Next XD", ""+mPager.getCurrentItem());
    }else{
        Log.d("Yay! XD", ""+mPager.getCurrentItem());
        new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("Encuesta enviada")
                .setContentText("¡Gracias por llenar la encuesta!")
                .show();
    }
    mPager.setCurrentItem(nextItemVar + 1);
    return true;
}
public boolean prevItem(){
    mPager.setCurrentItem(mPager.getCurrentItem() - 1);
    return true;
}

}
</code>```

Survey Fragment 1

```<code>public class SurveyFragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page1, container, false);

    RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.ans_group1);

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //nextItem();

            ((Pager) getActivity()).nextItem();

          /**/

        }
    });

    return rootView;
}

}
</code>```

Survey Fragment 2

```<code>public class SurveyFragment2 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page2, container, false);

    RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.ans_group2);

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //nextItem();
            ((Pager) getActivity()).nextItem();

        }
    });

    return rootView;
}

}
</code>```

Survey Fragment 3

```<code>public class SurveyFragment3 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page3, container, false);

    RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.ans_group3);

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //nextItem();
            ((Pager) getActivity()).nextItem();

        }
    });

    return rootView;
}
}
</code>```

And the list goes on and on, as I said before, answering the first time it shows the desired effect, if you swipe back it goes back, the errors are shown when:

Hit the back btn

Give a diferent answer to a question already answered.

答:
I finally found a fix/hack in my case.

I think the issue is that when you reCreate your fragment, OnCreateView is called with a non null savedInstanceState. It means that the previous instance of your fragment was saved somewhere.
Because of this saved instance, something happens deeper in the code and make the ((Pager) getActivity()).nextItem() call automatically during the fragment creation:

Your Fragment is create : OnCreateView is called where you setup the setOnCheckedChangeListener method.

The savedInstanceState try to update your fragment with the previous state

Your different RadioGroup are set back to their previous value and the setOnCheckedChangeListener is triggered.

Your ((Pager) getActivity()).nextItem(); method are called and produce the Exception.

Here is my Hack - just reset your radio button and move your change listener right after the state is restored :

```<code>@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);

    //hack to prevent the view to display previous selection
    radioGroup .clearCheck();
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       ViewPager viewPager = (ViewPager)     getActivity().findViewById(R.id.pager);
       public void onCheckedChanged(RadioGroup group, int checkedId) {
           //nextItem();
           ((Pager) getActivity()).nextItem();

       }
   });
}
</code>```

Hope it will help !

Body:
I used the google developers example in order to make a slider of Views
screen-slide

Everything was working fine, at the moment I implemented the onclick listener to change to the next fragment, the activity was working fine, at the moment I hit the back btn or go back and press another answer, the app shows:

FragmentManager is already executing transactions

It shows that the process is being called from pager.java and fragment2.java

Here are the samples:

ThaTransfomer.java

package name of the package

import android.support.v4.view.ViewPager;
import android.view.View;

public class ThaTransformer implements ViewPager.PageTransformer{
private static final float MIN_SCALE =0.85f;
private static final float MIN_ALPHA = 0.5f;

public void transformPage(View view, float position){
    int pageWidth = view.getWidth();
    int pageHeight = view.getHeight();
    if(position < -1){
        view.setAlpha(0);
    }else if(position <=1){
        float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
        float vertMargin = pageHeight * (1 - scaleFactor) / 2;
        float horzMargin = pageWidth * (1 - scaleFactor) / 2;
        float ThaResult0 = horzMargin - vertMargin / 2;
        float ThaResultNon0 = horzMargin + vertMargin / 2;
        if(position < 0){
            view.setTranslationX(ThaResult0);
        }else{
            view.setTranslationX(ThaResultNon0);
        }
        view.setScaleX(scaleFactor);
        view.setScaleY(scaleFactor);

        view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA));
    }else{
        view.setAlpha(0);
    }
}
}

Pager.java

public class Pager extends FragmentActivity {

/*Number of Pages*/
private static final int NUM_PAGES = 5;

private ViewPager mPager;

private PagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_slide);
    Button prevBtn = (Button) findViewById(R.id.previous);
    Button nextBtn = (Button) findViewById(R.id.next);

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    mPager.setPageTransformer(true, new ThaTransformer());
    mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);

    prevBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            prevItem();
        }
    });
    nextBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nextItem();
        }
    });
}

@Override
public void onBackPressed(){

    if(mPager.getCurrentItem()==0){
        /*Prevent bug if user is on first step*/
        super.onBackPressed();
    }else{
        /*Previous item*/
        mPager.setCurrentItem(mPager.getCurrentItem()-1);
    }
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        switch(position)
        {
            case 0: return new SurveyFragment1();
            case 1: return new SurveyFragment2();
            case 2: return new SurveyFragment3();
            case 3: return new SurveyFragment4();
            case 4: return new SurveyFragment5();
            default : return new SurveyFragment1();
        }
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}
public boolean nextItem(){
    int nextItemVar = mPager.getCurrentItem();
    if(nextItemVar<=3){
        Log.d("Next XD", ""+mPager.getCurrentItem());
    }else{
        Log.d("Yay! XD", ""+mPager.getCurrentItem());
        new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("Encuesta enviada")
                .setContentText("¡Gracias por llenar la encuesta!")
                .show();
    }
    mPager.setCurrentItem(nextItemVar + 1);
    return true;
}
public boolean prevItem(){
    mPager.setCurrentItem(mPager.getCurrentItem() - 1);
    return true;
}

}

Survey Fragment 1

public class SurveyFragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page1, container, false);

    RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.ans_group1);

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //nextItem();

            ((Pager) getActivity()).nextItem();

          /**/

        }
    });

    return rootView;
}

}

Survey Fragment 2

public class SurveyFragment2 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page2, container, false);

    RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.ans_group2);

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //nextItem();
            ((Pager) getActivity()).nextItem();

        }
    });

    return rootView;
}

}

Survey Fragment 3

public class SurveyFragment3 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page3, container, false);

    RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.ans_group3);

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //nextItem();
            ((Pager) getActivity()).nextItem();

        }
    });

    return rootView;
}
}

And the list goes on and on, as I said before, answering the first time it shows the desired effect, if you swipe back it goes back, the errors are shown when:

Hit the back btn

Give a diferent answer to a question already answered.

Body:
I finally found a fix/hack in my case.

I think the issue is that when you reCreate your fragment, OnCreateView is called with a non null savedInstanceState. It means that the previous instance of your fragment was saved somewhere.
Because of this saved instance, something happens deeper in the code and make the ((Pager) getActivity()).nextItem() call automatically during the fragment creation:

Your Fragment is create : OnCreateView is called where you setup the setOnCheckedChangeListener method.

The savedInstanceState try to update your fragment with the previous state

Your different RadioGroup are set back to their previous value and the setOnCheckedChangeListener is triggered.

Your ((Pager) getActivity()).nextItem(); method are called and produce the Exception.

Here is my Hack - just reset your radio button and move your change listener right after the state is restored :

@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);

    //hack to prevent the view to display previous selection
    radioGroup .clearCheck();
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       ViewPager viewPager = (ViewPager)     getActivity().findViewById(R.id.pager);
       public void onCheckedChanged(RadioGroup group, int checkedId) {
           //nextItem();
           ((Pager) getActivity()).nextItem();

       }
   });
}

Hope it will help !


问:
Missing "libiconv.h" when crosscompiling for Windows with mingw on Ubuntu
I have been working on a program in SDL and I would like to send it to my friends who only run a Windows environment. I have done some reading and found that I should use mingw to cross-compile for Windows. The binary I found and compiled was x86_64-w64-mingw32-g++, however I am getting some issues getting my program to compile. Using the following command I get the following error:

```<code>/usr/bin/x86_64-w64-mingw32-g++ sapphire.cpp `pkg-config --cflags --libs sdl2` -lSDL2_image -lSDL2_mixer -lSDL2_ttf -std=c++11
fatal error: iconv.h: No such file or directory
</code>```

While I realize I should make a makefile eventually, I am not going to do that now.

I tried installing iconv (Version 1.15) from here and used the following commands to compile it:

```<code>./configure --prefix=/usr/local
make
make all
</code>```

My iconv.h is located in /usr/include but if I include that I get another error for missing gnu/stubs.h and if I include that then I get a myriad of errors that I'm not sure how/if I could fix seen here. Does anyone know how I could perhaps fix this? I would appreciate any help!

Thanks in advance!

答:
You can use pkg-config with mingw in a crosscompiler environment but you should take care to where pkg-config searches for his .pc files.

I'm assuming your mingw crosscompiler is installed in /usr/x86_64-w64-mingw32, change it to the installation path where his "include" and "lib" subdirectories are.

Provided SDL windows developement package is installed in the same prefix on your computer and the installation has a correct pkg-config .pc file you can do:

```<code>export PKG_CONFIG_PATH=/usr/x86_64-w64-mingw32/lib/pkgconfig
</code>```

and then try pkg-config from the command line:

```<code>pkg-config sdl2 --cflags
</code>```

This should point you to some path inside /usr/x86_64-w64-mingw32, if it does your compilation will be successful.

Please note that if you want to compile a package for crosscompile (like the iconv you tried to compile) you should add to the ./configure script parameters:

```<code>--host=x86_64-w64-mingw32 --prefix=/usr/xx86_64-w64-mingw32
</code>```

... and this may work or not, depending the package support the mingw32 compiler or not.

The way you compiled iconv built another linux version of it in /usr/local!

NOTE: As far as I know Ubuntu does not provide a windows package for SDL2, while other linux distro do, so you'll need to cross-compile SDL2 with the option I gave before you can compile your code. SDL2 does support cross-compilation using mingw.

Body:
I have been working on a program in SDL and I would like to send it to my friends who only run a Windows environment. I have done some reading and found that I should use mingw to cross-compile for Windows. The binary I found and compiled was x86_64-w64-mingw32-g++, however I am getting some issues getting my program to compile. Using the following command I get the following error:

/usr/bin/x86_64-w64-mingw32-g++ sapphire.cpp `pkg-config --cflags --libs sdl2` -lSDL2_image -lSDL2_mixer -lSDL2_ttf -std=c++11
fatal error: iconv.h: No such file or directory

While I realize I should make a makefile eventually, I am not going to do that now.

I tried installing iconv (Version 1.15) from here and used the following commands to compile it:

./configure --prefix=/usr/local
make
make all

My iconv.h is located in /usr/include but if I include that I get another error for missing gnu/stubs.h and if I include that then I get a myriad of errors that I'm not sure how/if I could fix seen here. Does anyone know how I could perhaps fix this? I would appreciate any help!

Thanks in advance!

Body:
You can use pkg-config with mingw in a crosscompiler environment but you should take care to where pkg-config searches for his .pc files.

I'm assuming your mingw crosscompiler is installed in /usr/x86_64-w64-mingw32, change it to the installation path where his "include" and "lib" subdirectories are.

Provided SDL windows developement package is installed in the same prefix on your computer and the installation has a correct pkg-config .pc file you can do:

export PKG_CONFIG_PATH=/usr/x86_64-w64-mingw32/lib/pkgconfig

and then try pkg-config from the command line:

pkg-config sdl2 --cflags

This should point you to some path inside /usr/x86_64-w64-mingw32, if it does your compilation will be successful.

Please note that if you want to compile a package for crosscompile (like the iconv you tried to compile) you should add to the ./configure script parameters:

--host=x86_64-w64-mingw32 --prefix=/usr/xx86_64-w64-mingw32

... and this may work or not, depending the package support the mingw32 compiler or not.

The way you compiled iconv built another linux version of it in /usr/local!

NOTE: As far as I know Ubuntu does not provide a windows package for SDL2, while other linux distro do, so you'll need to cross-compile SDL2 with the option I gave before you can compile your code. SDL2 does support cross-compilation using mingw.


问:
Solr cloud - reloading elevate.xml
I am using Apache Solr 6.5 with Query Elevation Component (/elevate endpoint) to support elevation of particular documents in my queries.

I am using elevate.xml file in

```<code><instanceDir>/conf/<config-file>
</code>```

directory. However on production server (Solr configured as cloud with zookepper to maintain configuration) changes in the elevate.xml are not loaded. To check if it works, I just query the elevated phrase and as a result I get elevated documents from previous version of elevate.xml.

Of course I am restarting all Solr cloud instances after loading new version of elevate.xml and updated file is visible in the Solr's Admin UI files section (of the particular core of course).

The query I am using to test results, to prove that I am not using stardard /query component:

```<code>/elevate?df=name&fl=id,name,[elevated]&indent=on&q=heart&wt=json
</code>```

What should I do to actually tell Solr that the new elevate.xml was loaded? That works fine on my development standalone configuration of Solr (not cloud one) after the solr service is restarted, the documents are elevated by updated elevate.xml file.

答:
Ok I think I figured it out. The problem was with a directory in which elevate.xml file was anticipated by Solr.

The documentation states (as for 6.5.0 version)

```<code>config-file

Path to the file that defines query elevation.
This file must exist in     <instanceDir>/conf/<config-file> or <dataDir>/<config-file>.
</code>```

In my dev configuration that was true for both cases (the file was read either from conf or data directory). However on production (in cloud environment with external zooKeepers) the file was read from the root directory of a core (aka collection), where also solrconfig.xml and schema.xml exists.

Probably it has some explanation and it's just data dir itself, but since I don't know how to check what are values of instanceDir and dataDir variables, the documentation was misleading for me.

I hope it helps other Solr adepts.

Title: Solr cloud - reloading elevate.xml

Body:
I am using Apache Solr 6.5 with Query Elevation Component (/elevate endpoint) to support elevation of particular documents in my queries.

I am using elevate.xml file in

<instanceDir>/conf/<config-file>

directory. However on production server (Solr configured as cloud with zookepper to maintain configuration) changes in the elevate.xml are not loaded. To check if it works, I just query the elevated phrase and as a result I get elevated documents from previous version of elevate.xml.

Of course I am restarting all Solr cloud instances after loading new version of elevate.xml and updated file is visible in the Solr's Admin UI files section (of the particular core of course).

The query I am using to test results, to prove that I am not using stardard /query component:

/elevate?df=name&fl=id,name,[elevated]&indent=on&q=heart&wt=json

What should I do to actually tell Solr that the new elevate.xml was loaded? That works fine on my development standalone configuration of Solr (not cloud one) after the solr service is restarted, the documents are elevated by updated elevate.xml file.

Body:
Ok I think I figured it out. The problem was with a directory in which elevate.xml file was anticipated by Solr.

The documentation states (as for 6.5.0 version)

config-file

Path to the file that defines query elevation.
This file must exist in     <instanceDir>/conf/<config-file> or <dataDir>/<config-file>.

In my dev configuration that was true for both cases (the file was read either from conf or data directory). However on production (in cloud environment with external zooKeepers) the file was read from the root directory of a core (aka collection), where also solrconfig.xml and schema.xml exists.

Probably it has some explanation and it's just data dir itself, but since I don't know how to check what are values of instanceDir and dataDir variables, the documentation was misleading for me.

I hope it helps other Solr adepts.


问:
PHP fatal error - Call to a member function prepare() on resource
I have looked at other questions but i can't see a link between mine and others issues so i was wondering if i could get some advice on where i am going wrong.

I read about not mixing API's but im not sure if i am or not?

submitNoteText.php:

```<code>?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{
    var_dump($_POST['notetext1']);

    $stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
    $stmt->bind_param("si", $notetext2, $noteid2);

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];
    $stmt->execute();

    $stmt->close();
}
else
{
    if (isset($_POST['notetext1'])) {
        var_dump($notetext2);
    }
    else
    {
        echo "Test";
    }

}

?>
</code>```

connectionDetails.php:

```<code><?php
$myServer = "test ip";
$connectionInfo = array('Database' => 'DiscoverThePlanet', 'UID' => 'Test', 'PWD' => 'Test');

//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
  or die("Couldn't connect to SQL Server on $myServer");

//Test connection to server
// if ($conn)
// {
//     echo "connection successful";    # code...
// }

?>
</code>```

The error is in the submitNoteText.php and is this line:

```<code>$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
</code>```

答:
You are calling variables before you declare them

```<code>$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
$stmt->bind_param("si", $notetext2, $noteid2);

$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];
</code>```

Switch order to

```<code>$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];

$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
$stmt->bind_param("si", $notetext2, $noteid2);
</code>```

Ok, i just noticed :

you are calling :

$conn->prepare()

but $conn is not instance of PDO. You are mixing api. Change your $conn according to docs:
http://php.net/manual/pl/pdo.construct.php

Body:
I have looked at other questions but i can't see a link between mine and others issues so i was wondering if i could get some advice on where i am going wrong.

I read about not mixing API's but im not sure if i am or not?

submitNoteText.php:

?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{
    var_dump($_POST['notetext1']);

    $stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
    $stmt->bind_param("si", $notetext2, $noteid2);

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];
    $stmt->execute();

    $stmt->close();
}
else
{
    if (isset($_POST['notetext1'])) {
        var_dump($notetext2);
    }
    else
    {
        echo "Test";
    }

}

?>

connectionDetails.php:

<?php
$myServer = "test ip";
$connectionInfo = array('Database' => 'DiscoverThePlanet', 'UID' => 'Test', 'PWD' => 'Test');

//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
  or die("Couldn't connect to SQL Server on $myServer");

//Test connection to server
// if ($conn)
// {
//     echo "connection successful";    # code...
// }

?>

The error is in the submitNoteText.php and is this line:

$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");

Body:
You are calling variables before you declare them

$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
$stmt->bind_param("si", $notetext2, $noteid2);

$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];

Switch order to

$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];

$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
$stmt->bind_param("si", $notetext2, $noteid2);

Ok, i just noticed :

you are calling :

$conn->prepare()

but $conn is not instance of PDO. You are mixing api. Change your $conn according to docs:
http://php.net/manual/pl/pdo.construct.php


问:
Recursively delete particular directories and files
I want to delete particular directory in following mainDir.

```<code>public readonly DirectoryInfo mainDir = new DirectoryInfo("C:\Export\DataFiles\");
</code>```

The mainDir may contain subdirectories and subdirectories may contain more directories...

I only get file name with fullpath.. I want to delete all parents directories of the file (including files), but not the main directory. What is the better way to do it?

Example files:

```<code>C:\Export\DataFiles\20392\483928\292833\file1.txt
C:\Export\DataFiles\20392\483928\292833\file2.txt
</code>```

Here, I want to delete C:\Export\DataFiles\20392

```<code>C:\Export\DataFiles\3222\file1.txt
</code>```

Here, I want to delete C:\Export\DataFiles\3222

```<code>C:\Export\DataFiles\4342\425622\file1.txt
C:\Export\DataFiles\4342\425622\file2.txt
C:\Export\DataFiles\4342\425622\file3.txt
</code>```

Here, I want to delete C:\Export\DataFiles\4342

EDIT:

I cannot use following:

```<code>mainDir.delete(true);
</code>```

It will delete all the directories and files in the mainDir.

答:
The easiest option is to use the Directory.Delete(folder_path, recursive: true) method. This method will delete all sub-directories including the files they contain in a recursive way (if recursive is set to true).

Also, you need to get the right path based on the folder you always want to delete from. For this you can use Regex or String.Split(). Since the base folder you want to delete from always has the same name, this can be easily achieved by checking on this name after you split the path string.

An implementation I wrote:

```<code>string folderToSplitOn = "DataFiles";

// Split your input string to detect from which path to delete
string path = @"C:\Export\DataFiles\20392\483928\292833\file1.txt";
string[] splittedString = path.Split('\\');

// Assuming you want to split from DataFiles, loop through your splitted results like this
string pathToDeleteFrom = null;
for (int i = 0; i < splittedString.Length; i++)
{
    pathToDeleteFrom += splittedString[i] + @"\";

    // It's now equal to the folder you want to delete from. Add the extra folder and finish
    if (splittedString[i].Equals(folderToSplitOn))
    {
        pathToDeleteFrom += splittedString[i + 1] + @"\";
        break;
    }
}

// Now you can delete all files and subfolders
Directory.Delete(pathToDeleteFrom, true);
</code>```

Body:
I want to delete particular directory in following mainDir.

public readonly DirectoryInfo mainDir = new DirectoryInfo("C:\Export\DataFiles\");

The mainDir may contain subdirectories and subdirectories may contain more directories...

I only get file name with fullpath.. I want to delete all parents directories of the file (including files), but not the main directory. What is the better way to do it?

Example files:

C:\Export\DataFiles\20392\483928\292833\file1.txt
C:\Export\DataFiles\20392\483928\292833\file2.txt

Here, I want to delete C:\Export\DataFiles\20392

C:\Export\DataFiles\3222\file1.txt

Here, I want to delete C:\Export\DataFiles\3222

C:\Export\DataFiles\4342\425622\file1.txt
C:\Export\DataFiles\4342\425622\file2.txt
C:\Export\DataFiles\4342\425622\file3.txt

Here, I want to delete C:\Export\DataFiles\4342

EDIT:

I cannot use following:

mainDir.delete(true);

It will delete all the directories and files in the mainDir.

Body:
The easiest option is to use the Directory.Delete(folder_path, recursive: true) method. This method will delete all sub-directories including the files they contain in a recursive way (if recursive is set to true).

Also, you need to get the right path based on the folder you always want to delete from. For this you can use Regex or String.Split(). Since the base folder you want to delete from always has the same name, this can be easily achieved by checking on this name after you split the path string.

An implementation I wrote:

string folderToSplitOn = "DataFiles";

// Split your input string to detect from which path to delete
string path = @"C:\Export\DataFiles\20392\483928\292833\file1.txt";
string[] splittedString = path.Split('\\');

// Assuming you want to split from DataFiles, loop through your splitted results like this
string pathToDeleteFrom = null;
for (int i = 0; i < splittedString.Length; i++)
{
    pathToDeleteFrom += splittedString[i] + @"\";

    // It's now equal to the folder you want to delete from. Add the extra folder and finish
    if (splittedString[i].Equals(folderToSplitOn))
    {
        pathToDeleteFrom += splittedString[i + 1] + @"\";
        break;
    }
}

// Now you can delete all files and subfolders
Directory.Delete(pathToDeleteFrom, true);


问:
How to update id set from 1?
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

```<code>id  name
3   ABC
5   XYZ
9   PQR
</code>```

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

```<code>id  name
1   ABC
2   XYZ
3   PQR
</code>```

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

答:
In my opinion you shouldn't mess with auto_increment columns at all. Let them be as they are. Their only job is to identify a row uniquely. If you want a nice serial number use another column (make it unique if you wish)!

You will always run into trouble and there will always happen things, that mess with your nice 1, 2, 3, ... sequence. A transaction gets rolled back? Boom, your sequence is 1, 2, 3, 5, ... instead of your intended 1, 2, 3, 4, ...

This can also be a very heavy operation. An auto_increment column is always also a primary key. Every other index on this table includes the primary key. Every time you reset your auto_increments, every index on this table is rewritten.

So my advice is, don't mess with auto_increments.

Title: How to update id set from 1?

Body:
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

id  name
3   ABC
5   XYZ
9   PQR

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

id  name
1   ABC
2   XYZ
3   PQR

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks


问:
Using Regexkitlite in iPhone,iPad
Can any one tell how can we set the regular expression in regexkitlite for validating float numbers,email,web address..etc....or can any one say what is the rules for using the expression ?</p>

答:
You do a

```<code>[text stringByMatching:@"..."]
</code>```

and if that call returns nil, then your number, email, etc. isn't accepted.

ContentLicense: CC BY-SA 2.5

Title: Using Regexkitlite in iPhone,iPad

Body:
You do a

[text stringByMatching:@"..."]

and if that call returns nil, then your number, email, etc. isn't accepted.


问:
Include different fonts in an HTML document
I have to add a folder with a font family that has different styles (bold, light, etc.), the fonts are in .ot, .ttf and .woff. The font family and the main folder where the fonts are is called HKExplorerSoft.

How should I add these fonts to the projects and how can I use them later in my CSS? I understand I have to create a @font-face rule, something like:

```<code>@font-face {
  font-family: 'HKExplorerSoft';
  src: url('assets/HKExplorerSoft/hkexplorersoft-black-webfont.woff');
}
</code>```

But that doesn't work or I'm not sure how to use this in the CSS later.

答:
Do it this way (in your stylesheet):

```<code>@import url('assets/HKExplorerSoft/hkexplorersoft-black-webfont.woff');
</code>```

Check that the filepath is correct...

and then use this name in your styles like:

```<code>.myclass {
  font-family: 'HKExplorerSoft';
}
</code>```

Body:
I have to add a folder with a font family that has different styles (bold, light, etc.), the fonts are in .ot, .ttf and .woff. The font family and the main folder where the fonts are is called HKExplorerSoft.

How should I add these fonts to the projects and how can I use them later in my CSS? I understand I have to create a @font-face rule, something like:

@font-face {
  font-family: 'HKExplorerSoft';
  src: url('assets/HKExplorerSoft/hkexplorersoft-black-webfont.woff');
}

But that doesn't work or I'm not sure how to use this in the CSS later.

Body:
Do it this way (in your stylesheet):

@import url('assets/HKExplorerSoft/hkexplorersoft-black-webfont.woff');

Check that the filepath is correct...

and then use this name in your styles like:

.myclass {
  font-family: 'HKExplorerSoft';
}


问:
I want to create a label which keeps track of how many times a view controller has been visited
I have a table view cell that performs a segue. Now my question is:

I want to put a label that counts how many times a particular view controller has been visited/viewed. Is there anything that we can do to when we click a table cell which performs a segue to another view controller and label in another view controller increments like:
Visited 1 times,
Visited 2 times,
Visited 3 times.

I did not implement this basic thing, I have something like

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let val2 = mySongsArray[indexPath.row] performSegue(withIdentifier: "JustinTableViewCell" , sender: val2)
}
</code>```

I am using Swift 3.

答:
Use UserDefault.
UserDefault help to store data until application not uninstalled.

Write this code in Second View controller which want count.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let user: UserDefaults = UserDefaults.init()
        var count: Int = user.integer(forKey: "COUNT")
        count += 1
        user.set(count, forKey: "COUNT")
        user.synchronize()

        let Countstr: String = String(count)
        lblCount.text = Countstr
}
</code>```

Body:
I have a table view cell that performs a segue. Now my question is:

I want to put a label that counts how many times a particular view controller has been visited/viewed. Is there anything that we can do to when we click a table cell which performs a segue to another view controller and label in another view controller increments like:
Visited 1 times,
Visited 2 times,
Visited 3 times.

I did not implement this basic thing, I have something like

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let val2 = mySongsArray[indexPath.row] performSegue(withIdentifier: "JustinTableViewCell" , sender: val2)
}

I am using Swift 3.

Body:
Use UserDefault.
UserDefault help to store data until application not uninstalled.

Write this code in Second View controller which want count.

override func viewDidLoad() {
        super.viewDidLoad()

        let user: UserDefaults = UserDefaults.init()
        var count: Int = user.integer(forKey: "COUNT")
        count += 1
        user.set(count, forKey: "COUNT")
        user.synchronize()

        let Countstr: String = String(count)
        lblCount.text = Countstr
}


问:
Is there any hashable built-in object is mutable in python?
Curious about whether we can use hash() to check if an object is mutable or not?</p>

答:
>>> from collections.abc import Hashable
>>> mutable = [list, bytearray, set, dict]
>>> immutable = [int, float, complex, str, tuple, frozenset, bytes]
>>> all(isinstance(x(), Hashable) for x in immutable)
True
>>> any(isinstance(x(), Hashable) for x in mutable)
False
```

all mutable objects are unhashable.

Body:
>>> from collections.abc import Hashable
>>> mutable = [list, bytearray, set, dict]
>>> immutable = [int, float, complex, str, tuple, frozenset, bytes]
>>> all(isinstance(x(), Hashable) for x in immutable)
True
>>> any(isinstance(x(), Hashable) for x in mutable)
False

all mutable objects are unhashable.


问:
Get ClickOnce's installation uid
I'm developing an application deployed throgh ClickOnce and I need to be able to distinguish each installation.
Is there a way to get some sort of deployment id that changes for every installation (so 2 users on the same PC get 2 different id's) but stays the same if the app is updated?

Thanks

答:
After some more research I wasn't able to find anything so I ended up creating the UID myself by hashing the CPU id, motherboard info and user GUID.

Got some inspiration from a CodeProject article and a MSDN Forum question

```<code>Public Function SHA256Hash(ByVal s As String) As String
    Dim hashFunction As SHA256 = SHA256Managed.Create
    Dim bytes() As Byte = (New ASCIIEncoding).GetBytes(s)
    Dim hash() As Byte = hashFunction.ComputeHash(bytes)
    Return GetStringFromHash(hash)
End Function

Private _HardwareID As String
Public Function HardwareID() As String
    If String.IsNullOrWhiteSpace(_HardwareID) Then
        _HardwareID = SHA256Hash(String.Format("CPU>>{0}|BASE>>{1}|USER>>{2}", cpuID, baseID, userID))
    End If

    Return _HardwareID
End Function

Private Function identifier(ByVal wmiClass As String, ByVal wmiProperty As String)
    Dim result As String = String.Empty
    Dim mc As New Management.ManagementClass(wmiClass)
    Dim moc As Management.ManagementObjectCollection = mc.GetInstances()

    For Each mo As Management.ManagementObject In moc
        'Only get the first one
        If String.IsNullOrWhiteSpace(result) Then
            Try
                result = mo(wmiProperty).ToString
            Catch ex As Exception
            End Try
        End If
    Next

    Return result
End Function

Private Function cpuID() As String
    'Uses first CPU identifier available in order of preference
    'Don't get all identifiers, as it is very time consuming
    Dim retVal As String = identifier("Win32_Processor", "UniqueID")
    If String.IsNullOrWhiteSpace(retVal) Then 'If no UniqueID, use ProcessorID
        retVal = identifier("Win32_Processor", "ProcessorId")
        If String.IsNullOrWhiteSpace(retVal) Then 'If no ProcessorId, use Name
            retVal = identifier("Win32_Processor", "Name")
            If String.IsNullOrWhiteSpace(retVal) Then 'If no Name, use Manufacturer
                retVal = identifier("Win32_Processor", "Manufacturer")
            End If
        End If
    End If

    Return retVal
End Function

Private Function baseID() As String
    Return String.Concat(identifier("Win32_BaseBoard", "Model"), _
                         identifier("Win32_BaseBoard", "Manufacturer"), _
                         identifier("Win32_BaseBoard", "Name"), _
                         identifier("Win32_BaseBoard", "SerialNumber"))
End Function

Private Function userID() As String
    Return System.DirectoryServices.AccountManagement.UserPrincipal.Current.Guid.Value.ToString
End Function
</code>```

Title: Get ClickOnce's installation uid

Body:
After some more research I wasn't able to find anything so I ended up creating the UID myself by hashing the CPU id, motherboard info and user GUID.

Got some inspiration from a CodeProject article and a MSDN Forum question

Public Function SHA256Hash(ByVal s As String) As String
    Dim hashFunction As SHA256 = SHA256Managed.Create
    Dim bytes() As Byte = (New ASCIIEncoding).GetBytes(s)
    Dim hash() As Byte = hashFunction.ComputeHash(bytes)
    Return GetStringFromHash(hash)
End Function

Private _HardwareID As String
Public Function HardwareID() As String
    If String.IsNullOrWhiteSpace(_HardwareID) Then
        _HardwareID = SHA256Hash(String.Format("CPU>>{0}|BASE>>{1}|USER>>{2}", cpuID, baseID, userID))
    End If

    Return _HardwareID
End Function

Private Function identifier(ByVal wmiClass As String, ByVal wmiProperty As String)
    Dim result As String = String.Empty
    Dim mc As New Management.ManagementClass(wmiClass)
    Dim moc As Management.ManagementObjectCollection = mc.GetInstances()

    For Each mo As Management.ManagementObject In moc
        'Only get the first one
        If String.IsNullOrWhiteSpace(result) Then
            Try
                result = mo(wmiProperty).ToString
            Catch ex As Exception
            End Try
        End If
    Next

    Return result
End Function

Private Function cpuID() As String
    'Uses first CPU identifier available in order of preference
    'Don't get all identifiers, as it is very time consuming
    Dim retVal As String = identifier("Win32_Processor", "UniqueID")
    If String.IsNullOrWhiteSpace(retVal) Then 'If no UniqueID, use ProcessorID
        retVal = identifier("Win32_Processor", "ProcessorId")
        If String.IsNullOrWhiteSpace(retVal) Then 'If no ProcessorId, use Name
            retVal = identifier("Win32_Processor", "Name")
            If String.IsNullOrWhiteSpace(retVal) Then 'If no Name, use Manufacturer
                retVal = identifier("Win32_Processor", "Manufacturer")
            End If
        End If
    End If

    Return retVal
End Function

Private Function baseID() As String
    Return String.Concat(identifier("Win32_BaseBoard", "Model"), _
                         identifier("Win32_BaseBoard", "Manufacturer"), _
                         identifier("Win32_BaseBoard", "Name"), _
                         identifier("Win32_BaseBoard", "SerialNumber"))
End Function

Private Function userID() As String
    Return System.DirectoryServices.AccountManagement.UserPrincipal.Current.Guid.Value.ToString
End Function


答:
If you want to import custom fonts you may have a look to this answer provided here :

Using .otf fonts on web browsers

Using @font-face

Title: Include different fonts in an HTML document


问:
Laravel eager loading combine where for multiple tables
I have problem with Laravel eager loading, I want to search many to one related tables.

I have two models, Book and Author.
I have relation belongsTo (in Book model) and hasMany (in Author model).

```<code>Books: id, title, description, author, tags, type
Author: id, name, birth, tags, type
</code>```

(this is not the real columns, I have a lot of columns, this is only for example)

I must to use models for searching, I can't use DB or raw queries for the relations.

So, my question is how can I search by parent table into Model->with() function ?

```<code>Model->with('author', function($query) use($search) {
    $query->where('author.name', '=', $search);
    $query->orWhere('book.title', '=', $search);
});
</code>```

The important thing is that I need to get Books, and I must to be able to use $book->author (or on $results->toArray() to get all Book data with Author data in ->author property)

I hope that you understand me what I want to ask.

Best regards

答:
You can use whereHas() to search by author name and orWhere() to also search by book title:

```<code>Book::whereHas('author', function($q) use($search) {
        $q->where('name', 'like', '%'.$search.'%');
    })
    ->orWhere('title', 'like', '%'.$search.'%')
    ->get();
</code>```

So, this query will find all books with defined title or author's name. If you also need to load the author data, add ->with('author') to the query.

Body:
I have problem with Laravel eager loading, I want to search many to one related tables.

I have two models, Book and Author.
I have relation belongsTo (in Book model) and hasMany (in Author model).

Books: id, title, description, author, tags, type
Author: id, name, birth, tags, type

(this is not the real columns, I have a lot of columns, this is only for example)

I must to use models for searching, I can't use DB or raw queries for the relations.

So, my question is how can I search by parent table into Model->with() function ?

Model->with('author', function($query) use($search) {
    $query->where('author.name', '=', $search);
    $query->orWhere('book.title', '=', $search);
});

The important thing is that I need to get Books, and I must to be able to use $book->author (or on $results->toArray() to get all Book data with Author data in ->author property)

I hope that you understand me what I want to ask.

Best regards

Body:
You can use whereHas() to search by author name and orWhere() to also search by book title:

Book::whereHas('author', function($q) use($search) {
        $q->where('name', 'like', '%'.$search.'%');
    })
    ->orWhere('title', 'like', '%'.$search.'%')
    ->get();

So, this query will find all books with defined title or author's name. If you also need to load the author data, add ->with('author') to the query.


问:
Android add separate google map api key for release and debug build modes
i am developing an android application using android studio 2.3. I added google map activity to my project using built in add activity dialog.

When i check the google map api key it is saved in a separate xml file inside values folder but under debug varient. I need to add a new api key that is going to use only for relase mode (builds). How do i add such a separate api key xml file for release mode as well?

Thanks in advance!!

答:
Just create same xml file in release folder.

You're default debug key is probably in file project_location/src/debug/res/values/some_file_name.xml.

You need to create same file in project_location/src/release/res/values/some_file_name.xml And put you'r release key there.


答:
AndroidManifest.xml:

```<code><meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_maps_api_key"/>
</code>```

app/build.gradle:

```<code>android {
    ...

    buildTypes {
        debug {
            resValue "string", "google_maps_api_key", "[YOUR DEBUG KEY]"
        }
        release {
            resValue "string", "google_maps_api_key", "[YOUR RELEASE KEY]"
        }
    }
}
</code>```

Title: Android add separate google map api key for release and debug build modes

Body:
i am developing an android application using android studio 2.3. I added google map activity to my project using built in add activity dialog.

When i check the google map api key it is saved in a separate xml file inside values folder but under debug varient. I need to add a new api key that is going to use only for relase mode (builds). How do i add such a separate api key xml file for release mode as well?

Thanks in advance!!

Body:
AndroidManifest.xml:

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_maps_api_key"/>

app/build.gradle:

android {
    ...

    buildTypes {
        debug {
            resValue "string", "google_maps_api_key", "[YOUR DEBUG KEY]"
        }
        release {
            resValue "string", "google_maps_api_key", "[YOUR RELEASE KEY]"
        }
    }
}


问:
How to create a calculated field that references a cell value in an excel pivot table
I have my data that looks like the following:

```<code>Col1 | Value
A    | 1
B    | 1
A    | 3
C    | 7
</code>```

and a pivot table that sums up the values for col1.
In addition I have an exchange rete in a another cell (in another worksheet)  and I would like to create a calculated field in my pivot table that multiplies the Value for the exchange rate in that cell.
Is this possible? How?
The reason for this is that the users might change the exchange rate in the cell but they would not know how to change it in the calculated field.
I know that I can simply add a column in my source data with the calculated value, but I would like to do it as calculated pivot table field if this is at all possible.

答:
You can achieve something similar to what you're after by 'slaving' a Table to a PivotTable, with a little VBA. See this answer I posted, that can be adapted to effectively achieve what you want.

Or alternately, you could multiply the individual totals in the source data by a named range called Exchange_Rate, and have a small bit of VBA that refreshes the Pivot whenever that Exchange_Rate input parameter is changed by users.

Here's how that looks:

...and if I change the ExchangeRate variable in that orange input cell:

To do this, I have a small snippet of VBA in the relevant Sheet Module that simply monitors that input cell for any change, and then refreshes the PivotTable so that the Pivot reflects the updated values in the underlying source data:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("ExchangeRate")) Is Nothing Then ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
End Sub
</code>```

Or you could record a macro while setting up a calculated field at a specific exchange rate, then modify that code so that the rate part gets replaced to match any change to that orange cell:

...and here's the event handler code that does this:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("ExchangeRate")) Is Nothing Then _
    ActiveSheet.PivotTables("PivotTable1").CalculatedFields("Local Cost"). _
        StandardFormula = "='Value ($USD)'/ " & Range("ExchangeRate")
End Sub
</code>```

Or if you have the ability to use PowerPivot, you could use Rob Collie's Disconnected Slicer trick.

Body:
I have my data that looks like the following:

Col1 | Value
A    | 1
B    | 1
A    | 3
C    | 7

and a pivot table that sums up the values for col1.
In addition I have an exchange rete in a another cell (in another worksheet)  and I would like to create a calculated field in my pivot table that multiplies the Value for the exchange rate in that cell.
Is this possible? How?
The reason for this is that the users might change the exchange rate in the cell but they would not know how to change it in the calculated field.
I know that I can simply add a column in my source data with the calculated value, but I would like to do it as calculated pivot table field if this is at all possible.

Body:
You can achieve something similar to what you're after by 'slaving' a Table to a PivotTable, with a little VBA. See this answer I posted, that can be adapted to effectively achieve what you want.

Or alternately, you could multiply the individual totals in the source data by a named range called Exchange_Rate, and have a small bit of VBA that refreshes the Pivot whenever that Exchange_Rate input parameter is changed by users.

Here's how that looks:

...and if I change the ExchangeRate variable in that orange input cell:

To do this, I have a small snippet of VBA in the relevant Sheet Module that simply monitors that input cell for any change, and then refreshes the PivotTable so that the Pivot reflects the updated values in the underlying source data:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("ExchangeRate")) Is Nothing Then ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
End Sub

Or you could record a macro while setting up a calculated field at a specific exchange rate, then modify that code so that the rate part gets replaced to match any change to that orange cell:

...and here's the event handler code that does this:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("ExchangeRate")) Is Nothing Then _
    ActiveSheet.PivotTables("PivotTable1").CalculatedFields("Local Cost"). _
        StandardFormula = "='Value ($USD)'/ " & Range("ExchangeRate")
End Sub

Or if you have the ability to use PowerPivot, you could use Rob Collie's Disconnected Slicer trick.


问:
How do I drop a file from a branch and go back to the trunk version?
I have an SVN branch that has files with committed modifications on it.
We've now decided that some of these modifications are not required.

How do I effectively discard all the changes I've made to these files on the branch and get the branch to go back to using the trunk revision of these particular files?

Edit: I should have added that some of the files were new on the branch, but have subsequently been added to trunk by a completely different branch and now I want to use those. I sorted these ones by SVN Deleting them from the branch then using SVN Copy to copy the versions from the trunk - which seems to have worked.

答: Have you tried deleting the file from the branch, and then merge from trunk? You may have to tell it that "mine conflict" (mc) if prompted.</p>


问:
How to use JWT with PHP and MySQL
I finished my designs for the login and signup pages of my app. I am trying to learn how to use JWT library along with PHP and MySQL database to keep a user logged in or assure that he is allowed to take actions in the app. I see that some people use it with firebase.

I searched a lot but can't find how to start.

I am using angular 2 as frontend.

答:
Get a JWT from your PHP backend and save it in the application (in memory or SessionStorage or LocalStorage).

Create a CanActivate implementation that checks the presence of the JWT. If it doesn't find it, it re-routes user to a login page. See https://angular.io/docs/ts/latest/guide/router.html#!#guards

When user clicks a logout button, remove the JWT.

Title: How to use JWT with PHP and MySQL


问:
Is there any tag to know type of road/highway/route in OSRM RouteStep Object?
Context : I am querying OSRM to return route between two co-ordinates. It returns me requested route along with parts(steps) with instructions for route ( Array of RouteStep bjects in v5 ).

http://project-osrm.org/docs/v5.6.4/api/#route-object

What I want : I want to know if there is way to know type of road for any particular RouteStep whether it is a motorway, highway, one way etc.

Any lead is appreciated.

答:
This information is not preserved beyond the initial pre-processing stage. A hack that I have seen some people use for this is to encode additional information in the street name.

For this you would need to modify profiles/car.lua (for example) and something like:

result.name = "{highway: \"" .. data.highway .. "\", name:\"" .. result.name .. "\"}" (disclaimer: I did not run this line in lua).


问:
Unable to connect to git remote repository
After performing git push -u origin master, I got:

fatal: unable to access 'https://github.com/xxxx/xxxx.git': Failed to connect to 127.0.0.1 port 8087: Connection refused
```

Same error occurred, when I tried to clone other repositories, too.

The Port 8087 doesn't seem to be busy. What could go wrong?

Edit:
when I do clone from git:// instead of https://, it works just fine.

答:
This happens because a proxy is configured in git.

Since it's https proxy (and not http) git config http.proxy and git config --global http.proxy can't help.

1 : take a look at your git configuration

```<code>git config --global -l
</code>```

If you have nothing related to https proxy like https_proxy=... the problem is not here.

If you have something related to https proxy then remove it from the file ~/.gitconfig and try again

2 : if it still doesn't work, unset environment variables

Check your environment variables :

```<code>env|grep -i proxy
</code>```

You should have one or several lines with https_proxy=...

Unset one by one with :
unset https_proxy (or HTTPS_PROXY depending of the name of the variable)

3 : check environment variables again

env|grep -i proxy

If it shows nothing you should be good.

Note : This solution can applies to http and https proxy problems. just the variables name changes from https to http

ContentLicense: CC BY-SA 4.0

Body:
After performing git push -u origin master, I got:

fatal: unable to access 'https://github.com/xxxx/xxxx.git': Failed to connect to 127.0.0.1 port 8087: Connection refused

Same error occurred, when I tried to clone other repositories, too.

The Port 8087 doesn't seem to be busy. What could go wrong?

Edit:
when I do clone from git:// instead of https://, it works just fine.

Body:
This happens because a proxy is configured in git.

Since it's https proxy (and not http) git config http.proxy and git config --global http.proxy can't help.

1 : take a look at your git configuration

git config --global -l

If you have nothing related to https proxy like https_proxy=... the problem is not here.

If you have something related to https proxy then remove it from the file ~/.gitconfig and try again

2 : if it still doesn't work, unset environment variables

Check your environment variables :

env|grep -i proxy

You should have one or several lines with https_proxy=...

Unset one by one with :
unset https_proxy (or HTTPS_PROXY depending of the name of the variable)

3 : check environment variables again

env|grep -i proxy

If it shows nothing you should be good.

Note : This solution can applies to http and https proxy problems. just the variables name changes from https to http


问:
Unit Testing Visual Studio Online Selenium ChromeDriver Exception
I use Selenium ChromeDriver in a Unit Test project to test some action on a web page ...

var chromeDriver = new ChromeDriver();
 chromeDriver.Navigate().GoToUrl("https://www.google.com");

Chrome driver has been installed from nuget

Install-Package Selenium.WebDriver.ChromeDriver -Version 2.28.0.

When build my project in Visual Studio Online I receive some error:

System.InvalidOperationException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455520

Any solution to solve this?

答:
In general chrome will be installed in the path - C:\Program Files (x86)\Google\Chrome\Application

So please check for installation path. If chrome is not in that path then uninstall old one and install chrome using link - http://filehippo.com/download_google_chrome/

The below Nuget packages should be installed

selenium.webdriver

selenium.webdriver.chromedriver

The below code will open chrome and navigate to google page

```<code>using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Chrome;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://google.com");
        }
    }
}
</code>```

Body:
In general chrome will be installed in the path - C:\Program Files (x86)\Google\Chrome\Application

So please check for installation path. If chrome is not in that path then uninstall old one and install chrome using link - http://filehippo.com/download_google_chrome/

The below Nuget packages should be installed

selenium.webdriver

selenium.webdriver.chromedriver

The below code will open chrome and navigate to google page

using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Chrome;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://google.com");
        }
    }
}


问:
What is the relationship between a thread and its parent stack?
pthreads all have their own stack and share the heap. They inherit various aspects of the parent at creation time (sig masks, fpenv etc.). There seems to be little said about the relationship between the child thread and the parents stack.

So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work? Is the child thread able to see the stack of the parent process? Does the childs stack get populated with a copy of the parent stack at creation time?

It's useful to me to know what is guaranteed by the standard and what practically works.

答:
So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work? Is the child thread able to see the stack of the parent process?

Practically yes. Pretty much every pthreads implementation out there supports it. Provided the "parent" thread doesn't complete before the newly created thread which might still be using the stack address(es) from the parent, this is fine. But the standard doesn't actually require it. Passing a stack address (address of an automatic variable) from the "parent" thread to the newly created thread is said as implementation defined. So, to be absolutely sure, you'd need to dynamically allocate (with malloc & friends) and pass it the pthread_create().

Does the childs stack get populated with a copy of the parent stack at creation time?

This is again implementation-defined. A new thread can be created by copying the parent stack or a separate stack is allocated. Either would be valid and there are no requirements to do it one way or other.

See the rationale section of [pthread_create()]1 for a relevant information.


问:
Can not find mi_fifo.so and mi_rpc.so files while install Kamailio on Sierra
I try to start kamailio on Sierra OS. When I run kamailio with "/usr/local/sbin/kamailio -c" I get this error:

```<code> 0(49276) ERROR: <core> [core/sr_module.c:571]: load_module(): could not find module <mi_fifo> in </usr/local/lib64/kamailio/modules/>
 0(49276) CRITICAL: <core> [core/cfg.y:3401]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 219, column 12-23: failed to load module
 0(49276) ERROR: <core> [core/sr_module.c:571]: load_module(): could not find module <mi_rpc> in </usr/local/lib64/kamailio/modules/>
 0(49276) CRITICAL: <core> [core/cfg.y:3401]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 236, column 12-22: failed to load module
 0(49276) ERROR: <core> [core/modparam.c:152]: set_mod_param_regex(): No module matching <mi_fifo> found
 0(49276) CRITICAL: <core> [core/cfg.y:3404]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 290, column 54: Can't set module parameter
ERROR: bad config file (3 errors)
 0(49276) INFO: <core> [core/sctp_core.c:53]: sctp_core_destroy(): SCTP API not initialized
</code>```

When I open /usr/local/lib64/kamailio/modules/ there are no mi_fifo.so and no mi_rpc.so files. Where can I get these files?

答:
I guess you are running Kamailio v5.0.x. Starting with v5.0.0, the Management Interface (MI) was removed, being marked as deprecated for several years. With it, all modules prefixed with mi_ have been removed.

The RPC Interface has to be used now. To get the equivalent of FIFO or Datagram Socket for controlling Kamailio, you have to use jsonrpcs module.

In short, remove the lines related to loading mi_fifo and mi_rpc (respectively loadmodule and modparam lines) and load jsronrpcs.

More details about what needs to be done when upgrading from Kamailio v4.4 to v5.0 are listed at:

https://www.kamailio.org/wiki/install/upgrade/4.4.x-to-5.0.0

Body:
I try to start kamailio on Sierra OS. When I run kamailio with "/usr/local/sbin/kamailio -c" I get this error:

 0(49276) ERROR: <core> [core/sr_module.c:571]: load_module(): could not find module <mi_fifo> in </usr/local/lib64/kamailio/modules/>
 0(49276) CRITICAL: <core> [core/cfg.y:3401]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 219, column 12-23: failed to load module
 0(49276) ERROR: <core> [core/sr_module.c:571]: load_module(): could not find module <mi_rpc> in </usr/local/lib64/kamailio/modules/>
 0(49276) CRITICAL: <core> [core/cfg.y:3401]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 236, column 12-22: failed to load module
 0(49276) ERROR: <core> [core/modparam.c:152]: set_mod_param_regex(): No module matching <mi_fifo> found
 0(49276) CRITICAL: <core> [core/cfg.y:3404]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 290, column 54: Can't set module parameter
ERROR: bad config file (3 errors)
 0(49276) INFO: <core> [core/sctp_core.c:53]: sctp_core_destroy(): SCTP API not initialized

When I open /usr/local/lib64/kamailio/modules/ there are no mi_fifo.so and no mi_rpc.so files. Where can I get these files?


问:
How to convert an Int32 array pointer to an Int8_t array pointer?
Any idea.
I tried this:

```<code>int *p = (int*)malloc(N*sizeof(int));
...//set the value of p
int8_t *q = reinterpret_cast<int8_t *>(p);
</code>```

But it doesn't work. I want to get the result q to be
continuous. But the result shows that, if p has 4 elements:{1,2,3,4,5,6,7,8}, Then q would be {1,0,0,0,2,0,0,0}

答:
Your code doesn't act as you expect because reinterpret_cast won't change those ints into int8_ts, it'll just reinterpret the value representation of the ints as bytes. Instead of using malloc and reinterpret_cast you should use std::vector:

```<code>//create an int vector of size N
std::vector<int> p (N);

//copy p contents into a vector of int8_t
std::vector<int8_t> q {p.begin(), p.end()};
</code>```

Then if you really need a int8_t you can use q.data(), but it's far preferable to just use the vector or iterators to it instead of raw pointers.

Body:
Any idea.
I tried this:

int *p = (int*)malloc(N*sizeof(int));
...//set the value of p
int8_t *q = reinterpret_cast<int8_t *>(p);

But it doesn't work. I want to get the result q to be
continuous. But the result shows that, if p has 4 elements:{1,2,3,4,5,6,7,8}, Then q would be {1,0,0,0,2,0,0,0}

Body:
Your code doesn't act as you expect because reinterpret_cast won't change those ints into int8_ts, it'll just reinterpret the value representation of the ints as bytes. Instead of using malloc and reinterpret_cast you should use std::vector:

//create an int vector of size N
std::vector<int> p (N);

//copy p contents into a vector of int8_t
std::vector<int8_t> q {p.begin(), p.end()};

Then if you really need a int8_t you can use q.data(), but it's far preferable to just use the vector or iterators to it instead of raw pointers.


问:
ServletActionContext getAction method returns null
I am using a servlet filter where I am trying to get the action associated with the current request.

Relevant sections of my filter:

```<code>private ServletContext context;

public void init(FilterConfig config) throws ServletException {
    this.context = config.getServletContext();
}

protected void doFilter(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    ServletActionContext actionContext = new ServletActionContext(context, request, response);

    Action action = actionContext.getAction();
    // action == null

}
</code>```

My problem is that action ends up being null. Both of the context variables get populated with a value, but for some reason it cant find the action. Any ideas? Thanks!

答:
ServletActionContext are initialised and all required variable are filled properly when control pass through ActionServlet.

Filter are executed before ActionServlet and and Creating object in filter method doesnt set Action

That is the main reason because of that some getter method of ServletActionContext returns null values because it doesn't gone through ActionServlet and hence all properties are not initialised.

Body:
I am using a servlet filter where I am trying to get the action associated with the current request.

Relevant sections of my filter:

private ServletContext context;

public void init(FilterConfig config) throws ServletException {
    this.context = config.getServletContext();
}

protected void doFilter(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    ServletActionContext actionContext = new ServletActionContext(context, request, response);

    Action action = actionContext.getAction();
    // action == null

}

My problem is that action ends up being null. Both of the context variables get populated with a value, but for some reason it cant find the action. Any ideas? Thanks!


答: Recreate the debug and\or release folder structure in the same folder as your "main" one.  Any files placed here will replace the ones in main depending on the build type.