问:
Bot Framework: How to exit Conversation?
so right now I'm using Microsoft.Bot.Builder.Dialogs.Conversation.SendAsync and Microsoft.Bot.Builder.Dialogs.Conversation.ResumeAsync to implement a way to pause and resume conversation but it seems impossible to 'exit' or go back to the previous state. It's stuck in the conversation dialog.

Do I just implement a 'Cancel' command? If so, what data do I need to clear so that it will be back to the original state?

```<code>    public static readonly IDialog<string> dialog = Chain
        .PostToChain()
        .Switch(
            new Case<Message, IDialog<string>>((msg) =>
            {
                var regex = new Regex("login", RegexOptions.IgnoreCase);
                return regex.IsMatch(msg.Text);
            }, (ctx, msg) =>
            {
                return Chain.ContinueWith(new ChatDialog(msg),
                            async (context, res) =>
                            {
                                var token = await res;
                                //var valid = await Helpers.ValidateAccessToken(token);
                                //var name = await Helpers.GetProfileName(token);
                                var name = "User";
                                context.UserData.SetValue("name", name);
                                return Chain.Return($"You are logged in as: {name}");
                            });
            })
        ).Unwrap().PostToUser();
</code>```

so if I send a 'login' it will go and start a new ChatDialog conversation but it seems to get stuck in this state. Even if I try to send another command, it will keep asking for login. Do I implement another Case class to handle a 'Cancel' command? Or should it automatically cancel the conversation when the user sends the same 'login' command more than once? Seems kinda clunky to have to send a 'cancel' command separately.

答:
I would consider how your users will interpret the end of the conversation, and think about those scenarios and how people end conversations.

You can add code to handle resetting or the end of a conversation based on specific keywords, and by using the GlobalMessageHandler pattern.

https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/core-GlobalMessageHandlers

Also, expect users to just "hang up" / close the window once they are done.

A good set of metrics can help collect information on how people are using the bot for the owners to improve it.
i.e: Did interaction X lead on to expected interaction Y, or what was the last interaction we saw for this conversation... etc.

Body:
so right now I'm using Microsoft.Bot.Builder.Dialogs.Conversation.SendAsync and Microsoft.Bot.Builder.Dialogs.Conversation.ResumeAsync to implement a way to pause and resume conversation but it seems impossible to 'exit' or go back to the previous state. It's stuck in the conversation dialog.

Do I just implement a 'Cancel' command? If so, what data do I need to clear so that it will be back to the original state?

    public static readonly IDialog<string> dialog = Chain
        .PostToChain()
        .Switch(
            new Case<Message, IDialog<string>>((msg) =>
            {
                var regex = new Regex("login", RegexOptions.IgnoreCase);
                return regex.IsMatch(msg.Text);
            }, (ctx, msg) =>
            {
                return Chain.ContinueWith(new ChatDialog(msg),
                            async (context, res) =>
                            {
                                var token = await res;
                                //var valid = await Helpers.ValidateAccessToken(token);
                                //var name = await Helpers.GetProfileName(token);
                                var name = "User";
                                context.UserData.SetValue("name", name);
                                return Chain.Return($"You are logged in as: {name}");
                            });
            })
        ).Unwrap().PostToUser();

so if I send a 'login' it will go and start a new ChatDialog conversation but it seems to get stuck in this state. Even if I try to send another command, it will keep asking for login. Do I implement another Case class to handle a 'Cancel' command? Or should it automatically cancel the conversation when the user sends the same 'login' command more than once? Seems kinda clunky to have to send a 'cancel' command separately.


来源: stackexchange

问:
Div with text wont stay centered
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" id="locations">

  <div class="locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div></code>```

Obviously the code is doubled inside the "row" div.

答:
Bring this below code out of row and that should go the way you want.

```<code><div class="locationName">
    City
</div>
</code>```

You are facing this problem because you can see in the image(link) you
  provided that the middle image has moved slightly down and hence
  it affects the title of the next row everytime.

ContentLicense: CC BY-SA 3.0

Title: Div with text wont stay centered

Body:
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}

    City

Obviously the code is doubled inside the "row" div.

Body:
Bring this below code out of row and that should go the way you want.

<div class="locationName">
    City
</div>

You are facing this problem because you can see in the image(link) you
  provided that the middle image has moved slightly down and hence
  it affects the title of the next row everytime.


问:
How do I implement a global variable?
What I need help with: Passing an integer value that is in file2.c to file3.c via global variable using file1.h

Hello, I am having an issue using a global variable to identify one of the ports I'm using on a cipher text project. Its pretty big, so I have just added the code snippets which address my issue.

What I am currently using to compile: gcc -o executable3 file2.c file1.h (this works)

and my second line (doesnt work): gcc -o executable3 file3.c

My Error message when compiling: undefined reference to `GLOBALVARIABLE'
collect2: ld returned 1 exit status

My file1.h file:

```<code> ifndef FILE1_H
 define FILE1_H
 include <stdio.h>
 include <stdlib.h>
 extern int *GLOBALVARIABLE;
 endif
</code>```

My file where I initialize the GLOBALVARIABLE value and set it equal to the port number (file 2):

```<code>#include "file1.h"
#define SIZE  128000
int *GLOBALVARIABLE;
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;

portno = atoi(argv[1]);
GLOBALVARIABLE = &portno;
</code>```

File that causes compiling conflict stated above (file 3):

```<code>#include "file1.h"
#define SIZE  16000
int main(int argc, char *argv[])
{
int sockfd, portno;
portno = atoi(argv[3]);
if (portno == *GLOBALVARIABLE){
printf("Theres been a port error, you are using the wrong port for this
command");
exit(1);
</code>```

Please help!
Thank you!

答:
You're using your compiler in the wrong way. By default, gcc emits a runnable binary, that means it already does the linking step. When linking, all symbols (except those imported from shared objects) must be defined.

What you have to do is only compile your source files (option -c) into object files and then link together these object files:

```<code>gcc -c -ofile2.o file2.c             # <- compile
gcc -c -ofile3.o file3.c             # <- compile
gcc -oexecutable file2.o file3.o     # <- link
</code>```

In practice, add flags enabling warnings, chosing a C standard, etc.

edit: As pointed out in the comments, main should only exist once. Which one would you expect to be executed otherwise?

Two more thoughts here:

Don't put header files (.h) on your compiler command lines. They are included in the source files where needed.

If you wanted to share a variable between two independent programs, this is not possible using extern. "global variables" only exist in the scope of one process. If you want to share data between processes, there's e.g. shared memory, pipes, etc. (google for them).

Title: How do I implement a global variable?

Body:
What I need help with: Passing an integer value that is in file2.c to file3.c via global variable using file1.h

Hello, I am having an issue using a global variable to identify one of the ports I'm using on a cipher text project. Its pretty big, so I have just added the code snippets which address my issue.

What I am currently using to compile: gcc -o executable3 file2.c file1.h (this works)

and my second line (doesnt work): gcc -o executable3 file3.c

My Error message when compiling: undefined reference to `GLOBALVARIABLE'
collect2: ld returned 1 exit status

My file1.h file:

 ifndef FILE1_H
 define FILE1_H
 include <stdio.h>
 include <stdlib.h>
 extern int *GLOBALVARIABLE;
 endif

My file where I initialize the GLOBALVARIABLE value and set it equal to the port number (file 2):

#include "file1.h"
#define SIZE  128000
int *GLOBALVARIABLE;
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;

portno = atoi(argv[1]);
GLOBALVARIABLE = &portno;

File that causes compiling conflict stated above (file 3):

#include "file1.h"
#define SIZE  16000
int main(int argc, char *argv[])
{
int sockfd, portno;
portno = atoi(argv[3]);
if (portno == *GLOBALVARIABLE){
printf("Theres been a port error, you are using the wrong port for this
command");
exit(1);

Please help!
Thank you!

Body:
You're using your compiler in the wrong way. By default, gcc emits a runnable binary, that means it already does the linking step. When linking, all symbols (except those imported from shared objects) must be defined.

What you have to do is only compile your source files (option -c) into object files and then link together these object files:

gcc -c -ofile2.o file2.c             # <- compile
gcc -c -ofile3.o file3.c             # <- compile
gcc -oexecutable file2.o file3.o     # <- link

In practice, add flags enabling warnings, chosing a C standard, etc.

edit: As pointed out in the comments, main should only exist once. Which one would you expect to be executed otherwise?

Two more thoughts here:

Don't put header files (.h) on your compiler command lines. They are included in the source files where needed.

If you wanted to share a variable between two independent programs, this is not possible using extern. "global variables" only exist in the scope of one process. If you want to share data between processes, there's e.g. shared memory, pipes, etc. (google for them).


问:
Resize View in iPad
I am trying to convert my iphone app to ipad app. My problem is when i run this i am not able to resize the screen.In my iphone app i use one imageView, When itried to run on ipad it was showing same imaegeview three times side by side, I have to adjust this as one imageview.Can any body pls help me out for this issue.

Thanks.

答:
If you are going to be doing strange image resizing, your best option would be to look at look at this thread:

How to scale a UIImageView proportionally?

However, you should be regenerating your images for the different screen resolutions (otherwise they will look like an SNES game).

ContentLicense: CC BY-SA 2.5

Title: Resize View in iPad


问:
Jenkins somehow creates ws-cleanup_timestamp file
I have a Jenkins job, that triggers a script. Everything is ok, but in the foulder, where a script is placed, it creates a file with name

```<code>JOBNAME_ws-cleanup_TIMESTAMP
</code>```

JOBNAME AND TIMESTAMP are variables from a Jenkins job.

Why does it happen. Why does Jenkins create a file?

答:
You probably should use latest Jenkins workspace cleanup plugin
https://www.jenkins.io/doc/pipeline/steps/ws-cleanup/

Body:
I have a Jenkins job, that triggers a script. Everything is ok, but in the foulder, where a script is placed, it creates a file with name

JOBNAME_ws-cleanup_TIMESTAMP

JOBNAME AND TIMESTAMP are variables from a Jenkins job.

Why does it happen. Why does Jenkins create a file?

ContentLicense: CC BY-SA 4.0


问:
Removing dynamically an element from a list
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

```<code>def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test
</code>```

I am getting the following output:

```<code>[5]
</code>```

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

答:
You can use the following code:

```<code>while len(test):
   if condition_to_remove is True:
        test.pop()
</code>```

Following question has some good answers that might help you:

Remove items from a list while iterating

Body:
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test

I am getting the following output:

[5]

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

Body:
You can use the following code:

while len(test):
   if condition_to_remove is True:
        test.pop()

Following question has some good answers that might help you:

Remove items from a list while iterating


问:
OAuth 2.0 Auth code grant - Is there anyway to Authenticate user when requesting for Auth Code
Whats the best way to programmatically authenticate user using OAuth 2.0 Authentication Code Grant ?

Wondering if there is a way to combine step A and B as stated on the spec - https://www.rfc-editor.org/rfc/rfc6749#section-4.1, i.e pass user ID and password as part of authorize call ? Something like,
/authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb&user_id=john.doe@mail&password=xxxx

I believe one way is to submit() the form returned by the Authorization server with user id and password. Taking this route would create a dependency on the form and any changes to it given it is not a public API.

答:
The Authorization Code grant is designed to be used with a full browser i.e. should not be used to authenticate the user programmatically. In fact using it programmatically would defeat the purpose of OAuth 2.0 to not divulge the user's credentials to the Client.

Grants like Client Credentials and Resource Owner Password Credentials have been designed to be used with non-browser Clients.

Alternatively you could create an access_token and refresh_token for your Client in a browser using the Authorization Code grant, then pass the tokens to your non-browser Client so that it can use the refresh_token on its own to obtain a new access token when the old one expires.


问:
Stop and delete Docker container if it's running
I am looking to pragmatically stop and delete a Docker container if it is running.  This is for a build script.

Take the following example.  How would I stop and delete the Docker container "rabbitmq" as seen under the NAMES column in a bash script?

```<code>docker ps

CONTAINER ID        IMAGE             COMMAND                  CREATED             STATUS              PORTS                   NAMES
9909a5e2856f        rabbitmq-image   "/docker-entrypoint.s"   11 minutes ago      Up 11 minutes       0.0.0.0:5672->5672/tcp, rabbitmq
8990dd1fe503        redis-image      "/entrypoint.sh redis"   6 weeks ago         Up 4 days           0.0.0.0:32770->6379/tcp redis
etc
</code>```

The following command will delete the container and does what I'm looking to do

```<code>docker stop rabbitmq && docker rm -f rabbitmq
</code>```

However, it's combing it into a script that I would like to know? I think it would look something like this.

```<code>#!/bin/bash

if [ /*docker ps check some value */ ]; then
   docker stop rabbitmq && docker rm -f rabbitmq
fi
</code>```

答:
I have a similar problem, but didn't like the accepted answer as it suppresses all errors from the commands, rather than just the "not found" error.

However, docker ps -q --filter "name=rabbitmq" only produces output if a container of that name actually exists, so inspired by Test if a command outputs an empty string I came up with:

```<code>docker ps -q --filter "name=rabbitmq" | grep -q . && docker stop rabbitmq && docker rm -fv rabbitmq
</code>```

The following command is also useful for testing filter definitions:

```<code>docker ps -q --filter "name=rabbitmq" | grep -q . && echo Found || echo Not Found
</code>```

My actual use case was in defining a pair of Ansible tasks that deleted all currently existing containers (whether running or not) from a list of names generated in an earlier task:

```<code>- name: Check for containers that actually exist
  shell: 'docker ps -aq --filter "name={{ item }}"'
  with_items:
    - '{{ previous_command.stdout_lines }}'
  register: found_containers

- name: Remove the containers found by the above command
  shell: 'docker stop {{ item.item }} && docker rm -fv {{ item.item }}'
  with_items: '{{ found_containers.results }}'
  when: item.stdout
</code>```

Body:
I am looking to pragmatically stop and delete a Docker container if it is running.  This is for a build script.

Take the following example.  How would I stop and delete the Docker container "rabbitmq" as seen under the NAMES column in a bash script?

docker ps

CONTAINER ID        IMAGE             COMMAND                  CREATED             STATUS              PORTS                   NAMES
9909a5e2856f        rabbitmq-image   "/docker-entrypoint.s"   11 minutes ago      Up 11 minutes       0.0.0.0:5672->5672/tcp, rabbitmq
8990dd1fe503        redis-image      "/entrypoint.sh redis"   6 weeks ago         Up 4 days           0.0.0.0:32770->6379/tcp redis
etc

The following command will delete the container and does what I'm looking to do

docker stop rabbitmq && docker rm -f rabbitmq

However, it's combing it into a script that I would like to know? I think it would look something like this.

#!/bin/bash

if [ /*docker ps check some value */ ]; then
   docker stop rabbitmq && docker rm -f rabbitmq
fi

Body:
I have a similar problem, but didn't like the accepted answer as it suppresses all errors from the commands, rather than just the "not found" error.

However, docker ps -q --filter "name=rabbitmq" only produces output if a container of that name actually exists, so inspired by Test if a command outputs an empty string I came up with:

docker ps -q --filter "name=rabbitmq" | grep -q . && docker stop rabbitmq && docker rm -fv rabbitmq

The following command is also useful for testing filter definitions:

docker ps -q --filter "name=rabbitmq" | grep -q . && echo Found || echo Not Found

My actual use case was in defining a pair of Ansible tasks that deleted all currently existing containers (whether running or not) from a list of names generated in an earlier task:

- name: Check for containers that actually exist
  shell: 'docker ps -aq --filter "name={{ item }}"'
  with_items:
    - '{{ previous_command.stdout_lines }}'
  register: found_containers

- name: Remove the containers found by the above command
  shell: 'docker stop {{ item.item }} && docker rm -fv {{ item.item }}'
  with_items: '{{ found_containers.results }}'
  when: item.stdout


问:
Android example which uses onResume, onStart and onRestart
I would like an example Android app which uses onResume, onStart and onRestart.</p>

答:
```<code>package com.test;

import stuff here

public class Pick_Color extends Activity implements OnClickListener
{

        private Button b11;
            private Button b12;
    private Button b13;
    private Button b14;

    private Button b_final;

private EditText RED;
private EditText GREEN;
private EditText BLUE;

static int temp_red;
static int temp_green;
static int temp_blue;

public void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.pickcolor);
    Log.d("pick color","on create");
    b11=(Button)findViewById(R.id.buttonR1C1);
    b12=(Button)findViewById(R.id.buttonR1C2);
    b13=(Button)findViewById(R.id.buttonR1C3);
    b14=(Button)findViewById(R.id.buttonR1C4);

        b11.setBackgroundColor(Color.argb(255, 255, 255,0));
        b12.setBackgroundColor(Color.argb(255, 255, 0,255));
        b13.setBackgroundColor(Color.argb(255, 0, 255,255));
        b14.setBackgroundColor(Color.argb(255, 102, 153,51));

        b11.setOnClickListener(this);
        b12.setOnClickListener(this);
        b13.setOnClickListener(this);
        b14.setOnClickListener(this);

     RED=(EditText) findViewById(R.id.RED_TEXT);
     GREEN=(EditText) findViewById(R.id.GREEN_TEXT);
     BLUE=(EditText) findViewById(R.id.BLUE_TEXT);

       RED.setText(Integer.toString(temp_red));
       GREEN.setText(Integer.toString(temp_green));
       BLUE.setText(Integer.toString(temp_blue));

     b_final=(Button)findViewById(R.id.button_result);
     b_final.setBackgroundColor(Color.argb(255,temp_red,temp_green,temp_blue));
     b_final.setOnClickListener(this);

     OnKeyListener text_listener= new OnKeyListener()
        {
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                int flag=0;

                try
                {
                    switch(v.getId())
                    {
                        case R.id.RED_TEXT:
                                flag=1;
                            temp_red=Integer.parseInt(RED.getText().toString());

                            if(temp_red<0 || temp_red>255)
                                throw new NumberFormatException();

                        //  Log.d("Pick_Color","temp_red = "+temp_red);

                                            break;

                        case R.id.GREEN_TEXT:
                                flag=2;
                            temp_green=Integer.parseInt(GREEN.getText().toString());

                            if(temp_green<0 || temp_green>255)
                                throw new NumberFormatException();

                        //  Log.d("Pick_Color","temp_green = "+temp_green);

                                            break;

                        case R.id.BLUE_TEXT:
                                flag=3;
                            temp_blue=Integer.parseInt(BLUE.getText().toString());

                            if(temp_blue<0 || temp_blue>255)
                                throw new NumberFormatException();

                        //  Log.d("Pick_Color","temp_blue = "+temp_blue);

                                            break;
                    }
                }
                catch(NumberFormatException n)
                {
                    if(flag==1)
                        {
                        RED.setText("");
                        Log.d("Pick Color","Red Error");
                        }
                    if(flag==2)
                        {
                        GREEN.setText("");
                        Log.d("Pick Color","Green Error");
                        }
                    if(flag==3)
                        {
                        BLUE.setText("");
                        Log.d("Pick Color","Blue Error");
                        }
                }

                Log.d("Pick Color","temp_red = "+temp_red+" temp_green = "+temp_green+" temp_blue = "+temp_blue+"");
                 b_final.setBackgroundColor(Color.argb(255,temp_red, temp_green, temp_blue));
                return false;
            }
        };

            RED.setOnKeyListener(text_listener);
            GREEN.setOnKeyListener(text_listener);
            BLUE.setOnKeyListener(text_listener);

  }

protected void onResume()
{
   super.onResume();

   RED.setText(Integer.toString(temp_red));
   GREEN.setText(Integer.toString(temp_green));
   BLUE.setText(Integer.toString(temp_blue));

   b_final.setBackgroundColor(Color.argb(255,temp_red,temp_green,temp_blue));
}

public void onClick(View v)
{
    switch (v.getId())
    {
    // --------------  FIRST ROW --------------
    case R.id.buttonR1C1:

            RED.setText("255");
            GREEN.setText("255");
            BLUE.setText("0");
            temp_red=Integer.parseInt(RED.getText().toString());
            temp_green=Integer.parseInt(GREEN.getText().toString());
            temp_blue=Integer.parseInt(BLUE.getText().toString());
            b_final.setBackgroundColor(Color.argb(255,255,255,0));

            writeColor("Color 255 255 255 0");

        break;

    case R.id.buttonR1C2:

        RED.setText("255");
        GREEN.setText("0");
        BLUE.setText("255");
        temp_red=Integer.parseInt(RED.getText().toString());
        temp_green=Integer.parseInt(GREEN.getText().toString());
        temp_blue=Integer.parseInt(BLUE.getText().toString());
        b_final.setBackgroundColor(Color.argb(255,255,0,255));

            writeColor("Color 255 255 0 255");

        break;

    case R.id.buttonR1C3:

        RED.setText("0");
        GREEN.setText("255");
        BLUE.setText("255");
        temp_red=Integer.parseInt(RED.getText().toString());
        temp_green=Integer.parseInt(GREEN.getText().toString());
        temp_blue=Integer.parseInt(BLUE.getText().toString());
        b_final.setBackgroundColor(Color.argb(255,0,255,255));

            writeColor("Color 255 0 255 255");

        break;

    case R.id.buttonR1C4:

        RED.setText("102");
        GREEN.setText("153");
        BLUE.setText("51");
        temp_red=Integer.parseInt(RED.getText().toString());
        temp_green=Integer.parseInt(GREEN.getText().toString());
        temp_blue=Integer.parseInt(BLUE.getText().toString());
        b_final.setBackgroundColor(Color.argb(255,102,153,51));

            writeColor("Color 255 102 153 51");

        break;

    case R.id.button_result:
        writeColor("Color 255 "+temp_red+" "+temp_green+" "+temp_blue);
        finish();
        break;

    }
}

public void writeColor(String string)
{
    TouchList.Current_Color=string;
    try
    {
    TouchList.dos.writeUTF(TouchList.Current_Color);
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
}
}
</code>```


问:
How can I get URLs of open pages from Chrome and Firefox?
I'm writing a system tray app that needs to check if an internal web based app is open.

I can check IE using the following:

```<code>SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
        string filename;
        bool sdOpen = false;
        foreach (SHDocVw.InternetExplorer ie in shellWindows)
        {
            filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
            if (filename.Equals("iexplore"))
            {
                string[] urlParts = (ie.LocationURL.ToString()).Split('/');
                string website = urlParts[2];
                if (website == "myApp:8080") { sdOpen = true; };
            }
        }

        if (sdOpen) { Console.WriteLine("App is open"); } else { Console.WriteLine("App is not open"); };

        Console.ReadKey(true);
</code>```

However, some of the users using the system prefer Chrome or Firefox.

How can I do the same as above (i.e. get the urls of any open tabs in the browser) for Chrome and Firefox? (I'm not going to bother with other browsers as these are the only ones in use in our organisation.)

答:
Below code work pretty well with Chrome Version 58.0.3029.110:

Please add reference of UIAutomationClient and UIAutomationProvider from Assembly provided by .NET.

```<code>        foreach (Process proc in procsChrome)
        {
            // the chrome process must have a window
            if (proc.MainWindowHandle == IntPtr.Zero)
                continue;

            // to find the tabs we first need to locate something reliable - the 'New Tab' button
            AutomationElement root = AutomationElement.FromHandle(proc.MainWindowHandle);
            var SearchBar = root.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
            if (SearchBar != null)
                return (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
        }
</code>```

Body:
I'm writing a system tray app that needs to check if an internal web based app is open.

I can check IE using the following:

SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
        string filename;
        bool sdOpen = false;
        foreach (SHDocVw.InternetExplorer ie in shellWindows)
        {
            filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
            if (filename.Equals("iexplore"))
            {
                string[] urlParts = (ie.LocationURL.ToString()).Split('/');
                string website = urlParts[2];
                if (website == "myApp:8080") { sdOpen = true; };
            }
        }

        if (sdOpen) { Console.WriteLine("App is open"); } else { Console.WriteLine("App is not open"); };

        Console.ReadKey(true);

However, some of the users using the system prefer Chrome or Firefox.

How can I do the same as above (i.e. get the urls of any open tabs in the browser) for Chrome and Firefox? (I'm not going to bother with other browsers as these are the only ones in use in our organisation.)

Body:
Below code work pretty well with Chrome Version 58.0.3029.110:

Please add reference of UIAutomationClient and UIAutomationProvider from Assembly provided by .NET.

        foreach (Process proc in procsChrome)
        {
            // the chrome process must have a window
            if (proc.MainWindowHandle == IntPtr.Zero)
                continue;

            // to find the tabs we first need to locate something reliable - the 'New Tab' button
            AutomationElement root = AutomationElement.FromHandle(proc.MainWindowHandle);
            var SearchBar = root.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
            if (SearchBar != null)
                return (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
        }


问:
How to stop a value from going into negative value
I'm developing an incremental game here is the link for visual reference:

https://code.sololearn.com/WF65X6DEns7o/#css

The problem i have is that buttons can be clicked unlimited times and INCOME value will go into the negative.

How can disable the button if the player doesn't have enough INCOME to click the button

function buttonOne() {
  a++;
  document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
  income -= 500;
  document.getElementById("HeaderLabel").innerHTML = " OK, good, now let's   watch as your money starts to generate slowly but surely.
 After all no   empire was built in a day.
 When you have enough money you can buy more   units. " ;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 1000)
}

function buttonTwo() {
  b++;
  document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
  income -= 1000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 2000)
}

function buttonThree() {
  c++;
  document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
  income -= 2000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 3000)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gameMoneyBG">
  <div id="gameMoney"> Income : $ 500 </div</div>

    <button id="buttonOne" onclick="buttonOne()">
          <b>Small Units</b></button>
    <div id="progbar1">
      <div id="myprogbar1"> </div>
    </div>
    <br /> <br />
    <div id="btnLabel1"> Units Owned : 0 </div>
    <div id="costLabel1">
      Unit Cost : $ 500 </div>

    <br /><br />

    <button id="buttonTwo" onclick="buttonTwo()"><b>Large Units</b></button>
    <div id="progbar2">
      <div id="myprogbar2"> </div>
    </div>
    <br /><br />
    <div id="btnLabel2"> Units Owned : 0 </div>
    <div id="costLabel2"> Unit Cost : $ 1000 </div>

    <br /><br />

    <button id="buttonThree" onclick="buttonThree()"><b>City Lofts</b></button>
    <div id="progbar3">
      <div id="myprogbar3"> </div>
    </div>
    <br /><br />
    <div id="btnLabel3"> Lofts Owned : 0 </div>
    <div id="costLabel3"> Loft Cost : $ 2000 </div></code>```

答:
First of all as I saw that each function reduces the income with a different value. So first of all define constant integers and set these values in them.
And about your code you can nest the content of the function in an if-else statement

```<code>var buttonOnePrice = 500;

function buttonOne() {
if(income >= buttonOnePrice) {
a++;
document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
income-=buttonOnePrice;
document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets
watch as your money starts to generate slowly but surely. <p> After all no
empire was built in a day. <p> When you have enough money you can buy more
units." ;

window.setInterval (function move() {
var elem = document.getElementById("myprogbar1");
var width = 1;
var id = setInterval(frame, 4);
function frame() {
    if (width >= 100) {
        clearInterval(id);
    } else {
        width++;
        elem.style.width = width + '%';
    }
   }
   }, 1000)
}
    } else {
}
</code>```

and you can handle he else statement as you want. for example you can show an alert "insufficient funds" or something like that

Body:
I'm developing an incremental game here is the link for visual reference:

https://code.sololearn.com/WF65X6DEns7o/#css

The problem i have is that buttons can be clicked unlimited times and INCOME value will go into the negative.

How can disable the button if the player doesn't have enough INCOME to click the button

function buttonOne() {
  a++;
  document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
  income -= 500;
  document.getElementById("HeaderLabel").innerHTML = " OK, good, now let's   watch as your money starts to generate slowly but surely.
 After all no   empire was built in a day.
 When you have enough money you can buy more   units. " ;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 1000)
}

function buttonTwo() {
  b++;
  document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
  income -= 1000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 2000)
}

function buttonThree() {
  c++;
  document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
  income -= 2000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 3000)
}

 Income : $ 500 </div

    <button id="buttonOne" onclick="buttonOne()">
          Small Units</button>

 Units Owned : 0

      Unit Cost : $ 500

    <button id="buttonTwo" onclick="buttonTwo()">Large Units</button>

 Units Owned : 0

 Unit Cost : $ 1000

    <button id="buttonThree" onclick="buttonThree()">City Lofts</button>

 Lofts Owned : 0

 Loft Cost : $ 2000

Body:
First of all as I saw that each function reduces the income with a different value. So first of all define constant integers and set these values in them.
And about your code you can nest the content of the function in an if-else statement

var buttonOnePrice = 500;

function buttonOne() {
if(income >= buttonOnePrice) {
a++;
document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
income-=buttonOnePrice;
document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets
watch as your money starts to generate slowly but surely. <p> After all no
empire was built in a day. <p> When you have enough money you can buy more
units." ;

window.setInterval (function move() {
var elem = document.getElementById("myprogbar1");
var width = 1;
var id = setInterval(frame, 4);
function frame() {
    if (width >= 100) {
        clearInterval(id);
    } else {
        width++;
        elem.style.width = width + '%';
    }
   }
   }, 1000)
}
    } else {
}

and you can handle he else statement as you want. for example you can show an alert "insufficient funds" or something like that


问:
log4php + PHP 7 - catching and logging Throwable
I am having trouble logging a "TypeError" with log4php. I suspect this is because I recently upgraded from php 5.5 to 7.1.

Usually, my syntax looks like this:

```<code><?

use Logger;

class MyClass
{
    /** @var Logger */
    private $logger;

    function __construct(array $configParams)
    {
        Logger::configure('logger.xml');
        $this->logger = Logger::getLogger(__CLASS__);
    }

    public function dostuff()
    {
        try
        {
            // ...
        }
        catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex);
        }
    }
}

?>
</code>```

The above syntax will print lots of info to the log file, including a stack trace. However after reading the latest php7 docs, I believe I'm meant to handle the \Throwable interface, in order to catch both errors and exceptions (which is great). So I replace the above catch with the following:

```<code>catch (\Throwable $ex)
</code>```

This still prints stack-trace information for my exceptions, but when a "TypeError" is caught, nothing gets printed to the log file.

I assume that this is due to log4php not knowing how to log errors. How can I log errors using log4php in a universal way?

Thanks,

答:
I think you should use $ex->getMessage() for error() method your code should be

```<code> catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex->getMessage());
        }
</code>```

For logging trace you should use trace

```<code> catch (Exception $ex)
            {
                $this->logger->trace("ERROR CAUGHT", $ex);
            }
</code>```

Body:
I am having trouble logging a "TypeError" with log4php. I suspect this is because I recently upgraded from php 5.5 to 7.1.

Usually, my syntax looks like this:

<?

use Logger;

class MyClass
{
    /** @var Logger */
    private $logger;

    function __construct(array $configParams)
    {
        Logger::configure('logger.xml');
        $this->logger = Logger::getLogger(__CLASS__);
    }

    public function dostuff()
    {
        try
        {
            // ...
        }
        catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex);
        }
    }
}

?>

The above syntax will print lots of info to the log file, including a stack trace. However after reading the latest php7 docs, I believe I'm meant to handle the \Throwable interface, in order to catch both errors and exceptions (which is great). So I replace the above catch with the following:

catch (\Throwable $ex)

This still prints stack-trace information for my exceptions, but when a "TypeError" is caught, nothing gets printed to the log file.

I assume that this is due to log4php not knowing how to log errors. How can I log errors using log4php in a universal way?

Thanks,

Body:
I think you should use $ex->getMessage() for error() method your code should be

 catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex->getMessage());
        }

For logging trace you should use trace

 catch (Exception $ex)
            {
                $this->logger->trace("ERROR CAUGHT", $ex);
            }


答:
You can check if the income is below some thresold and then call:

```<code>document.getElementById("btnLabel1").disabled = true;
</code>```

When the income gets higher you can set it back to false.

Title: How to stop a value from going into negative value

Body:
You can check if the income is below some thresold and then call:

document.getElementById("btnLabel1").disabled = true;

When the income gets higher you can set it back to false.


问:
I am changing the value of data-* attribute with the onclick function in jQuery. The value of the atribute changes but did not work
My problem is in the following link,
http://www.cannonfoam.com/prdetail?id=212. This is a product page. where product have one primery image and two secondary images. the following link is provide detail and process to the liabrary that i have used for image zoom on hover. http://www.elevateweb.co.uk/image-zoom. this liabrary use src attribute to show small image and then data-zoom-image attribute have the path of image that is to show as zoomed image..

Now, problem is that i have been asked that primary image should be replaced with a secondary image when clicked on a secondary image. I have created a function that replace src attribute value and data-zoom-image attribute value. image is changing successfully and when i inspect element then i can see that data-zoom-image attribute changes as well. but in zoomed image only primary image is visible..

i am unable to understad that when image path is changing in data-zoom-image attribute the why zoomed image is not beeing changed in zoom section..

please some body help me in this respact.. my client is geting angry on me.. waiting for correct solution..

答:
If you have an image like this:

```<code><img id="zoom_01" src="small/image1.png" data-zoom-image="large/image1.jpg"/>
</code>```

Then you can activate the zoom functionality with this:

```<code>$("#zoom_01").elevateZoom();
</code>```

Body:
If you have an image like this:

<img id="zoom_01" src="small/image1.png" data-zoom-image="large/image1.jpg"/>

Then you can activate the zoom functionality with this:

$("#zoom_01").elevateZoom();


问:
CSS Font Images
another quick question. I've seen this multiple times now in different code sets. Someone calls for an image from the css

HTML:

```<code>    <a href="#"><i class="icon-map-marker2"></i></a>
</code>```

CSS

```<code>.icon-map-marker2:before {
    content: "\e6f9";
}
</code>```

Which gives the output of this:

As you can see the picture isn't transparent background. I was looking to edit it to give it transparency, but can't seem to find out how. I've also tried things with the CSS like:

```<code>style="background-color:rgba(0, 0, 0, 0.5);"
// Changing the last value's number though and stuff like that
opacity: 1;
// etc
</code>```

I want to keep the gold color, but have a transparent background! Thanks for the assistance!

An example is on Canvas' live preview - Hover Home -> One Page: http://preview.themeforest.net/item/canvas-the-multipurpose-html5-template/full_screen_preview/9228123?_ga=2.252490057.1116575863.1496646725-686174233.1494200798

答:
An option... Download the photo and save it as a png with a transparent BG.

Personally I use Photoshop though there is a free software called Gimp - Free & Open Source Image Editor that will allow you to format transparent photos and then save them as .png.

Typical method involved saving an image locally, editing and

exporting as transparent png.

Right click the hosted photo in your browser and then choose Open Image In New Tab

Right click on the image within the newly opened tab and select Save link as, then choose your destination folder.

Open your image editor software, see my link below for GIMP if needed.

Typically, if you have a good contrast between the BG and the
image or the background is one solid color, as is in your case. You can pull the image out of the background by using the Magic Wand tool.

You can also use the lasso tool to make the selection, where you sort of draw around the selection. However, this method is a bit more tedious and time consuming.

Once you have your image selected apart from the background you wish to remove, simply hit the delete button to delete the selected pixels. *MAKE SURE YOU HAVE THE BACKGROUND SELECTED AND NOT THE IMAGE WHEN YOU DELETE!

Only need feather if you have soft edges, if not skip feathering.

Feather: Feather the selection. Under Select->Modify->Feather. Enter a low number like .5 though you may need to experiment to find the right amount
to feather your softer edges, when needed. Then select the inversion and delete the selected inversion to apply the feather and soften your edge.

Now export your image as a .png file and host it so you can link to the new transparent image.

In PhotoShop, you would choose File->Save For Web  Choose PNG-24 and select Transparent

Note the size, preview if needed, then save.

Now re-host within your websites image file structure or online at    imgur or other img site and link to the newly posted
transparent pic.

Title: CSS Font Images

Body:
another quick question. I've seen this multiple times now in different code sets. Someone calls for an image from the css

HTML:

CSS

.icon-map-marker2:before {
    content: "\e6f9";
}

Which gives the output of this:

As you can see the picture isn't transparent background. I was looking to edit it to give it transparency, but can't seem to find out how. I've also tried things with the CSS like:

style="background-color:rgba(0, 0, 0, 0.5);"
// Changing the last value's number though and stuff like that
opacity: 1;
// etc

I want to keep the gold color, but have a transparent background! Thanks for the assistance!

An example is on Canvas' live preview - Hover Home -> One Page: http://preview.themeforest.net/item/canvas-the-multipurpose-html5-template/full_screen_preview/9228123?_ga=2.252490057.1116575863.1496646725-686174233.1494200798


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答: You aren't limited to DEBUG and RELEASE. You can specify other constants with #define or in the project properties.

OwnerDisplayName: WindyCityEagle

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

OwnerDisplayName: lc


问:
when i try to register by my app i didn't get any respnse
I am trying to save my data to server. can any one help me?

when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??

```<code>public class Register extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
        etCity;
Button register;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    etName = (EditText) findViewById(R.id.name);
    etEmail = (EditText) findViewById(R.id.email);
    etMobile = (EditText) findViewById(R.id.mobile);
    etCity = (EditText) findViewById(R.id.etCity);
    etPassword = (EditText) findViewById(R.id.password);
    //etRePassword = (EditText) findViewById(R.id.rePassword);
    register = (Button) findViewById(R.id.bRegister);
    register.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    final String name = etName.getText().toString();
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    final String city = etCity.getText().toString();
    final String phoneno = etMobile.getText().toString();

    StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + " Response");
            if(response.equals("SUCCESS")){
                startActivity(new Intent(Register.this,MainActivity.class));
            }
            else{
                Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.toString());
            if(error.networkResponse == null){
                if(error.getClass().equals(TimeoutError.class));
                Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
            }
        }
    }){
        @Override
        public Map<String, String> getHeaders()throws AuthFailureError{
            Map<String, String> headers = new HashMap<>();
            headers.put("name",name);
            headers.put("email",email);
            headers.put("password",password);
            headers.put("city",city);
            headers.put("phoneno",phoneno);
            return headers;
        }
    };
    registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    /*Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + "");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    Intent intent = new Intent(Register.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                    builder.setMessage("Registration failed").setNegativeButton("Retry", null)
                            .create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //super.getHeaders();
            Map<String,String> headers = new HashMap<>();
            String credential = "raju@gmail.com:123";
            String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
            //headers.put("Content-Type");
            headers.put("Authorization",auth);
            //
            return headers;
        }
    };*/
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            registerRequest.setShouldCache(false);
            queue.add(registerRequest);
}
}
</code>```

Here Is my server code....

```<code>@RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(@RequestBody MobileUserModel mobileUser) {

    MobileUserModel user = new MobileUserModel();
    user.setActivationKey(mobileUser.getActivationKey());
    user.setCity(mobileUser.getCity());
    user.setEmail(mobileUser.getEmail());

    user.setImeino(mobileUser.getImeino());

    user.setName(mobileUser.getName());

    user.setPassword(mobileUser.getPassword());

    user.setPhoneno(mobileUser.getPhoneno());

    userrepository.save(user);

    System.out.println("Saved");

    // return "User has been saved Successfully";
    return "SUCCESS";

}
</code>```

答:
Make Sure you have given Internet permissions in your manifest.</p>

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

Body:
I am trying to save my data to server. can any one help me?

when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??

public class Register extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
        etCity;
Button register;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    etName = (EditText) findViewById(R.id.name);
    etEmail = (EditText) findViewById(R.id.email);
    etMobile = (EditText) findViewById(R.id.mobile);
    etCity = (EditText) findViewById(R.id.etCity);
    etPassword = (EditText) findViewById(R.id.password);
    //etRePassword = (EditText) findViewById(R.id.rePassword);
    register = (Button) findViewById(R.id.bRegister);
    register.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    final String name = etName.getText().toString();
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    final String city = etCity.getText().toString();
    final String phoneno = etMobile.getText().toString();

    StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + " Response");
            if(response.equals("SUCCESS")){
                startActivity(new Intent(Register.this,MainActivity.class));
            }
            else{
                Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.toString());
            if(error.networkResponse == null){
                if(error.getClass().equals(TimeoutError.class));
                Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
            }
        }
    }){
        @Override
        public Map<String, String> getHeaders()throws AuthFailureError{
            Map<String, String> headers = new HashMap<>();
            headers.put("name",name);
            headers.put("email",email);
            headers.put("password",password);
            headers.put("city",city);
            headers.put("phoneno",phoneno);
            return headers;
        }
    };
    registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    /*Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + "");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    Intent intent = new Intent(Register.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                    builder.setMessage("Registration failed").setNegativeButton("Retry", null)
                            .create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //super.getHeaders();
            Map<String,String> headers = new HashMap<>();
            String credential = "raju@gmail.com:123";
            String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
            //headers.put("Content-Type");
            headers.put("Authorization",auth);
            //
            return headers;
        }
    };*/
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            registerRequest.setShouldCache(false);
            queue.add(registerRequest);
}
}

Here Is my server code....

@RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(@RequestBody MobileUserModel mobileUser) {

    MobileUserModel user = new MobileUserModel();
    user.setActivationKey(mobileUser.getActivationKey());
    user.setCity(mobileUser.getCity());
    user.setEmail(mobileUser.getEmail());

    user.setImeino(mobileUser.getImeino());

    user.setName(mobileUser.getName());

    user.setPassword(mobileUser.getPassword());

    user.setPhoneno(mobileUser.getPhoneno());

    userrepository.save(user);

    System.out.println("Saved");

    // return "User has been saved Successfully";
    return "SUCCESS";

}

Body:
Make Sure you have given Internet permissions in your manifest.

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


问:
org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP
unable to compile jsp in netbeans with glass fish server3.1.2,it is showing the following exception

```<code>org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
';' expected

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
';' expected

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
not a statement

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
';' expected
</code>```

my java and jsp code

```<code><%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@page language="java" import= "java.sql.*"%>
<%
String driver="org.postgresql.Driver";
Class.forName(driver).newInstance();
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try
{
  String url="jdbc:postgresql://localhost:5432/ksa?user="postgres"password="postgres"";
  con=DriverManager.getConnection("url");
  stmt=con.createStatement();
}
catch(Exception e)
               {
  System.out.println(e.getMessage());
       }
if(request.getParameter("action")!=null)
       {
           String name=request.getParameter("name");
           String address=request.getParameter("address");
           String id=request.getParameter("id");
           stmt.executeUpdate("insert into cd values('"+ name +"','"+ address +"')");
           rst=stmt.executeQuery("select * from cd");
       }
%>
</code>```

netbeans shows the error in the line

```<code>String url="jdbc:postgresql://localhost:5432/ksa?user="postgres"password="postgres"";
</code>```

iam using postgresql9.1,the glassfish log shows the following

```<code>SEVERE: Error compiling file: /home/adapco/.netbeans/7.1.1/config/GF3_1/domain1  /generated/jsp/cddata/org/apache/jsp/index_jsp.java
WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
</code>```

答: I think it's a small wrong,your '{' and '}' don't match,and i met the same question. </p>

Body:
unable to compile jsp in netbeans with glass fish server3.1.2,it is showing the following exception

org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
';' expected

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
';' expected

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
not a statement

PWC6197: An error occurred at line: 9 in the jsp file: /index.jsp
PWC6199: Generated servlet error:
';' expected

my java and jsp code

<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@page language="java" import= "java.sql.*"%>
<%
String driver="org.postgresql.Driver";
Class.forName(driver).newInstance();
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try
{
  String url="jdbc:postgresql://localhost:5432/ksa?user="postgres"password="postgres"";
  con=DriverManager.getConnection("url");
  stmt=con.createStatement();
}
catch(Exception e)
               {
  System.out.println(e.getMessage());
       }
if(request.getParameter("action")!=null)
       {
           String name=request.getParameter("name");
           String address=request.getParameter("address");
           String id=request.getParameter("id");
           stmt.executeUpdate("insert into cd values('"+ name +"','"+ address +"')");
           rst=stmt.executeQuery("select * from cd");
       }
%>

netbeans shows the error in the line

String url="jdbc:postgresql://localhost:5432/ksa?user="postgres"password="postgres"";

iam using postgresql9.1,the glassfish log shows the following

SEVERE: Error compiling file: /home/adapco/.netbeans/7.1.1/config/GF3_1/domain1  /generated/jsp/cddata/org/apache/jsp/index_jsp.java
WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception


答:
There is an example in the website.

Here is a hint.

```<code>var ez = $('#zoom_01').data('elevateZoom');
ez.swaptheimage('http://www.cannonfoam.com/assets/images/product/True Restb.jpg', 'http://www.cannonfoam.com/assets/images/product/True Restb.jpg');
</code>```

my suggestion is that you should take a look and modify your click event.

Title: I am changing the value of data-* attribute with the onclick function in jQuery. The value of the atribute changes but did not work

Body:
My problem is in the following link,
http://www.cannonfoam.com/prdetail?id=212. This is a product page. where product have one primery image and two secondary images. the following link is provide detail and process to the liabrary that i have used for image zoom on hover. http://www.elevateweb.co.uk/image-zoom. this liabrary use src attribute to show small image and then data-zoom-image attribute have the path of image that is to show as zoomed image..

Now, problem is that i have been asked that primary image should be replaced with a secondary image when clicked on a secondary image. I have created a function that replace src attribute value and data-zoom-image attribute value. image is changing successfully and when i inspect element then i can see that data-zoom-image attribute changes as well. but in zoomed image only primary image is visible..

i am unable to understad that when image path is changing in data-zoom-image attribute the why zoomed image is not beeing changed in zoom section..

please some body help me in this respact.. my client is geting angry on me.. waiting for correct solution..

Body:
There is an example in the website.

Here is a hint.

var ez = $('#zoom_01').data('elevateZoom');
ez.swaptheimage('http://www.cannonfoam.com/assets/images/product/True Restb.jpg', 'http://www.cannonfoam.com/assets/images/product/True Restb.jpg');

my suggestion is that you should take a look and modify your click event.


问:
Why can't an operator declared in a derived class hide an operator declared in a base class?
From C# 5.0 Specification

3.6 Signatures and overloading

...

The signature of an operator consists of the name of the operator and the type of each of its formal  parameters, considered in the
  order left to right. The signature of an operator specifically does
  not include  the result type.

...

10.10 Operators

...

Like other members, operators declared in a base class are inherited
  by derived classes. Because operator  declarations always require
  the class or struct in which the operator is declared to participate
  in the signature of  the operator, it is not possible for an
  operator declared in a derived class to hide an operator declared in a
  base  class. Thus, the new modifier is never required, and therefore
  never permitted, in an operator declaration.

The first paragraph doesn't say that "the class or struct in which
the operator is declared" is part of the operator's signature. So
what does "operator  declarations always require  the class or
struct in which the operator is declared to participate  in the
signature of  the operator" in the second paragraph mean?

Does that apply to an operator's signature  but not to a method's
signature?

If "it is not possible for an operator declared in a derived class
to hide an operator declared in a base  class", is it possible for a
method and why?

Thanks.

答:
Operator is basically (but not always) static function with special syntax. + is like static T Add(T first, T second), = is like static void Assign(ref T location, T value) and so on. Certain operators in C# can be overloaded, some (like assignment = operator) cannot. When compiler sees an operator that can be overloaded - it should find corresponding static function to use (unless such function is built-in, like for integer addition for example). So suppose compiler sees a + b where a is TypeA and b is TypeB. Compiler goes to the types TypeA and TypeB (and their parents if necessary) to see if there is a static function with matching name and signature for given case. In this case it should be public static int op_Addition(TypeAOrBaseType a, TypeBOrBaseType b) (operator + will be compiled to method with name op_Addition). From that it should be clear why class you declare operator in should participate in operators signature - if you declare something like static int operator +(TypeC a, TypeD b) in type TypeA - it just never can be used, because when you add TypeC and TypeD - compiler will never look for corresponding operator in TypeA - why would it? It will look inTypeC and  TypeD.

Of course it's not the case for regular methods - in regular methods you can use any types in signature, and it's not required to use instance of declaring type in signature (though you might say that in instance methods instance of declaring type is always implicitly passed and can be used with this keyword).

Hiding does not make much sense for operators, because it's hard to make meaningful operator with exactly the same signature in parent and child class. In comments you can see that it's still possible to make such operator (which is useless), but even then it's not hiding, because if it were hiding - one of those operators should be chosen on use (either from child class or from parent class), but instead compiler complains about ambiguity. For regular methods hiding is often useful and so is allowed.


问:
Emit each item from Flowable Room ORM
I have a list of items in the Room ORM which I would like to display in a Recycler view. The data is being added from the network to the db. The problem is I am getting every time the whole list emited from the Flowable and not each item. I have tried with .distinctUntilChanged with no difference.

```<code>@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();
</code>```

I have tried also to return only a single item which loads only the first one that is the db.

答:
You can use flatMap to get stream of items.

```<code>itemDao.getItems().flatMap(list -> {
      Item[] items = new Item[list.size()];
      list.toArray(items);
      return Flowable.fromArray(items);
    }).subscribe(item -> {
      // Now you can do with each item.

    });
</code>```

If you only need the first item:

```<code>itemDao.getItems().flatMap(list -> {
          Item[] items = new Item[list.size()];
          list.toArray(items);
          return Flowable.fromArray(items);
        })
         .firstElement()
         .subscribe(first -> {
          // Now you can do with the first one.

        });
</code>```

Title: Emit each item from Flowable Room ORM

Body:
I have a list of items in the Room ORM which I would like to display in a Recycler view. The data is being added from the network to the db. The problem is I am getting every time the whole list emited from the Flowable and not each item. I have tried with .distinctUntilChanged with no difference.

@Query("SELECT * FROM items")
Flowable<List<Item>> getItems();

I have tried also to return only a single item which loads only the first one that is the db.

Body:
You can use flatMap to get stream of items.

itemDao.getItems().flatMap(list -> {
      Item[] items = new Item[list.size()];
      list.toArray(items);
      return Flowable.fromArray(items);
    }).subscribe(item -> {
      // Now you can do with each item.

    });

If you only need the first item:

itemDao.getItems().flatMap(list -> {
          Item[] items = new Item[list.size()];
          list.toArray(items);
          return Flowable.fromArray(items);
        })
         .firstElement()
         .subscribe(first -> {
          // Now you can do with the first one.

        });


问:
UIButton embeded in UIVIew no responsible
I have a problem

i created 6 UIButtons put them in a UIView1

then put the UIView1 into another UIView2

then return UIView2 as UITableView.tableHeaderView

now the problem is when i touch the buttons

no responsiblity

here is some information
1. UIButtons UIView1 UIView2 fremes are these

```<code>    2017-06-04 16:26:40.014 LOLHelper[8590:223132] BUT frame is :8.000000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.014 LOLHelper[8590:223132] BUT frame is :86.500000 8.000000 71.000000 18.000000
2017-06-04 16:26:40.014 LOLHelper[8590:223132] BUT frame is :165.500000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] BUT frame is :244.000000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] BUT frame is :322.500000 8.000000 71.000000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] BUT frame is :401.500000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] SubView frame is: :-3.000000 0.000000 480.000000 20.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] headerView frame is: :0.000000 0.000000 320.000000 20.000000
</code>```

2.i turn on the userInteractionEnabled of UIButtons UIView1 UIView2 , u can see in the code :

```<code>    #import "TableViewDataSource.h"

@implementation TableViewDataSource

@synthesize tableView;
@synthesize tableCell;
@synthesize LHfetchedResultsController;
@synthesize numberOfRows;
@synthesize dataTemp;
@synthesize paused;
@synthesize type;
@synthesize imgAche;
@synthesize cellHeight;
@synthesize subHeaderViewFrame;

-(id)initWithTableView:(UITableView *) tableView
{
    self = [super init];
    if (self) {
        self.tableView = tableView;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.tableHeaderView = [self setHeaderView];
    }
    return self;
}
-(UIView *)setHeaderView
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIView * container = [[UIView alloc] init];
    container.frame = CGRectMake(0, 0, screenSize.width, 20);
    container.userInteractionEnabled = YES;

    UIView * headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, screenSize.width*1.5, 20);
    headerView.tag = 01;
    headerView.userInteractionEnabled = YES;
    [container addSubview:headerView];
    for (int i = 1; i < 7; i++) {
        UIButton * button = [[UIButton alloc] init];
        button.tag = i+10;
        button.titleLabel.font = [UIFont boldSystemFontOfSize:12];
        [button setTitle:[NSString stringWithFormat:@"but0%d",i] forState:UIControlStateNormal];
        [button setTitle:[NSString stringWithFormat:@"but0%d s",i] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.translatesAutoresizingMaskIntoConstraints = NO;
        [button setTitleColor:[UIColor brownColor] forState:UIControlStateSelected];
        button.enabled = YES;
        button.userInteractionEnabled = YES;
        [headerView addSubview:button];
    }
    UIButton *button01 = [headerView viewWithTag:11];
    UIButton *button02 = [headerView viewWithTag:12];
    UIButton *button03 = [headerView viewWithTag:13];
    UIButton *button04 = [headerView viewWithTag:14];
    UIButton *button05 = [headerView viewWithTag:15];
    UIButton *button06 = [headerView viewWithTag:16];

    NSDictionary * views = NSDictionaryOfVariableBindings(button01,button02,button03,button04,button05,button06);
    NSString * vflV1 = @"V:|-1-[button01]-1-|";
    NSString * vflV2 = @"V:|-1-[button02]-1-|";
    NSString * vflV3 = @"V:|-1-[button03]-1-|";
    NSString * vflV4 = @"V:|-1-[button04]-1-|";
    NSString * vflV5 = @"V:|-1-[button05]-1-|";
    NSString * vflV6 = @"V:|-1-[button06]-1-|";
    NSString * vflH1 = @"H:|-[button01]-[button02(==button01)]-[button03(==button01)]-[button04(==button01)]-[button05(==button01)]-[button06(==button01)]-|";

    NSArray * constraintsV1 = [NSLayoutConstraint constraintsWithVisualFormat:vflV1 options:0 metrics:NULL views:views];
    NSArray * constraintsV2 = [NSLayoutConstraint constraintsWithVisualFormat:vflV2 options:0 metrics:NULL views:views];
    NSArray * constraintsV3 = [NSLayoutConstraint constraintsWithVisualFormat:vflV3 options:0 metrics:NULL views:views];
    NSArray * constraintsV4 = [NSLayoutConstraint constraintsWithVisualFormat:vflV4 options:0 metrics:NULL views:views];
    NSArray * constraintsV5 = [NSLayoutConstraint constraintsWithVisualFormat:vflV5 options:0 metrics:NULL views:views];
    NSArray * constraintsV6 = [NSLayoutConstraint constraintsWithVisualFormat:vflV6 options:0 metrics:NULL views:views];
    NSArray * constraintsH1 = [NSLayoutConstraint constraintsWithVisualFormat:vflH1 options:0 metrics:NULL views:views];

    [headerView addConstraints:constraintsV1];
    [headerView addConstraints:constraintsV2];
    [headerView addConstraints:constraintsV3];
    [headerView addConstraints:constraintsV4];
    [headerView addConstraints:constraintsV5];
    [headerView addConstraints:constraintsV6];
    [headerView addConstraints:constraintsH1];

    return container;
}
</code>```

i have not find the reason

anyone could help me?

i also add some UISwipeGestureRecognizer into UIView2

thank u

答:
Thank u Guys
i got the solution
reason is that
        [button addTarget:NULL action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
i set target NULL, and write click: in the same file, but actually i get the table from the main controller, so when i click button, xcode will find click: in the main controller, then can not find, so no responsibility.
after i set target self or write click: in main controller
it works

Body:
I have a problem

i created 6 UIButtons put them in a UIView1

then put the UIView1 into another UIView2

then return UIView2 as UITableView.tableHeaderView

now the problem is when i touch the buttons

no responsiblity

here is some information
1. UIButtons UIView1 UIView2 fremes are these

    2017-06-04 16:26:40.014 LOLHelper[8590:223132] BUT frame is :8.000000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.014 LOLHelper[8590:223132] BUT frame is :86.500000 8.000000 71.000000 18.000000
2017-06-04 16:26:40.014 LOLHelper[8590:223132] BUT frame is :165.500000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] BUT frame is :244.000000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] BUT frame is :322.500000 8.000000 71.000000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] BUT frame is :401.500000 8.000000 70.500000 18.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] SubView frame is: :-3.000000 0.000000 480.000000 20.000000
2017-06-04 16:26:40.015 LOLHelper[8590:223132] headerView frame is: :0.000000 0.000000 320.000000 20.000000

2.i turn on the userInteractionEnabled of UIButtons UIView1 UIView2 , u can see in the code :

    #import "TableViewDataSource.h"

@implementation TableViewDataSource

@synthesize tableView;
@synthesize tableCell;
@synthesize LHfetchedResultsController;
@synthesize numberOfRows;
@synthesize dataTemp;
@synthesize paused;
@synthesize type;
@synthesize imgAche;
@synthesize cellHeight;
@synthesize subHeaderViewFrame;

-(id)initWithTableView:(UITableView *) tableView
{
    self = [super init];
    if (self) {
        self.tableView = tableView;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.tableHeaderView = [self setHeaderView];
    }
    return self;
}
-(UIView *)setHeaderView
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIView * container = [[UIView alloc] init];
    container.frame = CGRectMake(0, 0, screenSize.width, 20);
    container.userInteractionEnabled = YES;

    UIView * headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, screenSize.width*1.5, 20);
    headerView.tag = 01;
    headerView.userInteractionEnabled = YES;
    [container addSubview:headerView];
    for (int i = 1; i < 7; i++) {
        UIButton * button = [[UIButton alloc] init];
        button.tag = i+10;
        button.titleLabel.font = [UIFont boldSystemFontOfSize:12];
        [button setTitle:[NSString stringWithFormat:@"but0%d",i] forState:UIControlStateNormal];
        [button setTitle:[NSString stringWithFormat:@"but0%d s",i] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.translatesAutoresizingMaskIntoConstraints = NO;
        [button setTitleColor:[UIColor brownColor] forState:UIControlStateSelected];
        button.enabled = YES;
        button.userInteractionEnabled = YES;
        [headerView addSubview:button];
    }
    UIButton *button01 = [headerView viewWithTag:11];
    UIButton *button02 = [headerView viewWithTag:12];
    UIButton *button03 = [headerView viewWithTag:13];
    UIButton *button04 = [headerView viewWithTag:14];
    UIButton *button05 = [headerView viewWithTag:15];
    UIButton *button06 = [headerView viewWithTag:16];

    NSDictionary * views = NSDictionaryOfVariableBindings(button01,button02,button03,button04,button05,button06);
    NSString * vflV1 = @"V:|-1-[button01]-1-|";
    NSString * vflV2 = @"V:|-1-[button02]-1-|";
    NSString * vflV3 = @"V:|-1-[button03]-1-|";
    NSString * vflV4 = @"V:|-1-[button04]-1-|";
    NSString * vflV5 = @"V:|-1-[button05]-1-|";
    NSString * vflV6 = @"V:|-1-[button06]-1-|";
    NSString * vflH1 = @"H:|-[button01]-[button02(==button01)]-[button03(==button01)]-[button04(==button01)]-[button05(==button01)]-[button06(==button01)]-|";

    NSArray * constraintsV1 = [NSLayoutConstraint constraintsWithVisualFormat:vflV1 options:0 metrics:NULL views:views];
    NSArray * constraintsV2 = [NSLayoutConstraint constraintsWithVisualFormat:vflV2 options:0 metrics:NULL views:views];
    NSArray * constraintsV3 = [NSLayoutConstraint constraintsWithVisualFormat:vflV3 options:0 metrics:NULL views:views];
    NSArray * constraintsV4 = [NSLayoutConstraint constraintsWithVisualFormat:vflV4 options:0 metrics:NULL views:views];
    NSArray * constraintsV5 = [NSLayoutConstraint constraintsWithVisualFormat:vflV5 options:0 metrics:NULL views:views];
    NSArray * constraintsV6 = [NSLayoutConstraint constraintsWithVisualFormat:vflV6 options:0 metrics:NULL views:views];
    NSArray * constraintsH1 = [NSLayoutConstraint constraintsWithVisualFormat:vflH1 options:0 metrics:NULL views:views];

    [headerView addConstraints:constraintsV1];
    [headerView addConstraints:constraintsV2];
    [headerView addConstraints:constraintsV3];
    [headerView addConstraints:constraintsV4];
    [headerView addConstraints:constraintsV5];
    [headerView addConstraints:constraintsV6];
    [headerView addConstraints:constraintsH1];

    return container;
}

i have not find the reason

anyone could help me?

i also add some UISwipeGestureRecognizer into UIView2

thank u


问:
Trouble sending data between PHP and Python
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being received by the PHP script.

The python search script is called from PHP and the first result is displayed with the following commands

```<code>exec("python print.py",$output,$ret_code);

echo $output[0];
</code>```

The python script -

```<code>from whoosh.index import open_dir

ixtemp = open_dir("index")

searcher = ixtemp.searcher()

results = searcher.find("content", u""+"test")

for k in results:
    print k['filename']
</code>```

Running the PHP now gives the following error -

Notice: Undefined offset: 0 in
  /opt/lampp/htdocs/new/search.php on
  line 17

The python script is working when I run it by itself. After a little investigation it seems that any print statements before the line "searcher = ixtemp.searcher()" can be read by the PHP, but all after are not received by the PHP script. I've also tried the popen() and proc_open functions too, but they have the same problem.

Any ideas on what the problem is or how I can work around it?

Thanks

答:
I ran out ideas and decided to chmod 777 the directory...and...it worked. I'm not sure why it did since data could always be sent above the searcher() function anyway.

Perhaps while initiating the search the method was trying to modify protected index files?

But that couldn't in itself be the problem since it always worked from the interpreter.

So it must have been the PHP file. It seems to have been protection against indirectly modifying the index files.

Body:
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being received by the PHP script.

The python search script is called from PHP and the first result is displayed with the following commands

exec("python print.py",$output,$ret_code);

echo $output[0];

The python script -

from whoosh.index import open_dir

ixtemp = open_dir("index")

searcher = ixtemp.searcher()

results = searcher.find("content", u""+"test")

for k in results:
    print k['filename']

Running the PHP now gives the following error -

Notice: Undefined offset: 0 in
  /opt/lampp/htdocs/new/search.php on
  line 17

The python script is working when I run it by itself. After a little investigation it seems that any print statements before the line "searcher = ixtemp.searcher()" can be read by the PHP, but all after are not received by the PHP script. I've also tried the popen() and proc_open functions too, but they have the same problem.

Any ideas on what the problem is or how I can work around it?

Thanks


问:
How to Display and load images from URL that are visible in UITableViewCell
I tried this link, but I didn't get my solution.

I want to display and load images from URL that are visible in UITableViewCell and other cell images have to load when we scroll table view in Objective-C.

答:
use SDWebImage for this. it has almost all features what you need. It's also easy to coding like this.

Objective C

```<code>[imageView sd_setImageWithURL:[NSURL URLWithString:@"your domain"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
</code>```

Additional:

swift 3:

```<code>imageView.sd_setImage(with: URL(string: "your domain"), placeholderImage: UIImage(named: "placeholder.png"))
</code>```

Body:
use SDWebImage for this. it has almost all features what you need. It's also easy to coding like this.

Objective C

[imageView sd_setImageWithURL:[NSURL URLWithString:@"your domain"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Additional:

swift 3:

imageView.sd_setImage(with: URL(string: "your domain"), placeholderImage: UIImage(named: "placeholder.png"))


问:
Connecting to my Local Mac from Azure Vmware for IOS Development
I have an Azure Vmware Server with VS Studio 2017 community installed.
I want to connect the VS 2017 to my Mac for IOS Development.

I have enabled the remote login on my Mac but I am not able to connect using the Mac agent
Any help is appreciated.

答:
Mac agent use port 22 to connect with client computer. We need to enable this port on Windows Firewall and Network Security Group for your Azure VM.

Steps to enable a port on Windows Firewall.

Step 1, open Windows Firewall by inputting 'wf.msc' in Run window.

Step 2, add new rule for both inbound rules and outbound rules. In the specific port box, input 22.

Steps to enable SSH on Network Security Group.

Step 1, open the Network Security Group of your VM.

Step 2, add new rule for both inbound security rules and outbound security rules.

Please also make sure that your Mac machine has a public IP address and the port 22 is not disabled by any software.


问:
Joining table into 4 columns and show another fields
I have a new problem, as information from my question before, I already successfully show 4 column from joining another table, but I got another problem to show another column, for more detail :

Table personal (tbl_personal)

```<code>+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+
</code>```

Table master (tbl_master)

```<code>+---+---------+---------+-----------+--------+----+
|ID |Employee1|Employee2|Departement|Division|Note|
+---+---------+---------+-----------+--------+----+
| 1 | 1       | 2       | MSO       | MWS    | etc|
| 2 | 2       | 1       | DSO       | SE     | etc|
| 3 | 3       | 4       | OSO       | GA     | etc|
+---+---------+---------+-----------+--------+----+
</code>```

I want to show into web page from tbl_master above in codeigniter like this :

```<code>+---+-------+-----------+-------+-----------+-----------+--------+----+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |Departement|Division|Note|
+---+-------+-----------+-------+-----------+-----------+--------+----+
| 1 | Nia   | Accountant| Tia   | Banking   | MSO       | MWS    | etc|
| 2 | Tia   | Banking   | Nia   | Accountant| DSO       | SE     | etc|
| 3 | Ria   | Technicall| Dia   | Admin     | OSO       | GA     | etc|
+---+---------+---------+-------+-----------+-----------+--------+----+
</code>```

I already got solution to show Name 1, Skill 1 until Skill 2 with this code :

```<code>select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID
</code>```

but I have another problem to show departemen, Division, and Note columns, if there any advice, please, thanks...

答:
You just need to change your select and add those columns:</p>

```<code>select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2,tm.Departement, tm.Division, tm.Note
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID
</code>```

Body:
I have a new problem, as information from my question before, I already successfully show 4 column from joining another table, but I got another problem to show another column, for more detail :

Table personal (tbl_personal)

+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+

Table master (tbl_master)

+---+---------+---------+-----------+--------+----+
|ID |Employee1|Employee2|Departement|Division|Note|
+---+---------+---------+-----------+--------+----+
| 1 | 1       | 2       | MSO       | MWS    | etc|
| 2 | 2       | 1       | DSO       | SE     | etc|
| 3 | 3       | 4       | OSO       | GA     | etc|
+---+---------+---------+-----------+--------+----+

I want to show into web page from tbl_master above in codeigniter like this :

+---+-------+-----------+-------+-----------+-----------+--------+----+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |Departement|Division|Note|
+---+-------+-----------+-------+-----------+-----------+--------+----+
| 1 | Nia   | Accountant| Tia   | Banking   | MSO       | MWS    | etc|
| 2 | Tia   | Banking   | Nia   | Accountant| DSO       | SE     | etc|
| 3 | Ria   | Technicall| Dia   | Admin     | OSO       | GA     | etc|
+---+---------+---------+-------+-----------+-----------+--------+----+

I already got solution to show Name 1, Skill 1 until Skill 2 with this code :

select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID

but I have another problem to show departemen, Division, and Note columns, if there any advice, please, thanks...

Body:
You just need to change your select and add those columns:

select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2,tm.Departement, tm.Division, tm.Note
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID


问:
Get external SD card path programatically
My tablet have Internal Storage,USB Storage,External SD card Storage.I need to access External SD card.Still I cannot get the correct answer.</p>

答:
its so easy to get the paths of internal and external sd card paths.
for that we just need to use the reflection mehtod and no need of rooting or signing of app.
Add the following permission in manifest.

uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"

Code:

final Class surfaceControlClass = Class.forName("android.os.storage.StorageManager");

Method method1 = surfaceControlClass.getMethod("getVolumePaths")

method1.setAccessible(true);

final Object object = context.getSystemService(Context.STORAGE_SERVICE);

String[] volumes = method1.invoke(object)


问:
Specifying default value for django hidden form field - bone DRY?
So let's say at the last minute (in the view) I decide I want to specify a default for a field and make it hidden, like so:

```<code>form.fields['coconut'] = forms.ModelChoiceField(
    label="",
    widget=forms.HiddenInput(),
    queryset=swallow.coconuts.all(),
    initial=some_particular_coconut,
)
</code>```

My question is this:  Do I really need to specify queryset here?  I mean, I already know, from initial, exactly which coconut I'm talking about.  Why do I also need to specify that the universe of available coconuts is the set of coconuts which this particular swallow carried (by the husk)?

Is there a way I can refrain from specifying queryset?  Simply omitting causes django to raise TypeError.

If indeed it is required, isn't this a bit damp?

答:
The reason django requires a queryset is because when you render the field to the page, django only sends the id. when it comes back, it needs knowlege of the queryset in order to re-inflate that object.
if you already know the queryset at form creation time, why not simply specify form.fields['coconut'].initial = some_particular_coconut in your view and leave the rest of the definition in your forms.py?

If you find that you only really need to send the id anyway (you don't have to re-inflate to an object at your end), why not send it in a char field?

Body:
So let's say at the last minute (in the view) I decide I want to specify a default for a field and make it hidden, like so:

form.fields['coconut'] = forms.ModelChoiceField(
    label="",
    widget=forms.HiddenInput(),
    queryset=swallow.coconuts.all(),
    initial=some_particular_coconut,
)

My question is this:  Do I really need to specify queryset here?  I mean, I already know, from initial, exactly which coconut I'm talking about.  Why do I also need to specify that the universe of available coconuts is the set of coconuts which this particular swallow carried (by the husk)?

Is there a way I can refrain from specifying queryset?  Simply omitting causes django to raise TypeError.

If indeed it is required, isn't this a bit damp?


问:
Setting the class/innerHTML of a table with ng-click()
```<code><tr ng-repeat="employee in vm.contacts">
  <td ng-click="clickedOn(this)" ng-repeat="weekDay in vm.daysOfTheWeek">
    <span>
      <a>
        {{innerHTML}}
      </a>
    </span>
  </td>
</tr>
</code>```

Okay, so how do I select a td? I'm overwhelmed here. I want ng-click to change the {{innerHTML}} of that single element, but it's a nested ng-repeat... so I can't just do magic to both the 'employee' and the 'weekDay' at the same time?

答:
This will give each td a unique id. </p>

```<code><td ng-class="td-{{$index}}">
</code>```

Body:
        {{innerHTML}}

Okay, so how do I select a td? I'm overwhelmed here. I want ng-click to change the {{innerHTML}} of that single element, but it's a nested ng-repeat... so I can't just do magic to both the 'employee' and the 'weekDay' at the same time?

Body:
This will give each td a unique id.

<td ng-class="td-{{$index}}">