问:
Doesn't python's ffmpy works with temporary files made using tempfile.TemporaryFile?
I am making a function whose purpose is to take a mp3 file and analyse and process it. So, taking help from this SO answer, I am making a temporary wav file, and then using python ffmpy library I am trying to convert mp3(actual given file) to wav file. But the catch is that I am giving the temporary wav file generated above as the output file to ffmpy to store the result to i.e. I am doing this:

```<code>import ffmpy
import tempfile
from scipy.io import wavfile

# audioFile variable is known here

tempWavFile = tempfile.TemporaryFile(suffix="wav")
ff_obj = ffmpy.FFmpeg(
                      global_options="hide_banner",
                      inputs={audioFile:None},
                      outputs={tempWavFile: " -acodec pcm_s16le -ac 1 -ar 44000"}
                     )

ff_obj.run()

[fs, frames] = wavfile.read(tempWavFile)
print(" fs is: ", fs)
print(" frames is: ", frames)
</code>```

But on line ff_obj.run() this error occurs:

```<code>File "/home/tushar/.local/lib/python3.5/site-packages/ffmpy.py", line 95, in run
    stderr=stderr
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1490, in _execute_child
    restore_signals, start_new_session, preexec_fn)
TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly
</code>```

So, my question is:

When I replaced tempWavFile = tempfile.TemporaryFile(suffix="wav") with tempWavFile = tempfile.mktemp('.wav'), no error occurs, why so ?

What does this error mean and what is the cause of it's occurrence and how can it be corrected ?

答:
tempfile.TemporaryFile returns a file-like object:

```<code>>>> tempWavFile = tempfile.TemporaryFile(suffix="wav")
>>> tempWavFile
<_io.BufferedRandom name=12>
</code>```

On the other hand, tempfile.mktemp returns a string to a path to a real file which has just been created on the file system:

```<code>>>> tempWavFile = tempfile.mktemp('.wav')
>>> tempWavFile
'/var/folders/f1/9b4sf0gx0dx78qpkq57sz4bm0000gp/T/tmpf2117fap.wav'
</code>```

After creating tempWavFile, you pass it to ffmpy.FFmpeg, which will aggregate input and output files and parameters in a single command, to be passed to subprocess. The command-line takes the form of a list, and probably looks something like the following: ["ffmpeg", "-i", "input.wav", "output.wav"].

Finally, ffmpy passes this list to subprocess.Popen and that's where it explodes when you use tempfile.TemporaryFile. This is normal because subprocess does not know anything about your arguments and expects all of them to be strings. When it sees the _io.BufferedRandom object returned by  tempfile.TemporaryFile, it doesn't know what to do.

So, to fix it, just use tempfile.mkstemp, which is safer anyway than tempfile.TemporaryFile.

From the Python docs:

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

  Creates a temporary file in the most secure manner possible.

  ...

  Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.

You originally mentioned mktemp, which is deprecated since Python 2.3 (see docs) and should be replaced by mkstemp.

Body:
I am making a function whose purpose is to take a mp3 file and analyse and process it. So, taking help from this SO answer, I am making a temporary wav file, and then using python ffmpy library I am trying to convert mp3(actual given file) to wav file. But the catch is that I am giving the temporary wav file generated above as the output file to ffmpy to store the result to i.e. I am doing this:

import ffmpy
import tempfile
from scipy.io import wavfile

# audioFile variable is known here

tempWavFile = tempfile.TemporaryFile(suffix="wav")
ff_obj = ffmpy.FFmpeg(
                      global_options="hide_banner",
                      inputs={audioFile:None},
                      outputs={tempWavFile: " -acodec pcm_s16le -ac 1 -ar 44000"}
                     )

ff_obj.run()

[fs, frames] = wavfile.read(tempWavFile)
print(" fs is: ", fs)
print(" frames is: ", frames)

But on line ff_obj.run() this error occurs:

File "/home/tushar/.local/lib/python3.5/site-packages/ffmpy.py", line 95, in run
    stderr=stderr
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1490, in _execute_child
    restore_signals, start_new_session, preexec_fn)
TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly

So, my question is:

When I replaced tempWavFile = tempfile.TemporaryFile(suffix="wav") with tempWavFile = tempfile.mktemp('.wav'), no error occurs, why so ?

What does this error mean and what is the cause of it's occurrence and how can it be corrected ?

Body:
tempfile.TemporaryFile returns a file-like object:

>>> tempWavFile = tempfile.TemporaryFile(suffix="wav")
>>> tempWavFile
<_io.BufferedRandom name=12>

On the other hand, tempfile.mktemp returns a string to a path to a real file which has just been created on the file system:

>>> tempWavFile = tempfile.mktemp('.wav')
>>> tempWavFile
'/var/folders/f1/9b4sf0gx0dx78qpkq57sz4bm0000gp/T/tmpf2117fap.wav'

After creating tempWavFile, you pass it to ffmpy.FFmpeg, which will aggregate input and output files and parameters in a single command, to be passed to subprocess. The command-line takes the form of a list, and probably looks something like the following: ["ffmpeg", "-i", "input.wav", "output.wav"].

Finally, ffmpy passes this list to subprocess.Popen and that's where it explodes when you use tempfile.TemporaryFile. This is normal because subprocess does not know anything about your arguments and expects all of them to be strings. When it sees the _io.BufferedRandom object returned by  tempfile.TemporaryFile, it doesn't know what to do.

So, to fix it, just use tempfile.mkstemp, which is safer anyway than tempfile.TemporaryFile.

From the Python docs:

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

  Creates a temporary file in the most secure manner possible.

  ...

  Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.

You originally mentioned mktemp, which is deprecated since Python 2.3 (see docs) and should be replaced by mkstemp.


来源: stackexchange

问:
Bootstrap navbar corrections
I'm having a problem with my navbar that I'm making with bootstrap.

search form has a lot of unused space behind it, how could I get rid of it?

Can I make navbar to collapse as soon at it would make 2 line navigation bar?

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

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

        </button>
     Name

Page 1-1

Page 1-2

Page 1-3

        something

Page 1-1

Page 1-2

Page 1-3

        something

Page 1-1

Page 1-2

Page 1-3

        something

Page 1-1

Page 1-2

Page 1-3

        admin

Page 1-1

Page 1-2

Page 1-3

    <form class="navbar-form navbar-right form-inline">
      label 1

        <input type="text" class="form-control input-sm" style="border-radius: 10px 0 0 10px;">

          <button class="btn btn-default btn-sm" type="submit" style="border-radius: 0 10px 10px 0;">

                    </button>

      label 2

        <input type="text" class="form-control input-sm" style="border-radius: 10px 0 0 10px;">

          <button class="btn btn-default btn-sm" type="submit" style="border-radius: 0 10px 10px 0;">

                    </button>

      label 3

        <input type="text" class="form-control input-sm" style="border-radius: 10px 0 0 10px;">

          <button class="btn btn-default btn-sm" type="submit" style="border-radius: 0 10px 10px 0;">

                    </button>

    </form>

```

https://jsfiddle.net/nooorz24/ove78e91/1/

答:
The nav bar will collapse depending on the screen size you set. Right now you are linking to the CDN, so you would have to override the @media sections of the CSS.

The extra space will need to be overridden too. It looks like it's in the stylesheet here:

```<code>@media (min-width: 768px)
navbar.less:385
.navbar-right {
    float: right!important;
    margin-right: -15px;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bootstrap navbar corrections

Body:
I'm having a problem with my navbar that I'm making with bootstrap.

search form has a lot of unused space behind it, how could I get rid of it?

Can I make navbar to collapse as soon at it would make 2 line navigation bar?

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

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

        </button>
     Name

Page 1-1

Page 1-2

Page 1-3

        something

Page 1-1

Page 1-2

Page 1-3

        something

Page 1-1

Page 1-2

Page 1-3

        something

Page 1-1

Page 1-2

Page 1-3

        admin

Page 1-1

Page 1-2

Page 1-3

    <form class="navbar-form navbar-right form-inline">
      label 1

        <input type="text" class="form-control input-sm" style="border-radius: 10px 0 0 10px;">

          <button class="btn btn-default btn-sm" type="submit" style="border-radius: 0 10px 10px 0;">

                    </button>

      label 2

        <input type="text" class="form-control input-sm" style="border-radius: 10px 0 0 10px;">

          <button class="btn btn-default btn-sm" type="submit" style="border-radius: 0 10px 10px 0;">

                    </button>

      label 3

        <input type="text" class="form-control input-sm" style="border-radius: 10px 0 0 10px;">

          <button class="btn btn-default btn-sm" type="submit" style="border-radius: 0 10px 10px 0;">

                    </button>

    </form>

https://jsfiddle.net/nooorz24/ove78e91/1/

Body:
The nav bar will collapse depending on the screen size you set. Right now you are linking to the CDN, so you would have to override the @media sections of the CSS.

The extra space will need to be overridden too. It looks like it's in the stylesheet here:

@media (min-width: 768px)
navbar.less:385
.navbar-right {
    float: right!important;
    margin-right: -15px;
}


问:
Tic Tac Toe how to tell user there is no winner?
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.</p>

```<code>public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

答:
Probably it doesnt work because of this piece of code

```<code>if (activePlayer ==0)

    mesg = "O is the winner!";

if(activePlayer==1)

    mesg = "X is the winner!";

else
    gameover=true;
mesg="there is no winner ";
</code>```

try to use curly braces, its best practise anyways. Like this:

```<code>if (activePlayer ==0){

    mesg = "O is the winner!";

}else if(activePlayer==1){

    mesg = "X is the winner!";

}else{
    gameover=true;
    mesg="there is no winner ";
}
</code>```

Body:
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.

public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Body:
Probably it doesnt work because of this piece of code

if (activePlayer ==0)

    mesg = "O is the winner!";

if(activePlayer==1)

    mesg = "X is the winner!";

else
    gameover=true;
mesg="there is no winner ";

try to use curly braces, its best practise anyways. Like this:

if (activePlayer ==0){

    mesg = "O is the winner!";

}else if(activePlayer==1){

    mesg = "X is the winner!";

}else{
    gameover=true;
    mesg="there is no winner ";
}


问:
Firebase value event listener firing even after activity is finished?
I have been working with firebase and i noticed something strange.
One of the value event listener that i had registered in activity is fired even after i have finished the activity.
I have added code to open a new activity in the'onDataChanged' method , so even if i am in a different activity the new activity is opened.  This is causing  big problems in the app.
I know that i have to call remove listener but i expected that the listener will be removed automatically after the activity is finished. Is there a simpler way in which i can remove all the value event listeners of an activity ? Thanks in advance.</p>

答:
You need to remove the listener once you leave the main activity. In order to do that, you can create a method like this:

```<code>private HashMap<DatabaseReference, ValueEventListener> hashMap = new HashMap<>();
public static void removeValueEventListener(HashMap<DatabaseReference, ValueEventListener> hashMap) {
    for (Map.Entry<DatabaseReference, ValueEventListener> entry : hashMap.entrySet()) {
        DatabaseReference databaseReference = entry.getKey();
        ValueEventListener valueEventListener = entry.getValue();
        databaseReference.removeEventListener(valueEventListener);
    }
}
</code>```

Every time you want to remove a lister, you can use this line of code:

```<code>hashMap.put(yourRef, eventListener);
</code>```

Than just call removeValueEventListener(hashMap); according to the activity life-cycle. You can add this line in your onPause() or onStop() methods. In this way you can remove all the listeners at once.

Body:
You need to remove the listener once you leave the main activity. In order to do that, you can create a method like this:

private HashMap<DatabaseReference, ValueEventListener> hashMap = new HashMap<>();
public static void removeValueEventListener(HashMap<DatabaseReference, ValueEventListener> hashMap) {
    for (Map.Entry<DatabaseReference, ValueEventListener> entry : hashMap.entrySet()) {
        DatabaseReference databaseReference = entry.getKey();
        ValueEventListener valueEventListener = entry.getValue();
        databaseReference.removeEventListener(valueEventListener);
    }
}

Every time you want to remove a lister, you can use this line of code:

hashMap.put(yourRef, eventListener);

Than just call removeValueEventListener(hashMap); according to the activity life-cycle. You can add this line in your onPause() or onStop() methods. In this way you can remove all the listeners at once.

ContentLicense: CC BY-SA 4.0


问:
I want to schedule an Oracle Sql script to run on the database server
I want to schedule an Oracle Sql script to run using Sql*Plus on my database server at midnight.

Currently I run it manually using:

```<code>nohup sqlplus username/password @myscript.sql &
</code>```

How can I schedule it? I don't want to pass username and password openly. Is there a way to hide it?

答:
One way of 'hiding' your password:

In the script do a

```<code>CONN username/password
</code>```

Then run your script as:

```<code>sqlplus /nolog @script_name
</code>```

Body:
I want to schedule an Oracle Sql script to run using Sql*Plus on my database server at midnight.

Currently I run it manually using:

nohup sqlplus username/password @myscript.sql &

How can I schedule it? I don't want to pass username and password openly. Is there a way to hide it?

Body:
One way of 'hiding' your password:

In the script do a

CONN username/password

Then run your script as:

sqlplus /nolog @script_name


问:
Using a regex in Java
I need to build a regular expression for all nonempty sequences of letters other than : file, for,from.

So I should end up getting all the values from my text input excluding the above 3 words.

Is this a correct way to represent it?

```<code>^(?:(?!file|for|from).)*$
</code>```

Also I was trying to use this regex pattern in my java program and assumed it should work. But it does not.

My sample code is as follows:

```<code>Pattern p = Pattern.compile("^(?:(?!file|for|from).)*$");

// Split input with the pattern

String[] result =

         p.split("file is not there from for this time for this test");

for (int i=0; i<result.length; i++)

    System.out.println(result[i]);
</code>```

Is there an error in my regex or is there some error with the way I am using regex in java?

Please advise.

Thank you.

答:
You should do something like this:</p>

```<code>String s = "file is not there from for this time for this test";
String[] splits = s.split("file|from|for");
</code>```

ContentLicense: CC BY-SA 2.5

Title: Using a regex in Java

Body:
I need to build a regular expression for all nonempty sequences of letters other than : file, for,from.

So I should end up getting all the values from my text input excluding the above 3 words.

Is this a correct way to represent it?

^(?:(?!file|for|from).)*$

Also I was trying to use this regex pattern in my java program and assumed it should work. But it does not.

My sample code is as follows:

Pattern p = Pattern.compile("^(?:(?!file|for|from).)*$");

// Split input with the pattern

String[] result =

         p.split("file is not there from for this time for this test");

for (int i=0; i<result.length; i++)

    System.out.println(result[i]);

Is there an error in my regex or is there some error with the way I am using regex in java?

Please advise.

Thank you.

Body:
You should do something like this:

String s = "file is not there from for this time for this test";
String[] splits = s.split("file|from|for");


问:
how to read xml file data from azure service bus queue
I just want to read XML file data that i have sent in azure service bus from queue. My code is

while (client.Peek() != null)
{
    BrokeredMessage orderOutMsg = client.Receive();

    if (orderOutMsg != null)
    {
        // Deserialize the message body to a pizza order.
        XDocument orderOut = orderOutMsg.GetBody<XDocument>();
        Console.WriteLine("Received order, {0} {1} ", orderOut.Root.Element("Customer").Element("Location_Code").Value, orderOut.Root.Element("Customer").Element("Phone_Number").Value);

        orderOutMsg.Complete();
    }
}
```

答:
GetBody<T> tries to deserialize the message into type T using DataContractSerializer.

What you probably want is just to read a string and then parse into XML:

var body = orderOutMsg.GetBody<string>();
XDocument orderOut = XDocument.Parse(body);
```


问:
How to install Nokogiri with Rails on Ubuntu 16.04
I am trying to install Rails by using

```<code>sudo gem install rails
</code>```

on a fresh version of Ubuntu 16.04. Ruby 2.3.1p112 is already installed. During the installation of Rails, once fetching Nokogiri is complete, I get the error below:

```<code>Fetching: nokogiri-1.8.0.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing rails:
        ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/nokogiri-1.8.0/ext/nokogiri
/usr/bin/ruby2.3 -r ./siteconf20170608-1635-1vnwqbn.rb extconf.rb
checking if the C compiler accepts ... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
        --help
        --clean
/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
        from /usr/lib/ruby/2.3.0/mkmf.rb:571:in `block in try_compile'
        from /usr/lib/ruby/2.3.0/mkmf.rb:522:in `with_werror'
        from /usr/lib/ruby/2.3.0/mkmf.rb:571:in `try_compile'
        from extconf.rb:138:in `nokogiri_try_compile'
        from extconf.rb:162:in `block in add_cflags'
        from /usr/lib/ruby/2.3.0/mkmf.rb:629:in `with_cflags'
        from extconf.rb:161:in `add_cflags'
        from extconf.rb:407:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.0/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/nokogiri-1.8.0 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.0/gem_make.out
</code>```

This is the content of mkmf.log:

```<code>"gcc -o conftest -I/usr/include/x86_64-linux-gnu/ruby-2.3.0 -I/usr/include/ruby-2.3.0/ruby/backward -I/usr/include/ruby-2.3.0 -I. -Wdate-time -D_FORTIFY_SOURCE=2   -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -fPIC  conftest.c  -L. -L/usr/lib/x86_64-linux-gnu -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic     -lruby-2.3  -lpthread -lgmp -ldl -lcrypt -lm   -lc "
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */
</code>```

I have no idea what is wrong. The log does not help and I already tried installing libgmp-dev, ruby-dev, zlib1g-dev and liblzma-dev as they were suggested to people who are getting errors during Nokogiri gem installation.

答:
After trying to find the missing dependency for a while, I ran the gcc command in the mkmf.log just in case some compilation error messages are being omitted.

It turned out that I didn't have gcc installed. Once I installed it, I got some progress with the installation only to encounter another similar error. In the end, installing the dependencies below resulted in a successful installation of Rails.

Please make sure you have gcc, make, zlib1g-dev, sqlite3 installed before running gem install rails:

```<code>sudo apt-get install gcc make zlib1g-dev sqlite3
</code>```

Body:
I am trying to install Rails by using

sudo gem install rails

on a fresh version of Ubuntu 16.04. Ruby 2.3.1p112 is already installed. During the installation of Rails, once fetching Nokogiri is complete, I get the error below:

Fetching: nokogiri-1.8.0.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing rails:
        ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/nokogiri-1.8.0/ext/nokogiri
/usr/bin/ruby2.3 -r ./siteconf20170608-1635-1vnwqbn.rb extconf.rb
checking if the C compiler accepts ... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
        --help
        --clean
/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
        from /usr/lib/ruby/2.3.0/mkmf.rb:571:in `block in try_compile'
        from /usr/lib/ruby/2.3.0/mkmf.rb:522:in `with_werror'
        from /usr/lib/ruby/2.3.0/mkmf.rb:571:in `try_compile'
        from extconf.rb:138:in `nokogiri_try_compile'
        from extconf.rb:162:in `block in add_cflags'
        from /usr/lib/ruby/2.3.0/mkmf.rb:629:in `with_cflags'
        from extconf.rb:161:in `add_cflags'
        from extconf.rb:407:in `'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.0/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/nokogiri-1.8.0 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.8.0/gem_make.out

This is the content of mkmf.log:

"gcc -o conftest -I/usr/include/x86_64-linux-gnu/ruby-2.3.0 -I/usr/include/ruby-2.3.0/ruby/backward -I/usr/include/ruby-2.3.0 -I. -Wdate-time -D_FORTIFY_SOURCE=2   -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -fPIC  conftest.c  -L. -L/usr/lib/x86_64-linux-gnu -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic     -lruby-2.3  -lpthread -lgmp -ldl -lcrypt -lm   -lc "
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

I have no idea what is wrong. The log does not help and I already tried installing libgmp-dev, ruby-dev, zlib1g-dev and liblzma-dev as they were suggested to people who are getting errors during Nokogiri gem installation.

Body:
After trying to find the missing dependency for a while, I ran the gcc command in the mkmf.log just in case some compilation error messages are being omitted.

It turned out that I didn't have gcc installed. Once I installed it, I got some progress with the installation only to encounter another similar error. In the end, installing the dependencies below resulted in a successful installation of Rails.

Please make sure you have gcc, make, zlib1g-dev, sqlite3 installed before running gem install rails:

sudo apt-get install gcc make zlib1g-dev sqlite3


问:
How to save data in Local Storage before leaving a page on IOS devices?
I recently figured out that the onbeforeunload event is not supported on IOS devices. I also did some research and tried other events like the pagehide event but it also didn't work. What I'm trying to achieve is to save some data in the local storage before leaving the page. It works fine for windows and android but not for IOS devices. This is the code:

```<code>window.onbeforeunload = function(e){
    save_something_in_local_storage();
};
</code>```

I could also identify IOS devices with:

```<code>var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
</code>```

Trying other events like for example pagehide also won't work:

```<code>window.addEventListener("pagehide", function(evt){
   alert('pagehide');
}, false);
</code>```

Anyone knows a workaround for IOS?

答: Try to save data after focusout event (if you have input). And after success saving, clean up localstorage

Body:
I recently figured out that the onbeforeunload event is not supported on IOS devices. I also did some research and tried other events like the pagehide event but it also didn't work. What I'm trying to achieve is to save some data in the local storage before leaving the page. It works fine for windows and android but not for IOS devices. This is the code:

window.onbeforeunload = function(e){
    save_something_in_local_storage();
};

I could also identify IOS devices with:

var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

Trying other events like for example pagehide also won't work:

window.addEventListener("pagehide", function(evt){
   alert('pagehide');
}, false);

Anyone knows a workaround for IOS?


问:
Adding JSON values into a list
I'm wanting to iterate through my JSON file, and add two values into a list.

In theory, I'm wanting to have a nested list as: ips = [["custom3","modemId"],["custom3","modemId"]] and so on. My JSON file has 171 of each custom3 and modemId values. So in theory my nested list will contain 171 lists.

I'm having trouble adding the values into a list, in which I would like to append each list together, to create 171 lists.

```<code>json1 = open('C:\\Users\\' + comp_name + '\\Documents\\Programming Projects\\Python\\Python Firmware Script\\curl\\src\\out.json')
json1_obj = json.load(json1)

for i in json1_obj['data']:
    ip = [i['custom3']['modemId']]
</code>```

A snippet of my JSON data:

```<code>{
    "data": [
        {
            "custom3": "192.168.243.132",
            "modemId": "000408"
        },
        {
            "custom3": "192.168.244.156",
            "modemId": "000310"
        }
    ]
}
</code>```

I have 171 objects as above, but I'm only showing two. From the above, I would like to create two lists and append them each into a nested list.

How do I iterate through each JSON object and create a nested list with my JSON data in Python?

答:
If you want the values of custom3 and modemIds, you could do,</p>

```<code>[item.values() for item in json_data['data']]
</code>```

Title: Adding JSON values into a list

Body:
I'm wanting to iterate through my JSON file, and add two values into a list.

In theory, I'm wanting to have a nested list as: ips = [["custom3","modemId"],["custom3","modemId"]] and so on. My JSON file has 171 of each custom3 and modemId values. So in theory my nested list will contain 171 lists.

I'm having trouble adding the values into a list, in which I would like to append each list together, to create 171 lists.

json1 = open('C:\\Users\\' + comp_name + '\\Documents\\Programming Projects\\Python\\Python Firmware Script\\curl\\src\\out.json')
json1_obj = json.load(json1)

for i in json1_obj['data']:
    ip = [i['custom3']['modemId']]

A snippet of my JSON data:

{
    "data": [
        {
            "custom3": "192.168.243.132",
            "modemId": "000408"
        },
        {
            "custom3": "192.168.244.156",
            "modemId": "000310"
        }
    ]
}

I have 171 objects as above, but I'm only showing two. From the above, I would like to create two lists and append them each into a nested list.

How do I iterate through each JSON object and create a nested list with my JSON data in Python?

Body:
If you want the values of custom3 and modemIds, you could do,

[item.values() for item in json_data['data']]


问:
Find years where 22nd March will be a Tuesday
I need to find out in which years between 2017 and 2100 (both inclusive) will the 22nd March be a Tuesday.

I tried using the datetime module but I couldn't figure out how...

答:
A bit late to the party, but how about using math instead of building hundreds of datetime.datetime objects just to throw them away?

```<code># adjusted Zeller's formula, returns 0 - Sunday, 1 - Monday ... 6 - Saturday
def get_weekday(y, m, d):
    return (d+(13*((10+m)%12+1)-1)//5+y%100+y%100//4+(y//100)//4-2*(y//100))%7

start_year = 2017
end_year = 2100

target_date = 22
target_month = 2    # 0 - January, 1 - February ... 11 - December
target_weekday = 2  # 0 - Sunday, 1 - Monday ... 6 - Saturday

years = [year for year in range(start_year, end_year + 1) if
         get_weekday(year, target_month, target_date) == target_weekday]
# gives: [2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095]
</code>```

Body:
A bit late to the party, but how about using math instead of building hundreds of datetime.datetime objects just to throw them away?

# adjusted Zeller's formula, returns 0 - Sunday, 1 - Monday ... 6 - Saturday
def get_weekday(y, m, d):
    return (d+(13*((10+m)%12+1)-1)//5+y%100+y%100//4+(y//100)//4-2*(y//100))%7

start_year = 2017
end_year = 2100

target_date = 22
target_month = 2    # 0 - January, 1 - February ... 11 - December
target_weekday = 2  # 0 - Sunday, 1 - Monday ... 6 - Saturday

years = [year for year in range(start_year, end_year + 1) if
         get_weekday(year, target_month, target_date) == target_weekday]
# gives: [2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095]


问:
Delete and fill the information
Hello I have this table and I want to be able to delete the data on P(number) and tituloP(number).
I have done the query to delete if the user choose the last P(number) its the easier.
Now I have to do a cicle that if user delete a middle data it auto fill 1 field.

There is the example:

```<code>IIDD | ID | Num_Slides | P1 | P2 | P3 | P4 | P5 | tituloP1 | tituloP2 | tituloP3 | tituloP4 | tituloP5
1    | 4  | 5          | 1  | 2  | 4  | 5  | 2  |Sometext  |Sometext2 |Sometext3 |Sometext4 |Sometext5 |
</code>```

If user choose to delete P5 its easier I just need to fill the P5 with 0 and tituloP5 with blank field and Num_Slides 4

But If user choose to delete P3, tituloP3 I have to set P5 to 0 and tituloP5 to blank field SET P4 to 2 tituloP4 to Sometext5 and SET P3 to 5 tituloP3 to Sometext4 this way the information will be updated without P'gaps

I have this for cicle so far but dont work

```<code>if (isset($_POST['Confirmar'])){
    $max = 5;
    $menos1 = $max - 1;
    for ($i = 4; $i >= 1; $i--){
        $sqlya="SELECT P$i, tituloP$i FROM slider_settings where slider_settings.ID = 4";
        for ($k = $menos1; $k <= $menos1; $k++){
            $inserirya = "UPDATE slider_settings SET P$k ='P$i', tituloP$k ='tituloP$i' where slider_settings.ID = 4";
            $con1 = $connect->query($sqlya);
            $com2 = $connect->query($inserirya);
        }
    }
}
</code>```

答:
//This Will Provide U Update Query

```<code>function createUpdateString($position,&$str){

if($position==5){
    return false;
}
$nextPosition =  $position+1;

$str[] = " P{$position} =  P{$nextPosition}";
$str[] = " tituloP{$position} =  tituloP{$nextPosition}";
return createUpdateString($nextPosition,$str);
}
</code>```

//Supose Your removing 3

//Update The p3 and tituloP3 values 0 and ""

```<code>$updatePostion = 3;
$str = array();
//This function will create query string for you
createUpdateString($updatePostion,$str);
$queryString = implode(",",$str);

if(!empty($queryString)){
$query = "UPDATE TABLE_NAME SET ".$queryString ."where slider_settings.ID = 4";
}
</code>```

Title: Delete and fill the information

Body:
Hello I have this table and I want to be able to delete the data on P(number) and tituloP(number).
I have done the query to delete if the user choose the last P(number) its the easier.
Now I have to do a cicle that if user delete a middle data it auto fill 1 field.

There is the example:

IIDD | ID | Num_Slides | P1 | P2 | P3 | P4 | P5 | tituloP1 | tituloP2 | tituloP3 | tituloP4 | tituloP5
1    | 4  | 5          | 1  | 2  | 4  | 5  | 2  |Sometext  |Sometext2 |Sometext3 |Sometext4 |Sometext5 |

If user choose to delete P5 its easier I just need to fill the P5 with 0 and tituloP5 with blank field and Num_Slides 4

But If user choose to delete P3, tituloP3 I have to set P5 to 0 and tituloP5 to blank field SET P4 to 2 tituloP4 to Sometext5 and SET P3 to 5 tituloP3 to Sometext4 this way the information will be updated without P'gaps

I have this for cicle so far but dont work

if (isset($_POST['Confirmar'])){
    $max = 5;
    $menos1 = $max - 1;
    for ($i = 4; $i >= 1; $i--){
        $sqlya="SELECT P$i, tituloP$i FROM slider_settings where slider_settings.ID = 4";
        for ($k = $menos1; $k <= $menos1; $k++){
            $inserirya = "UPDATE slider_settings SET P$k ='P$i', tituloP$k ='tituloP$i' where slider_settings.ID = 4";
            $con1 = $connect->query($sqlya);
            $com2 = $connect->query($inserirya);
        }
    }
}

Body:
//This Will Provide U Update Query

function createUpdateString($position,&$str){

if($position==5){
    return false;
}
$nextPosition =  $position+1;

$str[] = " P{$position} =  P{$nextPosition}";
$str[] = " tituloP{$position} =  tituloP{$nextPosition}";
return createUpdateString($nextPosition,$str);
}

//Supose Your removing 3

//Update The p3 and tituloP3 values 0 and ""

$updatePostion = 3;
$str = array();
//This function will create query string for you
createUpdateString($updatePostion,$str);
$queryString = implode(",",$str);

if(!empty($queryString)){
$query = "UPDATE TABLE_NAME SET ".$queryString ."where slider_settings.ID = 4";
}


问:
R - Find which value of a data frame to minimize a sum
In R, I have the data frame which follows :

```<code>Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1
</code>```

I would solve this optimization problem which follows :

(1) : argmin Sum(| |Mean_1| - |Mean_2| | + |nb_element_1-nb_element_2|)

(2) : 1.1*|Mean_1| > |Mean_2| > 0.75*|Mean_1|

I want to find which elements give the smallest sum value constrained by (2)

Is there a function which can do that ? Like solve() where we have to solve (1) = 0 or others functions ?

Thank You.

Edit : What I wanted is to have the best combination between an element from Mean_1 and Mean_2 that give the smallest sum value, example :

```<code>(Mean_1[1],Nb_element_1[1]) with (Mean_2[3],Nb_element_2[3])
(Mean_1[2],Nb_element_1[2]) with (Mean_2[1],Nb_element_2[1])
(Mean_1[3],Nb_element_1[3]) with (Mean_2[4],Nb_element_2[4])
(Mean_1[4],Nb_element_1[4]) with (Mean_2[2],Nb_element_2[2])
</code>```

Give the smallest sum value (not in this particular case, it's just an example to explain)

Actually, Mean_1 and Nb_element_1 are associated as Mean_2 and Nb_element_2.

So it faciliates the problem.

Thank you again.

Body:
In R, I have the data frame which follows :

Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1

I would solve this optimization problem which follows :

(1) : argmin Sum(| |Mean_1| - |Mean_2| | + |nb_element_1-nb_element_2|)

(2) : 1.1*|Mean_1| > |Mean_2| > 0.75*|Mean_1|

I want to find which elements give the smallest sum value constrained by (2)

Is there a function which can do that ? Like solve() where we have to solve (1) = 0 or others functions ?

Thank You.

Edit : What I wanted is to have the best combination between an element from Mean_1 and Mean_2 that give the smallest sum value, example :

(Mean_1[1],Nb_element_1[1]) with (Mean_2[3],Nb_element_2[3])
(Mean_1[2],Nb_element_1[2]) with (Mean_2[1],Nb_element_2[1])
(Mean_1[3],Nb_element_1[3]) with (Mean_2[4],Nb_element_2[4])
(Mean_1[4],Nb_element_1[4]) with (Mean_2[2],Nb_element_2[2])

Give the smallest sum value (not in this particular case, it's just an example to explain)

Actually, Mean_1 and Nb_element_1 are associated as Mean_2 and Nb_element_2.

So it faciliates the problem.

Thank you again.

Body:
Would something like this work ?

df <- read.table(text="Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1",header=TRUE,sep="")

solve1 <- function(df){
  coords <- expand.grid(1:nrow(df),1:nrow(df))
  df <- cbind(df[coords[[1]],c(1,3)],df[coords[[2]],c(2,4)])
  df <- transform(df,
                sum_value = abs(abs(Mean_1) -abs(Mean_2)) + abs(Nb_element_1-Nb_element_2),
                constraint_test = 1.1*abs(Mean_1) > abs(Mean_2) & abs(Mean_2) > 0.75*abs(Mean_1))
  # head(df)
  # Mean_1   Mean_2 Nb_element_1 Nb_element_2 sum_value constraint_test
  # 1    42.66667 51.89474            3           38  44.22807           FALSE
  # 2    65.00000 51.89474            3           38  48.10526            TRUE
  # 3   163.32653 51.89474            3           38 146.43179           FALSE
  # 4    22.83333 51.89474            3           38  64.06141           FALSE
  # 1.1  42.66667 51.89474            1           38  46.22807           FALSE
  # 2.1  65.00000 51.89474            1           38  50.10526            TRUE
  result <- df[which(df$sum_value == min(subset(df,constraint_test)$sum_value)),]
}

r <- solve1(df)
# Mean_1   Mean_2 Nb_element_1 Nb_element_2 sum_value constraint_test
# 2.16     65 51.89474            1            1  13.10526            TRUE


问:
Dynamically change datatables column width via API
I know we can set the columns width on a datatable via the columns.width option. But now I want to change that option on the xhr event.

Based on the ajax response I get from the server I want to hide/show a column and adjust the other columns width accordingly (they are all fixed size). Is there any way to achieve that via API?

I looked around all docs but seems it's not possible to achieve.

答:
You cannot change settings once the dataTable is initalised. But if you are using column.width and you have turned autoWidth off, then the width of each column is easy to change. Here is an example :

```<code>var table = $('#example').DataTable({
   autoWidth: false,
   ajax: {
     url: 'https://api.myjson.com/bins/avxod'
   },
   columns: [
     { data: 'name', width: 50 },
     { data: 'position', width: 50 },
     { data: 'salary', width: 50 },
     { data: 'office',  width: 50}
  ]
})

$('#example').on('xhr.dt', function() {
  $('#example thead th:eq(1)').width('400');
})
</code>```

demo -> http://jsfiddle.net/cc7x6h64/

It works because column.width is injected into each  as style="width: xxx;"

Body:
You cannot change settings once the dataTable is initalised. But if you are using column.width and you have turned autoWidth off, then the width of each column is easy to change. Here is an example :

var table = $('#example').DataTable({
   autoWidth: false,
   ajax: {
     url: 'https://api.myjson.com/bins/avxod'
   },
   columns: [
     { data: 'name', width: 50 },
     { data: 'position', width: 50 },
     { data: 'salary', width: 50 },
     { data: 'office',  width: 50}
  ]
})

$('#example').on('xhr.dt', function() {
  $('#example thead th:eq(1)').width('400');
})

demo -> http://jsfiddle.net/cc7x6h64/

It works because column.width is injected into each <th> as style="width: xxx;"


问:
Unable to fetch DOM element reference in AfterviewInit in angular 2, also with timeout able to set focus in Chrome not IE
Forced to use setTimeout(), working fine in chrome but not in IE

ngAfterViewInit(){
     setTimeout(()=>{
            this.businessInfoName._inputElement.nativeElement.focus();
     },2000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><md-input
    class="firstField"
    autofocus
    [ngClass]="{submitted:searchClicked}"
    #businessInfoName
    [(ngModel)]="submission.accountHolderCompany.contactName"
    aria-placeholder="Name of Business"
    placeholder="Name of Business"
    required
    name="businessname"
    (focus)="v_businessName = true"
    (blur)="v_businessName = false;replaceSpacesWithEmpty()"
    #businessName="ngModel"
    restrictKey
    maxlength="50"
></md-input></code>```

答:
Instead of referencing the element on the scope of the component use a ViewChild decorator to grab a reference to the element in class and then reference it in the ngAfterViewInit like so:

@ViewChild('businessInfoName') businessInfoNameRef: TemplateRef;

ngAfterViewInit(){
  this.businessInfoNameRef.nativeElement.focus();
}
```

Demo

Body:
Forced to use setTimeout(), working fine in chrome but not in IE

ngAfterViewInit(){
     setTimeout(()=>{
            this.businessInfoName._inputElement.nativeElement.focus();
     },2000);
}

<md-input
    class="firstField"
    autofocus
    [ngClass]="{submitted:searchClicked}"
    #businessInfoName
    [(ngModel)]="submission.accountHolderCompany.contactName"
    aria-placeholder="Name of Business"
    placeholder="Name of Business"
    required
    name="businessname"
    (focus)="v_businessName = true"
    (blur)="v_businessName = false;replaceSpacesWithEmpty()"
    #businessName="ngModel"
    restrictKey
    maxlength="50"
></md-input>

Body:
Instead of referencing the element on the scope of the component use a ViewChild decorator to grab a reference to the element in class and then reference it in the ngAfterViewInit like so:

@ViewChild('businessInfoName') businessInfoNameRef: TemplateRef;

ngAfterViewInit(){
  this.businessInfoNameRef.nativeElement.focus();
}

Demo


问:
Can i put text in the left and in the right side of the elements of a listview?
i have to make a listview that haves a list of names, and also, aligned to the left, but in the same field, the sex of the person, male or female

is possible to do it? how?

code examples welcome

EDIT

I try with the first user answer, and i got this exception: 12-14 22:39:56.191: ERROR/AndroidRuntime(917): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

this is the code of the XML item i make:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left side"
        android:layout_alignParentLeft="true"/>
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right side"
        android:layout_alignParentRight="true"/>
</RelativeLayout>
</code>```

and this is the code where i have my list:

```<code>public class PendingInvitations extends ListActivity {

......
.....
....
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    private List<String> usernames=new ArrayList<String>();
        for (int i=0;i<friends.size();i++)
              {
                usernames.add(i,friends.get(i).getFullName());
              }

              setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item2, usernames));
</code>```

答:
this would be the view that is used for each cell

```<code><?xml version="1.0" encoding="utf-8"?>
     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent" android:layout_height="wrap_content" >
         <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Left side" android:layout_alignParentLeft="true"/>
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Right side" android:layout_alignParentRight="true"/>
     </RelativeLayout>
</code>```

this is an example since i have no idea where your knowledge is at with lists, if the above xml was called "temp.xml" you would use this in the setlistadapter function

```<code>    import android.app.ListActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;

    public class FooList extends ListActivity extends BaseAdapter {
        String[] listItems = {"item 1", "item 2 ", "list", "android", "item 3", "foobar", "bar", };
        @Override
         public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.layout_with_listview);

             // implement your own adapter

         }

    }
public View getView(int position, View convertView, ViewGroup parent) {
                // A ViewHolder keeps references to children views to avoid unneccessary calls
                // to findViewById() on each row.
                ViewHolder holder;

                // When convertView is not null, we can reuse it directly, there is no need
                // to reinflate it. We only inflate a new View when the convertView supplied
                // by ListView is null.
                if (convertView == null) {
                    convertView = mInflater.inflate(R.layout.temp, null);

                    // Creates a ViewHolder and store references to the two children views
                    // we want to bind data to.
                    holder = new ViewHolder();
                    holder.left = (TextView) convertView.findViewById(R.id.left);
                    holder.right = (TextView) convertView.findViewById(R.id.right);

                    convertView.setTag(holder);
                } else {
                    // Get the ViewHolder back to get fast access to the TextView
                    // and the ImageView.
                    holder = (ViewHolder) convertView.getTag();
                }

                // Bind the data efficiently with the holder.

                holder.left.setText("left text");
                holder.right.setText("right text");

                return convertView;
            }

    class ViewHolder
    {
         public TextView left;
        public TextView right;
    }
</code>```

Body:
i have to make a listview that haves a list of names, and also, aligned to the left, but in the same field, the sex of the person, male or female

is possible to do it? how?

code examples welcome

EDIT

I try with the first user answer, and i got this exception: 12-14 22:39:56.191: ERROR/AndroidRuntime(917): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

this is the code of the XML item i make:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left side"
        android:layout_alignParentLeft="true"/>
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right side"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

and this is the code where i have my list:

public class PendingInvitations extends ListActivity {

......
.....
....
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    private List<String> usernames=new ArrayList<String>();
        for (int i=0;i<friends.size();i++)
              {
                usernames.add(i,friends.get(i).getFullName());
              }

              setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item2, usernames));

Body:
this would be the view that is used for each cell

<?xml version="1.0" encoding="utf-8"?>
     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent" android:layout_height="wrap_content" >
         <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Left side" android:layout_alignParentLeft="true"/>
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Right side" android:layout_alignParentRight="true"/>
     </RelativeLayout>

this is an example since i have no idea where your knowledge is at with lists, if the above xml was called "temp.xml" you would use this in the setlistadapter function

    import android.app.ListActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;

    public class FooList extends ListActivity extends BaseAdapter {
        String[] listItems = {"item 1", "item 2 ", "list", "android", "item 3", "foobar", "bar", };
        @Override
         public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.layout_with_listview);

             // implement your own adapter

         }

    }
public View getView(int position, View convertView, ViewGroup parent) {
                // A ViewHolder keeps references to children views to avoid unneccessary calls
                // to findViewById() on each row.
                ViewHolder holder;

                // When convertView is not null, we can reuse it directly, there is no need
                // to reinflate it. We only inflate a new View when the convertView supplied
                // by ListView is null.
                if (convertView == null) {
                    convertView = mInflater.inflate(R.layout.temp, null);

                    // Creates a ViewHolder and store references to the two children views
                    // we want to bind data to.
                    holder = new ViewHolder();
                    holder.left = (TextView) convertView.findViewById(R.id.left);
                    holder.right = (TextView) convertView.findViewById(R.id.right);

                    convertView.setTag(holder);
                } else {
                    // Get the ViewHolder back to get fast access to the TextView
                    // and the ImageView.
                    holder = (ViewHolder) convertView.getTag();
                }

                // Bind the data efficiently with the holder.

                holder.left.setText("left text");
                holder.right.setText("right text");

                return convertView;
            }

    class ViewHolder
    {
         public TextView left;
        public TextView right;
    }


问:
GSM Module - SIM900 and NEO-6M Gps module arduino code not working together
Here is my code including both GSM and GPS code. Im trying to send GPS coordinates as SMS after a call is made to the GSM module. Both work separately but when i combine both of the GSM and GPS code it doesn't print the GPS coordinates.</p>

```<code>    #include "SIM900.h"
    #include <SoftwareSerial.h>
    #include "call.h"

    #include "sms.h"
    #include "TinyGPS++.h"
    long lat,lon; // create variable for latitude and longitude object
    SoftwareSerial gpsSerial(10, 11); // create gps sensor connection
    TinyGPSPlus gps;

    SMSGSM sms;

    CallGSM call;
    boolean started=false;
    char sms_text[160];
    char message[160];
    char latitude[12]; char longitude[12];

    void setup()
    {

        Serial.begin(9600);
          gpsSerial.begin(9600);

        if (gsm.begin(9600))
        {
            Serial.println("\nstatus=READY");
            started=true;
        }
        else
            Serial.println("\nstatus=IDLE");
    }

    void loop()
    {

      switch (call.CallStatus())
      {
        case CALL_NONE: // Nothing is happening

          break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us

          Serial.println("RECEIVING CALL");
          call.HangUp();
            while(gpsSerial.available()){ // check for gps data
       if(gps.encode(gpsSerial.read())){ // encode gps data

         Serial.println("Latitude= ");
         Serial.print(gps.location.lat(), 6);
         Serial.println("Longitude= ");
         Serial.print(gps.location.lng(), 6);
       }
      }// The gps data doesnt seem to be printed on the serial monitor

          break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established

          Serial.println("TALKING. Line busy.");

          break;
      }
      delay(1000);
    }
</code>```

答:
You can't use delay if you want to process GPS characters.  You must constantly read the GPS characters and process them, every time through loop.

After checking for GPS characters, you can check the call status, but only occasionally.  Checking the call status takes time, which can make it lose GPS characters.  GPS data is completely parsed once per second, so that would be a good time to check the call status.

Here's your sketch, modified to always check for GPS characters, then check the call status:

```<code>#include <SIM900.h>
#include <call.h>
#include <sms.h>

SMSGSM sms;
CallGSM call;
boolean started=false;

#undef STATUS_NONE // bad SIM900 library!
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix; // create variable that holds latitude and longitude

// BEST:
//#include <AltSoftSerial.h>
//AltSoftSerial gpsSerial; // GPS TX to UNO pin 8 (optional: GPS RX to UNO pin 9)

// 2nd BEST:
#include <NeoSWSerial.h>
NeoSWSerial gpsSerial( 10, 11 );

void setup()
{
  Serial.begin(9600);

  if (gsm.begin(9600))
  {
      Serial.println( F("\nstatus=READY") ); // F macro saves RAM
      started=true;
  }
  else
      Serial.println( F("\nstatus=IDLE") );

  gpsSerial.begin(9600);
}

void loop()
{
  //  Always check for GPS characters.  A GPS fix will become available
  //    ONCE PER SECOND.  After the fix comes in, the GPS device will
  //    be quiet for a while.  That's a good time to check the phone status.

  if (gps.available( gpsSerial )){
    fix = gps.read(); // get latest PARSED gps data

    //  Display what was received
    Serial.print( F("Latitude= ") );
    Serial.println( fix.latitude(), 6 );
    Serial.print( F("Longitude= ") );
    Serial.println( fix.longitude(), 6 );

    //  Then check the current GSM status, ONLY ONCE PER SECOND
    CheckCall();
  }

  //delay(1000);   NEVER use delay!  You will lose GPS characters.
}

void CheckCall()
{
  //  You can use the 'fix' structure in here, if you want.

  switch (call.CallStatus())
  {
    case CALL_NONE: // Nothing is happening

      break;

    case CALL_INCOM_VOICE : // Yes! Someone is calling us

      Serial.println("RECEIVING CALL");
      call.HangUp();

      break;

    case CALL_COMM_LINE_BUSY:  // In this case the call would be established

      Serial.println("TALKING. Line busy.");

      break;
  }
}
</code>```

Notice that is uses my NeoGPS and NeoSWSerial libraries.  NeoGPS is smaller, faster, more reliable and more accurate than all other libraries.

You should avoid SoftwareSerial, because it is very inefficient.  It disables interrupts for long periods of time, when a character is sent or received.  Disabling interrupts for 1ms is an eternity for a 16MHz Arduino.  It can't do anything else but wait for the character to finish.  It could have executed 10,000 instructions during that time.

Both AltSoftSerial and NeoSWSerial are much more efficient, and they can send and receive at the same time.

If you could connect the GPS to pins 8 & 9, use AltSoftSerial instead.  It can be used reliably up to 19200, and then increasingly less reliably up to 115200, depending on how many interrupts are being handled.

If you cannot move it to those pins, use my NeoSWSerial instead.  It is almost as efficient as AltSoftSerial, but still much, much better than SoftwareSerial.  It can use any two pins, but only at baud rates 9600, 19200 and 38400.

NOTE:

To use NeoSWSerial on these two pins, you have to modify files in the SIM900 library (probably in the Libraries/GSM-GPRS-GPS-Shield-GSMSHIELD directory).  You have to search and replace all occurrences of "SoftwareSerial" with "NeoSWSerial".  These 4 files must be changed:

```<code>  GSM.h
  SIM900.h
  WideTextFinder.h and cpp
</code>```

NeoGPS and NeoSWSerial are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.  The examples NMEAsimple.ino and NMEAloc.ino are a good place to start.  Tabular.ino displays all the pieces in the default configuration.

Body:
Here is my code including both GSM and GPS code. Im trying to send GPS coordinates as SMS after a call is made to the GSM module. Both work separately but when i combine both of the GSM and GPS code it doesn't print the GPS coordinates.

    #include "SIM900.h"
    #include <SoftwareSerial.h>
    #include "call.h"

    #include "sms.h"
    #include "TinyGPS++.h"
    long lat,lon; // create variable for latitude and longitude object
    SoftwareSerial gpsSerial(10, 11); // create gps sensor connection
    TinyGPSPlus gps;

    SMSGSM sms;

    CallGSM call;
    boolean started=false;
    char sms_text[160];
    char message[160];
    char latitude[12]; char longitude[12];

    void setup()
    {

        Serial.begin(9600);
          gpsSerial.begin(9600);

        if (gsm.begin(9600))
        {
            Serial.println("\nstatus=READY");
            started=true;
        }
        else
            Serial.println("\nstatus=IDLE");
    }

    void loop()
    {

      switch (call.CallStatus())
      {
        case CALL_NONE: // Nothing is happening

          break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us

          Serial.println("RECEIVING CALL");
          call.HangUp();
            while(gpsSerial.available()){ // check for gps data
       if(gps.encode(gpsSerial.read())){ // encode gps data

         Serial.println("Latitude= ");
         Serial.print(gps.location.lat(), 6);
         Serial.println("Longitude= ");
         Serial.print(gps.location.lng(), 6);
       }
      }// The gps data doesnt seem to be printed on the serial monitor

          break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established

          Serial.println("TALKING. Line busy.");

          break;
      }
      delay(1000);
    }

Body:
You can't use delay if you want to process GPS characters.  You must constantly read the GPS characters and process them, every time through loop.

After checking for GPS characters, you can check the call status, but only occasionally.  Checking the call status takes time, which can make it lose GPS characters.  GPS data is completely parsed once per second, so that would be a good time to check the call status.

Here's your sketch, modified to always check for GPS characters, then check the call status:

#include <SIM900.h>
#include <call.h>
#include <sms.h>

SMSGSM sms;
CallGSM call;
boolean started=false;

#undef STATUS_NONE // bad SIM900 library!
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix; // create variable that holds latitude and longitude

// BEST:
//#include <AltSoftSerial.h>
//AltSoftSerial gpsSerial; // GPS TX to UNO pin 8 (optional: GPS RX to UNO pin 9)

// 2nd BEST:
#include <NeoSWSerial.h>
NeoSWSerial gpsSerial( 10, 11 );

void setup()
{
  Serial.begin(9600);

  if (gsm.begin(9600))
  {
      Serial.println( F("\nstatus=READY") ); // F macro saves RAM
      started=true;
  }
  else
      Serial.println( F("\nstatus=IDLE") );

  gpsSerial.begin(9600);
}

void loop()
{
  //  Always check for GPS characters.  A GPS fix will become available
  //    ONCE PER SECOND.  After the fix comes in, the GPS device will
  //    be quiet for a while.  That's a good time to check the phone status.

  if (gps.available( gpsSerial )){
    fix = gps.read(); // get latest PARSED gps data

    //  Display what was received
    Serial.print( F("Latitude= ") );
    Serial.println( fix.latitude(), 6 );
    Serial.print( F("Longitude= ") );
    Serial.println( fix.longitude(), 6 );

    //  Then check the current GSM status, ONLY ONCE PER SECOND
    CheckCall();
  }

  //delay(1000);   NEVER use delay!  You will lose GPS characters.
}

void CheckCall()
{
  //  You can use the 'fix' structure in here, if you want.

  switch (call.CallStatus())
  {
    case CALL_NONE: // Nothing is happening

      break;

    case CALL_INCOM_VOICE : // Yes! Someone is calling us

      Serial.println("RECEIVING CALL");
      call.HangUp();

      break;

    case CALL_COMM_LINE_BUSY:  // In this case the call would be established

      Serial.println("TALKING. Line busy.");

      break;
  }
}

Notice that is uses my NeoGPS and NeoSWSerial libraries.  NeoGPS is smaller, faster, more reliable and more accurate than all other libraries.

You should avoid SoftwareSerial, because it is very inefficient.  It disables interrupts for long periods of time, when a character is sent or received.  Disabling interrupts for 1ms is an eternity for a 16MHz Arduino.  It can't do anything else but wait for the character to finish.  It could have executed 10,000 instructions during that time.

Both AltSoftSerial and NeoSWSerial are much more efficient, and they can send and receive at the same time.

If you could connect the GPS to pins 8 & 9, use AltSoftSerial instead.  It can be used reliably up to 19200, and then increasingly less reliably up to 115200, depending on how many interrupts are being handled.

If you cannot move it to those pins, use my NeoSWSerial instead.  It is almost as efficient as AltSoftSerial, but still much, much better than SoftwareSerial.  It can use any two pins, but only at baud rates 9600, 19200 and 38400.

NOTE:

To use NeoSWSerial on these two pins, you have to modify files in the SIM900 library (probably in the Libraries/GSM-GPRS-GPS-Shield-GSMSHIELD directory).  You have to search and replace all occurrences of "SoftwareSerial" with "NeoSWSerial".  These 4 files must be changed:

  GSM.h
  SIM900.h
  WideTextFinder.h and cpp

NeoGPS and NeoSWSerial are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.  The examples NMEAsimple.ino and NMEAloc.ino are a good place to start.  Tabular.ino displays all the pieces in the default configuration.


问:
MySQL SELECT NOT IN
I have table:

```<code>+----+--------------+--------------------------+
| id | user         | mac                      |
+----+--------------+--------------------------+
|  3 | user003      | 148fc78371212b           |
|  4 | user004      |                          |
|  5 | user005      | 171248fc78312d           |
|  6 | user006      | 212e148fc78371           |
+----+--------------+--------------------------+
</code>```

I need to select only ID if mac encrypted value NOT EXISTS duplicate in row mac.

If for example:

user003 is having edit on form gui and leave old encrypted mac address 148fc78371212b it needs to get count from result in mysql 1

user003 is having edit on form gui and enter new encrypted mac address 212e148fc78371 it needs to get count from result in mysql 0 (so that i can then alert message Duplicate MAC address)

i need query that checks if user does not change its own mac address to allow editing (return 1) and if user change mac address and that address exists in mac address for another user (return 0) MAC address exists.

I try using this:

```<code>SELECT mac FROM users
WHERE user='user003' AND mac='148fc78371212b' OR mac NOT IN (SELECT mac FROM users);
</code>```

But i always get count result 1...i could not figure out how to archive above result?

So my query needs to look like this in theory:

```<code>SELECT mac FROM users WHERE user=? AND mac=? AND MAC DOES NOT EXISTS IN MAC
FIELD EXCEPT WHERE user=? AND mac=? (so to exclude searching duplicate mac
on defined user)
</code>```

答:
If I have understood your description, the attribute mac can be null, if it is not null, then it must unique.

If that is the case, then your approach is wrong. You should not be allowing users to insert data into the table which makes the table inconsistent. Consistency should be described in the database, therefore you should not be checking from your application that the operation will create an inconsistency.

However achieving this is a bit tricky. You can't use a unique index because you allow multiple NULL values; you need to use a trigger:

```<code>CREATE TRIGGER ins_transaction BEFORE INSERT ON yourtable
FOR EACH ROW
BEGIN
  IF (0<(
    SELECT COUNT(*)
    FROM yourtable
    WHERE mac=NEW.mac
    AND user<>NEW.user
   )) THEN
   SIGNAL 'Sorry - no dups'
  END IF
END
</code>```

Title: MySQL SELECT NOT IN

Body:
I have table:

+----+--------------+--------------------------+
| id | user         | mac                      |
+----+--------------+--------------------------+
|  3 | user003      | 148fc78371212b           |
|  4 | user004      |                          |
|  5 | user005      | 171248fc78312d           |
|  6 | user006      | 212e148fc78371           |
+----+--------------+--------------------------+

I need to select only ID if mac encrypted value NOT EXISTS duplicate in row mac.

If for example:

user003 is having edit on form gui and leave old encrypted mac address 148fc78371212b it needs to get count from result in mysql 1

user003 is having edit on form gui and enter new encrypted mac address 212e148fc78371 it needs to get count from result in mysql 0 (so that i can then alert message Duplicate MAC address)

i need query that checks if user does not change its own mac address to allow editing (return 1) and if user change mac address and that address exists in mac address for another user (return 0) MAC address exists.

I try using this:

SELECT mac FROM users
WHERE user='user003' AND mac='148fc78371212b' OR mac NOT IN (SELECT mac FROM users);

But i always get count result 1...i could not figure out how to archive above result?

So my query needs to look like this in theory:

SELECT mac FROM users WHERE user=? AND mac=? AND MAC DOES NOT EXISTS IN MAC
FIELD EXCEPT WHERE user=? AND mac=? (so to exclude searching duplicate mac
on defined user)

Body:
If I have understood your description, the attribute mac can be null, if it is not null, then it must unique.

If that is the case, then your approach is wrong. You should not be allowing users to insert data into the table which makes the table inconsistent. Consistency should be described in the database, therefore you should not be checking from your application that the operation will create an inconsistency.

However achieving this is a bit tricky. You can't use a unique index because you allow multiple NULL values; you need to use a trigger:

CREATE TRIGGER ins_transaction BEFORE INSERT ON yourtable
FOR EACH ROW
BEGIN
  IF (0<(
    SELECT COUNT(*)
    FROM yourtable
    WHERE mac=NEW.mac
    AND user<>NEW.user
   )) THEN
   SIGNAL 'Sorry - no dups'
  END IF
END


问:
PuppetMaster hits depracated API of PuppetDb not sure why
Following is the error that I get when I try to run the command puppet agent -t on Puppet Agent. It happens when PuppetServer tries to reach V3 of PuppetDb instead of V4, although the V3 is depracated, and should not be called ideally. Not sure how to fix this.

All the configs are in place as defined here : http://jurjenbokma.com/ApprenticesNotes/ar27s05.xhtml

```<code>Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Failed to submit 'replace facts' command for puppetmaster.test.org to PuppetDB at puppetmaster.test.org:8081: [404 ] <html><head><meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/><title>Error 404 </title></head><body><h2>HTTP ERROR: 404</h2><p>Problem accessing /v3/commands. Reason:```    Not Found```</p><hr /><i><small>Powered by Jetty://</small></i></body></html>
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run
</code>```

答:
I was following a tutorial for an older version, whereas, for latest version (Puppet v4.x) we need to have different modules.
There is an interface between PuppetMaster and PuppetDb which is responsible for making API calls to PuppetDb, in the link being followed it asks to install

sudo puppet resource packagepuppetdb-terminusensure=latest which uses /v3 api of PuppetDb, whereas, for the latest version we need to install

sudo puppet resource packagepuppetdb-terminiensure=latest
which uses /v4 api of PuppetDb...

And the problem is solved!

Body:
Following is the error that I get when I try to run the command puppet agent -t on Puppet Agent. It happens when PuppetServer tries to reach V3 of PuppetDb instead of V4, although the V3 is depracated, and should not be called ideally. Not sure how to fix this.

All the configs are in place as defined here : http://jurjenbokma.com/ApprenticesNotes/ar27s05.xhtml

Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Failed to submit 'replace facts' command for puppetmaster.test.org to PuppetDB at puppetmaster.test.org:8081: [404 ] <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/><title>Error 404 </title>
HTTP ERROR: 404

Problem accessing /v3/commands. Reason:
    Not Found

Powered by Jetty://
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run


问:
Unable to fetch data in Codeigniter PHP
developing quiz in Codeigniter PHP, unable to fetch data its's showing like this, its the field name "quizID" , "question" for every question displaying like this

'quizID'?>.'question'?>

Quiz Model File Code

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class quizmodel extends CI_Model {

public function getQuestions()
{
    $this->db->select("quizID, question, choice1, choice2, choice3,
answer");
    $this->db->from("QuizQuestion");

    $query = $this->db->get();

    return $query->result();

    $num_data_returned = $query->num_rows;

    if ($num_data_returned < 1) {
      echo "There is no data in the database";
      exit();
    }
}
}
</code>```

Question File Code

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Questions extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->database();
}

public function quizdisplay()
{
    $this->load->model('quizmodel');
    $this->data['questions'] = $this->quizmodel->getQuestions();
    $this->load->view('play_quiz', $this->data);
 }

    public function resultdisplay()
 {
    $this->data['checks'] = array(
         'ques1' => $this->input->post('quizid1'),
         'ques2' => $this->input->post('quizid2'),
         'ques3' => $this->input->post('quizid3'),
         'ques4' => $this->input->post('quizid4'),
         'ques5' => $this->input->post('quizid5'),
         'ques6' => $this->input->post('quizid6'),
         'ques7' => $this->input->post('quizid7'),
         'ques8' => $this->input->post('quizid8'),
         'ques9' => $this->input->post('quizid9'),
         'ques10' => $this->input->post('quizid10'),
    );

    $this->load->model('quizmodel');
    $this->data['results'] = $this->quizmodel->getQuestions();
    $this->load->view('result_display', $this->data);
}
}
</code>```

Play Quiz File Code

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Play Quiz</title>

</head>
<body>

<div id="container">
<h1>Play the Quiz!</h1>

<form method="post" action="<?php echo base_url();?
>index.php/Questions/resultdisplay">

<?php foreach($questions as $row) { ?>

<?php $ans_array = array($row->choice1, $row->choice2, $row->choice3, $row-
>answer);
shuffle($ans_array); ?>

<p><?=$row->quizID?>.<?=$row->question?></p>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[0]?
>" required> <?=$ans_array[0]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[1]?
>"> <?=$ans_array[1]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[2]?
>"> <?=$ans_array[2]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[3]?
>"> <?=$ans_array[3]?><br>

<?php } ?>

<br><br>
<input type="submit" value="Submit!">

</form>

</div>

</body>
</html>
</code>```

答:
the controller has an error:

instead of $this->data['questions'] = $this->quizmodel->getQuestions();

it should say data['questions'] = $this->quizmodel->getQuestions();

same goes for: $this->data['results'] = $this->quizmodel->getQuestions();

which should be: data['results'] = $this->quizmodel->getQuestions();

$this is a singleton Codeigniter instance, read more here:

The model has also an error, class declaration must be uppercase, read more here

```<code>class Quizmodel extends CI_Model
</code>```

you may also note, that in the model after return $query->result(); the remaining code is unreachable, you may want to change it like so:

```<code>$num_data_returned = $query->num_rows();

if ($num_data_returned < 1) {
  echo "There is no data in the database";
  exit();
}else{
   return $query->result();
}
</code>```

Title: Unable to fetch data in Codeigniter PHP

Body:
developing quiz in Codeigniter PHP, unable to fetch data its's showing like this, its the field name "quizID" , "question" for every question displaying like this

'quizID'?>.'question'?>

Quiz Model File Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class quizmodel extends CI_Model {

public function getQuestions()
{
    $this->db->select("quizID, question, choice1, choice2, choice3,
answer");
    $this->db->from("QuizQuestion");

    $query = $this->db->get();

    return $query->result();

    $num_data_returned = $query->num_rows;

    if ($num_data_returned < 1) {
      echo "There is no data in the database";
      exit();
    }
}
}

Question File Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Questions extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->database();
}

public function quizdisplay()
{
    $this->load->model('quizmodel');
    $this->data['questions'] = $this->quizmodel->getQuestions();
    $this->load->view('play_quiz', $this->data);
 }

    public function resultdisplay()
 {
    $this->data['checks'] = array(
         'ques1' => $this->input->post('quizid1'),
         'ques2' => $this->input->post('quizid2'),
         'ques3' => $this->input->post('quizid3'),
         'ques4' => $this->input->post('quizid4'),
         'ques5' => $this->input->post('quizid5'),
         'ques6' => $this->input->post('quizid6'),
         'ques7' => $this->input->post('quizid7'),
         'ques8' => $this->input->post('quizid8'),
         'ques9' => $this->input->post('quizid9'),
         'ques10' => $this->input->post('quizid10'),
    );

    $this->load->model('quizmodel');
    $this->data['results'] = $this->quizmodel->getQuestions();
    $this->load->view('result_display', $this->data);
}
}

Play Quiz File Code

<!DOCTYPE html>

<meta charset="utf-8">
<title>Play Quiz</title>

Play the Quiz!

<form method="post" action="<?php echo base_url();?
>index.php/Questions/resultdisplay">

<?php foreach($questions as $row) { ?>

<?php $ans_array = array($row->choice1, $row->choice2, $row->choice3, $row-
>answer);
shuffle($ans_array); ?>

<?=$row->quizID?>.<?=$row->question?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[0]?
>" required> <?=$ans_array[0]?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[1]?
>"> <?=$ans_array[1]?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[2]?
>"> <?=$ans_array[2]?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[3]?
>"> <?=$ans_array[3]?>

<?php } ?>

<input type="submit" value="Submit!">

</form>

Body:
the controller has an error:

instead of $this->data['questions'] = $this->quizmodel->getQuestions();

it should say data['questions'] = $this->quizmodel->getQuestions();

same goes for: $this->data['results'] = $this->quizmodel->getQuestions();

which should be: data['results'] = $this->quizmodel->getQuestions();

$this is a singleton Codeigniter instance, read more here:

The model has also an error, class declaration must be uppercase, read more here

class Quizmodel extends CI_Model

you may also note, that in the model after return $query->result(); the remaining code is unreachable, you may want to change it like so:

$num_data_returned = $query->num_rows();

if ($num_data_returned < 1) {
  echo "There is no data in the database";
  exit();
}else{
   return $query->result();
}


问:
replace part of href between 2 words jquery
This is simple and I have done it before but can't make it work right now.

I need to change the name of the image in below href

var href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"

$('.share, .share-2').prop('href', function () {
    $(this).replace(/(picture=).*?(&)/,'$1' + imgNew + '$2');
});
```

答:
```<code> var href="https://www.facebook.com/sharer/sharer.php?
 u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-
 1654-45654.jpg"
 href.split('/')
 ["https:", "", "www.facebook.com", "sharer", "sharer.php?u=http:", "",
 "myurl.com", "&description='tets'&picture=http:", "", "myurl.com", "img",
 "name-1654-45654.jpg"]
  href.split('/').length
 12
 href.split('/')[11]
"name-1654-45654.jpg"
</code>```


问:
Cell reuse bug in collectionView
Hello to all dear friends. I'm experiencing a problem with cell reuse. In practice I select multiple cells. In the "didSelected" method, I modify a property, called "isSelectedCell", to true and add a green border (to indicate the selection); While in the "didDeselect" method I carry it to false and remove the color of the border. But when I scroll down some cells, never selected, appear to be selected and the property is true. Because? How do I prevent this. It seems that when a cell is reused, the properties take on old ones and not their own.</p>

答:
If you are using a custom cell, override prepareForReuse and reset all properties to default values</p>

```<code>override func prepareForReuse() {
    super.prepareForReuse()
    // reset custom properties to default values
}
</code>```

Title: Cell reuse bug in collectionView

Body:
If you are using a custom cell, override prepareForReuse and reset all properties to default values

override func prepareForReuse() {
    super.prepareForReuse()
    // reset custom properties to default values
}


问:
get the byte array from the InputStream
I am trying to get the byte array data in the InputStream by calling the getBytes() method but nothing is being printed in the console. The count hat the vlaue 9. How can I print out the bytes of the InputStream?</p>

```<code>import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String args[]) throws Exception {
        InputStream inputStream = null;
        ServerSocket serverSocket = new ServerSocket(27015);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            inputStream = clientSocket.getInputStream();
            byte[] temp = new byte[512];
            int count = inputStream.read(temp); // here I am getting 9
            byte[] byteData = Test.getBytes(inputStream); // byteData is here empty.
            System.out.println("byteData: " + byteData);

        }
    }

    public static byte[] getBytes(InputStream is) throws IOException {

        int len;
        int size = 512;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1) {
                bos.write(buf, 0, len);
            }
            buf = bos.toByteArray();
        }
        return buf;
    }

}
</code>```

答:
in the line:

```<code>  int count = inputStream.read(temp); // here I am getting 9
</code>```

you have read the file alredy until the end,

so the line:

```<code>        byte[] byteData = Test.getBytes(inputStream); // byteData is here empty.
</code>```

has nothing to read.

So you should remove the first line and take the length of the Array as number of Bytes in your Input stream

Title: get the byte array from the InputStream

Body:
I am trying to get the byte array data in the InputStream by calling the getBytes() method but nothing is being printed in the console. The count hat the vlaue 9. How can I print out the bytes of the InputStream?

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String args[]) throws Exception {
        InputStream inputStream = null;
        ServerSocket serverSocket = new ServerSocket(27015);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            inputStream = clientSocket.getInputStream();
            byte[] temp = new byte[512];
            int count = inputStream.read(temp); // here I am getting 9
            byte[] byteData = Test.getBytes(inputStream); // byteData is here empty.
            System.out.println("byteData: " + byteData);

        }
    }

    public static byte[] getBytes(InputStream is) throws IOException {

        int len;
        int size = 512;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1) {
                bos.write(buf, 0, len);
            }
            buf = bos.toByteArray();
        }
        return buf;
    }

}

Body:
in the line:

  int count = inputStream.read(temp); // here I am getting 9

you have read the file alredy until the end,

so the line:

        byte[] byteData = Test.getBytes(inputStream); // byteData is here empty.

has nothing to read.

So you should remove the first line and take the length of the Array as number of Bytes in your Input stream


问:
Automapper. Map if source member is null
I have two classes and map one to other with Automapper. For instance:

```<code>public class Source
{
    // IdName is a simple class containing two fields: Id (int) and Name (string)
    public IdName Type { get; set; }

    public int TypeId {get; set; }

    // another members
}

public class Destination
{
    // IdNameDest is a simple class such as IdName
    public IdNameDest Type { get; set; }

    // another members
}
</code>```

Then I use Automapper to map Source  to Destination:

```<code>cfg.CreateMap<Source, Destination>();
</code>```

It works properly but sometimes member Type in class Source becomes null. In these cases I would like to map member Type in class Destination from TypeId property. That's what I want in a nutshel:

```<code>if Source.Type != null
then map Destination.Type from it
else map it as
    Destination.Type = new IdNameDest { Id = Source.Id }
</code>```

Is it possible with AutoMapper?

答:
You can use the .ForMember() method while declaring the mapping.
Like so :

```<code>cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type != null ? src.Type : new IdNameDest { Id = src.Id }));
</code>```

Body:
I have two classes and map one to other with Automapper. For instance:

public class Source
{
    // IdName is a simple class containing two fields: Id (int) and Name (string)
    public IdName Type { get; set; }

    public int TypeId {get; set; }

    // another members
}

public class Destination
{
    // IdNameDest is a simple class such as IdName
    public IdNameDest Type { get; set; }

    // another members
}

Then I use Automapper to map Source  to Destination:

cfg.CreateMap<Source, Destination>();

It works properly but sometimes member Type in class Source becomes null. In these cases I would like to map member Type in class Destination from TypeId property. That's what I want in a nutshel:

if Source.Type != null
then map Destination.Type from it
else map it as
    Destination.Type = new IdNameDest { Id = Source.Id }

Is it possible with AutoMapper?

Body:
You can use the .ForMember() method while declaring the mapping.
Like so :

cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type != null ? src.Type : new IdNameDest { Id = src.Id }));


问:
SQL query to get value based on some values in fields
I have a MySQL database with a table named generations the structure of the table is as follows

I want to get value 10 as output when ten_generation have value 1 otherwise it will not return any value, 20 as output if twenty_generation have value 1 otherwise it will not return any value, 30 as output if thirty_generation have value 1 otherwise it will not return any value. If all the three fields has a value 1 output will be 10,20,30 also the task_id will provided as the input.

答:
For MySQL you'd use CONCAT_WS:

```<code>select
  concat_ws(',',
    case when ten_generation = 1 then '10' end,
    case when twenty_generation = 1 then '20' end,
    case when thirty_generation = 1 then '30' end
  ) as result
from mytable
where task_id = 2;
</code>```

Body:
For MySQL you'd use CONCAT_WS:

select
  concat_ws(',',
    case when ten_generation = 1 then '10' end,
    case when twenty_generation = 1 then '20' end,
    case when thirty_generation = 1 then '30' end
  ) as result
from mytable
where task_id = 2;