问:
Why global variable is different from local variable in this function?
Here I have a function named max(a,b) to get the max number out of two.
And I found that the value of variable a and b using printf()  are different after executing

```<code>printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);
</code>```

when a and b are Global variables and Local variables. Below is my code:

```<code>#include<stdio.h>

int max(int a,int b)
{

    if(a>b)
    {
        //printf("In func max():%d %d \n",a,b);
        return a;
    }
    else {
        //printf("In func max():%d %d \n",a,b);
        return b;
    }

}
void jubu_test(void)
{
    int a=1;
    int b=2;
    printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);  //a=2,b=3
}
int c=2;
int d=1;
void quanju_test(void)
{
    printf("maxcd()=%d  c=%d d=%d \n",max(c++,d++),c,d);    //c=2,d=1
    c=2;
    d=1;
    int f=max(c++,d++);
    printf("maxcd()=%d after max: c=%d d=%d \n",f,c,d);     //c=3,d=2
}
int main(int argc, char** argv)
{
    jubu_test();
    quanju_test();
}
</code>```

The result I get on my computer is:

```<code>maxab()=2 after max: a=2 b=3
maxcd()=2  c=2 d=1
maxcd()=2 after max: c=3 d=2
</code>```

My question is: Why in the second output a and b is their original value and why the third output is a+1 and b+1? Why when a and b are Global variables, the value of a and b printed out only changes when we execute max(a++,b++) first? Why when a and b are local variables it doesn't matter?

Thanks!
(using gcc 5.3.0 on windows 10)

答: As I believe, it has nothing to do with the scope of the variables. C does not specify the exact order of the evaluation of function arguments. So, this is unspecified behaviour.</p>

Body:
Here I have a function named max(a,b) to get the max number out of two.
And I found that the value of variable a and b using printf()  are different after executing

printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);

when a and b are Global variables and Local variables. Below is my code:

#include<stdio.h>

int max(int a,int b)
{

    if(a>b)
    {
        //printf("In func max():%d %d \n",a,b);
        return a;
    }
    else {
        //printf("In func max():%d %d \n",a,b);
        return b;
    }

}
void jubu_test(void)
{
    int a=1;
    int b=2;
    printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);  //a=2,b=3
}
int c=2;
int d=1;
void quanju_test(void)
{
    printf("maxcd()=%d  c=%d d=%d \n",max(c++,d++),c,d);    //c=2,d=1
    c=2;
    d=1;
    int f=max(c++,d++);
    printf("maxcd()=%d after max: c=%d d=%d \n",f,c,d);     //c=3,d=2
}
int main(int argc, char** argv)
{
    jubu_test();
    quanju_test();
}

The result I get on my computer is:

maxab()=2 after max: a=2 b=3
maxcd()=2  c=2 d=1
maxcd()=2 after max: c=3 d=2

My question is: Why in the second output a and b is their original value and why the third output is a+1 and b+1? Why when a and b are Global variables, the value of a and b printed out only changes when we execute max(a++,b++) first? Why when a and b are local variables it doesn't matter?

Thanks!
(using gcc 5.3.0 on windows 10)


来源: stackexchange

问:
How to access lotusscript variable in button action formula?
In a view I have created a checkbox action button. The action button shows/hides the checkbox based on the formula I have set:

@If( AAAR = True; @True; @False )

I declared the variable AAAR under the view's declaration section like this:

Dim AAAR As Boolean

Now this flag is set in the OnSelect event so that whenever users clicks/selects a document from the view, this event triggers:

Sub Onselect(Source As Notesuiview)

```<code>Dim ws As New NotesUIWorkspace
Dim session As New NotesSession
Dim db As NotesDatabase
Dim uiview As NotesUIView
Dim doc As NotesDocument

Set db = session.CurrentDatabase
Set uiview = ws.CurrentView
Set doc = db.GetDocumentByID(uiview.CaretNoteID)

If doc.GetItemValue("AllotmentApprovalReq")(0) = "Yes"  Then
    AAAR = True
Else
    AAAR = False
End If
</code>```

End Sub

Now the problem is that, i want the checkbox menu should change its status (checkbox / no checkbox) based on this value AAAR. I have to do 'something' in
the OnSelect event but i don't know how to access and set the checkbox menu from there. Please help.

答:
Wow, this is a total mess: First of all: @Formulas variables and LotusScript- Variables have nothing to do with each other. In @Formula whenever you write a variable name it is always one of the following two:

An item with that name in the document that is currently in focus (an open document or the document under the cursor in a view). Beware: Actions are NOT automatically recalulated when you select another document, you need to enable the action bar properties of the view to update on focus change

A variable from earlier in the same formula

If your example is right, then the formula in your action button would simply be:

@If( AllotmentApprovalReq = "Yes"; @True; @False )

No need of any code in Onselect at all...

But again: You need to set the view action bar to recalculate on every focus change.

ContentLicense: CC BY-SA 3.0

Body:
In a view I have created a checkbox action button. The action button shows/hides the checkbox based on the formula I have set:

@If( AAAR = True; @True; @False )

I declared the variable AAAR under the view's declaration section like this:

Dim AAAR As Boolean

Now this flag is set in the OnSelect event so that whenever users clicks/selects a document from the view, this event triggers:

Sub Onselect(Source As Notesuiview)

Dim ws As New NotesUIWorkspace
Dim session As New NotesSession
Dim db As NotesDatabase
Dim uiview As NotesUIView
Dim doc As NotesDocument

Set db = session.CurrentDatabase
Set uiview = ws.CurrentView
Set doc = db.GetDocumentByID(uiview.CaretNoteID)

If doc.GetItemValue("AllotmentApprovalReq")(0) = "Yes"  Then
    AAAR = True
Else
    AAAR = False
End If

End Sub

Now the problem is that, i want the checkbox menu should change its status (checkbox / no checkbox) based on this value AAAR. I have to do 'something' in
the OnSelect event but i don't know how to access and set the checkbox menu from there. Please help.


问:
Creating and naming a new file according to a string - gulp
Total newbie in Gulp, really would like some assistance..

I am trying to name & create a new file using a string that exist in another file. this will give me the name of the white label that was deployed onto the server.

The content of the file that holds the string is (among other things) {"TITLE":"name_env"}

name_env should be the new name of the file with the suffix of .web
meaning that the new file would be like this name_env.web

What I've came up until now was:

```<code>    gulp.task('label', function () {
       var str = require('path/to/file/file.json')

       return file('label', str, {src: true})
             .pipe(gulp.dest('build/'))
        });
</code>```

Am I on the right track ?

Hopefully I've managed to explain myself..

答:
Here's gulp file which will do your task(assuming there's dist folder already exist!!)</p>

```<code>var gulp = require('gulp');
var fs = require('fs');

gulp.task('label', function() {
  var buffer = JSON.parse(fs.readFileSync('path/to/file.json', 'utf8'));
  return fs.writeFile('dist/' + buffer['TITLE'] + '.web' , buffer, { flag: 'wx' }, function(err) {
            if (err) throw err;
            console.log("It's saved!");
         });
});
</code>```

Body:
Total newbie in Gulp, really would like some assistance..

I am trying to name & create a new file using a string that exist in another file. this will give me the name of the white label that was deployed onto the server.

The content of the file that holds the string is (among other things) {"TITLE":"name_env"}

name_env should be the new name of the file with the suffix of .web
meaning that the new file would be like this name_env.web

What I've came up until now was:

    gulp.task('label', function () {
       var str = require('path/to/file/file.json')

       return file('label', str, {src: true})
             .pipe(gulp.dest('build/'))
        });

Am I on the right track ?

Hopefully I've managed to explain myself..

Body:
Here's gulp file which will do your task(assuming there's dist folder already exist!!)

var gulp = require('gulp');
var fs = require('fs');

gulp.task('label', function() {
  var buffer = JSON.parse(fs.readFileSync('path/to/file.json', 'utf8'));
  return fs.writeFile('dist/' + buffer['TITLE'] + '.web' , buffer, { flag: 'wx' }, function(err) {
            if (err) throw err;
            console.log("It's saved!");
         });
});


问:
How to inflate view in list view for odd and even position
How to inflate view in list view for odd and even position.I want to show left align xml in even position and right align xml to odd position.

```<code>This is my code:

 public View getView(final int position, View view, ViewGroup parent)
{
    LayoutInflater inflator = context.getLayoutInflater();
    if ((position % 2) == 0) {

         rowView = inflator.inflate(R.layout.chatbubble, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);
    }
    else {
        rowView1 = inflator.inflate(R.layout.chatbubble1, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView1.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);

    }

    return rowView;
}
</code>```

but for all position my data items are left align .

```<code>This is my xml  :
for left :
     <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/bubble_layout_parent"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      android:layout_margin="10dp"
       android:padding="5dp">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
   </LinearLayout>

  </LinearLayout>

  for right :
      <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/bubble_layout_parent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:padding="5dp"
      android:layout_gravity="right">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
       </LinearLayout>

       </LinearLayout>
</code>```

I am new to android development please help.

答:
You need to override these two base adapter methods

```<code>@Override
public int getViewTypeCount() {
  return 2;
}

@Override
public int getItemViewType(int position) {
  //return 0 or 1 according to your view
}
</code>```

and in getView()

```<code>int type = getItemViewType(position);
</code>```

and inflate your view according to type.
you can follow this simplifies example as well.

Body:
How to inflate view in list view for odd and even position.I want to show left align xml in even position and right align xml to odd position.

This is my code:

 public View getView(final int position, View view, ViewGroup parent)
{
    LayoutInflater inflator = context.getLayoutInflater();
    if ((position % 2) == 0) {

         rowView = inflator.inflate(R.layout.chatbubble, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);
    }
    else {
        rowView1 = inflator.inflate(R.layout.chatbubble1, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView1.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);

    }

    return rowView;
}

but for all position my data items are left align .

This is my xml  :
for left :
     <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/bubble_layout_parent"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      android:layout_margin="10dp"
       android:padding="5dp">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
   </LinearLayout>

  </LinearLayout>

  for right :
      <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/bubble_layout_parent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:padding="5dp"
      android:layout_gravity="right">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
       </LinearLayout>

       </LinearLayout>

I am new to android development please help.

Body:
You need to override these two base adapter methods

@Override
public int getViewTypeCount() {
  return 2;
}

@Override
public int getItemViewType(int position) {
  //return 0 or 1 according to your view
}

and in getView()

int type = getItemViewType(position);

and inflate your view according to type.
you can follow this simplifies example as well.


问:
Is it correct to attach code through volume in kubernetes?
In order to do ease development in Docker, the code is attached to the containers through volumes. In that way, there is no need to rebuild the images each time the code is changed.

So, is it correct to think to use the same idea in Kubernetes?

PS: I know that the concepts PersistentVolume and PersistentVolumeClaim allow to attach volume, but they are intended for data.

Update

To ease the development, I do need to use the volume for both code and data. This will avoid me to rebuild the images at each change of code.

Below this is what I am trying to do in minikube:

the deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: '/home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/'
</code>```

the service

```<code>apiVersion: v1
kind: Service
metadata:
  name: php-hostpath
  namespace: default
  labels:
    app: php-hostpath
spec:
  selector:
    app: php-hostpath
  ports:
  - port: 80
    targetPort: 80
  type: "LoadBalancer"
</code>```

The service and the deployment are well created in minikube:

```<code>$ kubectl get pods -l app=php-hostpath
NAME                            READY     STATUS    RESTARTS   AGE
php-hostpath-3796606162-bt94w   1/1       Running   0          19m

$ kubectl get service -l app=php-hostpath
NAME           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
php-hostpath   10.0.0.110   <pending>     80:30135/TCP   27m
</code>```

The folder src and the file src/index.php are also well created.

```<code><?php
echo "This is my first docker project";
</code>```

Now I want to check that every thing is running:

```<code>$ kubectl exec -ti php-hostpath-3796606162-bt94w bash
root@php-hostpath-3796606162-bt94w:/var/www/html# ls
root@php-hostpath-3796606162-bt94w:/var/www/html# exit
exit
</code>```

The folder src and the file index.php are not in /var/www/html!

Have I missed something?

PS: if I were in production env, I will not put my code in a volume.
Thanks,

答:
There is hostPath that allows you to bind mount a directory on the node into the a container.

In a multi node cluster you will want to restrict your dev pod to a particular node with nodeSelector (use the built-in label kubernetes.io/hostname: mydevhost).

With minikube look at the Mounted Host Folders section.

Body:
In order to do ease development in Docker, the code is attached to the containers through volumes. In that way, there is no need to rebuild the images each time the code is changed.

So, is it correct to think to use the same idea in Kubernetes?

PS: I know that the concepts PersistentVolume and PersistentVolumeClaim allow to attach volume, but they are intended for data.

Update

To ease the development, I do need to use the volume for both code and data. This will avoid me to rebuild the images at each change of code.

Below this is what I am trying to do in minikube:

the deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: '/home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/'

the service

apiVersion: v1
kind: Service
metadata:
  name: php-hostpath
  namespace: default
  labels:
    app: php-hostpath
spec:
  selector:
    app: php-hostpath
  ports:
  - port: 80
    targetPort: 80
  type: "LoadBalancer"

The service and the deployment are well created in minikube:

$ kubectl get pods -l app=php-hostpath
NAME                            READY     STATUS    RESTARTS   AGE
php-hostpath-3796606162-bt94w   1/1       Running   0          19m

$ kubectl get service -l app=php-hostpath
NAME           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
php-hostpath   10.0.0.110   <pending>     80:30135/TCP   27m

The folder src and the file src/index.php are also well created.

<?php
echo "This is my first docker project";

Now I want to check that every thing is running:

$ kubectl exec -ti php-hostpath-3796606162-bt94w bash
root@php-hostpath-3796606162-bt94w:/var/www/html# ls
root@php-hostpath-3796606162-bt94w:/var/www/html# exit
exit

The folder src and the file index.php are not in /var/www/html!

Have I missed something?

PS: if I were in production env, I will not put my code in a volume.
Thanks,


问:
HTML5 Input type datetime-local takes min-width in Table td
When I put HTML5 Input type "datetime-local" in a Table td, it takes some min-width and becomes non responsive when we adjust the screen size. Here is my code

```<code>    <div class="container">
    <table class="table table-bordered table-striped table-responsive table-hover">
        <tbody>
            <tr>
                <td><input type="text" class="form-control" value="Sample" /></td>
                <td><input type="datetime-local" class="form-control"  value=""/></td>
                <td><input type="datetime-local"  class="form-control"  value=""/></td>
                <td><input type="text" class="form-control" value="Sample" /></td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

But when I put the same control in Div it is responsive and works fine.

```<code><div class="container" style="margin-top:10px">
    <div class="row">
        <div class="col-xs-1">
            <input type="text" class="form-control" value="Sample" />
        </div>
        <div class="col-xs-5">
            <input type="datetime-local" class="form-control" value="" />
        </div>
        <div class="col-xs-5">
            <input type="datetime-local" class="form-control" value="" />
        </div>
        <div class="col-xs-1">
            <input type="text" class="form-control" value="Sample" />
        </div>
    </div>
</code>```

But I want to use the Table. How can I use HTML5 Input type "datetime-local "control in Table and be responsive?

答:
Add one more

 inside container you can solve this problem...........

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

            <input type="text" class="form-control" value="Sample" />

            <input type="datetime-local" class="form-control" value="" />

            <input type="datetime-local" class="form-control" value="" />

            <input type="text" class="form-control" value="Sample" />

```

Body:
When I put HTML5 Input type "datetime-local" in a Table td, it takes some min-width and becomes non responsive when we adjust the screen size. Here is my code

                <input type="text" class="form-control" value="Sample" />
                <input type="datetime-local" class="form-control"  value=""/>
                <input type="datetime-local"  class="form-control"  value=""/>
                <input type="text" class="form-control" value="Sample" />

But when I put the same control in Div it is responsive and works fine.

            <input type="text" class="form-control" value="Sample" />

            <input type="datetime-local" class="form-control" value="" />

            <input type="datetime-local" class="form-control" value="" />

            <input type="text" class="form-control" value="Sample" />

But I want to use the Table. How can I use HTML5 Input type "datetime-local "control in Table and be responsive?

Body:
Add one more <div class="table-responsive"></div> inside container you can solve this problem...........

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="table-responsive">
    <table class="table table-bordered table-striped table-hover">
      <tbody>
        <tr>
          <td>
            <input type="text" class="form-control" value="Sample" />
          </td>
          <td>
            <input type="datetime-local" class="form-control" value="" />
          </td>
          <td>
            <input type="datetime-local" class="form-control" value="" />
          </td>
          <td>
            <input type="text" class="form-control" value="Sample" />
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>


问:
UWP: Have page wait until user is done with a User Control
I am writing code that asks the user to select an employee and type in the employee's password before continuing their action. I made the Employee Selection segment a user control so I can attach the segment to the pages that needs it. I also would like the page to pause when the user control is up and to continue where it left off when the user has selected an employee. Is there are way to force the code the pause at any moment?</p>

答:
I suggest to use a ContentDialog instead of UserControl, and it will block MainPage. But keep in mind that await dialog.ShowAsync()  won't block the UI.

If you need to "Pause" OnNavigatedFrom() event you can look on Template10 page events , they added possibility to wait untill job is finished then navigate from current page.

EDIT

You could also can add a flag into your usercontrol so you can add a check and cancel navigation from page untill _myUserControl.CanNavigateFrom()


问:
jQuery + Bootstrap Navigation Bar - How to highlight the link when visited
Please visit this link.

Try to click "Portfolio" link, it should be highlighted with blue background.

But after clicking outside the navigation bar it will be highlighted with blue.

```<code>    //scrolling
$('nav a').on('click', function() {

    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top;

    $('body,html').animate({
        scrollTop: scrollPoint
    }, 500);

    return false;

});

//change color
$(window).scroll(function() {
    var windscroll = $(window).scrollTop();
    if (windscroll) {
        $('section').each(function(i) {
            if ($(this).position().top <= windscroll) {
                $('nav a.active').removeClass('active');
                $('nav a').eq(i).addClass('active');
            }
        });

    }
}).scroll();
</code>```

答:
Try this</p>

```<code>nav a.active,
nav a.active:hover {
  background-color: blue !important;
}
</code>```

Body:
Please visit this link.

Try to click "Portfolio" link, it should be highlighted with blue background.

But after clicking outside the navigation bar it will be highlighted with blue.

    //scrolling
$('nav a').on('click', function() {

    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top;

    $('body,html').animate({
        scrollTop: scrollPoint
    }, 500);

    return false;

});

//change color
$(window).scroll(function() {
    var windscroll = $(window).scrollTop();
    if (windscroll) {
        $('section').each(function(i) {
            if ($(this).position().top <= windscroll) {
                $('nav a.active').removeClass('active');
                $('nav a').eq(i).addClass('active');
            }
        });

    }
}).scroll();

Body:
Try this

nav a.active,
nav a.active:hover {
  background-color: blue !important;
}


问:
How to run this form .change() on load?
I have created a script that dynamically updates the query based on filters (what user has chosen in the form) and loads the external php file with updated data, but I want to make the change function load when page is loaded.

The query is updated successfully when user changes any input and the external results are loaded. I want however to load the results when page is loaded and not wait for user input.

I have managed to make the form updates what the user has selected by storing cookies, still not sure how to make it load when he visits the page. I tried to add .trigger('change') at the end of $(".QueryElement").change(function() but I get inconsistent results, it does not work.

This is my code:

```<code><script type="text/javascript">
$(function() {

    /*
    * Retrieve cookies in form
    */
    $("#showposts").val($.cookie('deluxe-' + 'numposts'));

    $(".tags, .categories, #show-all-tags, #show-all-cats").each(function() {
        if ($.cookie('deluxe-' + $(this).attr('id')) == 'checked') {
            $(this).attr('checked', true);
        }
        if ($.cookie('deluxe-' + $(this).attr('id')) == 'unchecked') {
            $(this).attr('checked', false);
        }
    });

    /*
    * This function is to add filters
    */
    $(".QueryElement").change(function() {

        var query = '';
        $.cookie('deluxe-form-state', 'activated', { path: '/', expires: 100 });

        query += "showposts=" + $("#showposts").val();
        $.cookie('deluxe-' + 'numposts', $("#showposts").val(), { path: '/', expires: 100 });

        function add_filters(showall, maincls, type) {
            if ($(showall).is(":checked") == false) {
            $.cookie('deluxe-' + $(showall).attr('id'), 'unchecked', { path: '/', expires: 100 });
            var val = [];
            $(maincls + ':checked').each(function(i){
            val[i] = $(this).attr('id');
            $.cookie('deluxe-' + $(this).attr('id'), 'checked', { path: '/', expires: 100 });
            });
            $(maincls + ':not(:checked)').each(function(i){
            $.cookie('deluxe-' + $(this).attr('id'), 'unchecked', { path: '/', expires: 100 });
            });
            query += "&" + type + "=" + val;
            } else {
            $.cookie('deluxe-' + $(showall).attr('id'), 'checked', { path: '/', expires: 100 });
            $(maincls + ':checked').each(function(i){
            $.cookie('deluxe-' + $(this).attr('id'), 'checked', { path: '/', expires: 100 });
            });
            $(maincls + ':not(:checked)').each(function(i){
            $.cookie('deluxe-' + $(this).attr('id'), 'unchecked', { path: '/', expires: 100 });
            });
            query += "&" + type + "=";
            }
        }

        add_filters('.show-all-cats', '.categories', 'cat');
        add_filters('.show-all-tags', '.tags', 'tag');

        $("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + query);

    });

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

And this is my queryform if you need it.

```<code><?php

########################################
# showposts=
########################################

echo '<select id="showposts" class="QueryElement">';
    for ($i = 5; $i <= 50; $i += 5) {
        echo '<option value="'.$i.'">'.$i.'</option>';
    }
echo '</select>';

########################################
# cat=
########################################

$categories = get_categories();
foreach($categories as $cat) {
    echo '<input type="checkbox" name="'.$cat->cat_ID.'" id="'.$cat->cat_ID.'" class="categories QueryElement" /> '.$cat->cat_name;
}
    echo '<input type="checkbox" name="show-all-cats" id="show-all-cats" class="QueryElement show-all-cats" checked="checked"> Include all categories';

########################################
# tag=
########################################

$tags = get_tags();
foreach($tags as $tag) {
    echo '<input type="checkbox" name="'.$tag->slug.'" id="'.$tag->slug.'" class="tags QueryElement" /> '.$tag->name;
}
    echo '<input type="checkbox" name="show-all-tags" id="show-all-tags" class="QueryElement show-all-tags" checked="checked"> Include all tags';

?>
</code>```

Edit: trigger at the end of function works but for first time load only, i get incosistent changes when the user updates the form when the page is loaded. The form is supposed to act as content filter, and the external file is supposted to act as content results filtered by the form.

答:
Abstracting the change function should do the trick.

```<code>getData();
$('el').change(getData);

function getData(){
  //.change function here
}
</code>```

or

An event trigger should work.

```<code>$('el').trigger('change');
</code>```

jquery docs on .trigger()

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

ContentLicense: CC BY-SA 2.5

Title: How to run this form .change() on load?

Body:
I have created a script that dynamically updates the query based on filters (what user has chosen in the form) and loads the external php file with updated data, but I want to make the change function load when page is loaded.

The query is updated successfully when user changes any input and the external results are loaded. I want however to load the results when page is loaded and not wait for user input.

I have managed to make the form updates what the user has selected by storing cookies, still not sure how to make it load when he visits the page. I tried to add .trigger('change') at the end of $(".QueryElement").change(function() but I get inconsistent results, it does not work.

This is my code:

And this is my queryform if you need it.

<?php

########################################
# showposts=
########################################

echo '<select id="showposts" class="QueryElement">';
    for ($i = 5; $i <= 50; $i += 5) {
        echo '<option value="'.$i.'">'.$i.'</option>';
    }
echo '</select>';

########################################
# cat=
########################################

$categories = get_categories();
foreach($categories as $cat) {
    echo '<input type="checkbox" name="'.$cat->cat_ID.'" id="'.$cat->cat_ID.'" class="categories QueryElement" /> '.$cat->cat_name;
}
    echo '<input type="checkbox" name="show-all-cats" id="show-all-cats" class="QueryElement show-all-cats" checked="checked"> Include all categories';

########################################
# tag=
########################################

$tags = get_tags();
foreach($tags as $tag) {
    echo '<input type="checkbox" name="'.$tag->slug.'" id="'.$tag->slug.'" class="tags QueryElement" /> '.$tag->name;
}
    echo '<input type="checkbox" name="show-all-tags" id="show-all-tags" class="QueryElement show-all-tags" checked="checked"> Include all tags';

?>

Edit: trigger at the end of function works but for first time load only, i get incosistent changes when the user updates the form when the page is loaded. The form is supposed to act as content filter, and the external file is supposted to act as content results filtered by the form.

Body:
Abstracting the change function should do the trick.

getData();
$('el').change(getData);

function getData(){
  //.change function here
}

or

An event trigger should work.

$('el').trigger('change');

jquery docs on .trigger()

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.


问:
MSBuild folder not included after installing Visual Studio
I installed Visual Studio 2015 program using a default installation.
Later, I installed WDK 10 and SDK 10.0.14393.795 separately.

I have to place two configuration files in the attached path shown below but I cannot find it:
C:\Users\user_name\AppData\Local\Microsoft\MSBuild\v4.0

How can I fix that problem?
The system is Windows 7 64-bits

Best regards,
R. Ferreiro

答:
Finally, after performing several tests I solved the problem.
Firtsly, I updated my operating system with the latest updates.
Then, I installed Visual Studio 15, SDK and WDK 10 separately.

Solution: When Visual Studio is installed, open it the first time and the required MSBuild folder will be created.

Thank you for your help,
R. Ferreiro


问:
Inline assembler causes freezing inside of another function
I've noticed that when using my inline assembly code is either incredibly slow or stops compared to my C++ code which finishes very quickly. I'm curious as to why to happens when I call upon the inline assembler in a different function as opposed to having the assembler where the function was called. I tested both ways and found that my program did not freeze when omitting the function.

```<code>    __asm {

    push dword ptr[rw] //rw is a C++ floating-point variable
    fld[esp] // Using the stack as temporary storage in order to insert it into the FPU
    add esp, 4 //preserving the memory

    push dword ptr[lwB]
    fld[esp]
    add esp, 4

    fsubp ST(1), ST(0) // Subtracting rw - lwB

    push dword ptr[sp]
    fld[esp]
    add esp, 4

    fdivp ST(1), ST(0) // Dividing previous resultant by span -> (rw - lwB) / sp

    push dword ptr[dimen]
    fld[esp]
    add esp, 4

    fmulp ST(1), ST(0) // Multiplying previous resultant by dimension > ((rw - lwB) / (sp)* dimen)

    sub esp, 4 // Allocating space in order to save result temporarily to ram then to eax then to a C++ variable
    fstp[esp]
    pop eax
    mov fCord, eax

    }
    return (int)fCord; //fCord is also a floating-point C++ variable
</code>```

The much faster C++ Code:

```<code>    return (int)(((rw - lwB) / (sp)* dimen));
</code>```

答:
Thanks all, I had a pretty strange issue but it might just be common. I had an inline assembler in a different function and called upon it for calculations. After moving this function into where it was called instead, I have fixed the issue. I'm sure there is a bigger lesson at hand though.

Obviously, the code is inefficient and the comments/answers are helpful in general, although my problem was a bit different.

For anybody wondering, here is the optimal assembly code that the compiler built:

```<code>float finCord;
 __asm {
    movss       xmm0, dword ptr[rw]
    subss       xmm0, dword ptr[lwB]
    divss       xmm0, dword ptr[sp]
    mulss       xmm0, dword ptr[dimen]
    movss         dword ptr[fCord],xmm0
    }
int answer = (int)finCord;
</code>```

Body:
I've noticed that when using my inline assembly code is either incredibly slow or stops compared to my C++ code which finishes very quickly. I'm curious as to why to happens when I call upon the inline assembler in a different function as opposed to having the assembler where the function was called. I tested both ways and found that my program did not freeze when omitting the function.

    __asm {

    push dword ptr[rw] //rw is a C++ floating-point variable
    fld[esp] // Using the stack as temporary storage in order to insert it into the FPU
    add esp, 4 //preserving the memory

    push dword ptr[lwB]
    fld[esp]
    add esp, 4

    fsubp ST(1), ST(0) // Subtracting rw - lwB

    push dword ptr[sp]
    fld[esp]
    add esp, 4

    fdivp ST(1), ST(0) // Dividing previous resultant by span -> (rw - lwB) / sp

    push dword ptr[dimen]
    fld[esp]
    add esp, 4

    fmulp ST(1), ST(0) // Multiplying previous resultant by dimension > ((rw - lwB) / (sp)* dimen)

    sub esp, 4 // Allocating space in order to save result temporarily to ram then to eax then to a C++ variable
    fstp[esp]
    pop eax
    mov fCord, eax

    }
    return (int)fCord; //fCord is also a floating-point C++ variable

The much faster C++ Code:

    return (int)(((rw - lwB) / (sp)* dimen));

Body:
Thanks all, I had a pretty strange issue but it might just be common. I had an inline assembler in a different function and called upon it for calculations. After moving this function into where it was called instead, I have fixed the issue. I'm sure there is a bigger lesson at hand though.

Obviously, the code is inefficient and the comments/answers are helpful in general, although my problem was a bit different.

For anybody wondering, here is the optimal assembly code that the compiler built:

float finCord;
 __asm {
    movss       xmm0, dword ptr[rw]
    subss       xmm0, dword ptr[lwB]
    divss       xmm0, dword ptr[sp]
    mulss       xmm0, dword ptr[dimen]
    movss         dword ptr[fCord],xmm0
    }
int answer = (int)finCord;


问:
New data is not getting created if it is not present on the autocomplete dropdown on rails app
I am trying to implement jquery autocomplete on a field in rails app. I am following Railscasts video. I have successfully implemented the autocomplete feature. But I am also trying to add new data if it is not present on the autocomplete dropdown. I spent a lot of time on this but not able to overcome this issue. Following is my code:

equipment.rb

```<code>def manufacturer_name
    manufacturer.try(:name)
end

def manufacturer_name=(name)
    self.manufacturer = Manufacturer.find_or_create_by(:name => params[:other][:manufacturer_name], :status => 1)
end
</code>```

js

```<code>$('#equipment_manufacturer_name').autocomplete({
    source: function(req, res) {
    var arraySource = $('#equipment_manufacturer_name').data('autocomplete-source');
    var results = $.ui.autocomplete.filter(arraySource, req.term);
    res(results.slice(0, 10));
    }
});
</code>```

html.erb field

```<code><label for="select">Manufacturer * :</label>
<%= f.text_field :manufacturer_name, data: {autocomplete_source: Manufacturer.order(:name).map(&:name)} %>
</code>```

答:
If you are adding new data using ajax then you have to reload or refresh the autocomplete data.
One more thing it might be adding in the autocomplete list but you mentioned slice(0, 10), check whether this might causing the issue.</p>

Body:
I am trying to implement jquery autocomplete on a field in rails app. I am following Railscasts video. I have successfully implemented the autocomplete feature. But I am also trying to add new data if it is not present on the autocomplete dropdown. I spent a lot of time on this but not able to overcome this issue. Following is my code:

equipment.rb

def manufacturer_name
    manufacturer.try(:name)
end

def manufacturer_name=(name)
    self.manufacturer = Manufacturer.find_or_create_by(:name => params[:other][:manufacturer_name], :status => 1)
end

js

$('#equipment_manufacturer_name').autocomplete({
    source: function(req, res) {
    var arraySource = $('#equipment_manufacturer_name').data('autocomplete-source');
    var results = $.ui.autocomplete.filter(arraySource, req.term);
    res(results.slice(0, 10));
    }
});

html.erb field

Manufacturer * :
<%= f.text_field :manufacturer_name, data: {autocomplete_source: Manufacturer.order(:name).map(&:name)} %>


问:
EmptyThrowable: The APK file *.apk does not exist on disk
This is an Android application using gradle. After clicking Run, I found APP_V1.3.4_2016-02-22_11:30:29_google_play.apk in outputs/apk, but the event log says:

11:30:31 EmptyThrowable: The APK file /.../WorkSpace/Android/.../app/build/outputs/apk/APP_V1.3.4_2016-02-22_11:30:14_google_play.apk does not exist on disk.

11:30:32 Session 'app': Error Installing APK

Here is my build.gradle file:

```<code>apply plugin: 'com.android.application'

def releaseTime() {
    return new Date().format("yyyy-MM-dd_HH:mm:ss",
        TimeZone.getTimeZone("GMT+08:00"))
}

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 29
        versionName "1.3.4"
        manifestPlaceholders = [SOME_CHANNEL_VALUE: "some_channel"]
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    signingConfigs {
        debug {}

        release {
            // ...
        }
    }

    buildTypes {
        debug {
            zipAlignEnabled true
            minifyEnabled false
            shrinkResources true
        }

        release {
            zipAlignEnabled true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                'proguard-rules.pro'
            signingConfig signingConfigs.release

            applicationVariants.all { variant ->

                def time = releaseTime()

                variant.outputs.each { output ->
                    def apk = output.outputFile
                    def endFileName = "${time}_${variant.productFlavors[0].name}.apk"

                    if (apk != null &&
                        apk.name.endsWith('.apk') &&
                        !apk.name.endsWith('${endFileName}')) {
                        def fileName = "APP_V${defaultConfig.versionName}_${endFileName}"
                        output.outputFile = new File(apk.parentFile, fileName)
                    }
                }
            }
        }
    }

    productFlavors {
        google_play {
            manifestPlaceholders = [SOME_CHANNEL_VALUE: "google_play"]
        }
    }
}

dependencies {
    // ...
}
</code>```

So is there any wrong with releaseTime()?

答:
I have tried all the things like

Delete folders app/apks and app//build/outputs/apk previously

SyncGradle and Rebuild Project

lintOptions {
            abortOnError false
        }

but got issue resolved by Clicking on Build>Build APK

Body:
This is an Android application using gradle. After clicking Run, I found APP_V1.3.4_2016-02-22_11:30:29_google_play.apk in outputs/apk, but the event log says:

11:30:31 EmptyThrowable: The APK file /.../WorkSpace/Android/.../app/build/outputs/apk/APP_V1.3.4_2016-02-22_11:30:14_google_play.apk does not exist on disk.

11:30:32 Session 'app': Error Installing APK

Here is my build.gradle file:

apply plugin: 'com.android.application'

def releaseTime() {
    return new Date().format("yyyy-MM-dd_HH:mm:ss",
        TimeZone.getTimeZone("GMT+08:00"))
}

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 29
        versionName "1.3.4"
        manifestPlaceholders = [SOME_CHANNEL_VALUE: "some_channel"]
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    signingConfigs {
        debug {}

        release {
            // ...
        }
    }

    buildTypes {
        debug {
            zipAlignEnabled true
            minifyEnabled false
            shrinkResources true
        }

        release {
            zipAlignEnabled true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                'proguard-rules.pro'
            signingConfig signingConfigs.release

            applicationVariants.all { variant ->

                def time = releaseTime()

                variant.outputs.each { output ->
                    def apk = output.outputFile
                    def endFileName = "${time}_${variant.productFlavors[0].name}.apk"

                    if (apk != null &&
                        apk.name.endsWith('.apk') &&
                        !apk.name.endsWith('${endFileName}')) {
                        def fileName = "APP_V${defaultConfig.versionName}_${endFileName}"
                        output.outputFile = new File(apk.parentFile, fileName)
                    }
                }
            }
        }
    }

    productFlavors {
        google_play {
            manifestPlaceholders = [SOME_CHANNEL_VALUE: "google_play"]
        }
    }
}

dependencies {
    // ...
}

So is there any wrong with releaseTime()?


问:
Correct file path within Spring application
It sounds very odd but last few hours I am trying to write a json file in web app folder in a Spring application from my java class. I have attached snap that may clear the understanding of it. click to Refer the file system snap here..."jsonfiles" is the folder i am writing files marked with red circle. Please suggest the correct file path for json file from java class. Thanks in advance. And also suggest is it a good practice to do it? I am new to this kind of scenario.

Java code that is writing to file:

```<code>FileWriter file = new FileWriter("../src/main/webaccess/jsonfiles/jsonfile.json")){
file.write(json.toString());
}
</code>```

答:
No it's not the right path to place output (JSON in your case) files within webapp folder.

Reason: During deployment you will loose this change, as war file will be extracted and your webapp folder will get over written.

Correct approach: Write to file system outside your tomcat directory. General practise is to define a environment variable pointing to external directory where your application has write permission and write all your contents there. It's similar to writting log files.

Body:
It sounds very odd but last few hours I am trying to write a json file in web app folder in a Spring application from my java class. I have attached snap that may clear the understanding of it. click to Refer the file system snap here..."jsonfiles" is the folder i am writing files marked with red circle. Please suggest the correct file path for json file from java class. Thanks in advance. And also suggest is it a good practice to do it? I am new to this kind of scenario.

Java code that is writing to file:

FileWriter file = new FileWriter("../src/main/webaccess/jsonfiles/jsonfile.json")){
file.write(json.toString());
}


问:
Logging inside Stream
I am trying to convert this piece of code to Java 8 stream:

```<code>if (list != null && !list.isEmpty()) {
    Actor actor = null;
    for (Actor actor : list) {
        log.info("Actor being read: "  actor.getCode());
        List<String> areaList = areaDAO.getArea(actor.getCode());
        if (!areaList.isEmpty()) {
            actor.setArea(areaList.get(0));
            log.info("Area{" + areaList.get(0)
                 + "} is fetched for actor{" + actor.getCode() + "}.");
        }
        this.getContext().setReadCount(1);
    }
}
</code>```

However I am not sure how to deal with logging in this case? Is it a good practice? Appreciate your help. Thanks

答:
Often we put logging into our code to support debugging. In this case I would recommend you to have a look at the peek method.

Here is a hint:

```<code>   List<Actor> actors = ...;

    actors.
        stream().
        peek(a -> System.out.println("Processing code: " + a.getCode())).
        forEach(a -> {/*Do something here*/});
</code>```

From the javadocs:

API Note:
      This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:

ContentLicense: CC BY-SA 4.0

Title: Logging inside Stream

Body:
I am trying to convert this piece of code to Java 8 stream:

if (list != null && !list.isEmpty()) {
    Actor actor = null;
    for (Actor actor : list) {
        log.info("Actor being read: "  actor.getCode());
        List<String> areaList = areaDAO.getArea(actor.getCode());
        if (!areaList.isEmpty()) {
            actor.setArea(areaList.get(0));
            log.info("Area{" + areaList.get(0)
                 + "} is fetched for actor{" + actor.getCode() + "}.");
        }
        this.getContext().setReadCount(1);
    }
}

However I am not sure how to deal with logging in this case? Is it a good practice? Appreciate your help. Thanks

Body:
Often we put logging into our code to support debugging. In this case I would recommend you to have a look at the peek method.

Here is a hint:

   List<Actor> actors = ...;

    actors.
        stream().
        peek(a -> System.out.println("Processing code: " + a.getCode())).
        forEach(a -> {/*Do something here*/});

From the javadocs:

API Note:
      This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:


问:
Repeatedly change UILabel text with UiButton
I have a few questions that I would like to show with a label. When I press the reset button, the next question in the array does not appear. Should I not place the questions in an array in order for the next element in the array to appear?</p>

```<code>func theFirstTwoQuestions() {

    // the questions will be contained in an Array
    // change the question label to one of the array values
    // when I press reset the next question will appear

    //self.questionLabel.text? = "\(questionsOneTwo)"
    questionLabel.isHidden = false
    var arrayQuestions = ["What's your name?", "How old are you", "your favorite color is?"]

    for question in arrayQuestions {

        questionLabel.text = arrayQuestions.first
    }

    resetButton(sender: UIButton)
    arrayQuestions.remove(at: 1)
    questionLabel.text = arrayQuestions.first // "How old are you" is now the first question
}
}
</code>```

答:
This should work for your problem.

```<code>func theFirstTwoQuestions()
{

// the questions will be contained in an Array
// change the question label to one of the array values
// when I press reset the next question will appear

    questionLabel.isHidden = false
    var arrayQuestions = ["What's your name?", "How old are you", "your favorite color is?"]
    var count = 0

    func onTapResetButton(sender: UIButton)
    {
        self.questionLabel.text = self.arrayQuestions[count] as? String
        if(count < arrayQuestions.count-1)
        {
            count += 1
        }
        else
        {
            count = 0
        }
    }
}
</code>```

Let me know if it worked for you. Cheers :]

Body:
I have a few questions that I would like to show with a label. When I press the reset button, the next question in the array does not appear. Should I not place the questions in an array in order for the next element in the array to appear?

func theFirstTwoQuestions() {

    // the questions will be contained in an Array
    // change the question label to one of the array values
    // when I press reset the next question will appear

    //self.questionLabel.text? = "\(questionsOneTwo)"
    questionLabel.isHidden = false
    var arrayQuestions = ["What's your name?", "How old are you", "your favorite color is?"]

    for question in arrayQuestions {

        questionLabel.text = arrayQuestions.first
    }

    resetButton(sender: UIButton)
    arrayQuestions.remove(at: 1)
    questionLabel.text = arrayQuestions.first // "How old are you" is now the first question
}
}

Body:
This should work for your problem.

func theFirstTwoQuestions()
{

// the questions will be contained in an Array
// change the question label to one of the array values
// when I press reset the next question will appear

    questionLabel.isHidden = false
    var arrayQuestions = ["What's your name?", "How old are you", "your favorite color is?"]
    var count = 0

    func onTapResetButton(sender: UIButton)
    {
        self.questionLabel.text = self.arrayQuestions[count] as? String
        if(count < arrayQuestions.count-1)
        {
            count += 1
        }
        else
        {
            count = 0
        }
    }
}

Let me know if it worked for you. Cheers :]


问:
Like and And Or ISNull using Linq to Entity Entity Framework4? How do you do that?
I have a screen in my project " Enquiry" where I user can perform 2 kinds of search.I cannot figure out how to do a "like" or "And or is null" in Linq to entity.

Simple Search  ( Search in all fields  using "Like" operator)

Advanced Advanced Search (Use "And" Operator)

So lets take these 3 tables and make up a noddy example.

Customer Table  (CustomerID,Name,Surname)

Address(AddressID,Street,City)

CustomerOrder (OrderID,OrderName)

Basic search :
this is how I would do it in Sql

```<code>  SELECT TOP (100) C.Name,C.Surname,CA.Street,CA.City,CO.OrderName
  FROM Customer C
  LEFT JOIN CustomerAddress CA ON C.CustomerID=CA.CustomerID
  LEFT JOIN CustomerOrders CO ON C.CustomerID=CA.CustomerID
  WHERE  (C.CustomerID LIKE '%' + @SearchText + '%'
  OR C.Surname LIKE '%' + @SearchText + '%'
  OR C.Name LIKE '%' + @SearchText + '%'
  OR CA.Street LIKE '%' + @SearchText + '%'
  OR CA.City LIKE '%' + @SearchText + '%'
  OR  CO.OrderName LIKE '%' + @SearchText + '%') )
</code>```

Advanced Search

This my sql where clause

```<code>    WHERE  (C.CustomerID =@CustomerID or @CustomerID ISNULL
    AND C.Surname =@Surname or @Surname ISNULL
    AND C.Name=@Name or @Name ISNULL
    AND CA.Street =@Street or @Street ISNULL
    AND CA.City =@City or @City ISNULL
    AND  CO.OrderName =@OrderName or @OrderName ISNULL)
    AND ((ModifiedDate BETWEEN ISNULL(convert(varchar,@FromDate,101),'01/01/1901')
    AND ISNULL(convert(varchar,@ToDate,101),'12/31/9999'))
</code>```

How do you do Likes or and or is null in entity framework?

thanks a lot!

答:
```<code>int? customerID = null;
string surname = "abc";

var q = from c in oc.Customers
  where (customerID == null || c.CustomerID == customerID)
    && (surname == null || c.Surname == surname)
  select c;
</code>```

Body:
I have a screen in my project " Enquiry" where I user can perform 2 kinds of search.I cannot figure out how to do a "like" or "And or is null" in Linq to entity.

Simple Search  ( Search in all fields  using "Like" operator)

Advanced Advanced Search (Use "And" Operator)

So lets take these 3 tables and make up a noddy example.

Customer Table  (CustomerID,Name,Surname)

Address(AddressID,Street,City)

CustomerOrder (OrderID,OrderName)

Basic search :
this is how I would do it in Sql

  SELECT TOP (100) C.Name,C.Surname,CA.Street,CA.City,CO.OrderName
  FROM Customer C
  LEFT JOIN CustomerAddress CA ON C.CustomerID=CA.CustomerID
  LEFT JOIN CustomerOrders CO ON C.CustomerID=CA.CustomerID
  WHERE  (C.CustomerID LIKE '%' + @SearchText + '%'
  OR C.Surname LIKE '%' + @SearchText + '%'
  OR C.Name LIKE '%' + @SearchText + '%'
  OR CA.Street LIKE '%' + @SearchText + '%'
  OR CA.City LIKE '%' + @SearchText + '%'
  OR  CO.OrderName LIKE '%' + @SearchText + '%') )

Advanced Search

This my sql where clause

    WHERE  (C.CustomerID =@CustomerID or @CustomerID ISNULL
    AND C.Surname =@Surname or @Surname ISNULL
    AND C.Name=@Name or @Name ISNULL
    AND CA.Street =@Street or @Street ISNULL
    AND CA.City =@City or @City ISNULL
    AND  CO.OrderName =@OrderName or @OrderName ISNULL)
    AND ((ModifiedDate BETWEEN ISNULL(convert(varchar,@FromDate,101),'01/01/1901')
    AND ISNULL(convert(varchar,@ToDate,101),'12/31/9999'))

How do you do Likes or and or is null in entity framework?

thanks a lot!


问:
I am trying to get a jquery plug in to work on my wordpress site
I am trying to get this plug in to work: https://gopalraju.github.io/gridtab/#features . Here is the test site I am using: http://testing.bdanzer.com/ . I enqueued the files via the functions.php file and added the script tag in the footer.php. They show up enqueued on the site but the jquery plug in isn't working? Here is the code:

Functions.php file:

```<code>function bdanzer_scripts() {
    wp_enqueue_script( 'gridtabready.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtabready.js', array( 'jquery' ), '1.0.0', false );
    wp_enqueue_script( 'gridtab.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtab.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_style( 'gridtab.css', get_template_directory_uri() . '/bdanzer/gridtab/gridtab.min.css' );
}
add_action( 'wp_enqueue_scripts', 'bdanzer_scripts', 11);
</code>```

Footer.php file:

```<code><script>
      $(document).ready(function() {
          $('.gridtab-1').gridtab({
              grid: 6,
              tabPadding: 0,
              borderWidth: 10,
              contentPadding: 40,
              responsive: [{
                  breakpoint: 991,
                  settings: {
                      grid: 4,
                      contentPadding: 30
                  }
              }, {
                  breakpoint: 767,
                  settings: {
                      grid: 3,
                      contentPadding: 20
                  }
              }, {
                  breakpoint: 520,
                  settings: {
                      grid: 2
                  }
              }]
          });

          $('.gridtab-2').gridtab({
              grid: 4,
              config:{
                layout: 'tab'
              },
              callbacks: {
                  open: function() {
                      console.log('open');
                  },
                  close: function() {
                      console.log('close');
                  }
              },
              responsive: [{
                  breakpoint: 991,
                  settings: {

                      grid: 3,
                  }
              }, {
                  breakpoint: 767,
                  settings: {
                      grid: 2,
                  }
              }, {
                  breakpoint: 520,
                  settings: {
                      grid: 1,
                  }
              }]
          });
          $('.gridtab-3').gridtab({
              grid: 3,
              config:{
                layout:'tab',
                activeTab:1,
                showClose:true,
                showArrows:true,
              }
          });

          $('.gridtab-4').gridtab({
              grid: 6,
              tabPadding: 0,
              borderWidth: 10,
              contentPadding: 40,
              config:{
                scrollToTab:true,
                showClose:true,
                showArrows:true
              },
              responsive: [{
                  breakpoint: 991,
                  settings: {
                      grid: 4,
                      contentPadding: 30
                  }
              }, {
                  breakpoint: 767,
                  settings: {
                      grid: 3,
                  }
              }, {
                  breakpoint: 520,
                  settings: {
                      grid: 2
                  }
              }]
          });
          $('.gridtab-5').gridtab({
              grid: 3,
              config:{
                layout:'tab',
                activeTab:1,
                keepOpen:true,
                showClose:true,
                showArrows:true,
                scrollToTab:true,
              }
          });
          $('.gridtab-6').gridtab({
              grid: 3,
              config:{
                layout:'tab',
                activeTab:1,
                showClose:true,
                showArrows:true,
                scrollToTab:true,
              }
          });
      });
    </script>
</code>```

答:
You have syntax error in gridtabready.js you didn't close .ready function please replace these js as below and it'll work fine

Take a look at this scrrenshot

```<code>jQuery(document).ready(function() {

        jQuery('.gridtab-1').gridtab({
            grid: 4,
            tabPadding: 0,
            borderWidth: 10,
            contentPadding: 40,
            responsive: [{
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2,
                }
            }]
        });

        jQuery('.gridtab-2').gridtab({
            grid: 6,
            layout: 'tab',
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab'
            },
            responsive: [{
                breakpoint: 1024,
                settings: {
                    grid: 4,
                }
            }, {
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2
                }
            }]
        });
        jQuery('.gridtab-3').gridtab({
            grid: 4,
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab',
                activeTab: 1
            },
            responsive: [{
                breakpoint: 600,
                settings: {
                    grid: 2,
                    contentPadding: 30
                }
            }]
        });
        jQuery('.gridtab-4').gridtab({
            grid: 6,
            borderWidth: 3,
            tabPadding: 0,
            contentPadding: 40,
            responsive: [{
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2
                }
            }]

        });
        jQuery('.gridtab-5').gridtab({
            grid: 4,
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab',
                activeTab: 1,
                keepOpen: true,
                showClose: true,
                showArrows: true,
                scrollToTab: true
            },
            responsive: [{
                breakpoint: 600,
                settings: {
                    grid: 2,
                    contentPadding: 30
                }
            }]
        });

        jQuery('.gridtab-6').gridtab({
            grid: 3,
            borderWidth: 3,
            tabPadding: 10,
            contentPadding: 40,
            config: {
                showClose: true,
                showArrows: true,
                layout: 'tab'
            },
            selectors: {
                tab: '.readmore',
                closeButton: '.closeBtn',
                nextArrow: '.nextBtn',
                prevArrow: '.prevBtn',
                disabledArrow: '.disabledBtn'
            },
            responsive: [{
                breakpoint: 600,
                settings: {
                    grid: 2,
                    contentPadding: 20
                }
            }, {
                breakpoint: 320,
                settings: {
                    grid: 1
                }
            }]

        });
        jQuery('.gridtab-7').gridtab({
            grid: 6,
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab',
                activeTab: 1,
                rtl: true,
                showClose: true,
                showArrows: true
            },
            responsive: [{
                breakpoint: 1024,
                settings: {
                    grid: 4,
                }
            }, {
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2
                }
            }]
        });
        });
</code>```

Body:
I am trying to get this plug in to work: https://gopalraju.github.io/gridtab/#features . Here is the test site I am using: http://testing.bdanzer.com/ . I enqueued the files via the functions.php file and added the script tag in the footer.php. They show up enqueued on the site but the jquery plug in isn't working? Here is the code:

Functions.php file:

function bdanzer_scripts() {
    wp_enqueue_script( 'gridtabready.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtabready.js', array( 'jquery' ), '1.0.0', false );
    wp_enqueue_script( 'gridtab.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtab.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_style( 'gridtab.css', get_template_directory_uri() . '/bdanzer/gridtab/gridtab.min.css' );
}
add_action( 'wp_enqueue_scripts', 'bdanzer_scripts', 11);

Footer.php file:

Body:
You have syntax error in gridtabready.js you didn't close .ready function please replace these js as below and it'll work fine

Take a look at this scrrenshot

jQuery(document).ready(function() {

        jQuery('.gridtab-1').gridtab({
            grid: 4,
            tabPadding: 0,
            borderWidth: 10,
            contentPadding: 40,
            responsive: [{
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2,
                }
            }]
        });

        jQuery('.gridtab-2').gridtab({
            grid: 6,
            layout: 'tab',
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab'
            },
            responsive: [{
                breakpoint: 1024,
                settings: {
                    grid: 4,
                }
            }, {
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2
                }
            }]
        });
        jQuery('.gridtab-3').gridtab({
            grid: 4,
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab',
                activeTab: 1
            },
            responsive: [{
                breakpoint: 600,
                settings: {
                    grid: 2,
                    contentPadding: 30
                }
            }]
        });
        jQuery('.gridtab-4').gridtab({
            grid: 6,
            borderWidth: 3,
            tabPadding: 0,
            contentPadding: 40,
            responsive: [{
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2
                }
            }]

        });
        jQuery('.gridtab-5').gridtab({
            grid: 4,
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab',
                activeTab: 1,
                keepOpen: true,
                showClose: true,
                showArrows: true,
                scrollToTab: true
            },
            responsive: [{
                breakpoint: 600,
                settings: {
                    grid: 2,
                    contentPadding: 30
                }
            }]
        });

        jQuery('.gridtab-6').gridtab({
            grid: 3,
            borderWidth: 3,
            tabPadding: 10,
            contentPadding: 40,
            config: {
                showClose: true,
                showArrows: true,
                layout: 'tab'
            },
            selectors: {
                tab: '.readmore',
                closeButton: '.closeBtn',
                nextArrow: '.nextBtn',
                prevArrow: '.prevBtn',
                disabledArrow: '.disabledBtn'
            },
            responsive: [{
                breakpoint: 600,
                settings: {
                    grid: 2,
                    contentPadding: 20
                }
            }, {
                breakpoint: 320,
                settings: {
                    grid: 1
                }
            }]

        });
        jQuery('.gridtab-7').gridtab({
            grid: 6,
            borderWidth: 3,
            contentPadding: 40,
            config: {
                layout: 'tab',
                activeTab: 1,
                rtl: true,
                showClose: true,
                showArrows: true
            },
            responsive: [{
                breakpoint: 1024,
                settings: {
                    grid: 4,
                }
            }, {
                breakpoint: 767,
                settings: {
                    grid: 3,
                    contentPadding: 20
                }
            }, {
                breakpoint: 520,
                settings: {
                    grid: 2
                }
            }]
        });
        });


问:
Pandas get values of column based on groupby count
I have a dataframe named test like so

```<code>   ALT_K1 ALT_K2  ALT_K3  HS  VS
    1       A       1      45   2
    1       A       1      32  32
    1      1-1      70     1   1
    1      1-1      70     0   9
    1      A        2      3   0
</code>```

and I groupby the first three columns and calculate the frequency of occurence like so

```<code>test_frequency = test.groupby(['ALT_K1', 'ALT_K2', 'ALT_K3']).size().reset_index(name='count')
</code>```

I want to be able to get the values of the columns HS and VS given the number of times the combination of the three columns appears. For example, for the combination (1, A, 1) I want the to get the values of HS [45, 32] and VS [2, 32]

Being stuck in this one for two days now and would appreciate any help.

Thanks

答:
I think you need custom lambda function with apply and unique:

```<code>test_frequency = test.groupby(['ALT_K1', 'ALT_K2', 'ALT_K3'])
                     .apply(lambda x: pd.Series([x['HS'].unique(),
                                                 x['VS'].unique()], index=['HS','VS']))
                     .reset_index()
print (test_frequency)

print (test_frequency)
   ALT_K1 ALT_K2  ALT_K3        HS       VS
0       1    1-1      70    [1, 0]   [1, 9]
1       1      A       1  [45, 32]  [2, 32]
2       1      A       2       [3]      [0]
</code>```

Body:
I have a dataframe named test like so

   ALT_K1 ALT_K2  ALT_K3  HS  VS
    1       A       1      45   2
    1       A       1      32  32
    1      1-1      70     1   1
    1      1-1      70     0   9
    1      A        2      3   0

and I groupby the first three columns and calculate the frequency of occurence like so

test_frequency = test.groupby(['ALT_K1', 'ALT_K2', 'ALT_K3']).size().reset_index(name='count')

I want to be able to get the values of the columns HS and VS given the number of times the combination of the three columns appears. For example, for the combination (1, A, 1) I want the to get the values of HS [45, 32] and VS [2, 32]

Being stuck in this one for two days now and would appreciate any help.

Thanks

Body:
I think you need custom lambda function with apply and unique:

test_frequency = test.groupby(['ALT_K1', 'ALT_K2', 'ALT_K3'])
                     .apply(lambda x: pd.Series([x['HS'].unique(),
                                                 x['VS'].unique()], index=['HS','VS']))
                     .reset_index()
print (test_frequency)

print (test_frequency)
   ALT_K1 ALT_K2  ALT_K3        HS       VS
0       1    1-1      70    [1, 0]   [1, 9]
1       1      A       1  [45, 32]  [2, 32]
2       1      A       2       [3]      [0]


问:
JavaScript: How to Get the Values from a Multi-Dimensional Array?
I'm trying to get the values from a multi-dimensional array. This is what I have so far.

I need the value of 99 and the image when I select the first option in the array, e.g. "Billy Joel".

```<code>var concertArray = [
    ["Billy Joel", "99", "equal.png"],
    ["Bryan Adams", "89", "higher.png"],
    ["Brian Adams", "25", "lower.png"]
];

function populate(){
    for(i = 0; i < concertArray.length; i++){
        var select = document.getElementById("test");
        select.options[select.options.length] = new Option(concertArray[i][0], concertArray[i][1]);
    }
}
</code>```

答:
You can access values by using 2 for loops as below.</p>

```<code>var concertArray = [
    ["Billy Joel", "99", "equal.png"],
    ["Bryan Adams", "89", "higher.png"],
    ["Brian Adams", "25", "lower.png"]
    ];

function populate(){
    for(i=0;i<arr.length;i++)
    {
        for(j=0;j<arr[i].length;j++)
        {
             console.log(arr[i][j]);
        }
    }
}
</code>```

Body:
I'm trying to get the values from a multi-dimensional array. This is what I have so far.

I need the value of 99 and the image when I select the first option in the array, e.g. "Billy Joel".

var concertArray = [
    ["Billy Joel", "99", "equal.png"],
    ["Bryan Adams", "89", "higher.png"],
    ["Brian Adams", "25", "lower.png"]
];

function populate(){
    for(i = 0; i < concertArray.length; i++){
        var select = document.getElementById("test");
        select.options[select.options.length] = new Option(concertArray[i][0], concertArray[i][1]);
    }
}

Body:
You can access values by using 2 for loops as below.

var concertArray = [
    ["Billy Joel", "99", "equal.png"],
    ["Bryan Adams", "89", "higher.png"],
    ["Brian Adams", "25", "lower.png"]
    ];

function populate(){
    for(i=0;i<arr.length;i++)
    {
        for(j=0;j<arr[i].length;j++)
        {
             console.log(arr[i][j]);
        }
    }
}


问:
Android; notification while device is in sleep state
I have a service that runs in the background that notifies to the status bar with a vibrate. However, when my phone goes into sleep state it no longer notifies with vibrates. How can I enable this functionality while the device is in sleep state?</p>

答:
First take care of the permissions (in the manifest file):

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

Then, most preferably use this in the Application file, or wherever:

```<code>PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
if(/*condition*/) {
    wakeLock.acquire(); //keep CPU awake
} else {
    wakeLock.release(); //disable keep CPU awake
}
</code>```

Although it is a pretty cool feature, with great power comes great responsibility: It drains your battery life, hence use it responsibility.

I prefer to release this PARTIAL_WAKE_LOCK by night as by base users do not use it beyond business hours.

Body:
First take care of the permissions (in the manifest file):

<uses-permission android:name="android.permission.WAKE_LOCK" />

Then, most preferably use this in the Application file, or wherever:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
if(/*condition*/) {
    wakeLock.acquire(); //keep CPU awake
} else {
    wakeLock.release(); //disable keep CPU awake
}

Although it is a pretty cool feature, with great power comes great responsibility: It drains your battery life, hence use it responsibility.

I prefer to release this PARTIAL_WAKE_LOCK by night as by base users do not use it beyond business hours.


问:
How do I implement this SQL query in Ruby on Rails
I have this delicious SQL query here that im trying to figure out how to implement in rails using their active record methods ==> .select() .where() ect...

SELECT
  topics.id
FROM topics
WHERE
  NOT EXISTS (
    SELECT *
    FROM votes
    WHERE votes.topic_id = topics.id
)

答:
Try this</p>

```<code>@topics = Topic.where("not exists (SELECT * FROM votes WHERE votes.topic_id = topics.id)")
</code>```

Body:
Try this

@topics = Topic.where("not exists (SELECT * FROM votes WHERE votes.topic_id = topics.id)")


问:
Count number of male and female
i want to count  no of male and female in a table called Gender having entry given below. Answer should be female=2 Male=3 in count.
Is there any query in SQL.</p>

```<code>Gender
MALE
MaLE
FEMALE
Female
</code>```

答:
Please try this :-</p>

```<code> Select count(CASE WHEN Gender = 'male' THEN 1 ELSE 0 END) as Male_count,
        count(CASE WHEN Gender = 'Female' THEN 1 ELSE 0 END) as Female_count
  FROM your_table
</code>```

Title: Count number of male and female

Body:
i want to count  no of male and female in a table called Gender having entry given below. Answer should be female=2 Male=3 in count.
Is there any query in SQL.

Gender
MALE
MaLE
FEMALE
Female

Body:
Please try this :-

 Select count(CASE WHEN Gender = 'male' THEN 1 ELSE 0 END) as Male_count,
        count(CASE WHEN Gender = 'Female' THEN 1 ELSE 0 END) as Female_count
  FROM your_table


问:
(Ruby) First x Recursive Nums
I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

```<code>def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end
</code>```

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

答:
Question is about recursion, but also you can use iteration, it's faster:

```<code>def factorials(num)
  m = 1
  (0...num).map {|e| e.zero? ? 1 : m *= e }
end
factorials(6)
=> [1, 1, 2, 6, 24, 120]
</code>```

Or by using hash memoisation (I would say its a recursion too):

```<code>factorials = Hash.new { |h, k| h[k] = h[k-1] * k }.update(0 => 1)
factorials.values_at(*(0..5))
=> [1, 1, 2, 6, 24, 120]
</code>```

Title: (Ruby) First x Recursive Nums

Body:
I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

Body:
Question is about recursion, but also you can use iteration, it's faster:

def factorials(num)
  m = 1
  (0...num).map {|e| e.zero? ? 1 : m *= e }
end
factorials(6)
=> [1, 1, 2, 6, 24, 120]

Or by using hash memoisation (I would say its a recursion too):

factorials = Hash.new { |h, k| h[k] = h[k-1] * k }.update(0 => 1)
factorials.values_at(*(0..5))
=> [1, 1, 2, 6, 24, 120]


问:
Reduce boot time in ionic-2 app
I am new to ionic-2 project.I just want to know how to reduce boot time of  app.Because after 3 sec of splash screen , it shows white screen and takes 9 sec to start.</p>

答:
Please follow below steps to reduce splash screen time:-

First, delete your node_modules folder
Delete any Temp Folder
Delete Plugins Folder
remove platform android using ionic platform rm android.
Now Reinstall Everything : -

(i) npm install (ii) ionic serve (iii) ionic platform add android

Now run this Command FINALLY ionic build android --prod

THIS WORKS 100% PERFECTLY.

If this doesn't work please don't give up. Try above steps 2 to 3 times, I'm SURE this will work.

Title: Reduce boot time in ionic-2 app


问:
Check if URL points to Azure Blob
If I have a random URL, how would I check if it points to a blob in Azure? If it points to an Azure Blob I can be sure that this blob exists and that I can access it.

I tried the following:

I made some tests with Exists, but it's not very satisfying:

```<code>new CloudBlockBlob(new Uri("http://example.com"))
ArgumentException: Invalid blob address 'http://example.com/', missing container information

new CloudBlockBlob(new Uri("https://example.com/fdh/3746C9A2-533E-4544-A10B-321A8BC40AEA/sample-file.txt")).Exists()
false

new CloudBlockBlob(new Uri("http://stackoverflow.com/questions/43109843/ways-to-migrate-documents-pdf-forms-from-ms-sharepoint-to-aem")).Exists()
StorageException: Blob type of the blob reference doesn't match blob type of the blob.
</code>```

So basically creating the CloudBlockBlob can fail, Exists can fail or return false.

But it just feels wrong to do it like this.

I could check the url to be https://<storage-account>.blob.core.windows.net/<container>/*, but I'm not sure if this is always correct.

If I could guarantee that 2. works I would do this because no HTTP request is necessary.

Are there other (better) ways to check if a random URL points to a blob in Azure (maybe something out of the (Azure Storage SDK) box)?

答:
Not really an elegant solution (read, it's a hack basically :D)

One thing you could do is make a HEAD request to the URL. What you would need to do is parse the response headers. There are 3 scenarios that you would need to consider:

URL points to a blob in blob storage and is publicly accessible.

URL points to a blob in blob storage but is not publicly accessible (container is private).

URL does not point to blob storage.

Now every request to Azure Blob Storage will have a response header called x-ms-request-id which contains a GUID like value. You can use this to differentiate between scenarios where URL points to blob storage and URL doesn't point to blob storage. Of course this check will fail (and that's why the solution is more of a  "hack" if the URL actually returns this header [some random site decides to include this exact header in response]).

In case #1, you will get status code 200 back. Because the blob is publicly accessible you will get additional headers back. One of the headers there would be x-ms-blob-type and that could potentially have 3 values: BlockBlob, AppendBlob or PageBlob.

In case #2, you will get status code 404 back however you will receive x-ms-request-id response header back.

Title: Check if URL points to Azure Blob

Body:
If I have a random URL, how would I check if it points to a blob in Azure? If it points to an Azure Blob I can be sure that this blob exists and that I can access it.

I tried the following:

I made some tests with Exists, but it's not very satisfying:

new CloudBlockBlob(new Uri("http://example.com"))
ArgumentException: Invalid blob address 'http://example.com/', missing container information

new CloudBlockBlob(new Uri("https://example.com/fdh/3746C9A2-533E-4544-A10B-321A8BC40AEA/sample-file.txt")).Exists()
false

new CloudBlockBlob(new Uri("http://stackoverflow.com/questions/43109843/ways-to-migrate-documents-pdf-forms-from-ms-sharepoint-to-aem")).Exists()
StorageException: Blob type of the blob reference doesn't match blob type of the blob.

So basically creating the CloudBlockBlob can fail, Exists can fail or return false.

But it just feels wrong to do it like this.

I could check the url to be https://<storage-account>.blob.core.windows.net/<container>/*, but I'm not sure if this is always correct.

If I could guarantee that 2. works I would do this because no HTTP request is necessary.

Are there other (better) ways to check if a random URL points to a blob in Azure (maybe something out of the (Azure Storage SDK) box)?


问:
Make keyboard go over UI not shift the whole UI in UWP
I'm building an app in Universal Windows Platform and I have put a TextBox at the bottom of screen but I don't want it to shift the whole UI upwards, and I don't want to reorder everything to be fit above the keyboard.

I just wanna do something like Cortana that the keyboard can be above all layers.

What the app looks like itself:

What the app looks like after opening keyboard:

What Cortana looks like (which I want my app to be like this):

```<code><Page
x:Class="Pi.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Pi"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Loaded="Page_Loaded">
<Page.Resources>
    <FontFamily x:Key="Dekar">/Assets/Fonts/Dekar.otf#Dekar</FontFamily>
    <FontFamily x:Key="Consolas">/Assets/Fonts/SFThin.otf#SF UI Display</FontFamily>
</Page.Resources>

<Grid Background="Black">
    <Rectangle Margin="0">
        <Rectangle.Fill>
            <ImageBrush ImageSource="Assets/MainBG2.jpg" Stretch="UniformToFill" Opacity="0.35"/>
        </Rectangle.Fill>
    </Rectangle>
    <TextBlock x:Name="TitleText" Height="21" Margin="10,18,10,0" TextWrapping="Wrap" Text="ADMIN ACCESS" VerticalAlignment="Top" Foreground="#FF00AEFF" FontSize="20" FontFamily="{StaticResource Dekar}" TextAlignment="Center" DoubleTapped="TitleText_DoubleTapped"/>
    <TextBox x:Name="CommandBox" Margin="0,0,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Bottom" FontFamily="{StaticResource Consolas}" Foreground="#FF8D8D8D" Background="#BF111E23" BorderThickness="0,1,0,0" FontSize="17" Height="50" PlaceholderText="Type here..." Padding="10,12,0,0" RequestedTheme="Dark" BorderBrush="#FF00AEFF" KeyUp="KeyPressed"/>
    <ScrollViewer Margin="10,65,10,60" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
        <TextBlock x:Name="ResultText" TextWrapping="Wrap" Text="What are your commands?" VerticalAlignment="Top" Foreground="#FFDEDEDE" FontSize="19" FontFamily="{StaticResource Consolas}" TextAlignment="Left"/>
</Grid>
</code>```

答:
By default the InputPane slides the page so that the focused element isn't covered by the keyboard. Your page has the focused TextBox at the bottom, so that has to slide up so the user can see what she types.

You can override this behavior by handling the InputPane.Showing event and setting the EnsuredFocusedElementInView property to let the InputPane know that you handled this and it doesn't need to slide.

You can move the TextBox to just above the InputPane's OccludedRect but leave the rest of the Page alone, then move the TextBox back in InoutPane.Hiding.

See

https://learn.microsoft.com/en-us/uwp/api/Windows.UI.ViewManagement.InputPane#events_

https://learn.microsoft.com/en-us/windows/uwp/input-and-devices/respond-to-the-presence-of-the-touch-keyboard#handling-the-showing-and-hiding-events

https://code.msdn.microsoft.com/windowsapps/keyboard-events-sample-866ba41c

Body:
I'm building an app in Universal Windows Platform and I have put a TextBox at the bottom of screen but I don't want it to shift the whole UI upwards, and I don't want to reorder everything to be fit above the keyboard.

I just wanna do something like Cortana that the keyboard can be above all layers.

What the app looks like itself:

What the app looks like after opening keyboard:

What Cortana looks like (which I want my app to be like this):

<Page
x:Class="Pi.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Pi"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Loaded="Page_Loaded">
<Page.Resources>
    <FontFamily x:Key="Dekar">/Assets/Fonts/Dekar.otf#Dekar</FontFamily>
    <FontFamily x:Key="Consolas">/Assets/Fonts/SFThin.otf#SF UI Display</FontFamily>
</Page.Resources>

<Grid Background="Black">
    <Rectangle Margin="0">
        <Rectangle.Fill>
            <ImageBrush ImageSource="Assets/MainBG2.jpg" Stretch="UniformToFill" Opacity="0.35"/>
        </Rectangle.Fill>
    </Rectangle>
    <TextBlock x:Name="TitleText" Height="21" Margin="10,18,10,0" TextWrapping="Wrap" Text="ADMIN ACCESS" VerticalAlignment="Top" Foreground="#FF00AEFF" FontSize="20" FontFamily="{StaticResource Dekar}" TextAlignment="Center" DoubleTapped="TitleText_DoubleTapped"/>
    <TextBox x:Name="CommandBox" Margin="0,0,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Bottom" FontFamily="{StaticResource Consolas}" Foreground="#FF8D8D8D" Background="#BF111E23" BorderThickness="0,1,0,0" FontSize="17" Height="50" PlaceholderText="Type here..." Padding="10,12,0,0" RequestedTheme="Dark" BorderBrush="#FF00AEFF" KeyUp="KeyPressed"/>
    <ScrollViewer Margin="10,65,10,60" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
        <TextBlock x:Name="ResultText" TextWrapping="Wrap" Text="What are your commands?" VerticalAlignment="Top" Foreground="#FFDEDEDE" FontSize="19" FontFamily="{StaticResource Consolas}" TextAlignment="Left"/>
</Grid>


问:
Difference between SourceSet and SourceDirectorySet, Gradle
Just like the question title says. I found the following example in the Gradle docs:

```<code>apply plugin: 'java'

sourceSets {
   main {
      java {
         exclude 'some/unwanted/package/**'
      }
   }
}
</code>```

The docs say that main is a SourceSet and java is a SourceDirectorySet. The distinction still isn't that clear to me, though. Is a SourceSet just a container for SourceDirectorySets? What else can a SourceSet contain?

答:
It seems that the answer can be found in the docs:

A SourceSet represents a logical group of Java source and
resources.

while,

A SourceDirectorySet represents a set of source files composed
from a set of source directories, along with associated include and
exclude patterns.

What it means is that SourceSet is just a logical unit that groups SourceDirectorySets.

Body:
Just like the question title says. I found the following example in the Gradle docs:

apply plugin: 'java'

sourceSets {
   main {
      java {
         exclude 'some/unwanted/package/**'
      }
   }
}

The docs say that main is a SourceSet and java is a SourceDirectorySet. The distinction still isn't that clear to me, though. Is a SourceSet just a container for SourceDirectorySets? What else can a SourceSet contain?


问:
background color of UILabel is become clear after reload Table
I am working in UiTableViewController and and I created Custom cell with XIB. I just set black color to one label. Hear I am attached three image for better explanation.

at the time of selection in didSelectRowAtIndexPath method I change it black to blue.

the main problem is when i just scroll my table then the background color of that label become clear.

In cellForRowAtIndexpath method, I just add this condition,

```<code>if (inboxSelcted == 1) {
  cell.lblNoOfIndexItem.backgroundColor = [UIColor blueColor];
} else {
  cell.lblNoOfIndexItem.backgroundColor = [UIColor blackColor];
}
</code>```

答:
In cellForRowAtIndexpath method, try like this as per your screenshot inbox index is 2. So,

```<code>if (indexPath.row == 2) {
 cell.lblNoOfIndexItem.backgroundColor = [UIColor blueColor];
} else {
 cell.lblNoOfIndexItem.backgroundColor = [UIColor blackColor];
}
</code>```

And in didSelectRowAtIndexPath method,

```<code>if (indexPath.row == 2) {
 inboxSelcted = indexPath.row;
}
</code>```

try like this and let me know, does it work!

Body:
I am working in UiTableViewController and and I created Custom cell with XIB. I just set black color to one label. Hear I am attached three image for better explanation.

at the time of selection in didSelectRowAtIndexPath method I change it black to blue.

the main problem is when i just scroll my table then the background color of that label become clear.

In cellForRowAtIndexpath method, I just add this condition,

if (inboxSelcted == 1) {
  cell.lblNoOfIndexItem.backgroundColor = [UIColor blueColor];
} else {
  cell.lblNoOfIndexItem.backgroundColor = [UIColor blackColor];
}

Body:
In cellForRowAtIndexpath method, try like this as per your screenshot inbox index is 2. So,

if (indexPath.row == 2) {
 cell.lblNoOfIndexItem.backgroundColor = [UIColor blueColor];
} else {
 cell.lblNoOfIndexItem.backgroundColor = [UIColor blackColor];
}

And in didSelectRowAtIndexPath method,

if (indexPath.row == 2) {
 inboxSelcted = indexPath.row;
}

try like this and let me know, does it work!