问:
File Stream from 3 servers
I'm creating a manager gui to select a music or movie file from server. This selected file will be downloaded from this server to my client folder. How can I make it with 3 servers working together with sharing chunks on themselves?

I am doing this using C# Winforms on Visual Studio. I have implement it with 1 server and it is working. But when I try to connect 2nd or 3nd server on different port, client program freezes and no byte transfers. I have tried multithreading but couldn't connect on multiple servers, again.

Client

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CiDoMa
{
    public partial class Form1 : Form
    {
        string fileName, fileInitName;

        public Form1()
        {
            InitializeComponent();
        }

        private void Music_button_Click(object sender, EventArgs e)
        {

            fileInitName = fileName_textbox.Text;

            if (fileInitName.Contains(".mp3"))
            {
                fileName = "Music/" + fileInitName;
            }

            else if (fileInitName.Contains(".mp4"))
            {
                fileName = "Movie/" + fileInitName;
            }
            progressBar1.Value = 0;
            IPEndPoint ipep1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            IPEndPoint ipep2 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
            IPEndPoint ipep3 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9070);

            Socket server0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            server0.Connect(ipep1);
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(fileName);
            server0.Send(data, data.Length, SocketFlags.None);

            using (FileStream to = new FileStream("../../" + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    byte[] buffer = new byte[1024];
                    int rcv = 1;
                    while (rcv!=0)
                    {
                        rcv = server0.Receive(buffer, 1024, SocketFlags.None);
                        to.Write(buffer, 0, buffer.Length);
                    }
                    progressBar1.Value += 100;
                }

            server0.Shutdown(SocketShutdown.Both);
            server0.Close();
        }
    }
}
```

<p>Server</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace CiDoMaServer
{
    public partial class Form1 : Form
    {
        string fileName = "";
        IPEndPoint ipep, ipep2, ipep3;
        int rcv;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Server_init_Click(object sender, EventArgs e)
        {
            ipep = new IPEndPoint(IPAddress.Any,
                9050);
            ipep2 = new IPEndPoint(IPAddress.Any,
                9060);
            ipep3 = new IPEndPoint(IPAddress.Any,
                9070);
            IPEndPoint[] ipPoints = new IPEndPoint[3] { ipep, ipep2, ipep3 };

            Socket[] scon = new Socket[3];
            Socket[] server = new Socket[3];

            for (int i = 0; i < scon.Length; i++)
            {
                scon[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                scon[i].Bind(ipPoints[i]);
                //scon[i].Listen(10);
                //server[i] = scon[i].Accept();
            }
            scon[0].Listen(10);
            server[0] = scon[0].Accept();
            byte[] data = new byte[1024];
            rcv = server[0].Receive(data, data.Length, SocketFlags.None);
            fileName = Encoding.ASCII.GetString(data);

            while (rcv != 0) {
            using (FileStream from = new FileStream("../../" + fileName, FileMode.Open, FileAccess.Read))
            {
                int readCount;
                byte[] buffer = new byte[1024];
                while ((readCount = from.Read(buffer, 0, 1024)) != 0)
                {
                    server[0].Send(buffer, 1024, SocketFlags.None);
                }
                }
            }
            server[0].Close();
            scon[0].Close();

            /*for(int i=0; i<scon.Length; i++) {
                server[i].Close();
                scon[i].Close();
            }*/
        }
    }
}
</code>```

答:
If you are creating a server to serve multi client as a same time, your server should support asynchronous and multi threading. And it not easy to handle multi thread thus I thought it is the reason why you failed with multi threading but you can try to make it better

About example you can take a look at this example source code

and asynchronous socket

Hope it helpful with you

Title: File Stream from 3 servers

Body:
I'm creating a manager gui to select a music or movie file from server. This selected file will be downloaded from this server to my client folder. How can I make it with 3 servers working together with sharing chunks on themselves?

I am doing this using C# Winforms on Visual Studio. I have implement it with 1 server and it is working. But when I try to connect 2nd or 3nd server on different port, client program freezes and no byte transfers. I have tried multithreading but couldn't connect on multiple servers, again.

Client

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CiDoMa
{
    public partial class Form1 : Form
    {
        string fileName, fileInitName;

        public Form1()
        {
            InitializeComponent();
        }

        private void Music_button_Click(object sender, EventArgs e)
        {

            fileInitName = fileName_textbox.Text;

            if (fileInitName.Contains(".mp3"))
            {
                fileName = "Music/" + fileInitName;
            }

            else if (fileInitName.Contains(".mp4"))
            {
                fileName = "Movie/" + fileInitName;
            }
            progressBar1.Value = 0;
            IPEndPoint ipep1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            IPEndPoint ipep2 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
            IPEndPoint ipep3 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9070);

            Socket server0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            server0.Connect(ipep1);
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(fileName);
            server0.Send(data, data.Length, SocketFlags.None);

            using (FileStream to = new FileStream("../../" + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    byte[] buffer = new byte[1024];
                    int rcv = 1;
                    while (rcv!=0)
                    {
                        rcv = server0.Receive(buffer, 1024, SocketFlags.None);
                        to.Write(buffer, 0, buffer.Length);
                    }
                    progressBar1.Value += 100;
                }

            server0.Shutdown(SocketShutdown.Both);
            server0.Close();
        }
    }
}

Server

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace CiDoMaServer
{
    public partial class Form1 : Form
    {
        string fileName = "";
        IPEndPoint ipep, ipep2, ipep3;
        int rcv;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Server_init_Click(object sender, EventArgs e)
        {
            ipep = new IPEndPoint(IPAddress.Any,
                9050);
            ipep2 = new IPEndPoint(IPAddress.Any,
                9060);
            ipep3 = new IPEndPoint(IPAddress.Any,
                9070);
            IPEndPoint[] ipPoints = new IPEndPoint[3] { ipep, ipep2, ipep3 };

            Socket[] scon = new Socket[3];
            Socket[] server = new Socket[3];

            for (int i = 0; i < scon.Length; i++)
            {
                scon[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                scon[i].Bind(ipPoints[i]);
                //scon[i].Listen(10);
                //server[i] = scon[i].Accept();
            }
            scon[0].Listen(10);
            server[0] = scon[0].Accept();
            byte[] data = new byte[1024];
            rcv = server[0].Receive(data, data.Length, SocketFlags.None);
            fileName = Encoding.ASCII.GetString(data);

            while (rcv != 0) {
            using (FileStream from = new FileStream("../../" + fileName, FileMode.Open, FileAccess.Read))
            {
                int readCount;
                byte[] buffer = new byte[1024];
                while ((readCount = from.Read(buffer, 0, 1024)) != 0)
                {
                    server[0].Send(buffer, 1024, SocketFlags.None);
                }
                }
            }
            server[0].Close();
            scon[0].Close();

            /*for(int i=0; i<scon.Length; i++) {
                server[i].Close();
                scon[i].Close();
            }*/
        }
    }
}


来源: stackexchange

问:
Solr - How to search in all fields without passing query field?
I have tried as below,

```<code><field name="collector" type="text_general" indexed="true" stored="false"  multiValued="true" />
</code>```

and copy all my fields to copyField as below,

```<code><copyField source="fullname" dest="collector"/>
<copyField source="email" dest="collector"/>
<copyField source="city" dest="collector"/>
</code>```

and also I have put all copyField tags below

```<code><fields>

</fields>
</code>```

tags. But I cant search in all fields. I have to pass fullname before query like,

```<code>q=fullname:Mayur
</code>```

I want search by,

```<code>q=Mayur
</code>```

And I should search all fields contains Mayur word.

Help me please

答:
This has been deprecated in solr 7:
https://lucene.apache.org/solr/guide/7_0/major-changes-in-solr-7.html
It's recommended to use df parameter.

ContentLicense: CC BY-SA 3.0

Body:
I have tried as below,

<field name="collector" type="text_general" indexed="true" stored="false"  multiValued="true" />

and copy all my fields to copyField as below,

<copyField source="fullname" dest="collector"/>
<copyField source="email" dest="collector"/>
<copyField source="city" dest="collector"/>

and also I have put all copyField tags below

<fields>

</fields>

tags. But I cant search in all fields. I have to pass fullname before query like,

q=fullname:Mayur

I want search by,

q=Mayur

And I should search all fields contains Mayur word.

Help me please

ContentLicense: CC BY-SA 4.0


问:
I have .aar file inside library module, how to use it in app module?
I have .aar file inside library module, how to use it in app module, although I added this line inside the app gradle, please help me.</p>

```<code>implementation project(":my_library")
</code>```

答:
Instead of implementation, use api

```<code>api project(":my_library")
</code>```

Using api allows the sub-modules to be accessible along with the library, whereas using implementation won't allow that.

Body:
I have .aar file inside library module, how to use it in app module, although I added this line inside the app gradle, please help me.

implementation project(":my_library")

Body:
Instead of implementation, use api

api project(":my_library")

Using api allows the sub-modules to be accessible along with the library, whereas using implementation won't allow that.


答:
Implement that .aar file into app Module, This is the only way. Otherwise you can't access the file into .aar file from app module. </p>

```<code>implementation(name: 'your aar file name', ext: 'aar')
</code>```

Title: I have .aar file inside library module, how to use it in app module?

Body:
Implement that .aar file into app Module, This is the only way. Otherwise you can't access the file into .aar file from app module.

implementation(name: 'your aar file name', ext: 'aar')


问:
How do I open a doc or pdf file from php if i have the url using word?
I have a php application with a link that points to .doc and pdf files within my computer. I want to click the links and then open the file with office word or pdf reader.</p>

```<code>echo "<a href=\"temp\/es\/doc1.pdf\">Open</a>";
</code>```

答:
Welcome on Stackoverflow, what u're asking it's not php-related for what i can understand. Your link is build correctly (as long as the path actually exist).

The expected output you're asking it's all about you operating system preferences. For example if you are using Google Chrome you can expect the pdf file to be opened directly inside the browser.

Body:
I have a php application with a link that points to .doc and pdf files within my computer. I want to click the links and then open the file with office word or pdf reader.

echo "Open";


问:
How are all the events listeners in JavaScript kept active or alive?
I always wondered how an event handler in JavaScript was always listening for subsequent actions to trigger the event again and again even after the JavaScript code you write has been parsed.
I've tried to research online but I've not found any resources that explains how the events listeners are kept active or alive.

I understand how the call stack works but I just want to know how all the event listeners are kept alive or active.

For example addEventListener with a "click" event will always run the specified callback if the button is clicked. So how is the callback added by the addEventListener method always kept alive or active?

答: JS Engine keeps in memory all the handlers, attached to  specific events, and it becomes a JS engine to know what event have happened and what handler was attached to that event... Hopeful this will help</p>


问:
TS: how to transform Object.assign in ts file?
I have some Object.assign usage in my ts files, and I am using ts-loader to handle ts files, however, I still find there are Object.assign in output js files. I have added transform-object-assign in my .babelrc file, and I find normal js files are all transformed, only ts files not. So is there any method to transform it in ts files ?

答:
Object.assign is ES6 feature

it should be done only with change ts target version in tsconfig

```<code>{
    "compilerOptions": {
        "target": "es5",
    }
}
</code>```

Body:
Object.assign is ES6 feature

it should be done only with change ts target version in tsconfig

{
    "compilerOptions": {
        "target": "es5",
    }
}


问:
How to create an SSIS package that will insert records into null cells
My team is working on a project to put together individual files for data entry analysts to work off of. The package I created will drop a file for each individual analyst. There's a "Template" that all of these files are based on. Each file has data validation drop down cells in excel that contain options that agents can choose from. A through T contain the data that is being dropped into the excel file from our SQL server, and U through W contain the columns with data validation that the agents will use to prefill.

My Issue:

Whenever I run the package, the data will only fill in on columns A through T where there is no data validation cells in U through W. SSIS sees A through T as NULL values due to the validation in U through W.

I have tried moving the data to it's own tab, and referencing it on another, but the referencing formulas do not update without manual intervention. Formulas are set to automatic by default, so that is not the issue. Aside from that, I'm not sure how to overwrite the null values in columns A through T.

Package

Output file:

答:
The excel connection manager doesn't allow you to overwrite data in excel. If there is data in the rows of the cells you are trying to write to, the data will be inserted below the last unpopulated row.

I suggest perhaps you use an excel library for much needed flexibility, it will take away all your frustrations. My favorite one to use is NPOI.

Regards,

Jesse Petronio


问:
How to check if element in list matches with another element in a list of strings?

Input lists

```<code>list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
</code>```

Output list

```<code>output=['Google','AU-KBC Research Centre']
</code>```

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

答:
Try this.</p>

```<code>list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
exclusion_list = [i.lower() for i in exclusion_list]
for i in list1:
    if not any(map(lambda x:x in i.lower(), exclusion_list)):
        print(i)
</code>```

Body:
Input lists

list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']

Output list

output=['Google','AU-KBC Research Centre']

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

Body:
Try this.

list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
exclusion_list = [i.lower() for i in exclusion_list]
for i in list1:
    if not any(map(lambda x:x in i.lower(), exclusion_list)):
        print(i)


问:
I need to have a page created by JS display some code from the parent window
I have a html page and I need to send data (text and id specifically) from some html paragraph to a child page, created in a js file using window.open("");.

I already tried moving the script from the js file into the script tags. I tried using .innerText and .innerHTML and both returned Untitled, the id field did not show up entirely.

function newWindow(){
    var nuovaFin = window.open("");
    var title = opener.document.getElementById("titleHere").innerHTML;
    var id = opener.document.getElementById("idHere").id;

    nuovaFin.document.write("<title> "+ title +" </title>
 "+ id +"
 ");

};
```

<pre class="lang-HTML prettyprint-override"><code>
        <p id="titleHere" >ProvaText</p>

        <p id="idHere" >saas</p>
        <input type="button" id="btnNew" onclick="newWindow();"> test </input>
</code>```

I want the var title to be shown as the title of the newly created page, as it should, following the document.write argument, but it displays "Untitled", and the id from the paragraph isn't displayed at all.

答:
When you call window.open you actually get back the reference to the new window. After that you can manipulate it in the way you need. For example below code can open new window and set title to it:

```<code>function newWindowWithTitle(title){
    var newWin = window.open("");
    newWin.document.title = title;
};

newWindowWithTitle('My title');
</code>```

Here is another, more complex example, where we can open the window and write to its document successfully:

```<code>function newWindowWithTitleAndText(title, text){
    var newWin = window.open("");
    newWin.document.title = title;
    const p = document.createElement('p');
    p.innerText = text;
    newWin.document.body.appendChild(p);
};

newWindowWithTitleAndText('My title', 'some text');
</code>```

Body:
I have a html page and I need to send data (text and id specifically) from some html paragraph to a child page, created in a js file using window.open("");.

I already tried moving the script from the js file into the script tags. I tried using .innerText and .innerHTML and both returned Untitled, the id field did not show up entirely.

function newWindow(){
    var nuovaFin = window.open("");
    var title = opener.document.getElementById("titleHere").innerHTML;
    var id = opener.document.getElementById("idHere").id;

    nuovaFin.document.write("<title> "+ title +" </title>
 "+ id +"
 ");

};

ProvaText

saas

        <input type="button" id="btnNew" onclick="newWindow();"> test </input>

I want the var title to be shown as the title of the newly created page, as it should, following the document.write argument, but it displays "Untitled", and the id from the paragraph isn't displayed at all.

Body:
When you call window.open you actually get back the reference to the new window. After that you can manipulate it in the way you need. For example below code can open new window and set title to it:

function newWindowWithTitle(title){
    var newWin = window.open("");
    newWin.document.title = title;
};

newWindowWithTitle('My title');

Here is another, more complex example, where we can open the window and write to its document successfully:

function newWindowWithTitleAndText(title, text){
    var newWin = window.open("");
    newWin.document.title = title;
    const p = document.createElement('p');
    p.innerText = text;
    newWin.document.body.appendChild(p);
};

newWindowWithTitleAndText('My title', 'some text');


问:
Nuxt + Vue + Vuetify: this.$vuetify.breakpoint incorrectly initialized as 'xs'
Using vuetify breakpoints to switch between mobile and desktop layouts for a website

My code is (shrinked(

```<code>        <v-layout wrap :column="mobile">
           .
           .
           components and stuff
           .
           .
        <v-layout>

        <script>
           .
           .
           computed: {
             mobile: function () {
               return ['xs', 'sm'].includes(this.$vuetify.breakpoint.name)
             }
           }
           .
           .
        </script>
</code>```

So Im using a computed function to determine if the client has a small screen

My problem is that the this.$vuetify.breakpoint.name is initially set as xs

My workaround currently is having a loaded method and on the top level doing

```<code><v-app v-if="loaded"
  .
  .
    <v-layout>
      .
    </v-layout>
  .
  .
<v-app>
</code>```

But now I also have to wrap the entire thing with <NoSsr>

Is there a more correct way to load the components correctly so that they dont jump from mobie version to full size version after the page fully loads?

答:
Generic workaround suggested here is using mounted() hook to set up some form of flag that'll be checked inside computed:

    data: () => ({
      //  ...
      isMounted: false
    }),
    mounted() {
      this.isMounted = true;
    },
    // ...
    computed: {
      mobile: function () {
          return this.isMounted && ['xs', 'sm'].includes(this.$vuetify.breakpoint.name);
      }
    }
```

Alternatively, you can use any other means in your disposal to set up this flag of mobile detection as early as possible.

Body:
Using vuetify breakpoints to switch between mobile and desktop layouts for a website

My code is (shrinked(

        <v-layout wrap :column="mobile">
           .
           .
           components and stuff
           .
           .
        <v-layout>

So Im using a computed function to determine if the client has a small screen

My problem is that the this.$vuetify.breakpoint.name is initially set as xs

My workaround currently is having a loaded method and on the top level doing

<v-app v-if="loaded"
  .
  .
    <v-layout>
      .
    </v-layout>
  .
  .
<v-app>

But now I also have to wrap the entire thing with <NoSsr>

Is there a more correct way to load the components correctly so that they dont jump from mobie version to full size version after the page fully loads?

Body:
Generic workaround suggested here is using mounted() hook to set up some form of flag that'll be checked inside computed:

    data: () => ({
      //  ...
      isMounted: false
    }),
    mounted() {
      this.isMounted = true;
    },
    // ...
    computed: {
      mobile: function () {
          return this.isMounted && ['xs', 'sm'].includes(this.$vuetify.breakpoint.name);
      }
    }

Alternatively, you can use any other means in your disposal to set up this flag of mobile detection as early as possible.


问:
Extracing elements from a nested list based on elements of another nested list
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

```<code>users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

</code>```

答:
You would like first to create a dictionary of users, and then you can use nested list comprehension to match them in a single code line

dict_users = {x[0]: x[1] for x in users}
prod = [[x[0], [dict_users[y] for y in x[1]]] for x in prod]
```

<p>As you can see, you are iterating over each element in prod</p>

<pre class="lang-py prettyprint-override"><code>[_ for x in prod]
</code>```

With a list that match the elements of dict_users for each element in the list

[x[0], [dict_users[y] for y in x[1]]]
```

Body:
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

Body:
You would like first to create a dictionary of users, and then you can use nested list comprehension to match them in a single code line

dict_users = {x[0]: x[1] for x in users}
prod = [[x[0], [dict_users[y] for y in x[1]]] for x in prod]

As you can see, you are iterating over each element in prod

[_ for x in prod]

With a list that match the elements of dict_users for each element in the list

[x[0], [dict_users[y] for y in x[1]]]


问:
Reverse word of full sentence
I want to print string in reverse format:

Input:  My name is Archit Patel

Output: Patel Archit is name My.

I've tied the following but it displays as letaP tihcrA si eman ym.

```<code>public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}
</code>```

答:
Try this without in-built functions

```<code>public string ReverseFullSentence(string inputString)
        {
            string output = string.Empty;
            string[] splitStrings = inputString.Split(' ');
            for (int i = splitStrings.Length-1; i > -1 ; i--)
            {
                output = output + splitStrings[i]+ " ";
            }
                return output;
        }
</code>```

Title: Reverse word of full sentence

Body:
I want to print string in reverse format:

Input:  My name is Archit Patel

Output: Patel Archit is name My.

I've tied the following but it displays as letaP tihcrA si eman ym.

public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

Body:
Try this without in-built functions

public string ReverseFullSentence(string inputString)
        {
            string output = string.Empty;
            string[] splitStrings = inputString.Split(' ');
            for (int i = splitStrings.Length-1; i > -1 ; i--)
            {
                output = output + splitStrings[i]+ " ";
            }
                return output;
        }


问:
Microphone function in python doesnot stop listening
I am making a chatbot in python 3. I used the function Microphone to record my voice. If i plugin my earphone then it works perfectly. But without earphone if i say something, it takes the input (listens to me) but doesnot stop listening till i plugin my earphone and say something. Why does not it stop listening to me without earphone?
Here is my code snippet-

```<code>r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening....")
    r.pause_threshold = 1
    audio = r.listen(source)
</code>```

I want the chatbot to stop listening and start executing within 1 second gap when i have not connected earphone.

答:
If the prompt never returns, your microphone is most likely picking up too much ambient noise. To handle ambient noise, you’ll need to use the adjust_for_ambient_noise() method of the Recognizer class.

```<code>r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening....")
    r.adjust_for_ambient_noise(source) # This filters noise
    r.pause_threshold = 1
    audio = r.listen(source)
</code>```

I researched for hours and found the solution for my question.

Body:
I am making a chatbot in python 3. I used the function Microphone to record my voice. If i plugin my earphone then it works perfectly. But without earphone if i say something, it takes the input (listens to me) but doesnot stop listening till i plugin my earphone and say something. Why does not it stop listening to me without earphone?
Here is my code snippet-

r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening....")
    r.pause_threshold = 1
    audio = r.listen(source)

I want the chatbot to stop listening and start executing within 1 second gap when i have not connected earphone.

Body:
If the prompt never returns, your microphone is most likely picking up too much ambient noise. To handle ambient noise, you’ll need to use the adjust_for_ambient_noise() method of the Recognizer class.

r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening....")
    r.adjust_for_ambient_noise(source) # This filters noise
    r.pause_threshold = 1
    audio = r.listen(source)

I researched for hours and found the solution for my question.


问:
Bad notification for start Foreground, Invalid channel for service notification:
So, i have an app on store with 50000 users. Recently i updated my android studio and compiled SDK to 27. I made some changes to support android 8 changes including Notification changes(e.g. Notification should have unique channel). Tested this on Android One phone(Running android 8). And everything went smooth.
After updating the app on playstore i see these crashes on android 8 devices(mostly Google Pixel phones)

```<code>Fatal Exception: android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=-2 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0xffffcf00 actions=3 vis=PRIVATE)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:164)
   at android.app.ActivityThread.main(ActivityThread.java:6494)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

I see 7 of these Errors on Crashlytics. Each has same logs and there are about 5000+ crashes for around 10 users. So, apprently app was crashing on loop.

The problem i am having is these logs don't provide any log from where i can see the source in my app that is initiating this crash.
Is there any way i can find out which class is throwing this crash? Any help?

Also i have this code for notifications:

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, name, importance);
                mChannel.setDescription(description);
                notificationManager.createNotificationChannel(mChannel);
            }
        }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,id);
            builder.setContentTitle(pushMessages.size() + context.getString(R.string.new_notification))
                    .setContentIntent(pendingIntent)
                    .setContentText(pushMessages.get(0))
                    .setStyle(inboxStyle)
                    .setGroup(GROUP_KEY_NOTIFICATIONS)
                    .setGroupSummary(true)
                    .setAutoCancel(true);

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder.setSmallIcon(R.drawable.notification_img)
                        .setColor(context.getResources().getColor(R.color.settings_yellow));

            } else {
                builder.setSmallIcon(R.mipmap.ic_launcher);
            }
            summaryNotification = builder.build();
notificationManager.notify(i, summaryNotification);
</code>```

答:
it appears that you in 8.1 must create your own notification channel.

```<code> private void startForeground() {
    String channelId ="";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel("my_service", "My Background Service");
    }else{
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(101, notification);
    }

}
</code>```

and after

```<code> @RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(String channelId ,String channelName){
    NotificationChannel chan = new NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.createNotificationChannel(chan);
    return channelId;
}
</code>```

Update: Also don't forget to add the foreground permission as required Android P:

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

Body:
So, i have an app on store with 50000 users. Recently i updated my android studio and compiled SDK to 27. I made some changes to support android 8 changes including Notification changes(e.g. Notification should have unique channel). Tested this on Android One phone(Running android 8). And everything went smooth.
After updating the app on playstore i see these crashes on android 8 devices(mostly Google Pixel phones)

Fatal Exception: android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=-2 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0xffffcf00 actions=3 vis=PRIVATE)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:164)
   at android.app.ActivityThread.main(ActivityThread.java:6494)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I see 7 of these Errors on Crashlytics. Each has same logs and there are about 5000+ crashes for around 10 users. So, apprently app was crashing on loop.

The problem i am having is these logs don't provide any log from where i can see the source in my app that is initiating this crash.
Is there any way i can find out which class is throwing this crash? Any help?

Also i have this code for notifications:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, name, importance);
                mChannel.setDescription(description);
                notificationManager.createNotificationChannel(mChannel);
            }
        }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,id);
            builder.setContentTitle(pushMessages.size() + context.getString(R.string.new_notification))
                    .setContentIntent(pendingIntent)
                    .setContentText(pushMessages.get(0))
                    .setStyle(inboxStyle)
                    .setGroup(GROUP_KEY_NOTIFICATIONS)
                    .setGroupSummary(true)
                    .setAutoCancel(true);

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder.setSmallIcon(R.drawable.notification_img)
                        .setColor(context.getResources().getColor(R.color.settings_yellow));

            } else {
                builder.setSmallIcon(R.mipmap.ic_launcher);
            }
            summaryNotification = builder.build();
notificationManager.notify(i, summaryNotification);

Body:
it appears that you in 8.1 must create your own notification channel.

 private void startForeground() {
    String channelId ="";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel("my_service", "My Background Service");
    }else{
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(101, notification);
    }

}

and after

 @RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(String channelId ,String channelName){
    NotificationChannel chan = new NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.createNotificationChannel(chan);
    return channelId;
}

Update: Also don't forget to add the foreground permission as required Android P:

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


问:
Conditional "Browsable" Attribute

Is there a way to make a "Browsable" attribute conditional, so the property that applies it will sometimes appear in the properties page and sometimes not?

thanks :)

答:
John Cummings's solution basically worked for me but had the following two problems due to his introduction of the Generics (which was quite smart though):

1- the version SetBrowsableProperty<T>(T obj, string strPropertyName, bool bIsBrowsable) will fail when a collection is passed as the parameter obj because T, in that case, will be an implementation of IEnumerable (e.g. List, Array etc.) and not the type of the collection that was actually intended.

2- It allows passing in the primitive types as well, which is pointless in this case and will nearly always fail.

Complete revised solution:

So here is the revised solution that tackles these problems and has worked for me:
(I've slightly renamed the methods and the variables)

First of all, the actual method that does the main job of changing the Browsable attribute value:

```<code>/// <summary>
/// Sets the Browsable attribute value of a property of a non premitive type.
/// NOTE: The class property must be decorated with [Browsable(...)] attribute.
/// </summary>
/// <param name="type">The type that contains the property, of which the Browsable attribute value needs to be changed</param>
/// <param name="propertyName">Name of the type property, of which the Browsable attribute value needs to be changed</param>
/// <param name="isBrowsable">The new Browsable value</param>
public static void SetBrowsableAttributeOfAProperty(Type type, string propertyName, bool isBrowsable)
{
    //Validate type - disallow primitive types (this will eliminate problem-2 as mentioned above)
    if (type.IsEnum || BuiltInTypes.Contains(type))
        throw new Exception($"The type '{type.Name}' is not supported");

    var objPropertyInfo = TypeDescriptor.GetProperties(type);

    // Get the Descriptor's Properties
    PropertyDescriptor theDescriptor = objPropertyInfo[propertyName];

    if (theDescriptor == null)
        throw new Exception($"The property '{propertyName}' is not found in the Type '{type}'");

    // Get the Descriptor's "Browsable" Attribute
    BrowsableAttribute theDescriptorBrowsableAttribute = (BrowsableAttribute)theDescriptor.Attributes[typeof(BrowsableAttribute)];
    FieldInfo browsablility = theDescriptorBrowsableAttribute.GetType().GetField("Browsable", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);

    // Set the Descriptor's "Browsable" Attribute
    browsablility.SetValue(theDescriptorBrowsableAttribute, isBrowsable);
}
</code>```

Now the variant proposed in John Cummings's solution with <T>:

```<code>public static void SetBrowsableAttributeOfAProperty<T>(string propertyName, bool isBrowsable)
{
    SetBrowsableAttributeOfAProperty(typeof(T), propertyName, isBrowsable);
}
</code>```

Now the overload that had the problem no. 1, but the following modification handles it now:

```<code>/// <summary>
/// Sets the Browsable attribute value of a property of a non premitive type.
/// NOTE: The class property must be decorated with [Browsable(...)] attribute.
/// </summary>
/// <param name="obj">An instance of the type that contains the property, of which the Browsable attribute value needs to be changed.</param>
/// <param name="propertyName">Name of the type property, of which the Browsable attribute value needs to be changed</param>
/// <param name="isBrowsable">Browsable Value</param>
public static void SetBrowsableAttributeOfAProperty<T>(T obj, string propertyName, bool isBrowsable)
{
    if (typeof(T).GetInterface("IEnumerable") != null && typeof(T) != typeof(string))   //String type needs to be filtered out as String also implements IEnumerable<char> but its not a normal collection rather a primitive type
    {
        //Get the element type of the IEnumerable collection
        Type objType = obj.GetType().GetGenericArguments()?.FirstOrDefault();       //when T is a collection that implements IEnumerable except Array
        if (objType == null) objType = obj.GetType().GetElementType();              //when T is an Array

        SetBrowsableAttributeOfAProperty(objType, propertyName, isBrowsable);
    }
    else
        SetBrowsableAttributeOfAProperty(typeof(T), propertyName, isBrowsable);
</code>```

and here is a utility function to get all C# system built-in (primitive) types:

```<code>    public static List<Type> BuiltInTypes
        {
            get
            {
                if (builtInTypes == null)
                    builtInTypes = Enum.GetValues(typeof(TypeCode)).Cast<TypeCode>().Select(t => Type.GetType("System." + Enum.GetName(typeof(TypeCode), t)))
                                   .ToList();

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

Usage:

```<code> class Foo
{
    [Browsable(false)]
    public string Bar { get; set; }
}
void Example()
{
    SetBrowsableAttributeOfAProperty<Foo>("Bar", true);     //works

    Foo foo = new Foo();
    SetBrowsableAttributeOfAProperty(foo, "Bar", false);    //works

    List<Foo> foos = new List<Foo> { foo, new Foo { Bar = "item2" } };
    SetBrowsableAttributeOfAProperty(foos, "Bar", true);    //works now, whereas it would crash with an exception in John Cummings's solution
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Conditional "Browsable" Attribute

Body:
John Cummings's solution basically worked for me but had the following two problems due to his introduction of the Generics (which was quite smart though):

1- the version SetBrowsableProperty<T>(T obj, string strPropertyName, bool bIsBrowsable) will fail when a collection is passed as the parameter obj because T, in that case, will be an implementation of IEnumerable (e.g. List, Array etc.) and not the type of the collection that was actually intended.

2- It allows passing in the primitive types as well, which is pointless in this case and will nearly always fail.

Complete revised solution:

So here is the revised solution that tackles these problems and has worked for me:
(I've slightly renamed the methods and the variables)

First of all, the actual method that does the main job of changing the Browsable attribute value:

/// <summary>
/// Sets the Browsable attribute value of a property of a non premitive type.
/// NOTE: The class property must be decorated with [Browsable(...)] attribute.
/// </summary>
/// <param name="type">The type that contains the property, of which the Browsable attribute value needs to be changed</param>
/// <param name="propertyName">Name of the type property, of which the Browsable attribute value needs to be changed</param>
/// <param name="isBrowsable">The new Browsable value</param>
public static void SetBrowsableAttributeOfAProperty(Type type, string propertyName, bool isBrowsable)
{
    //Validate type - disallow primitive types (this will eliminate problem-2 as mentioned above)
    if (type.IsEnum || BuiltInTypes.Contains(type))
        throw new Exception($"The type '{type.Name}' is not supported");

    var objPropertyInfo = TypeDescriptor.GetProperties(type);

    // Get the Descriptor's Properties
    PropertyDescriptor theDescriptor = objPropertyInfo[propertyName];

    if (theDescriptor == null)
        throw new Exception($"The property '{propertyName}' is not found in the Type '{type}'");

    // Get the Descriptor's "Browsable" Attribute
    BrowsableAttribute theDescriptorBrowsableAttribute = (BrowsableAttribute)theDescriptor.Attributes[typeof(BrowsableAttribute)];
    FieldInfo browsablility = theDescriptorBrowsableAttribute.GetType().GetField("Browsable", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);

    // Set the Descriptor's "Browsable" Attribute
    browsablility.SetValue(theDescriptorBrowsableAttribute, isBrowsable);
}

Now the variant proposed in John Cummings's solution with <T>:

public static void SetBrowsableAttributeOfAProperty<T>(string propertyName, bool isBrowsable)
{
    SetBrowsableAttributeOfAProperty(typeof(T), propertyName, isBrowsable);
}

Now the overload that had the problem no. 1, but the following modification handles it now:

/// <summary>
/// Sets the Browsable attribute value of a property of a non premitive type.
/// NOTE: The class property must be decorated with [Browsable(...)] attribute.
/// </summary>
/// <param name="obj">An instance of the type that contains the property, of which the Browsable attribute value needs to be changed.</param>
/// <param name="propertyName">Name of the type property, of which the Browsable attribute value needs to be changed</param>
/// <param name="isBrowsable">Browsable Value</param>
public static void SetBrowsableAttributeOfAProperty<T>(T obj, string propertyName, bool isBrowsable)
{
    if (typeof(T).GetInterface("IEnumerable") != null && typeof(T) != typeof(string))   //String type needs to be filtered out as String also implements IEnumerable<char> but its not a normal collection rather a primitive type
    {
        //Get the element type of the IEnumerable collection
        Type objType = obj.GetType().GetGenericArguments()?.FirstOrDefault();       //when T is a collection that implements IEnumerable except Array
        if (objType == null) objType = obj.GetType().GetElementType();              //when T is an Array

        SetBrowsableAttributeOfAProperty(objType, propertyName, isBrowsable);
    }
    else
        SetBrowsableAttributeOfAProperty(typeof(T), propertyName, isBrowsable);

and here is a utility function to get all C# system built-in (primitive) types:

    public static List<Type> BuiltInTypes
        {
            get
            {
                if (builtInTypes == null)
                    builtInTypes = Enum.GetValues(typeof(TypeCode)).Cast<TypeCode>().Select(t => Type.GetType("System." + Enum.GetName(typeof(TypeCode), t)))
                                   .ToList();

                return builtInTypes;
            }
        }

Usage:

 class Foo
{
    [Browsable(false)]
    public string Bar { get; set; }
}
void Example()
{
    SetBrowsableAttributeOfAProperty<Foo>("Bar", true);     //works

    Foo foo = new Foo();
    SetBrowsableAttributeOfAProperty(foo, "Bar", false);    //works

    List<Foo> foos = new List<Foo> { foo, new Foo { Bar = "item2" } };
    SetBrowsableAttributeOfAProperty(foos, "Bar", true);    //works now, whereas it would crash with an exception in John Cummings's solution
}


问:
"Missing credentials" with PassportJS when I put enctype="multipart/form-data" and an input[type="file"]

THE PROBLEM

I've got a problem, when I use enctype="multipart/form-data" to my form (with an upload (.jpg/.png, etc.)) and I sumbit it, my flash displays "Missing credentials", without precisions. So how do I fix this ?

What I've tried

I searched solutions, but no one answered my problem. So I tried to resolve this, during 1-2 hours. I've found nothing. I asked too in another forum (alsacreations.com, if you know)

What I know, it is NOT a problem with my config/passport.js because otherwise, in my console, I would have logs.

Some code

```<code>[2] GET /api/auth/user 304 0.621 ms - -
[2] GET /api/auth/user 304 0.816 ms - -
[2] GET /favicon.ico 200 0.072 ms - 2780
[2] GET /assets/dist/app.js 304 1.433 ms - -
[2] GET /signup 304 2.842 ms - -
[2] POST /api/auth/user 200 5.250 ms - 2
[2] POST /signup 302 0.951 ms - 58
[2] GET /signup 200 3.036 ms - 3596
[2] GET /assets/styles/main-css.css 304 0.919 ms - -
[2] GET /assets/dist/main-js.js 304 2.542 ms - -
[2] GET /assets/dist/app.js 304 1.797 ms - -
[2] GET /assets/config/config-en.json 304 0.720 ms - -
[2] GET /assets/dist/manifest.json 304 0.584 ms - -
[2] GET /api/auth/user 200 0.529 ms - 5
[2] GET /api/auth/user 304 1.049 ms - -
[2] GET /assets/dist/app.js 304 0.994 ms - -
[2] GET /signup 200 4.576 ms - 3376
</code>```

As you see it there's no log...

Let's the demo!

https://forum.alsacreations.com/upload/1559134328-67719-alsa.png

I've a form (with enctype="multipart/form-data", etc.)

https://forum.alsacreations.com/upload/1559134431-67719-alsa.png

I upload my picture (as it happens an avatar)

https://forum.alsacreations.com/upload/1559134534-67719-alsa.png

BUT (else it'll be too easy...)
When I upload it, I've got this message ("Missing credentials"), is there any callback that I've not caught? (I wanna have more informations)

Thanks for your help.

(Sorry I can't place images, I'm under the 10 points of reputations, lol)

答:
Before you handle logic of upload image, have you checked user is logged in or not? By req.isAuthenticated() like this:</p>

```<code>app.get('/some_path', checkAuthentication, function(req,res) {
    // your logic upload files
});

function checkAuthentication(req,res,next) {
    if(req.isAuthenticated()) {
        //req.isAuthenticated() will return true if user is logged in
        next();
    } else{
        res.redirect("/login");
    }
}
</code>```

Body:
THE PROBLEM

I've got a problem, when I use enctype="multipart/form-data" to my form (with an upload (.jpg/.png, etc.)) and I sumbit it, my flash displays "Missing credentials", without precisions. So how do I fix this ?

What I've tried

I searched solutions, but no one answered my problem. So I tried to resolve this, during 1-2 hours. I've found nothing. I asked too in another forum (alsacreations.com, if you know)

What I know, it is NOT a problem with my config/passport.js because otherwise, in my console, I would have logs.

Some code

[2] GET /api/auth/user 304 0.621 ms - -
[2] GET /api/auth/user 304 0.816 ms - -
[2] GET /favicon.ico 200 0.072 ms - 2780
[2] GET /assets/dist/app.js 304 1.433 ms - -
[2] GET /signup 304 2.842 ms - -
[2] POST /api/auth/user 200 5.250 ms - 2
[2] POST /signup 302 0.951 ms - 58
[2] GET /signup 200 3.036 ms - 3596
[2] GET /assets/styles/main-css.css 304 0.919 ms - -
[2] GET /assets/dist/main-js.js 304 2.542 ms - -
[2] GET /assets/dist/app.js 304 1.797 ms - -
[2] GET /assets/config/config-en.json 304 0.720 ms - -
[2] GET /assets/dist/manifest.json 304 0.584 ms - -
[2] GET /api/auth/user 200 0.529 ms - 5
[2] GET /api/auth/user 304 1.049 ms - -
[2] GET /assets/dist/app.js 304 0.994 ms - -
[2] GET /signup 200 4.576 ms - 3376

As you see it there's no log...

Let's the demo!

https://forum.alsacreations.com/upload/1559134328-67719-alsa.png

I've a form (with enctype="multipart/form-data", etc.)

https://forum.alsacreations.com/upload/1559134431-67719-alsa.png

I upload my picture (as it happens an avatar)

https://forum.alsacreations.com/upload/1559134534-67719-alsa.png

BUT (else it'll be too easy...)
When I upload it, I've got this message ("Missing credentials"), is there any callback that I've not caught? (I wanna have more informations)

Thanks for your help.

(Sorry I can't place images, I'm under the 10 points of reputations, lol)

Body:
Before you handle logic of upload image, have you checked user is logged in or not? By req.isAuthenticated() like this:

app.get('/some_path', checkAuthentication, function(req,res) {
    // your logic upload files
});

function checkAuthentication(req,res,next) {
    if(req.isAuthenticated()) {
        //req.isAuthenticated() will return true if user is logged in
        next();
    } else{
        res.redirect("/login");
    }
}


问:
running node js app in background in ubuntu
I have a nodejs compiled application that I run from a terminal window on my ubuntu vps.Is there a way to run it in the background, meaning i can afford to close my terminal window and it still works. Note this exe prints the messages on the terminal window when its running

tried PM2, it errors out saying "awaiting restart"
tried nohup, it does not error out and shows process has started but exe does not what it shall do, meaning its not working.
if i do ./app , it works but then i can not close the terminal window.

答:
used tmux, loving it so far.
think might use PM2 with tmux where i can. </p>


问:
How can I optimize an animation in Processing, and keep it from leaving a trail of images?
I am creating a model of a solar system in processing, and after removing the background I noticed the planets were leaving a trail of their image behind them. The program runs fine when the background is back in, but I want to add a lot more and I am sure this is inefficient and will bog things down.

I am very new to processing, and I am really not sure how to solve this. Maybe delete previous images after a delay to create a shortened trail?

These are just the parts I think are important cherry picked from the code, this is just the example of one planet. Sorry if the code is clunky, any suggestions are happily accepted.

```<code>Planet p1;

void setup() {
 mercury = loadImage("mercury.png")

 p1 = new Planet(40, random(TWO_PI), 0.05);

}

void draw() {
  //background(0)
  translate(width / 2, height / 2);
  p1.display1();
  p1.orbit();
}

class Planet  {
  float radius;
  float angle;
  float distance;
  float orbitSpeed;

  Planet(float r, float d, float o) {
     radius = r;
     distance = d;
     orbitSpeed = o;
     angle = random(TWO_PI);
  }

  void orbit() {
    angle = angle + orbitSpeed;
  }

  void display1() {
    pushMatrix();
    rotate(angle);
    translate(distance, 0);
    imageMode(CENTER);
    image(mercury, radius, radius, 10, 10);
    popMatrix();
  }
}
</code>```

I realized that this would probably happen, and I am not sure how to stop it.

答:
Your code is simple enough that it doesn't need optimisations at this stage.
As micycle mentions, you are are drawing an image at a translated position, pretty similar to blitting.

In terms of the trails, one common trick you could use is not clear the screen completely, but draw a transparent rectangle as the background. The more transparency, the longer the trails.

Here's a tweaked version of your code:

```<code>// planet object
Planet p1;
// planet texture
PImage mercury;

void setup() {
  size(300, 300);
  // draw image from center
  imageMode(CENTER);
  // clear to black one
  background(0);
  // remove strokes (we'll use rect() later)
  noStroke();
  // set the fill to black but with 9/255 transparency (~3.5% transparent)
  fill(0,9);
  // init texture
  mercury = loadImage("mercury.png");
  // init planet
  p1 = new Planet(40, random(TWO_PI), 0.05);
}

void draw() {
  // draw a transparent rectangle instead of completely clearing the screen
  rect(0,0,width,height);
  // render planet
  translate(width / 2, height / 2);
  p1.display1();
  p1.orbit();
}

class Planet {
  float radius;
  float angle;
  float distance;
  float orbitSpeed;

  Planet(float r, float d, float o) {
    radius = r;
    distance = d;
    orbitSpeed = o;
    angle = random(TWO_PI);
  }

  void orbit() {
    angle = angle + orbitSpeed;
  }

  void display1() {
    pushMatrix();
    rotate(angle);
    translate(distance, 0);
    image(mercury, radius, radius, 10, 10);
    popMatrix();
  }
}
</code>```

It's an efficient quick'n'dirty hack as you won't need to store previous position and redraw multiple times, however it has it limitations in terms of the flexibility of the trails. Hopefully tweaking the fill() alpha parameter will get you the desired effect.

Later on if you're drawing many many many planets it things start running slow have a peak at VisualVM. Profile the CPU and see the methods that take the longest to complete and focus on those. Don't need to optimise everything, just the slowest calls. Remember that Processing have multiple renderers: JAVA2D is the default one, but there's also FX2D and P2D/P3D and they will behave differently. I strongly recommend optimising at the last moment (otherwise code might be less flexible and readable and will slow down development/iteration).

Body:
I am creating a model of a solar system in processing, and after removing the background I noticed the planets were leaving a trail of their image behind them. The program runs fine when the background is back in, but I want to add a lot more and I am sure this is inefficient and will bog things down.

I am very new to processing, and I am really not sure how to solve this. Maybe delete previous images after a delay to create a shortened trail?

These are just the parts I think are important cherry picked from the code, this is just the example of one planet. Sorry if the code is clunky, any suggestions are happily accepted.

Planet p1;

void setup() {
 mercury = loadImage("mercury.png")

 p1 = new Planet(40, random(TWO_PI), 0.05);

}

void draw() {
  //background(0)
  translate(width / 2, height / 2);
  p1.display1();
  p1.orbit();
}

class Planet  {
  float radius;
  float angle;
  float distance;
  float orbitSpeed;

  Planet(float r, float d, float o) {
     radius = r;
     distance = d;
     orbitSpeed = o;
     angle = random(TWO_PI);
  }

  void orbit() {
    angle = angle + orbitSpeed;
  }

  void display1() {
    pushMatrix();
    rotate(angle);
    translate(distance, 0);
    imageMode(CENTER);
    image(mercury, radius, radius, 10, 10);
    popMatrix();
  }
}

I realized that this would probably happen, and I am not sure how to stop it.

Body:
Your code is simple enough that it doesn't need optimisations at this stage.
As micycle mentions, you are are drawing an image at a translated position, pretty similar to blitting.

In terms of the trails, one common trick you could use is not clear the screen completely, but draw a transparent rectangle as the background. The more transparency, the longer the trails.

Here's a tweaked version of your code:

// planet object
Planet p1;
// planet texture
PImage mercury;

void setup() {
  size(300, 300);
  // draw image from center
  imageMode(CENTER);
  // clear to black one
  background(0);
  // remove strokes (we'll use rect() later)
  noStroke();
  // set the fill to black but with 9/255 transparency (~3.5% transparent)
  fill(0,9);
  // init texture
  mercury = loadImage("mercury.png");
  // init planet
  p1 = new Planet(40, random(TWO_PI), 0.05);
}

void draw() {
  // draw a transparent rectangle instead of completely clearing the screen
  rect(0,0,width,height);
  // render planet
  translate(width / 2, height / 2);
  p1.display1();
  p1.orbit();
}

class Planet {
  float radius;
  float angle;
  float distance;
  float orbitSpeed;

  Planet(float r, float d, float o) {
    radius = r;
    distance = d;
    orbitSpeed = o;
    angle = random(TWO_PI);
  }

  void orbit() {
    angle = angle + orbitSpeed;
  }

  void display1() {
    pushMatrix();
    rotate(angle);
    translate(distance, 0);
    image(mercury, radius, radius, 10, 10);
    popMatrix();
  }
}

It's an efficient quick'n'dirty hack as you won't need to store previous position and redraw multiple times, however it has it limitations in terms of the flexibility of the trails. Hopefully tweaking the fill() alpha parameter will get you the desired effect.

Later on if you're drawing many many many planets it things start running slow have a peak at VisualVM. Profile the CPU and see the methods that take the longest to complete and focus on those. Don't need to optimise everything, just the slowest calls. Remember that Processing have multiple renderers: JAVA2D is the default one, but there's also FX2D and P2D/P3D and they will behave differently. I strongly recommend optimising at the last moment (otherwise code might be less flexible and readable and will slow down development/iteration).


问:
Unable to Run any Gulp commands
I am relatively new to NodeJS and am learning to develop using Sharepoint Framework. It was working fine and all of a sudden started to throw errors.

My NodeJS version is:  V10.13.0.

My gulp version is:    CLI - 2.0.1 Local - 3.9.1

I get the following error when I try to use gulp serve or gulp bundle:

Error: Your dev environment is running NodeJS version v10.13.0 which
  does not meet the requirements for running this tool. This tool
  requires a version of NodeJS that matches >=8.9.4 <9.0.0.......

Could someone help me fix this issue please?

Many Thanks,

答:
Another solution for this is to install the Node version manager and then you can manage the version of node.js using it.

nvm-windows

Install the .exe file and then manage the node.js version.

node version manager command:

```<code>Usage:

  nvm install <version>        : Install node.js specific version
  nvm list                     : List the node.js installations.
  nvm use [version]            : Switch to specific node.js version
  .....
  ...
</code>```

Title: Unable to Run any Gulp commands

Body:
Another solution for this is to install the Node version manager and then you can manage the version of node.js using it.

nvm-windows

Install the .exe file and then manage the node.js version.

node version manager command:

Usage:

  nvm install <version>        : Install node.js specific version
  nvm list                     : List the node.js installations.
  nvm use [version]            : Switch to specific node.js version
  .....
  ...


问:
How do you handle CORS in an electron app?
I'm building an electron app and need to call APIs where the API provider has not enabled CORS.  The typically proposed solution is to use a reverse proxy which is trivial to do when running locally by using node and cors-anywhere like this:

```<code>let port = (process.argv.length > 2) ? parseInt (process.argv[2]) : 8080;
require ('cors-anywhere').createServer ().listen (port, 'localhost');
</code>```

The app can then be configured to proxy all requests through the reverse proxy on localhost:8080.

So, my questions are:

Is it possible to use node and cors-anywhere in an electron app to create a reverse proxy?  I don't want to force the app to make calls to a remote server.

Is there a better or standard way of doing this in an Electron app? I'm assuming I'm not the first to run into CORS issues. :)

答:
Just overide header before send request using webRequest.onBeforeSendHeaders

const filter = {
  urls: ['*://*.google.com/*']
};
const session = electron.remote.session
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    details.requestHeaders['Origin'] = null;
    details.headers['Origin'] = null;
    callback({ requestHeaders: details.requestHeaders })
});```

put these codes in renderer process

Body:
I'm building an electron app and need to call APIs where the API provider has not enabled CORS.  The typically proposed solution is to use a reverse proxy which is trivial to do when running locally by using node and cors-anywhere like this:

let port = (process.argv.length > 2) ? parseInt (process.argv[2]) : 8080;
require ('cors-anywhere').createServer ().listen (port, 'localhost');

The app can then be configured to proxy all requests through the reverse proxy on localhost:8080.

So, my questions are:

Is it possible to use node and cors-anywhere in an electron app to create a reverse proxy?  I don't want to force the app to make calls to a remote server.

Is there a better or standard way of doing this in an Electron app? I'm assuming I'm not the first to run into CORS issues. :)

Body:
Just overide header before send request using webRequest.onBeforeSendHeaders

const filter = {
  urls: ['*://*.google.com/*']
};
const session = electron.remote.session
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    details.requestHeaders['Origin'] = null;
    details.headers['Origin'] = null;
    callback({ requestHeaders: details.requestHeaders })
});

put these codes in renderer process


问:
2x one-to-many relationships in OO
Imagine these relationships:

1 A has many B's

1 B has many C's...

In reverse:

C has 1 B

B has 1A

By transitivity, C has 1 A

To model this relationship in DB, we have:

```<code>TableA
a_id

TableB
b_id
a_id (fk to TableA)

TableC
c_id
b_id (fk to TableB)
</code>```

To model this relationship in OO, we have:

```<code>objA
objB
objC
</code>```

And...
- objB has reference to objA
- objC has reference to objB

If objC has a method that needs to call a method of objA, what will you do?

Option 1.

```<code>b.getA().runMethodX()
</code>```

Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense.  Doing so is just like doing procedural programming.  Agree/Disagree?

Option 2.

Let objC has direct reference to objA and objB through constructor injection / setter

Is this a good idea?  but then objB that objC has reference to also has reference to objA.  Is this okay?  Or as long as it is not a case of cyclic object references, it is acceptable?

Option 3.

Move the method in question to objA, and pass objC in by parameter.

I'm not sure if this considers as an option.  I think it'll not work in every case.  Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.

Option 4.  (Delegation)

add runMethodXinA() to B, it calls

```<code>a.runMethodX()
</code>```

C calls

```<code>b.runMethodXinA()
</code>```

I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?

What are your though?  Any other options?  Comments?  Suggestions?

答:
I think the question is what kind of model you're going for. If you're going for a relational model where you know the entire structure ahead of time and it will not change, option 1 is acceptable. That is, the data/methods in A in a particular organizational pattern is required for C.

Option 2 may seem like a good idea. but you're essentially saving two references to the same object. Now if B gets mapped to a different A, B has to notify C to change its reference as well. No good.

Option 4 seems like the correct way to go for a truly OO approach, however. The point being that A can change its structure and you only have to adapt B - the immediate child. C doesn't know and doesn't care how A is implemented, it's enough that A simply exists and B knows what to do with it.

OwnerDisplayName: Henry

Title: 2x one-to-many relationships in OO

Body:
Imagine these relationships:

1 A has many B's

1 B has many C's...

In reverse:

C has 1 B

B has 1A

By transitivity, C has 1 A

To model this relationship in DB, we have:

TableA
a_id

TableB
b_id
a_id (fk to TableA)

TableC
c_id
b_id (fk to TableB)

To model this relationship in OO, we have:

objA
objB
objC

And...
- objB has reference to objA
- objC has reference to objB

If objC has a method that needs to call a method of objA, what will you do?

Option 1.

b.getA().runMethodX()

Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense.  Doing so is just like doing procedural programming.  Agree/Disagree?

Option 2.

Let objC has direct reference to objA and objB through constructor injection / setter

Is this a good idea?  but then objB that objC has reference to also has reference to objA.  Is this okay?  Or as long as it is not a case of cyclic object references, it is acceptable?

Option 3.

Move the method in question to objA, and pass objC in by parameter.

I'm not sure if this considers as an option.  I think it'll not work in every case.  Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.

Option 4.  (Delegation)

add runMethodXinA() to B, it calls

a.runMethodX()

C calls

b.runMethodXinA()

I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?

What are your though?  Any other options?  Comments?  Suggestions?

LastEditorDisplayName: cletus

OwnerDisplayName: lc

LastEditorDisplayName: lc


答:
I have done some changes in the code, remove opener from your title and id values, its just run by "document.getElementById", no need to "opener.document.getElementById".
Hope it will help.</p>

```<code>function newWindow(){
    var nuovaFin = window.open("");
    var title = document.getElementById("titleHere").innerHTML;
    var id = document.getElementById("idHere").id;

    nuovaFin.document.write("<html><title> "+ title +" </title><body> <p> "+ id +"</p> </body></html>");

};
</script>

 <p id="titleHere" >ProvaText</p>

 <p id="idHere" >saas</p>
 <input type="button" id="btnNew" onclick="newWindow();"> test </input>
</code>```

Title: I need to have a page created by JS display some code from the parent window

Body:
I have a html page and I need to send data (text and id specifically) from some html paragraph to a child page, created in a js file using window.open("");.

I already tried moving the script from the js file into the script tags. I tried using .innerText and .innerHTML and both returned Untitled, the id field did not show up entirely.

function newWindow(){
    var nuovaFin = window.open("");
    var title = opener.document.getElementById("titleHere").innerHTML;
    var id = opener.document.getElementById("idHere").id;

    nuovaFin.document.write("<title> "+ title +" </title>
 "+ id +"
 ");

};

ProvaText

saas

        <input type="button" id="btnNew" onclick="newWindow();"> test </input>

I want the var title to be shown as the title of the newly created page, as it should, following the document.write argument, but it displays "Untitled", and the id from the paragraph isn't displayed at all.

Body:
I have done some changes in the code, remove opener from your title and id values, its just run by "document.getElementById", no need to "opener.document.getElementById".
Hope it will help.

function newWindow(){
    var nuovaFin = window.open("");
    var title = document.getElementById("titleHere").innerHTML;
    var id = document.getElementById("idHere").id;

    nuovaFin.document.write("<html><title> "+ title +" </title><body> <p> "+ id +"</p> </body></html>");

};
</script>

 <p id="titleHere" >ProvaText</p>

 <p id="idHere" >saas</p>
 <input type="button" id="btnNew" onclick="newWindow();"> test </input>


问:
How can I remove a line from java source code(from file) that has only a opening or closing bracket in python?
I am doing some analysis on java source code and I want to get rid of lines that contain only an opening { or closing bracket}. And write it back to the same file. How can I achieve this? The code below only checks if the first character is a bracket, this might erase the next content after the bracket, which is something I do not want.

```<code>with open("source_code.txt", 'r') as f:
  for line in f:
    if not line[0].lstrip() == "{" or not line[0].lstrip() == "}":
      # Write it back to the same file i.e. source_code.txt

</code>```

INPUT:

```<code>/**
     * Copy all mappings from given map if they pass validation.
     * If a single value fails validation, none of the others will be committed either.
     *
     * @param map map of keys and values
     * @throws ValidationException if an entry in <tt>map</tt> fails validation
     */
    public void putAll(Map<K, V> map)
    throws ValidationException
    {
        for (K key: map.keySet()) {
            if (mValidators.containsKey(key)) {
                for (Validator validator : mValidators.get(key)) {
                    if (!validator.validate(map.get(key))) {
                       throw new ValidationException(validator.message());
                    }
                }
            }
        }

        mData.putAll(map);
    }
</code>```

OUTPUT:

```<code>/**
     * Copy all mappings from given map if they pass validation.
     * If a single value fails validation, none of the others will be committed either.
     *
     * @param map map of keys and values
     * @throws ValidationException if an entry in <tt>map</tt> fails validation
     */
    public void putAll(Map<K, V> map)
    throws ValidationException
        for (K key: map.keySet()) {
            if (mValidators.containsKey(key)) {
                for (Validator validator : mValidators.get(key)) {
                    if (!validator.validate(map.get(key))) {
                       throw new ValidationException(validator.message());
        mData.putAll(map);
</code>```

答:
Use splitlines() to split the text file to rows and use startswith() to check if a string starts with a substring.

with open("source_code.txt", 'r') as f:
    rows = f.read().splitlines()

output = []

for row in rows:
    if not (row.lstrip().startswith("{") or row.lstrip().startswith("}")):
        output.append(row)

with open("source_code.txt", 'w') as f:
    for row in output:
        f.write(row + '\n')
```

<p>This is the result</p>

```/**
     * Copy all mappings from given map if they pass validation.
     * If a single value fails validation, none of the others will be committed either.
     *
     * @param map map of keys and values
     * @throws ValidationException if an entry in <tt>map</tt> fails validation
     */
    public void putAll(Map<K, V> map)
    throws ValidationException
        for (K key: map.keySet()) {
            if (mValidators.containsKey(key)) {
                for (Validator validator : mValidators.get(key)) {
                    if (!validator.validate(map.get(key))) {
                       throw new ValidationException(validator.message());

        mData.putAll(map);
```

Body:
I am doing some analysis on java source code and I want to get rid of lines that contain only an opening { or closing bracket}. And write it back to the same file. How can I achieve this? The code below only checks if the first character is a bracket, this might erase the next content after the bracket, which is something I do not want.

with open("source_code.txt", 'r') as f:
  for line in f:
    if not line[0].lstrip() == "{" or not line[0].lstrip() == "}":
      # Write it back to the same file i.e. source_code.txt

INPUT:

/**
     * Copy all mappings from given map if they pass validation.
     * If a single value fails validation, none of the others will be committed either.
     *
     * @param map map of keys and values
     * @throws ValidationException if an entry in <tt>map</tt> fails validation
     */
    public void putAll(Map<K, V> map)
    throws ValidationException
    {
        for (K key: map.keySet()) {
            if (mValidators.containsKey(key)) {
                for (Validator validator : mValidators.get(key)) {
                    if (!validator.validate(map.get(key))) {
                       throw new ValidationException(validator.message());
                    }
                }
            }
        }

        mData.putAll(map);
    }

OUTPUT:

/**
     * Copy all mappings from given map if they pass validation.
     * If a single value fails validation, none of the others will be committed either.
     *
     * @param map map of keys and values
     * @throws ValidationException if an entry in <tt>map</tt> fails validation
     */
    public void putAll(Map<K, V> map)
    throws ValidationException
        for (K key: map.keySet()) {
            if (mValidators.containsKey(key)) {
                for (Validator validator : mValidators.get(key)) {
                    if (!validator.validate(map.get(key))) {
                       throw new ValidationException(validator.message());
        mData.putAll(map);

Body:
Use splitlines() to split the text file to rows and use startswith() to check if a string starts with a substring.

with open("source_code.txt", 'r') as f:
    rows = f.read().splitlines()

output = []

for row in rows:
    if not (row.lstrip().startswith("{") or row.lstrip().startswith("}")):
        output.append(row)

with open("source_code.txt", 'w') as f:
    for row in output:
        f.write(row + '\n')

This is the result

/**
     * Copy all mappings from given map if they pass validation.
     * If a single value fails validation, none of the others will be committed either.
     *
     * @param map map of keys and values
     * @throws ValidationException if an entry in <tt>map</tt> fails validation
     */
    public void putAll(Map<K, V> map)
    throws ValidationException
        for (K key: map.keySet()) {
            if (mValidators.containsKey(key)) {
                for (Validator validator : mValidators.get(key)) {
                    if (!validator.validate(map.get(key))) {
                       throw new ValidationException(validator.message());

        mData.putAll(map);


问:
How do i save exact values as displayed in JMeter test results including min, Max, avg values...?
I am trying to save test results as displayed in Summary, Aggregate report table but the results are not saved as the results displayed in the GUI while running jmx script.

I already tried to use Synthesis report too to get the results but still it does not work.

No error messages are displayed though.

答:
I am assuming that you are running in non-gui mode. Please check the below CLI sample:-

```<code>jmeter -n -t D:\TestScripts\script.jmx -l D:\TestScripts\scriptresults.jtl
</code>```

This will generate the jtl file at the end of the execution. You can then import this file in different listeners (Summary, Aggregate etc).

If in GUI mode. Then, use simple data writer or view result tree to generate the jtl file. Once completed, use summary report "Filename" field to point generated file as input as shown below:-

Then, use "Save Table Data" button to generate a summary.csv file.

Hope this helps.

Body:
I am assuming that you are running in non-gui mode. Please check the below CLI sample:-

jmeter -n -t D:\TestScripts\script.jmx -l D:\TestScripts\scriptresults.jtl

This will generate the jtl file at the end of the execution. You can then import this file in different listeners (Summary, Aggregate etc).

If in GUI mode. Then, use simple data writer or view result tree to generate the jtl file. Once completed, use summary report "Filename" field to point generated file as input as shown below:-

Then, use "Save Table Data" button to generate a summary.csv file.

Hope this helps.


问:
How to update pub package webdev for flutter web
when I try to "serve" my flutter web app
I'm getting this error:

This version of webdev does not support the build_daemon protocol
  used by your version of build_runner. A newer version of webdev is
  available which supports your version of the build_daemon. Please
  update.

how do I update webdev ?
"pub global" seems to offer only "activate"/ "deactivate"
and "pub upgrade" is only looking into the pubspec.yaml file

any idea?

答: I got the same problem now when I followed this tutorial https://medium.com/flutter-community/flutter-create-and-deploy-a-website-from-scratch-4a026ebd6c, but I didn't get pass the error by running flutter pub global activate.</p>


问:
Is there a less verbose way to retrieve non deprecated enum values?
See my code below. I have an enum where some values are marked deprecated. I need a Collection of all the values of the enum which are not deprecated.
I managed to accomplish the task using reflection, but it looks too verbose to me.
Is there a cleaner way to define the presence of the @Deprecated tag ?

```<code>import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DeprecatedEnumValues {

public enum MyEnum {
    AA,
    BB,
    @Deprecated CC,
    DD,
    @Deprecated EE,
}

public static void main(String[] args) {

    List<MyEnum> myNonDeprecatedEnumValues = new ArrayList<MyEnum>();

    for (Field field : MyEnum.class.getDeclaredFields()) {
        if (field.isEnumConstant() && !field.isAnnotationPresent(Deprecated.class)) {
            myNonDeprecatedEnumValues.add(MyEnum.valueOf(field.getName()));
        }
    }
    System.out.println(myNonDeprecatedEnumValues);
}
}
</code>```

答:
Here is the most effective implementation to get the non-deprecated enums with using the static block and Java 8 streams.

```<code>import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public enum MyEnum {
    AA,
    BB,
    @Deprecated
    CC,
    DD,
    @Deprecated
    EE;

    private static List<MyEnum> nonDeprecatedEnums;

    static {
        nonDeprecatedEnums = Arrays.stream(MyEnum.values()).filter(value -> {
            try {
                Field field = MyEnum.class.getField(value.name());
                return !field.isAnnotationPresent(Deprecated.class);
            } catch (NoSuchFieldException | SecurityException e) {
                return false;
            }
        }).collect(Collectors.toList());
    }

    /**
     * Retrieve enum values without the @Deprecated annotation
     */

    public static List<MyEnum> getNonDeprecatedEnums() {
        return nonDeprecatedEnums;
    }
}
</code>```

Body:
See my code below. I have an enum where some values are marked deprecated. I need a Collection of all the values of the enum which are not deprecated.
I managed to accomplish the task using reflection, but it looks too verbose to me.
Is there a cleaner way to define the presence of the @Deprecated tag ?

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DeprecatedEnumValues {

public enum MyEnum {
    AA,
    BB,
    @Deprecated CC,
    DD,
    @Deprecated EE,
}

public static void main(String[] args) {

    List<MyEnum> myNonDeprecatedEnumValues = new ArrayList<MyEnum>();

    for (Field field : MyEnum.class.getDeclaredFields()) {
        if (field.isEnumConstant() && !field.isAnnotationPresent(Deprecated.class)) {
            myNonDeprecatedEnumValues.add(MyEnum.valueOf(field.getName()));
        }
    }
    System.out.println(myNonDeprecatedEnumValues);
}
}

Body:
Here is the most effective implementation to get the non-deprecated enums with using the static block and Java 8 streams.

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public enum MyEnum {
    AA,
    BB,
    @Deprecated
    CC,
    DD,
    @Deprecated
    EE;

    private static List<MyEnum> nonDeprecatedEnums;

    static {
        nonDeprecatedEnums = Arrays.stream(MyEnum.values()).filter(value -> {
            try {
                Field field = MyEnum.class.getField(value.name());
                return !field.isAnnotationPresent(Deprecated.class);
            } catch (NoSuchFieldException | SecurityException e) {
                return false;
            }
        }).collect(Collectors.toList());
    }

    /**
     * Retrieve enum values without the @Deprecated annotation
     */

    public static List<MyEnum> getNonDeprecatedEnums() {
        return nonDeprecatedEnums;
    }
}


问:
show full version of thumbnail on rollover with jQuery?
WordPress creates a new image at a reduced size when I specify the dimensions I want it to display, so when I choose 300 x 230 it produces this file as the image source:

http://example.com/myphoto-300x230.jpg

from this full-size version:

http://example.com/myphoto.jpg

I'm using a plugin to expand the 300x230 on rollover. The expanded view is the 300x230 blown up, which is blurry. Is there a way to show the full-size version on rollover, so that it's myphoto-300x230.jpg by default but myphoto.jpg on rollover? Would I need to regex the filename to get rid of the numbers for the dimensions?

答:
You could use Regex to do that.  Here is a Regex to do that:

```<code>(?<url>(?:http|ftp|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+(?:[\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?\/)(?<file>\w+-[0-9]+x[0-9]+\.\w+)
</code>```

take the group "file" and then modify that approriately, then add the text from "url" to it to get the proper url :)

Body:
You could use Regex to do that.  Here is a Regex to do that:

(?<url>(?:http|ftp|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+(?:[\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?\/)(?<file>\w+-[0-9]+x[0-9]+\.\w+)

take the group "file" and then modify that approriately, then add the text from "url" to it to get the proper url :)


问:
Python: how to parse non-ASCII characters in string
In my Python script, I'm trying to read in a text file that contains columns with people's first and last names, some of which have non-ASCII characters like ñ. But when I do so, I get the error UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 66.

From what I've been reading online, I know you can handle this problem by ignoring or dropping the non-ASCII characters, but I don't want to do that. Is there a straight-forward way of converting all non-ASCII characters in a file into a normal string?

Currently, I'm opening my file with infile = open(filename, 'rU').

Not duplicate question: I'm asking about how to read in a file with unicode characters, not how to write unicode string out to a file.

答:
Make a copy of the file.

Make sure that your file in unicode and find out which unicode format it uses. some simple editors like geany helps you to find the right encoding that was used on creation of the file. Split file if it is big and process a part of it by editors.

Use the correct encoding (maybe it is old cp encoding) for opening the file and do file conversion to utf8. Or use a tool (like editor) to convert it to utf8