问:
Are there significant differences between the Chrome browser event loop versus the node event loop?
Philip Roberts does a brilliant job explaining the browser event loop here providing a clear explanation between the call stack, event loop, task queue, and then "outside" threads like webapis.  My question is do these parallel the equivalent components in the Node event loop and are they called basically the same thing.  That is, when I make a call using Node's file and web i/o libraries, these are things that happen outside the stack whose callbacks are queued in a task queue?</p>

答:
Both are quite different. Browser's event loop doesn't depends on I/O Operations. But Node js event loop depends on I/O operations. Here the Node js event loop main goal is to separate out the main process and try to execute I/O operations and other timer API's asynchronously.

And another difference is we don't have a function setImmediate() in Browser. Difference between setTimeout() and setImmediate() is In setTimeout() call back function will execute after the given minimum threshold value in milliseconds. But in setImmediate() once any I/O Operation is done, if particular code is given inside setImmediate(), it will be executed first.

Because normally

```<code>setTimeout(() => {
    //some process
}, 0);
</code>```

and

```<code>setImmediate(() => {
    //some process
});
</code>```

are same and we can't predict which will execute first. But in Node js perspective under nodejs event loop mechanism if both are present under the callback of any I/O Operation, setImmediate() will get executed first. so,

```<code>let fs = require('fs');
fs.readFile('/file/path', () => {
   setTimeout(() => {
      console.log('1');
   }, 0);
   setImmediate(() => {
      console.log('2');
   });
});
</code>```

The output for above code will be,

```<code>2
1
</code>```

Body:
Both are quite different. Browser's event loop doesn't depends on I/O Operations. But Node js event loop depends on I/O operations. Here the Node js event loop main goal is to separate out the main process and try to execute I/O operations and other timer API's asynchronously.

And another difference is we don't have a function setImmediate() in Browser. Difference between setTimeout() and setImmediate() is In setTimeout() call back function will execute after the given minimum threshold value in milliseconds. But in setImmediate() once any I/O Operation is done, if particular code is given inside setImmediate(), it will be executed first.

Because normally

setTimeout(() => {
    //some process
}, 0);

and

setImmediate(() => {
    //some process
});

are same and we can't predict which will execute first. But in Node js perspective under nodejs event loop mechanism if both are present under the callback of any I/O Operation, setImmediate() will get executed first. so,

let fs = require('fs');
fs.readFile('/file/path', () => {
   setTimeout(() => {
      console.log('1');
   }, 0);
   setImmediate(() => {
      console.log('2');
   });
});

The output for above code will be,

2
1


来源: stackexchange

问:
Typescript, from us currency to es currency
I'm trying to convert an us currency to a spanish currency (ok) but when I try to get again the us currency I get a Nan. What's wrong?

Thanks

```<code>const esp = Number('5000.55').toLocaleString(); // esp = '5.000,55'
const us = Number('5.000,55').toLocaleString('en-US'); // us = 'NaN'
</code>```

答:
Adding to HRK44's answer I would suggest using Intl.NumberFormat which is part of the Internationalization API. .toLocaleString is older, it does not actually support locale, it just uses system locale and performs way worse with bulk data.

You can then perform the conversion like below using appropriate language code:

```<code>var CurrencyFormat= new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
});

CurrencyFormat.format(5000.55); /* $5,500.55 */
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to convert an us currency to a spanish currency (ok) but when I try to get again the us currency I get a Nan. What's wrong?

Thanks

const esp = Number('5000.55').toLocaleString(); // esp = '5.000,55'
const us = Number('5.000,55').toLocaleString('en-US'); // us = 'NaN'

Body:
Adding to HRK44's answer I would suggest using Intl.NumberFormat which is part of the Internationalization API. .toLocaleString is older, it does not actually support locale, it just uses system locale and performs way worse with bulk data.

You can then perform the conversion like below using appropriate language code:

var CurrencyFormat= new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
});

CurrencyFormat.format(5000.55); /* $5,500.55 */


问:
Print multiple row outputs in csv file
Suppose

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

</code>```

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

```<code>Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum
</code>```

Expected Output:

答:
Try this code it is simple and easy</p>

```<code>dictionary = {'Group':['First','Second','Third','Fourth'],
'Number' :['Random','Odd','Even','Prime'],
'Angle':['Degree','Inclined','Steep','Gradient'],
'Max value' :['Largest','Maximum','Smallest','Minimum']}
df = pd.DataFrame(dictionary)
print (df)
#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)
</code>```

Title: Print multiple row outputs in csv file

Body:
Suppose

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum

Expected Output:

Body:
Try this code it is simple and easy

dictionary = {'Group':['First','Second','Third','Fourth'],
'Number' :['Random','Odd','Even','Prime'],
'Angle':['Degree','Inclined','Steep','Gradient'],
'Max value' :['Largest','Maximum','Smallest','Minimum']}
df = pd.DataFrame(dictionary)
print (df)
#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)


问:
How to stop activity from creating everytime when started from other activity?
I am trying to create a multiple activity app. having activity 1.mainactivity
2.mapsactivity. Now I have a navigation drawer i.e when user click on maps
an intent will be called to map activity. Because of this when the user starts operating in the mapsactivity and onBackpressed he again returns to mainactivity and when he again go to maps the activity starts again. Is there a solution to this problem, How can I run my activity even if navigating to other activity?

"This is a part of mainactivity having nav drawer"

```<code> public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
        } else if (id == R.id.nav_maps) {
            // Maps Activity
            Intent intent = new Intent(getApplicationContext(),AttendanceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_rider_app) {

       }
</code>```

答:
Override method onBackPressed() in your MapActivity and replace super.onBackPressed(); with

Intent mainActivtyIntent = new Intent(this, MainActivity.class)
mainActivtyIntent.addFlag(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(mainActivtyIntent);

Body:
I am trying to create a multiple activity app. having activity 1.mainactivity
2.mapsactivity. Now I have a navigation drawer i.e when user click on maps
an intent will be called to map activity. Because of this when the user starts operating in the mapsactivity and onBackpressed he again returns to mainactivity and when he again go to maps the activity starts again. Is there a solution to this problem, How can I run my activity even if navigating to other activity?

"This is a part of mainactivity having nav drawer"

 public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
        } else if (id == R.id.nav_maps) {
            // Maps Activity
            Intent intent = new Intent(getApplicationContext(),AttendanceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_rider_app) {

       }


问:
Differences between a conceptual UML class diagram and an ERD?
If I create a conceptual class diagram such that each class captures 'name' and 'attributes' but not 'operations', have I not basically created what would be otherwise considered an ERD?  I'm trying to gain an understanding of what the differences are between creating a conceptual class diagram as I have described versus calling it a ERD?  If these are still two different animals, can somebody please explain what the differences are? </p>

答:
IMO In Simple terms

Class diagram depicts the details of how will the system work.

ER diagram depicts how the system persists 'state' as a blue print.

Goal:
 Detail out state and behavior of the components(classes) of the system.
 Design 'efficient', flexile system(less coupling and more cohesion) using Solid principles.

Goal:
 Design a blue print of how to 'efficiently' persist the state of the system.
 Consider what kind of queries will be made (read vs write), are there any joins required
 consequently figure out the columns for indexing
 Use Normalization, ACID properties.

PS: notice the both the diagram tries to efficiently do thing in their on respect.

ContentLicense: CC BY-SA 2.5


问:
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

```<code>bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}
</code>```

答: A token is usually akin to a word in sponken language. In C++, (int, float, 5.523, const) will  be tokens. Is the minimal unit of text which constitutes a semantic element.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}


问:
Can IP range be made keys in Redis
Is it possible  that an ip range can be set as a key in a Redis. My requirement is that i have to fetch records based on ip address.
Now this ip address can be start_ip or end_ip or any ip falling in between it. I have to make to ip as the key.Can this be achieved</p>

答:
If you know the starting and ending index of your IPs, you can do this

```<code>var redis = require('redis');
var client = redis.createClient(port, host);
client.on('connect', function() {
    console.log('Redis client connected');
    //insert your code for storing your csv data in an array
    var csv_array = ['127.0.0.1','127.0.0.2','127.0.0.3'];//store your IP in this way
    //for storing in redis
    for(var i=0,index=1; i<csv_array.length; i++,index++){
        client.zadd(['ipaddress',index,csv_array[i]],function(err,res){
            console.log("added");
        });
    }
    //for retrieving specify starting, ending index
    client.zrevrangebyscore(['ipaddress',startingIndex,endingIndex],function(err,res){
        console.log(res);
    });
});
</code>```

If you don't know the index values then just replace the retrieve part with this:

```<code>var IP_array = [];
var starting, ending;
client.zrevrangebyscore(['ipaddress','+inf','-inf'],function(err,res){
    IP_array.push(res);
});
starting = IP_array.indexOf('127.0.0.1');//staring IP range
ending = IP_array.indexOf('129.32.21.180');// ending IP range
console.log(IP_array.slice(starting, ending));
</code>```

Title: Can IP range be made keys in Redis

Body:
If you know the starting and ending index of your IPs, you can do this

var redis = require('redis');
var client = redis.createClient(port, host);
client.on('connect', function() {
    console.log('Redis client connected');
    //insert your code for storing your csv data in an array
    var csv_array = ['127.0.0.1','127.0.0.2','127.0.0.3'];//store your IP in this way
    //for storing in redis
    for(var i=0,index=1; i<csv_array.length; i++,index++){
        client.zadd(['ipaddress',index,csv_array[i]],function(err,res){
            console.log("added");
        });
    }
    //for retrieving specify starting, ending index
    client.zrevrangebyscore(['ipaddress',startingIndex,endingIndex],function(err,res){
        console.log(res);
    });
});

If you don't know the index values then just replace the retrieve part with this:

var IP_array = [];
var starting, ending;
client.zrevrangebyscore(['ipaddress','+inf','-inf'],function(err,res){
    IP_array.push(res);
});
starting = IP_array.indexOf('127.0.0.1');//staring IP range
ending = IP_array.indexOf('129.32.21.180');// ending IP range
console.log(IP_array.slice(starting, ending));


问:
android UI elements' visibilty not changing
I've been writing an app for FTP file transfer and i need to hide a few UI elements and make a few visible on a button click.The visibility settings remain the same as when the app starts.They do not change.Any idea why?

here are my elements:

ip= (EditText) findViewById(R.id.ipadd);
portt=(EditText) findViewById(R.id.port);
conn= (Button) findViewById(R.id.connectb);
pb= (ProgressBar) findViewById(R.id.pb);
trans=(TextView) findViewById(R.id.transfer);
```

<p>here are the settings at the starting of the app(onCreate):</p>

<pre class="lang-java prettyprint-override"><code>pb.setVisibility(View.INVISIBLE);
trans.setVisibility(View.INVISIBLE);
ip.setVisibility(View.VISIBLE);
portt.setVisibility(View.VISIBLE);
conn.setVisibility(View.VISIBLE);
</code>```

These settings are applied.
And this is the code for the function when the button is clicked:

Ftp ftp;
errflag=false;
ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
while(!errflag) {
    try{
      ftp=new Ftp();
      String result = ftp.execute("hi").get();
      if(result.equals("Finished"))
          break;
    } catch(Exception e){
        e.printStackTrace();
    }
}
```

<p>Everything in the code works fine except for the visibility of these elements.
The control enters the while loop and exits properly but doesn't change the visibility of the elements.And yes the function is invoked on button click,so it is in the UI thread,but i've still tried wrapping up the code in runOnUIThread method which doesn't seem to make any changes.
Any comments will be appreciated.</p>

<p>Asynctask code:</p>

```public class Ftp extends AsyncTask<String ,String,String>
{

    protected String doInBackground(String... urls)
    {
        try
        {
            String ipadd= ip.getText().toString();
            int port =Integer.parseInt(portt.getText().toString());
            Socket socket=new Socket(ipadd,port);
            //Button conn=(Button) findViewById(R.id.connectb);

            //conn.setEnabled(false);
            BufferedReader br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedOutputStream bo= new BufferedOutputStream(socket.getOutputStream());
            PrintWriter pw= new PrintWriter(bo,true);
            String file=br.readLine();
            if(file.equals("Finished"))
                return file;
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            File f= new File(path, "/" + file);
            byte[] buff= new byte[1024];
            int len;
                pw.println("done");
                DataInputStream is= new DataInputStream(socket.getInputStream());
                FileOutputStream fos= new FileOutputStream(f);

            Thread.sleep(1);
            publishProgress(file);
                while((len=is.read(buff))!=-1)
                {

                    fos.write(buff,0,len);

                }
            Log.i("status","Finsihed");

           /* else
            {
                Toast.makeText(MainActivity.this,"File already exists!",Toast.LENGTH_LONG).show();
            }*/
        }catch(NumberFormatException nfe)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            nfe.printStackTrace();

        }
        catch(java.net.UnknownHostException un)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            //Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
            un.printStackTrace();
        }
        catch(java.net.NoRouteToHostException no)
        {errflag=true;

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"There is no active server at the specified IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            no.printStackTrace();
        }
        catch(Exception e)

        {
            errflag=true;
            Log.i("this","error");
            e.printStackTrace();
        }
        return "Not Yet";
    }
    protected void onProgressUpdate(String... para)
    {
        super.onProgressUpdate(para);
        trans.setText("Transfering file: "+para[0]);

    }

}`
```

<p>Then i made a new thread:</p>

```public class MyThread extends Thread
{
    public void run() {
        while (!errflag) {
            try {
                Ftp ftp = new Ftp();
                String res = ftp.execute("hi").get();
                if (res.equals("Finished"))
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
```

<p>and changed the function code to:</p>

```errflag=false;
            ip.setVisibility(View.INVISIBLE);
            portt.setVisibility(View.INVISIBLE);
            conn.setVisibility(View.INVISIBLE);
            trans.setVisibility(View.VISIBLE);
            pb.setVisibility(View.VISIBLE);

        /*ftp=new Ftp();
        String result = ftp.execute("hi").get();
        if(result.equals("Finished"))
            break;*/

        try {
            MyThread t = new MyThread();
            t.start();
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
```

答:
I consider, you should move your while loop in another thread.
Changing visibility means that views hierarchy will be redrawn on a next frame and it [visibility] will be taking into account only on a next drawing iteration. so as you block ui thread (in a while loop), this redraw phase will never be reached.

UPD: you should release your UI thread, so just move while loop in another thread.

```<code>ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
    @Override
    public void run() {
        errflag=false;
        while(!errflag) {
            try{
              ftp=new Ftp();
              String result = ftp.execute("hi").get();
              if(result.equals("Finished"))
                  break;
            } catch(Exception e){
                e.printStackTrace();
            }
        }
    }
});
</code>```

Body:
I've been writing an app for FTP file transfer and i need to hide a few UI elements and make a few visible on a button click.The visibility settings remain the same as when the app starts.They do not change.Any idea why?

here are my elements:

ip= (EditText) findViewById(R.id.ipadd);
portt=(EditText) findViewById(R.id.port);
conn= (Button) findViewById(R.id.connectb);
pb= (ProgressBar) findViewById(R.id.pb);
trans=(TextView) findViewById(R.id.transfer);

here are the settings at the starting of the app(onCreate):

pb.setVisibility(View.INVISIBLE);
trans.setVisibility(View.INVISIBLE);
ip.setVisibility(View.VISIBLE);
portt.setVisibility(View.VISIBLE);
conn.setVisibility(View.VISIBLE);

These settings are applied.
And this is the code for the function when the button is clicked:

Ftp ftp;
errflag=false;
ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
while(!errflag) {
    try{
      ftp=new Ftp();
      String result = ftp.execute("hi").get();
      if(result.equals("Finished"))
          break;
    } catch(Exception e){
        e.printStackTrace();
    }
}

Everything in the code works fine except for the visibility of these elements.
The control enters the while loop and exits properly but doesn't change the visibility of the elements.And yes the function is invoked on button click,so it is in the UI thread,but i've still tried wrapping up the code in runOnUIThread method which doesn't seem to make any changes.
Any comments will be appreciated.

Asynctask code:

public class Ftp extends AsyncTask<String ,String,String>
{

    protected String doInBackground(String... urls)
    {
        try
        {
            String ipadd= ip.getText().toString();
            int port =Integer.parseInt(portt.getText().toString());
            Socket socket=new Socket(ipadd,port);
            //Button conn=(Button) findViewById(R.id.connectb);

            //conn.setEnabled(false);
            BufferedReader br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedOutputStream bo= new BufferedOutputStream(socket.getOutputStream());
            PrintWriter pw= new PrintWriter(bo,true);
            String file=br.readLine();
            if(file.equals("Finished"))
                return file;
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            File f= new File(path, "/" + file);
            byte[] buff= new byte[1024];
            int len;
                pw.println("done");
                DataInputStream is= new DataInputStream(socket.getInputStream());
                FileOutputStream fos= new FileOutputStream(f);

            Thread.sleep(1);
            publishProgress(file);
                while((len=is.read(buff))!=-1)
                {

                    fos.write(buff,0,len);

                }
            Log.i("status","Finsihed");

           /* else
            {
                Toast.makeText(MainActivity.this,"File already exists!",Toast.LENGTH_LONG).show();
            }*/
        }catch(NumberFormatException nfe)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            nfe.printStackTrace();

        }
        catch(java.net.UnknownHostException un)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            //Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
            un.printStackTrace();
        }
        catch(java.net.NoRouteToHostException no)
        {errflag=true;

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"There is no active server at the specified IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            no.printStackTrace();
        }
        catch(Exception e)

        {
            errflag=true;
            Log.i("this","error");
            e.printStackTrace();
        }
        return "Not Yet";
    }
    protected void onProgressUpdate(String... para)
    {
        super.onProgressUpdate(para);
        trans.setText("Transfering file: "+para[0]);

    }

}`

Then i made a new thread:

public class MyThread extends Thread
{
    public void run() {
        while (!errflag) {
            try {
                Ftp ftp = new Ftp();
                String res = ftp.execute("hi").get();
                if (res.equals("Finished"))
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

and changed the function code to:

errflag=false;
            ip.setVisibility(View.INVISIBLE);
            portt.setVisibility(View.INVISIBLE);
            conn.setVisibility(View.INVISIBLE);
            trans.setVisibility(View.VISIBLE);
            pb.setVisibility(View.VISIBLE);

        /*ftp=new Ftp();
        String result = ftp.execute("hi").get();
        if(result.equals("Finished"))
            break;*/

        try {
            MyThread t = new MyThread();
            t.start();
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }

Body:
I consider, you should move your while loop in another thread.
Changing visibility means that views hierarchy will be redrawn on a next frame and it [visibility] will be taking into account only on a next drawing iteration. so as you block ui thread (in a while loop), this redraw phase will never be reached.

UPD: you should release your UI thread, so just move while loop in another thread.

ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
    @Override
    public void run() {
        errflag=false;
        while(!errflag) {
            try{
              ftp=new Ftp();
              String result = ftp.execute("hi").get();
              if(result.equals("Finished"))
                  break;
            } catch(Exception e){
                e.printStackTrace();
            }
        }
    }
});


问:
Table having column with multiple rows having comma separated values, want to insert each value in column of other table
enter code hereI need a query to insert. Maybe:

```<code>insert tblTestTable (TestData)
select value from STRING_SPLIT((select MyData from tblMyTable), ',')
</code>```

refer attachmentRefer image

答:
Something like this:

```CREATE TABLE TableA
(ColumnToSplit VARCHAR(500))
GO
INSERT INTO TableA
SELECT 'A,B,C'
UNION ALL
SELECT 'A,F,G'
UNION ALL
SELECT 'D,E,H'
GO</p>

<p>SELECT value
FROM TableA
 CROSS APPLY STRING_SPLIT(ColumnToSplit, ',')
GO```

Body:
enter code hereI need a query to insert. Maybe:

insert tblTestTable (TestData)
select value from STRING_SPLIT((select MyData from tblMyTable), ',')

refer attachmentRefer image

Body:
Something like this:

CREATE TABLE TableA
(ColumnToSplit VARCHAR(500))
GO
INSERT INTO TableA
SELECT 'A,B,C'
UNION ALL
SELECT 'A,F,G'
UNION ALL
SELECT 'D,E,H'
GO

SELECT value
FROM TableA
 CROSS APPLY STRING_SPLIT(ColumnToSplit, ',')
GO


问:
Normalization settings table (with duplicates in the same cell and with different types in the same column)
I have settings table like this:

```<code> id | user_id | key              | value
 1  |    1    | show brand logos | true
 2  |    1    | brand ids        | 1,3,4
 3  |    1    | search type      | advanced
</code>```

I use this and it works somehow, but I have read about normalization and it brakes even first normalization form rules: single valued attributes (there is a cell with 1,3,4) and attribute domain should not change (there are Boolean, String and Integers).

Have you any ideas how to normalize this table? I have searched a lot, but without success.

答:
create a key table:

```<code>id  | key
1   | show brand logos
2   | brand ids
3   | search type
</code>```

add three rows instead on one

```<code>id  | user_id | key             | value_bool| value_str| value_num
 1  |    1    | 1               | true      | null     | null
 2  |    1    | 2               | null      | null     | 1
 2  |    1    | 2               | null      | null     | 3
 2  |    1    | 2               | null      | null     | 4
 3  |    1    | 3               | null      | advanced | null
</code>```

Body:
I have settings table like this:

 id | user_id | key              | value
 1  |    1    | show brand logos | true
 2  |    1    | brand ids        | 1,3,4
 3  |    1    | search type      | advanced

I use this and it works somehow, but I have read about normalization and it brakes even first normalization form rules: single valued attributes (there is a cell with 1,3,4) and attribute domain should not change (there are Boolean, String and Integers).

Have you any ideas how to normalize this table? I have searched a lot, but without success.

Body:
create a key table:

id  | key
1   | show brand logos
2   | brand ids
3   | search type

add three rows instead on one

id  | user_id | key             | value_bool| value_str| value_num
 1  |    1    | 1               | true      | null     | null
 2  |    1    | 2               | null      | null     | 1
 2  |    1    | 2               | null      | null     | 3
 2  |    1    | 2               | null      | null     | 4
 3  |    1    | 3               | null      | advanced | null


问:
How To Select One row in Table and Echo In PHP
I have a table for my products and I select them in index page and it works true but I want to click one of the products (at index) and then go to product detail page and get selected product data and echo that I will get my row id at product detail page but i don't know how to select a row by that id and then show that data

The first line is working true and I get my product id from the index page
but I don't know how to write a select code and I want to show my selected data in article tag and my table name is "products" and my fields are name, type, img, price, des, id

```<code><?php

$myid = $_GET['pid'];

require_once 'setting.php';
$dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_set_charset($dbc, 'utf8');

$query = "SELECT * FROM products where id = $myid";
$result = mysqli_query($dbc, $query);

echo "
    <article>
        <img src = \"{$products['img']}\"><br>
        <a>name: </a>{$products['type']} <br>
        <a>title: </a>
        <a style='color:white;'>{$product['name']}</a> <br>
        <a>price: </a>{$products['price']} <br>
        <a>descrition: </a>{$products['des']} <br>
    </article>";

mysqli_close($dbc);
</code>```

I know my code is totally not true so that's an example to show my Target

答:
First you need to fetch the result row as an associative array using mysqli_fetch_assoc(result);

Try this :

```<code> <?php

                $myid = $_GET['pid'];

                require_once 'setting.php';
                $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
                mysqli_set_charset($dbc, 'utf8');

                $query = "SELECT * FROM products where id = $myid";
                $result = mysqli_query($dbc, $query);

                  $products = mysqli_fetch_assoc($result);

                echo "
                       <article>
                                <a>name: </a> $products['type'] <br>
                                <a>title: </a>
                                <a style='color:white;'>$product['name']</a> <br>
                                <a>price: </a>$products['price'] <br>
                                <a>descrition: </a>$products['des'] <br>
                       </article>";

                mysqli_close($dbc);
            ?

>
</code>```

Body:
I have a table for my products and I select them in index page and it works true but I want to click one of the products (at index) and then go to product detail page and get selected product data and echo that I will get my row id at product detail page but i don't know how to select a row by that id and then show that data

The first line is working true and I get my product id from the index page
but I don't know how to write a select code and I want to show my selected data in article tag and my table name is "products" and my fields are name, type, img, price, des, id

<?php

$myid = $_GET['pid'];

require_once 'setting.php';
$dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_set_charset($dbc, 'utf8');

$query = "SELECT * FROM products where id = $myid";
$result = mysqli_query($dbc, $query);

echo "

        name: {$products['type']}

        title:
        {$product['name']}

        price: {$products['price']}

        descrition: {$products['des']}

";

mysqli_close($dbc);

I know my code is totally not true so that's an example to show my Target

Body:
First you need to fetch the result row as an associative array using mysqli_fetch_assoc(result);

Try this :

 <?php

                $myid = $_GET['pid'];

                require_once 'setting.php';
                $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
                mysqli_set_charset($dbc, 'utf8');

                $query = "SELECT * FROM products where id = $myid";
                $result = mysqli_query($dbc, $query);

                  $products = mysqli_fetch_assoc($result);

                echo "
                       <article>
                                <a>name: </a> $products['type'] <br>
                                <a>title: </a>
                                <a style='color:white;'>$product['name']</a> <br>
                                <a>price: </a>$products['price'] <br>
                                <a>descrition: </a>$products['des'] <br>
                       </article>";

                mysqli_close($dbc);
            ?

>


答:
Try to execute your ftp method in a worker thread like below, probably you're blocking your UI to be updated.

Ftp ftp;
errflag=false;
ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
try {
      new Thread(new Runnable() {
        public void run() {
            // a potentially time consuming task
            while(!errflag) {
                ftp = new Ftp();
                String result = ftp.execute("hi").get();
                if(result.equals("Finished"))
                    break;
            }
        }
       }).start();

    } catch(Exception e){
        e.printStackTrace();
    }
}
```

Title: android UI elements' visibilty not changing


问:
C++: Clarification about "valid pointers and references"
I'm having an hard time understanding this description of stl unordered map's implementation:

The standard template library (STL) for C++ provides hash tables via std::unordered_map and std::unordered_set. The standard guarantees reference stability: References and pointers to the keys and values in the hash table must remain valid until the corresponding key is removed. In practice, this means the entries must be indirect and individually allocated, which adds a substantial CPU overhead.

Two questions:

When the author says "references and pointers to the keys and values ... must remain valid" does that mean that after I insert an item, the pointer and reference must live for the entirety of the program? When I use "new" to allocate the object on the heap and the pointer to it goes out of scope and is no longer valid. I'm not sure why the reference/pointer needs to stay valid given that the hash table has reference to the object on the heap.

How do "indirect and individually allocated" entries "add substantial CPU overhead"?

答:
When the author says "references and pointers to the keys and values ... must remain valid" does that mean that after I insert an item, the pointer and reference must live for the entirety of the program?

No. It means that if you take the address of an object in the map, or bind a reference to such an object, that pointer, or that reference, must not become dangling because of unrelated elements in the map being added or removed. It is a requirement on the implementation of std::unordered_map.

This is different to how e.g. std::vector behaves. Adding elements to a vector can cause it to reallocate, and all previously acquired pointers and references to elements are left dangling.

When I use new to allocate the object on the heap and the pointer to it goes out of scope and is no longer valid.

No, the pointer ceases to exist, other pointers with the same value are still pointing to the object you newed.

How do "indirect and individually allocated" entries "add substantial CPU overhead"?

Modern CPUs are much faster at accessing things that are adjacent in memory. E.g. they start loading later elements before they are asked to. Such prediction is harder if the target addresses don't follow a simple pattern.

The article that you linked is highlighting design choices that the standards committee made that make std::unordered_map unsuitable for the author's purposes. They have written a pair of classes that have the same public members (with the same meanings) as those of std::unordered_map, as a "drop in" replacement.


问:
Count written records in Spark with threads
I am using onTaskEnd Spark listener to get the number of records written into file like this:

```<code>import spark.implicits._
import org.apache.spark.sql._
import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd}

var recordsWritten: Long = 0L

val rowCountListener: SparkListener = new SparkListener() {
  override def onTaskEnd(taskEnd: SparkListenerTaskEnd) {
    synchronized {
      recordsWritten += taskEnd.taskMetrics.outputMetrics.recordsWritten
    }
  }
}

def rowCountOf(proc: => Unit): Long = {
  recordsWritten = 0L
  spark.sparkContext.addSparkListener(rowCountListener)
  try {
    proc
  } finally {
    spark.sparkContext.removeSparkListener(rowCountListener)
  }
  recordsWritten
}

val rc = rowCountOf { (1 to 100).toDF.write.csv(s"test.csv") }
println(rc)

=> 100
</code>```

However trying to run multiple actions in threads this obviously breaks:

```<code>Seq(1, 2, 3).par.foreach { i =>
  val rc = rowCountOf { (1 to 100).toDF.write.csv(s"test${i}.csv") }
  println(rc)
}

=> 600
=> 700
=> 750
</code>```

I can have each thread declare its own variable, but spark context is still shared and I am unable to reckognize to which thread does specific SparkListenerTaskEnd event belong to. Is there any way to make it work?

(Right, maybe I could just make it separate spark jobs. But it's just a single piece of the program, so for the sake of simplicity I would prefer to stay with threads. In the worst case I'll just execute it serially or forget about counting records...)

答:
A bit hackish but you could use accumulators as a filtering side-effect</p>

```<code>val acc = spark.sparkContext.longAccumulator("write count")
df.filter { _ =>
  acc.add(1)
  true
}.write.csv(...)
println(s"rows written ${acc.count}")
</code>```

Body:
I am using onTaskEnd Spark listener to get the number of records written into file like this:

import spark.implicits._
import org.apache.spark.sql._
import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd}

var recordsWritten: Long = 0L

val rowCountListener: SparkListener = new SparkListener() {
  override def onTaskEnd(taskEnd: SparkListenerTaskEnd) {
    synchronized {
      recordsWritten += taskEnd.taskMetrics.outputMetrics.recordsWritten
    }
  }
}

def rowCountOf(proc: => Unit): Long = {
  recordsWritten = 0L
  spark.sparkContext.addSparkListener(rowCountListener)
  try {
    proc
  } finally {
    spark.sparkContext.removeSparkListener(rowCountListener)
  }
  recordsWritten
}

val rc = rowCountOf { (1 to 100).toDF.write.csv(s"test.csv") }
println(rc)

=> 100

However trying to run multiple actions in threads this obviously breaks:

Seq(1, 2, 3).par.foreach { i =>
  val rc = rowCountOf { (1 to 100).toDF.write.csv(s"test${i}.csv") }
  println(rc)
}

=> 600
=> 700
=> 750

I can have each thread declare its own variable, but spark context is still shared and I am unable to reckognize to which thread does specific SparkListenerTaskEnd event belong to. Is there any way to make it work?

(Right, maybe I could just make it separate spark jobs. But it's just a single piece of the program, so for the sake of simplicity I would prefer to stay with threads. In the worst case I'll just execute it serially or forget about counting records...)

Body:
A bit hackish but you could use accumulators as a filtering side-effect

val acc = spark.sparkContext.longAccumulator("write count")
df.filter { _ =>
  acc.add(1)
  true
}.write.csv(...)
println(s"rows written ${acc.count}")


问:
Unexpected KeyError When Merging Two Multi-Index Dataframes in Pandas
I have two multi-index dataframes that I want to merge on a common column in the second level. Trying to outer merge the two dfs returns an unexpected KeyError on the final merge key.

I've tested the merge without the multi-index and it works fine. I've also flipped the order of the merge and it seems to always occur on the right_on param. Finally, I've confirmed that I can access the erring key-series outside of the merge just fine..

single index merge works fine:

```<code>[IN]:
df1 = pd.DataFrame({'A1': ['A1', 'A1', 'A2', 'A3'],
                    'B': ['121', '345', '123', '146'],
                    'C': ['K0', 'K1', 'K0', 'K1']})

df2 = pd.DataFrame({'A2': ['A1', 'A3'],
                    'X': ['B0', 'B3'],
                    'Y': ['121', '345'],
                    'Z': ['D0', 'D1']})

fine_merge = pd.merge(df1,df2,how='outer',left_on='A1', right_on='A2')
print(fine_merge)
</code>```

```<code>[OUT]:
  A1    B   C   A2    X    Y    Z
0  A1  121  K0   A1   B0  121   D0
1  A1  345  K1   A1   B0  121   D0
2  A2  123  K0  NaN  NaN  NaN  NaN
3  A3  146  K1   A3   B3  345   D1
</code>```

multi-index key works fine:

```<code>[IN]:
df1.columns = pd.MultiIndex.from_tuples([('left_header', c) for c in df1.columns])
df2.columns = pd.MultiIndex.from_tuples([('right_header', c) for c in df2.columns])

print(df2['right_header','A2'])
</code>```

```<code>[OUT]:
0    A1
1    A3
Name: (right_header, A2), dtype: object
</code>```

but multi-index merge returns a KeyError

```<code>[IN]:
error_merge = pd.merge(df1,df2, how='outer', left_on=['left_header','A1'], right_on=('right_header','A2'))
print(error_merge)
</code>```

```<code>[OUT]:
KeyError: 'A2'
</code>```

I am rather confused by this, especially given that if I reverse the merge or such that df1 is the right and right_on==['left_header','A1'] the resulting error is KeyError: 'A1'

Thanks for the help in advance.

edit: combine, join, concat all yield the following result:

```<code>
combined
  left_header          right_header
       A1    B   C       A2    X      Y    Z
0      A1  121  K0       A1   B0  121.0   D0
1      A1  345  K1       A3   B3  345.0   D1
2      A2  123  K0      NaN  NaN    NaN  NaN
3      A3  146  K1      NaN  NaN    NaN  NaN
</code>```

答:
You can try the below solutions:

Using combine.first

df1.combine_first(df2)

Using Concat:

pd.concat([df1, df2], axis=1)

Simple Join:

df1.join(df2, how='outer')

Body:
I have two multi-index dataframes that I want to merge on a common column in the second level. Trying to outer merge the two dfs returns an unexpected KeyError on the final merge key.

I've tested the merge without the multi-index and it works fine. I've also flipped the order of the merge and it seems to always occur on the right_on param. Finally, I've confirmed that I can access the erring key-series outside of the merge just fine..

single index merge works fine:

[IN]:
df1 = pd.DataFrame({'A1': ['A1', 'A1', 'A2', 'A3'],
                    'B': ['121', '345', '123', '146'],
                    'C': ['K0', 'K1', 'K0', 'K1']})

df2 = pd.DataFrame({'A2': ['A1', 'A3'],
                    'X': ['B0', 'B3'],
                    'Y': ['121', '345'],
                    'Z': ['D0', 'D1']})

fine_merge = pd.merge(df1,df2,how='outer',left_on='A1', right_on='A2')
print(fine_merge)

[OUT]:
  A1    B   C   A2    X    Y    Z
0  A1  121  K0   A1   B0  121   D0
1  A1  345  K1   A1   B0  121   D0
2  A2  123  K0  NaN  NaN  NaN  NaN
3  A3  146  K1   A3   B3  345   D1

multi-index key works fine:

[IN]:
df1.columns = pd.MultiIndex.from_tuples([('left_header', c) for c in df1.columns])
df2.columns = pd.MultiIndex.from_tuples([('right_header', c) for c in df2.columns])

print(df2['right_header','A2'])

[OUT]:
0    A1
1    A3
Name: (right_header, A2), dtype: object

but multi-index merge returns a KeyError

[IN]:
error_merge = pd.merge(df1,df2, how='outer', left_on=['left_header','A1'], right_on=('right_header','A2'))
print(error_merge)

[OUT]:
KeyError: 'A2'

I am rather confused by this, especially given that if I reverse the merge or such that df1 is the right and right_on==['left_header','A1'] the resulting error is KeyError: 'A1'

Thanks for the help in advance.

edit: combine, join, concat all yield the following result:

combined
  left_header          right_header
       A1    B   C       A2    X      Y    Z
0      A1  121  K0       A1   B0  121.0   D0
1      A1  345  K1       A3   B3  345.0   D1
2      A2  123  K0      NaN  NaN    NaN  NaN
3      A3  146  K1      NaN  NaN    NaN  NaN


问:
How to enable TaskO in Azure DevOps
I installed the TaskO extension for my Azure DevOps organization. However, when I open one of my projects that uses the Scrum or Agile process I do not see where to create the automated tasks. Does anyone know how to create tasks with this extension? </p>

答:
How to enable TaskO in Azure DevOps

I am afraid this TaskO extension is not very compatible with Azure Devops. I have installed this extension successfully for a long time, but I still could not make it work for my Azure Devops.

After install that extension for my Azure DevOps account, I could not see any add tasks UI display on my Azure DevOps. And on the page Q & A, there is also some feedback that they are not able to use this extension properly.

Besides, I have found a similar extension TaskO 2015, which is only work for TFS 2015. I am not very sure if this extension is work with Azure Deops. If this extension is work with Azure Devops, @Gouri S may need to provide us detailed instructions, which could help us to use this extension.

Hope this helps.

Title: How to enable TaskO in Azure DevOps


问:
QTcpSocket readyRead not emitted
The target is to receive some messages constantly from another tcp server.  Instead of python built-in tcp socket, I switch to QTcpsocket. The server side confirms a client connection. Well, the readyRead seems that has never been emitted and do not know what is wrong.

I have tried the python built-in socket and it works fine.

import socket
import sys
import struct
import json
import os

#crate a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Connect the socket to the port where the server is listening
server_address = ('localhost', 3336)
print('connectiong to {} port {}'.format(*server_address))
sock.connect(server_address)

file_count = 0
try:
    amount_received = 0
    amount_expected = 6000
    while amount_received < amount_expected:
        data = sock.recv(5000)
        data_string = data.decode("utf-8")
        #print('received {!r}'.format(data))
        if data_string.find("Header") != -1:
            dataChunkSize = int(data_string[data_string.find("Header")+6:data_string.find("|")])
            print(dataChunkSize)

        try:
            out = json.loads(data_string[data_string.find("JSONSTART|")+10 : data_string.find("JSONEND")])
            print(out)
            file_count += 1
            json_data_folder = "XXXX"
            if os.path.exists(json_data_folder):
                json_data_folder = os.path.join(json_data_folder, str(file_count)+'.json')
                with open(json_data_folder, 'w') as outfile:
                    json.dump(out, outfile, sort_keys=True)
                    print("save")
        except ValueError as e:
            print(e)
            data_false = data
        amount_expected += len(data)

finally:
    print('socket closed')
    sock.close()

```

```
from PyQt5.QtCore import QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket

class Client(QDialog):
    def __init__(self):
        super().__init__()
        self.tcpSocket = QTcpSocket(self)
        self.blockSize = 0
        self.makeRequest()
        self.tcpSocket.waitForConnected(1000)
        # send any message you like it could come from a widget text.
        #self.tcpSocket.write(b'hello')

        self.tcpSocket.readyRead.connect(self.dealCommunication)
        self.tcpSocket.error.connect(self.displayError)

    def makeRequest(self):
        HOST = 'localhost'
        PORT = 3336
        self.tcpSocket.connectToHost(HOST, PORT, QIODevice.ReadWrite)

    def dealCommunication(self):
        print('Message Comming')
        #data = self.tcpSocket.readAll()
        instr = QDataStream(self.tcpSocket)
        instr.setVersion(QDataStream.Qt_5_0)
        if self.blockSize == 0:
            if self.tcpSocket.bytesAvailable() < 2:
                return
            self.blockSize = instr.readUInt16()
        if self.tcpSocket.bytesAvailable() < self.blockSize:
            return
        # Print response to terminal, we could use it anywhere else we wanted.
        print(str(instr.readString(), encoding='utf-8'))

    def displayError(self, socketError):
        if socketError == QAbstractSocket.RemoteHostClosedError:
            pass
        else:
            print(self, "The following error occurred: %s." % self.tcpSocket.errorString())

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    client = Client()
    sys.exit(client.exec_())
```

The QTcpSocket client should constantly receive the input.

答:
You have to remove:

```<code>self.tcpSocket.waitForConnected (1000)
</code>```

In Qt the waitForXXX(...) method is blocking.

What is blocking in Qt?
It is a task that does not allow the Qt eventloop to be executed, thus preventing asynchronous tasks from executing.

This interferes with the data reception tasks that is triggered by readyRead a signal that is an asynchronous element.

In conclusion, do not use the waitForXXX(...) functions if you are going to use the event loop.

Title: QTcpSocket readyRead not emitted

Body:
The target is to receive some messages constantly from another tcp server.  Instead of python built-in tcp socket, I switch to QTcpsocket. The server side confirms a client connection. Well, the readyRead seems that has never been emitted and do not know what is wrong.

I have tried the python built-in socket and it works fine.

import socket
import sys
import struct
import json
import os

#crate a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Connect the socket to the port where the server is listening
server_address = ('localhost', 3336)
print('connectiong to {} port {}'.format(*server_address))
sock.connect(server_address)

file_count = 0
try:
    amount_received = 0
    amount_expected = 6000
    while amount_received < amount_expected:
        data = sock.recv(5000)
        data_string = data.decode("utf-8")
        #print('received {!r}'.format(data))
        if data_string.find("Header") != -1:
            dataChunkSize = int(data_string[data_string.find("Header")+6:data_string.find("|")])
            print(dataChunkSize)

        try:
            out = json.loads(data_string[data_string.find("JSONSTART|")+10 : data_string.find("JSONEND")])
            print(out)
            file_count += 1
            json_data_folder = "XXXX"
            if os.path.exists(json_data_folder):
                json_data_folder = os.path.join(json_data_folder, str(file_count)+'.json')
                with open(json_data_folder, 'w') as outfile:
                    json.dump(out, outfile, sort_keys=True)
                    print("save")
        except ValueError as e:
            print(e)
            data_false = data
        amount_expected += len(data)

finally:
    print('socket closed')
    sock.close()

from PyQt5.QtCore import QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket

class Client(QDialog):
    def __init__(self):
        super().__init__()
        self.tcpSocket = QTcpSocket(self)
        self.blockSize = 0
        self.makeRequest()
        self.tcpSocket.waitForConnected(1000)
        # send any message you like it could come from a widget text.
        #self.tcpSocket.write(b'hello')

        self.tcpSocket.readyRead.connect(self.dealCommunication)
        self.tcpSocket.error.connect(self.displayError)

    def makeRequest(self):
        HOST = 'localhost'
        PORT = 3336
        self.tcpSocket.connectToHost(HOST, PORT, QIODevice.ReadWrite)

    def dealCommunication(self):
        print('Message Comming')
        #data = self.tcpSocket.readAll()
        instr = QDataStream(self.tcpSocket)
        instr.setVersion(QDataStream.Qt_5_0)
        if self.blockSize == 0:
            if self.tcpSocket.bytesAvailable() < 2:
                return
            self.blockSize = instr.readUInt16()
        if self.tcpSocket.bytesAvailable() < self.blockSize:
            return
        # Print response to terminal, we could use it anywhere else we wanted.
        print(str(instr.readString(), encoding='utf-8'))

    def displayError(self, socketError):
        if socketError == QAbstractSocket.RemoteHostClosedError:
            pass
        else:
            print(self, "The following error occurred: %s." % self.tcpSocket.errorString())

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    client = Client()
    sys.exit(client.exec_())

The QTcpSocket client should constantly receive the input.

Body:
You have to remove:

self.tcpSocket.waitForConnected (1000)

In Qt the waitForXXX(...) method is blocking.

What is blocking in Qt?
It is a task that does not allow the Qt eventloop to be executed, thus preventing asynchronous tasks from executing.

This interferes with the data reception tasks that is triggered by readyRead a signal that is an asynchronous element.

In conclusion, do not use the waitForXXX(...) functions if you are going to use the event loop.


问:
Can an iOS App's system settings be configured via Enterprise Distribution?
Apple's Enterprise Deployment Guide says that apps distributed internally to an organization can be accompanied by a "Configuration Profile" that changes certain system settings (like VPN or wifi preferences).  Can the same system be used to distribute custom settings (as defined in the system wide "settings" application) for the enterprise application itself?</p>

答:
I don't think so.

http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/Preferences/Preferences.html

After reading the documention it should be techically possible to implement but it looks like this feature is not available (yet).


问:
How to Color Code Gridview based on date values
I would like to allow my Gridview control to display various colours based on conditions. A person has a date for a medical. I want the gridview to show a green color when the day has arrived. I want the date to show red when one day has passed on from the due date and orange like 7 days before the medical date. I have only managed to fix it for the green color which shows the medical on the day but I am having difficulties for the other conditions.

This is what i currently have. The first part of the If Statement works when i change the row to green based on the due date and the current date that is equal but I do not know how to set the if statement for the other conditions mentioned above. Please assist

```<code> If e.Row.RowType = DataControlRowType.DataRow Then

            Dim row As DataRow = (CType(e.Row.DataItem, DataRowView)).Row
            Dim DueDate As DateTime = row.Field(Of DateTime)(7)

            If DueDate.Date = DateTime.Today Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Green
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Green
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Green
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Green
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Green
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Green
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Green
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Green
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Green
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Green
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Green
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Green
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            ElseIf Day(DateTime.Now) > 1 Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            End If

        End If

</code>```

答:
If you have to make the entire row to be colored the same, then cellwise coloring is not required. Please use.</p>

```<code>   e.Row.BackColor = System.Drawing.Color.Green;
   e.Row.ForeColor = System.Drawing.Color.White;
</code>```

Body:
I would like to allow my Gridview control to display various colours based on conditions. A person has a date for a medical. I want the gridview to show a green color when the day has arrived. I want the date to show red when one day has passed on from the due date and orange like 7 days before the medical date. I have only managed to fix it for the green color which shows the medical on the day but I am having difficulties for the other conditions.

This is what i currently have. The first part of the If Statement works when i change the row to green based on the due date and the current date that is equal but I do not know how to set the if statement for the other conditions mentioned above. Please assist

 If e.Row.RowType = DataControlRowType.DataRow Then

            Dim row As DataRow = (CType(e.Row.DataItem, DataRowView)).Row
            Dim DueDate As DateTime = row.Field(Of DateTime)(7)

            If DueDate.Date = DateTime.Today Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Green
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Green
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Green
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Green
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Green
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Green
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Green
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Green
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Green
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Green
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Green
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Green
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Green
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            ElseIf Day(DateTime.Now) > 1 Then

                e.Row.Cells(0).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(0).ForeColor = System.Drawing.Color.White

                e.Row.Cells(1).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(1).ForeColor = System.Drawing.Color.White

                e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(2).ForeColor = System.Drawing.Color.White

                e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(3).ForeColor = System.Drawing.Color.White

                e.Row.Cells(4).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(4).ForeColor = System.Drawing.Color.White

                e.Row.Cells(5).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(5).ForeColor = System.Drawing.Color.White

                e.Row.Cells(6).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(6).ForeColor = System.Drawing.Color.White

                e.Row.Cells(7).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(7).ForeColor = System.Drawing.Color.White

                e.Row.Cells(8).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(8).ForeColor = System.Drawing.Color.White

                e.Row.Cells(9).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(9).ForeColor = System.Drawing.Color.White

                e.Row.Cells(10).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(10).ForeColor = System.Drawing.Color.White

                e.Row.Cells(11).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(11).ForeColor = System.Drawing.Color.White

                e.Row.Cells(12).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(12).ForeColor = System.Drawing.Color.White

                e.Row.Cells(13).BackColor = System.Drawing.Color.Orange
                e.Row.Cells(13).ForeColor = System.Drawing.Color.White

            End If

        End If

Body:
If you have to make the entire row to be colored the same, then cellwise coloring is not required. Please use.

   e.Row.BackColor = System.Drawing.Color.Green;
   e.Row.ForeColor = System.Drawing.Color.White;


问:
Ionic 3 native plugin of sms not working on my device
I am using Ionic 3 and my device is 4.4.2 android.

Setup:

```<code>ionic cordova plugin add cordova-sms-plugin
npm install --save @ionic-native/sms@4
</code>```

I have add to app.module

import { SMS } from '@ionic-native/sms';

providers: [..., SMS]

home.ts

```<code>...
import { SMS } from '@ionic-native/sms';

...
constructor(..., private sms: SMS){}

sendSMS(){
this.sms.send('0030699999999', 'sos')
}
</code>```

home.html

```<code><button ion-button block (click)="sendSMS()" margin-top color="dark">SMS</button>
</code>```

I install the apk to my phone with below command:

```<code>ionic cordova run android
</code>```

When I am pressing the button, my app breaks and exit, without sending a message.

I tried to remove platform android and added again, but nothing.

答:
I had to put a send_sms permission in manifest file (android).
Check in my phone v 4.4.2.
I didn't check it in iPhone.  </p>

Body:
I am using Ionic 3 and my device is 4.4.2 android.

Setup:

ionic cordova plugin add cordova-sms-plugin
npm install --save @ionic-native/sms@4

I have add to app.module

import { SMS } from '@ionic-native/sms';

providers: [..., SMS]

home.ts

...
import { SMS } from '@ionic-native/sms';

...
constructor(..., private sms: SMS){}

sendSMS(){
this.sms.send('0030699999999', 'sos')
}

home.html

<button ion-button block (click)="sendSMS()" margin-top color="dark">SMS</button>

I install the apk to my phone with below command:

ionic cordova run android

When I am pressing the button, my app breaks and exit, without sending a message.

I tried to remove platform android and added again, but nothing.


问:
Unable to store hashed password in database in django
I am using custom user model by extending AbstractBaseUser . However inspite of calling set_password inside custom user manager I am unable to store hashed password in my postgres database.

I followed the solution given at the below link but it didn't work:-

Django: set_password isn't hashing passwords?

Folloing is my code for models and managers

models.py

```<code>from django.contrib.auth.models import PermissionsMixin
from django.contrib.gis.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import InterestedUserManager

# Create your models here.

class User(AbstractBaseUser, PermissionsMixin):

    date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=False, unique=True)
    phone_no = models.CharField(max_length=10, blank=False)
    address = models.CharField(max_length=100, blank=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = ('user')
        verbose_name_plural = ('users')

    def __str__(self):
        return "%s %s -- %s" % (self.first_name, self.last_name, self.address)
</code>```

managers.py

```<code>from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        print("User object is ",user)
        print("User password is ".user.password)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True')

        return self._create_user(email, password, **extra_fields)

</code>```

views.py

```<code>class RegisterUserSerializer(ListCreateAPIView):
    serializer_class = CreateUserSerializer
    queryset = User.objects.all()

    # override create method of ListCreateAPIView to include token
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })
</code>```

serializers.py

```<code>class UserSerializer(ModelSerializer):
    class Meta:
        model = User

        fields = ('first_name', 'last_name', 'email', 'password', 'phone_no', 'address')

</code>```

settings.py

```<code>...

"""
Django settings for djan project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'rest_framework',
    'knox',
    'rest_framework_gis',  # rest framework for GIS
    'server',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

ROOT_URLCONF = 'djan.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djan.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        #db credentials goes here
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'knox.auth.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'server.InterestedUser'

...
</code>```

For example if you run following command in shell.

```<code>User.objects.create( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )
</code>```

Then, password is getting stored as plain text in my postgres database.

答:
You can simply use:

```<code>User.objects.<b>create_user</b>( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )</code>```

create_user is a manager method, which is defined in your custom model manager class UserManager.

Body:
I am using custom user model by extending AbstractBaseUser . However inspite of calling set_password inside custom user manager I am unable to store hashed password in my postgres database.

I followed the solution given at the below link but it didn't work:-

Django: set_password isn't hashing passwords?

Folloing is my code for models and managers

models.py

from django.contrib.auth.models import PermissionsMixin
from django.contrib.gis.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import InterestedUserManager

# Create your models here.

class User(AbstractBaseUser, PermissionsMixin):

    date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=False, unique=True)
    phone_no = models.CharField(max_length=10, blank=False)
    address = models.CharField(max_length=100, blank=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = ('user')
        verbose_name_plural = ('users')

    def __str__(self):
        return "%s %s -- %s" % (self.first_name, self.last_name, self.address)

managers.py

from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        print("User object is ",user)
        print("User password is ".user.password)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True')

        return self._create_user(email, password, **extra_fields)

views.py

class RegisterUserSerializer(ListCreateAPIView):
    serializer_class = CreateUserSerializer
    queryset = User.objects.all()

    # override create method of ListCreateAPIView to include token
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

serializers.py

class UserSerializer(ModelSerializer):
    class Meta:
        model = User

        fields = ('first_name', 'last_name', 'email', 'password', 'phone_no', 'address')

settings.py

...

"""
Django settings for djan project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'rest_framework',
    'knox',
    'rest_framework_gis',  # rest framework for GIS
    'server',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

ROOT_URLCONF = 'djan.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djan.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        #db credentials goes here
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'knox.auth.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'server.InterestedUser'

...

For example if you run following command in shell.

User.objects.create( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )

Then, password is getting stored as plain text in my postgres database.

Body:
You can simply use:

User.objects.create_user( first_name="rre", last_name="rre", email="rre@test.com", address="some-address", password="test@123", phone_no="9944002255" )

create_user is a manager method, which is defined in your custom model manager class UserManager.


问:
Use data from a CSV file as values of a variable in a loop in Bash
I have the need to create a loop that collects data from a CSV file and use them as variables in an HTTP POST and I do not know how to do it, could any one help me with this problem?

The structure of the CSV:

```<code>name_active1, ip1, type1
name_active2, ip2, type2
name_active3, ip3, type3
...
</code>```

And the variables would be

```<code>  $ NAME = name_active1
  $ IP = ip1
  $ TYPE = type1
</code>```

And so on.

答:
```<code>#!/usr/bin/bash
while read -r line; do
    NAME=$(echo $line | awk -F ',' '{print $1}');
    IP=$(echo $line | awk -F ',' '{print $2}');
    TYPE=$(echo $line | awk -F ',' '{print $3}');
    echo "NAME=$NAME";
    echo "IP=$IP";
    echo "TYPE=$TYPE";
done < $1;
</code>```

Body:
I have the need to create a loop that collects data from a CSV file and use them as variables in an HTTP POST and I do not know how to do it, could any one help me with this problem?

The structure of the CSV:

name_active1, ip1, type1
name_active2, ip2, type2
name_active3, ip3, type3
...

And the variables would be

  $ NAME = name_active1
  $ IP = ip1
  $ TYPE = type1

And so on.


答:
You can try something like:</p>

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

while IFS=', ' read -r NAME IP TYPE
do
    #You can do your processing here, e.g.
    echo "name=$NAME ip=$IP type=$TYPE"
done < data.csv

exit 0
</code>```

Title: Use data from a CSV file as values of a variable in a loop in Bash

Body:
You can try something like:

#!/bin/bash

while IFS=', ' read -r NAME IP TYPE
do
    #You can do your processing here, e.g.
    echo "name=$NAME ip=$IP type=$TYPE"
done < data.csv

exit 0


问:
Is it possible to handle the Environmental Variables within the Batch Script?
I created a very simple batch file as a launcher for a python script, however it does not work fine depending on the "PATH" setup for the user (Python 2 x Python 3).
Since changing the PATH can bring issues with other Python 2 based applications , could I make any update in the .bat to make a temporary change in the PATH while the Py script is running?

The idea is to use the batch to have the minimum interference from the user in the system setup (preferable a double click only).
In case of yes, what could I do?

```<code>@echo off
title ###Beta Script Launcher###
python myscript.py
pause
</code>```

答:
To make a temporary change to the path variable:

```<code>path c:\mydir;%path%
</code>```

the documentation

```<code>c:\srv> path /?
Displays or sets a search path for executable files.

PATH [[drive:]path[;...][;%PATH%]
PATH ;

Type PATH ; to clear all search-path settings and direct cmd.exe to search
only in the current directory.
Type PATH without parameters to display the current path.
Including %PATH% in the new path setting causes the old path to be
appended to the new setting.
</code>```

the normal way to do this for python, however, is to create a virtualenv (https://pypi.org/project/virtualenvwrapper-win/)

```<code>mkvirtualenv myenv
.. install everything in this environment ..
</code>```

and then use it in your start script

```<code>@echo off
title ###Beta Script Launcher###
call workon myenv
python myscript.py
pause
</code>```

(disclaimer, I'm one of the maintainers of virtualenvwrapper-win)

Body:
I created a very simple batch file as a launcher for a python script, however it does not work fine depending on the "PATH" setup for the user (Python 2 x Python 3).
Since changing the PATH can bring issues with other Python 2 based applications , could I make any update in the .bat to make a temporary change in the PATH while the Py script is running?

The idea is to use the batch to have the minimum interference from the user in the system setup (preferable a double click only).
In case of yes, what could I do?

@echo off
title ###Beta Script Launcher###
python myscript.py
pause

Body:
To make a temporary change to the path variable:

path c:\mydir;%path%

the documentation

c:\srv> path /?
Displays or sets a search path for executable files.

PATH [[drive:]path[;...][;%PATH%]
PATH ;

Type PATH ; to clear all search-path settings and direct cmd.exe to search
only in the current directory.
Type PATH without parameters to display the current path.
Including %PATH% in the new path setting causes the old path to be
appended to the new setting.

the normal way to do this for python, however, is to create a virtualenv (https://pypi.org/project/virtualenvwrapper-win/)

mkvirtualenv myenv
.. install everything in this environment ..

and then use it in your start script

@echo off
title ###Beta Script Launcher###
call workon myenv
python myscript.py
pause

(disclaimer, I'm one of the maintainers of virtualenvwrapper-win)


问:
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

```<code>bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}
</code>```

答:
When you split a large unit (long string) into a group of sub-units (smaller strings), each of the sub-units (smaller strings) is referred to as a "token".  If there are no more sub-units, then you are done parsing.

How do I tokenize a string in C++?

Body:
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}


问:
How to find out when, where, how an eventListener is added and removed in Chrome dev tools
I have an  tag that in some point in my JS application gets a click eventListener. And unexpectedly gets a second click event listener further in time. I expect the first one to be removed first, before it is added again.

How can i use the chrome dev tools to determine when an event listener is added, removed, and which code caused it, including a call stack?

I tried console logging stuff but i still cannot see the cause.

The adding and removing of listeners is done in such functions

```<code>class SomeClass {
    /**
     * Enables listeners so that clicking on the navigatableElement can work.
     */
    enableListeners() {
        this.disableListeners();
        this._navigatableElement.addEventListener('click', this._clickEventHandler.bind(this));
    }

    /**
     * Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
     */
    disableListeners() {
        this._navigatableElement.removeEventListener('click', this._clickEventHandler.bind(this));
    }
}
</code>```

答:
One possible method that can be used for debugging (but not in production code) is to write to Element.prototype.addEventListener, allowing you to log and console.trace whenever it's called:

const { addEventListener, removeEventListener } = EventTarget.prototype;
Element.prototype.addEventListener = function(...args) {
  console.log('Adding event listener!', this, args);
  console.trace();
  // debugger
  return addEventListener.apply(this, args);
};
Element.prototype.removeEventListener = function(...args) {
  console.log('Removing event listener!', this, args);
  console.trace();
  // debugger
  return removeEventListener.apply(this, args);
};

console.log('real script start');
const fn = () => console.log('fn');
foo.addEventListener('click', fn);
console.log('listener added.');
foo.removeEventListener('click', fn);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo">
</div></code>```

Your particular code is not working because every time you .bind, you're creating a new function. You can use the common React pattern of binding in the constructor, that way every reference to this._clickEventHandler will be to the same function. (removeEventListener needs to be called with the exact same function reference addEventListener was called with to work.)

```<code>class SomeClass {
  constructor() {
    this._clickEventHandler = this._clickEventHandler.bind(this);
  }
    /**
     * Enables listeners so that clicking on the navigatableElement can work.
     */
    enableListeners() {
        this.disableListeners();
        this._navigatableElement.addEventListener('click', this._clickEventHandler);
    }

    /**
     * Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
     */
    disableListeners() {
        this._navigatableElement.removeEventListener('click', this._clickEventHandler);
    }
}
</code>```

Body:
I have an  tag that in some point in my JS application gets a click eventListener. And unexpectedly gets a second click event listener further in time. I expect the first one to be removed first, before it is added again.

How can i use the chrome dev tools to determine when an event listener is added, removed, and which code caused it, including a call stack?

I tried console logging stuff but i still cannot see the cause.

The adding and removing of listeners is done in such functions

class SomeClass {
    /**
     * Enables listeners so that clicking on the navigatableElement can work.
     */
    enableListeners() {
        this.disableListeners();
        this._navigatableElement.addEventListener('click', this._clickEventHandler.bind(this));
    }

    /**
     * Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
     */
    disableListeners() {
        this._navigatableElement.removeEventListener('click', this._clickEventHandler.bind(this));
    }
}

Body:
One possible method that can be used for debugging (but not in production code) is to write to Element.prototype.addEventListener, allowing you to log and console.trace whenever it's called:

const { addEventListener, removeEventListener } = EventTarget.prototype;
Element.prototype.addEventListener = function(...args) {
  console.log('Adding event listener!', this, args);
  console.trace();
  // debugger
  return addEventListener.apply(this, args);
};
Element.prototype.removeEventListener = function(...args) {
  console.log('Removing event listener!', this, args);
  console.trace();
  // debugger
  return removeEventListener.apply(this, args);
};

console.log('real script start');
const fn = () => console.log('fn');
foo.addEventListener('click', fn);
console.log('listener added.');
foo.removeEventListener('click', fn);

<div id="foo">
</div>

Your particular code is not working because every time you .bind, you're creating a new function. You can use the common React pattern of binding in the constructor, that way every reference to this._clickEventHandler will be to the same function. (removeEventListener needs to be called with the exact same function reference addEventListener was called with to work.)

class SomeClass {
  constructor() {
    this._clickEventHandler = this._clickEventHandler.bind(this);
  }
    /**
     * Enables listeners so that clicking on the navigatableElement can work.
     */
    enableListeners() {
        this.disableListeners();
        this._navigatableElement.addEventListener('click', this._clickEventHandler);
    }

    /**
     * Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
     */
    disableListeners() {
        this._navigatableElement.removeEventListener('click', this._clickEventHandler);
    }
}


问:
How to make sure that the character length/set length in a field is set to a particular number when using php?
I have a form field which requires only numbers to be filled and the user should enter 8 digits in order to submit the form. What is the command that I need to use when writing my php/html code?

Tried using max but that also means I can enter 0 and still submit the form. Any thoughts on how to set a length so that you are forced to enter those number digits?

```<code><label>Line Number</label>
 <input type="number" name="Line" class="form-control" max="999" placeholder="Enter Line Number" value="<?php echo $Line; ?>" />
</code>```

I expect the answer to have 3 digits entered. Nothing less and nothing more. So can be 000 to 999. So even if you want to say 0 you need to enter 000 to submit the form.

if(empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} else {
    $Line = clean_text($_POST["Line"]);
}
```

答:
You can use the included filter functions.

Like this:

if(
    // check if `line` input is submitted
    filter_has_var(INPUT_POST, 'line') &&

    // checks and converts to INT, returns false if not in an int format
    filter_input(INPUT_POST, 'line', FILTER_VALIDATE_INT) &&

    // checks if the submitted int has a length of 8 - without entered whitespaces
    8 === strlen(trim(filter_input(INPUT_POST, 'line', FILTER_VALIDATE_INT)))
) {
    // do something
}
```

Body:
I have a form field which requires only numbers to be filled and the user should enter 8 digits in order to submit the form. What is the command that I need to use when writing my php/html code?

Tried using max but that also means I can enter 0 and still submit the form. Any thoughts on how to set a length so that you are forced to enter those number digits?

Line Number
 <input type="number" name="Line" class="form-control" max="999" placeholder="Enter Line Number" value="<?php echo $Line; ?>" />

I expect the answer to have 3 digits entered. Nothing less and nothing more. So can be 000 to 999. So even if you want to say 0 you need to enter 000 to submit the form.

if(empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} else {
    $Line = clean_text($_POST["Line"]);
}