问:
Get all "username" and "id" in MySQL database and split using php
I have MySQL database like this.

```<code>id........username
 1 .......rap
 2 .......dafy
 3 .......kay
</code>```

I want to make them like thies

```<code>username-id,username-id,use...
</code>```

for ex.

```<code>rap-1,dafy-2,kay-3
</code>```

the code should use the param to prevent the sql injection, but i have no idea how to write code.

答:
```<code><?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("database","my_user","my_password","my_db");

// Obviously change this to match yours
$sql = "SELECT GROUP_CONCAT(CONCAT(username , '-',id) SEPARATOR ',') as grp FROM table";
$result =  $mysqli->query($sql);
$final_result = []
while($row = $result->fetch_assoc())
{
    array_push($final_result, $row['grp']);
}

$mysqli -> close();
</code>```

Body:
I have MySQL database like this.

id........username
 1 .......rap
 2 .......dafy
 3 .......kay

I want to make them like thies

username-id,username-id,use...

for ex.

rap-1,dafy-2,kay-3

the code should use the param to prevent the sql injection, but i have no idea how to write code.


来源: stackexchange

问:
Images from facebook API gives error "Bad URL date param"
I have thousands of images from facebook stored in my database. However recently I noticed that the images stored in the database are returning this error:
"Bad URL date param"

It seems that we aren't supposed to store facebook images URL for a long time as they can expire.

My question is: how can I get the newer image URL from facebook API if the only information I have is the old image URL ? Maybe I could extract a specific data ID from the old URL, then query facebook API to get the new URL ?

Here's an example of an old (expired) URL :

```<code>https://scontent.xx.fbcdn.net/v/t1.0-9/15380747_1075074945947776_5898791779893134744_n.jpg?oh=7d445f227aa1922bebce375eae991a05&oe=597D1B48
</code>```

答:
Ben commented already on your question with a potential duplicate around this topic: Facebook Image URL gets expired

I've stumbled across this as well and decided to download the images to our servers to avoid this situation. Anyway there is an alternative option.

In case you have the PPCA (Public Page Content Access) permission, you could try to grasp the node-id of the photo and fetch the most recent version through facebooks graph api.

```<code>https://scontent.xx.fbcdn.net/v/t1.0-9/15380747_1075074945947776_5898791779893134744_n.jpg?oh=7d445f227aa1922bebce375eae991a05&oe=597D1B48
                                                ^^^^^^^^^^^^^^^^
</code>```

Which will lead to the following graph-query:

https://graph.facebook.com/v6.0/1075074945947776?fields=picture

Just tested it. In my case it gives me the most recent valid URL.

ContentLicense: CC BY-SA 3.0

Body:
I have thousands of images from facebook stored in my database. However recently I noticed that the images stored in the database are returning this error:
"Bad URL date param"

It seems that we aren't supposed to store facebook images URL for a long time as they can expire.

My question is: how can I get the newer image URL from facebook API if the only information I have is the old image URL ? Maybe I could extract a specific data ID from the old URL, then query facebook API to get the new URL ?

Here's an example of an old (expired) URL :

https://scontent.xx.fbcdn.net/v/t1.0-9/15380747_1075074945947776_5898791779893134744_n.jpg?oh=7d445f227aa1922bebce375eae991a05&oe=597D1B48

Body:
Ben commented already on your question with a potential duplicate around this topic: Facebook Image URL gets expired

I've stumbled across this as well and decided to download the images to our servers to avoid this situation. Anyway there is an alternative option.

In case you have the PPCA (Public Page Content Access) permission, you could try to grasp the node-id of the photo and fetch the most recent version through facebooks graph api.

https://scontent.xx.fbcdn.net/v/t1.0-9/15380747_1075074945947776_5898791779893134744_n.jpg?oh=7d445f227aa1922bebce375eae991a05&oe=597D1B48
                                                ^^^^^^^^^^^^^^^^

Which will lead to the following graph-query:

https://graph.facebook.com/v6.0/1075074945947776?fields=picture

Just tested it. In my case it gives me the most recent valid URL.

ContentLicense: CC BY-SA 4.0


问:
Why is it that my pipe does not read in the printf despite replacing stdin?
The objective is to use dup, dup2 and pipe to communicate between parent and child processes. Just to get a feel of how to use dup and pipes.
The function multby, called in by the child process, takes a number as an argument (3) and multiply it with a user input (in this case 5 as printed in parent) to get a product. (which should be 15)

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

void main(int argv, char *argc) {
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);
        close(testpipe[0]);
        close(0);
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        close(1);
        close(testpipe[1]);
        wait(NULL);
    }
}
</code>```

Here is the code for multby. I also added some fprintf statement to troubleshoot. In particular, it prints out the 2 numbers to be multiplied (which should be 3 and 5 as mentioned above).

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

int main(int argv, char *argc[]) {
  fprintf(stderr,"exec successful\n");
  if (argv < 2) {
    fprintf(stderr, "Usage: %s <factor>\n", argc[0]);
    return 1;
  }

  size_t a, b;
  sscanf(argc[1], "%zu", &a);
  fprintf(stderr, "a: %zu\n", a);

  if (scanf("%zu", &b) != 1) {
    fprintf(stderr, "No input %zu\n", a);
    return 1;
  }
  fprintf(stderr, "b: %zu\n", b);
  printf("%zu", a*b);
  fprintf(stderr, "multby successful\n");
  return 0;
}
</code>```

However, this is my result:
exec successful
a: 3
No input 3

5 was not registered from the read end of the pipe.

Could someone please advise me on what I am doing wrong?

答: You use printf(“5”); to relay the data to the child, but standard output is at least line-buffered so nothing is written until a newline is sent (or fflush(stdout)). Then you close(1); to close standard output, which does not flush the standard I/O buffers.  So nothing is sent to the child.  Use fclose(stdout); to get the 5 sent to the child.

Body:
The objective is to use dup, dup2 and pipe to communicate between parent and child processes. Just to get a feel of how to use dup and pipes.
The function multby, called in by the child process, takes a number as an argument (3) and multiply it with a user input (in this case 5 as printed in parent) to get a product. (which should be 15)

#include <stdio.h>
#include <unistd.h>

void main(int argv, char *argc) {
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);
        close(testpipe[0]);
        close(0);
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        close(1);
        close(testpipe[1]);
        wait(NULL);
    }
}

Here is the code for multby. I also added some fprintf statement to troubleshoot. In particular, it prints out the 2 numbers to be multiplied (which should be 3 and 5 as mentioned above).

#include <stdio.h>

int main(int argv, char *argc[]) {
  fprintf(stderr,"exec successful\n");
  if (argv < 2) {
    fprintf(stderr, "Usage: %s <factor>\n", argc[0]);
    return 1;
  }

  size_t a, b;
  sscanf(argc[1], "%zu", &a);
  fprintf(stderr, "a: %zu\n", a);

  if (scanf("%zu", &b) != 1) {
    fprintf(stderr, "No input %zu\n", a);
    return 1;
  }
  fprintf(stderr, "b: %zu\n", b);
  printf("%zu", a*b);
  fprintf(stderr, "multby successful\n");
  return 0;
}

However, this is my result:
exec successful
a: 3
No input 3

5 was not registered from the read end of the pipe.

Could someone please advise me on what I am doing wrong?


问:
Should I use the 'request' module for a new project?
The 'request' module has been a long-time standard for Node.js.  They have recently deprecated the library.

I am starting a new project, and looking for the best solution to do my networking.  I started off using the native 'https' module, but ran into problem after problem.  Using the request module seemed to be easy and work just fine.  There are also many other libraries to replace the request module.

Generally speaking, you should avoid using deprecated libraries when possible.  But does that rule of thumb apply here?

Is it bad to start a new project with the 'request' module?  If so, what is the new standard?

答:
I would personally not start a new project with the request() library unless it has a feature that no other library has that I absolutely need or unless I need another module that depends upon the request() module itself.

When I have the freedom to choose, I'm using got() for new projects instead.   Choosing from the list of alternatives is a personal decision so you just have to evaluate the type of interface they each have and what features they have.  For what I typically do with this type of library, got() seemed simple and clean, built from the ground up with promises, meets my needs and I've had no problems using it.

Axios, node-fetch and superagent have advantages in that you can use a similar interface in both node.js and in the browser.  All are popular and in wide use.

I tried bent, but didn't click with its programming interface.

I'd personally rather be using libraries that have a stated objective to continue to evolve with new developments in the language, new developments in nodejs libraries and add new features over time rather than a library that says it will not be adding new features.

I also like using a library that has promise support built-in from the core rather than added on only as a wrapper since I do all asynchronous programming with promises now.

Some other resources in examining the alternatives:

Feature comparison chart (written by the makers of got())

Migrating to got() from request

And, if you want to read about why the request() library has gone into maintenance mode, read here.

In a nutshell, it's an old architecture with tons of features glued onto the side, but because there are so many modules dependent upon it, they can't really break their API to fix or smooth things out.  And, because it's so popular, it is holding back the success of competing solutions that have designed a cleaner interface.  So, the decision was made to let the alternatives that have been designed in a more modern way take the mantle going forward and request() will go into maintenance mode to continue to support the other modules that are dependent upon it, but not try to evolve into a more modern interface.


问:
Best way to generate all 0-1 matrices that are row stochastic with all column sums positive?
I'm trying to efficiently generate the list of all 9-by-3 matrices, where each matrix satisfies the following properties:

Every entry is 0 or 1.

Every row sum is 1.

Every column contains at least one 1.

My first approach was as follows:

Generate a list, A, of all 0-1 matrices of size 9-by-3.

```<code> import numpy as np
 import itertools
 n=9
 k=3
 A=[np.reshape(np.array(i), (n,k)) for i in itertools.product([0, 1], repeat = n*k)]
</code>```

Extract from the list A those whose row sums are one and whose columns contain at least one positive entry:

```<code> matrix_list=[]
 N=len(A)
 for k in range(N):
     B=A[k]
     if (np.sum(B,axis=0)>1).all() and (np.sum(B,axis=1)==1).all():
         matrix_list.append(B)
</code>```

This approach I believe works, but it is quite inefficient. Could I somehow create my list of matrices by just considering how to generate all possible matrices that result from taking simple matrix, S:

```<code>    S=np.matrix([[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0]])
</code>```

and create all possible matrices that result from permuting entries in each row, without including the two matrices whose column sums (be it column 0 or column 1) are zero?

答:
A friend not monitoring my question has suggested this, which works:</p>

```<code>    from itertools import combinations
    matrices=[]
    nine=set(range(9))
    for i in range(1,9):
        for combinationI in combinations(nine,i):
            m=[0]*9
            for cI in combinationI:
                m[cI]=[1,0,0]
            remaining=nine.difference(combinationI)
            for j in range(1,9-i):
                for combinationJ in combinations(remaining,j):
                    matrix=m[:]
                    for cJ in combinationJ:
                        matrix[cJ]=[0,1,0]
                    r=remaining.difference(set(combinationJ))
                    for cR in r:
                        matrix[cR]=[0,0,1]
                    matrices.append(matrix)
</code>```

Body:
I'm trying to efficiently generate the list of all 9-by-3 matrices, where each matrix satisfies the following properties:

Every entry is 0 or 1.

Every row sum is 1.

Every column contains at least one 1.

My first approach was as follows:

Generate a list, A, of all 0-1 matrices of size 9-by-3.

 import numpy as np
 import itertools
 n=9
 k=3
 A=[np.reshape(np.array(i), (n,k)) for i in itertools.product([0, 1], repeat = n*k)]

Extract from the list A those whose row sums are one and whose columns contain at least one positive entry:

 matrix_list=[]
 N=len(A)
 for k in range(N):
     B=A[k]
     if (np.sum(B,axis=0)>1).all() and (np.sum(B,axis=1)==1).all():
         matrix_list.append(B)

This approach I believe works, but it is quite inefficient. Could I somehow create my list of matrices by just considering how to generate all possible matrices that result from taking simple matrix, S:

    S=np.matrix([[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0]])

and create all possible matrices that result from permuting entries in each row, without including the two matrices whose column sums (be it column 0 or column 1) are zero?

Body:
A friend not monitoring my question has suggested this, which works:

    from itertools import combinations
    matrices=[]
    nine=set(range(9))
    for i in range(1,9):
        for combinationI in combinations(nine,i):
            m=[0]*9
            for cI in combinationI:
                m[cI]=[1,0,0]
            remaining=nine.difference(combinationI)
            for j in range(1,9-i):
                for combinationJ in combinations(remaining,j):
                    matrix=m[:]
                    for cJ in combinationJ:
                        matrix[cJ]=[0,1,0]
                    r=remaining.difference(set(combinationJ))
                    for cR in r:
                        matrix[cR]=[0,0,1]
                    matrices.append(matrix)


问:
Indexing subclass fields by IndexEmbedded
I'm am using NHibernate.Search and Lucene.Net. I will ask if anyone have experienced similar problems. This is the situation regarding the following three classes.

```<code>[Indexed]
public class File
{
    [Field]
    public virtual string FileId { get; private set; }

    [ContainedIn]
    public virtual List<Record> Records { get; private set; }
}

[Indexed]
public class CaseFile : File
{
    [Field]
    public virtual int CaseYear { get; set; }
    [Field]
    public virtual int CaseSequenceNumber { get; set; }
}

[Indexed]
public class Record
{
    [IndexedEmbedded]
    public virtual File ParentFile { get; set; }
}
</code>```

The problem is when I try to index the record class. The goal is to get all fields of both the File class and the subclass CaseFile contained in the Record index. But when I index the Record class I only get fields of the File superclass in my Record index. The fields of the CaseFile subclass are missing in the Record index.

I have also tried the [IndexedEmbedded(TargetElement = typeof(CaseFile))] on the ParentFile property in the Record class, but this leads to totally empty indexes, or no indexing at all.

If I index the File class, the expected subclass properties are indexed as expected in the File index.

Have anyone experienced similar problems with Hibernate/NHibernate search?

答:
I was having the same issue, and I managed to achieve a workaround by doing something similar to the following.

It's not the nicest solution though.

```<code>[Indexed]
public class File
{
    [Field]
    public virtual string FileId { get; private set; }

    [ContainedIn]
    public virtual List<Record> Records { get; private set; }

    [Field(Index.Tokenized, Store = Store.Yes)]
    public virtual string CaseYearSearch
    {
        get
        {
            if(GetType() == typeof(CaseFile))
            {
                return ((CaseFile)this).CaseYear;
            }
            return "";
        }
    }

    [Field(Index.Tokenized, Store = Store.Yes)]
    public virtual string CaseSequenceNumberSearch
    {
        get
        {
            if(GetType() == typeof(CaseFile))
            {
                return ((CaseFile)this).CaseSequenceNumber;
            }
            return "";
        }
    }
}

public class CaseFile : File
{
    public virtual int CaseYear { get; set; }
    public virtual int CaseSequenceNumber { get; set; }
}

[Indexed]
public class Record
{
    [IndexedEmbedded]
    public virtual File ParentFile { get; set; }
}
</code>```

I'm using a MultiFieldQueryParser to query.

```<code>IFullTextSession session = Search.CreateFullTextSession(Session);

var parser = new MultiFieldQueryParser(new[] { "File.CaseYearSearch", "File.CaseSequenceNumberSearch" }, new CustomAnalyzer());
parser.SetDefaultOperator(QueryParser.Operator.OR);

var booleanQuery = new BooleanQuery();
booleanQuery.Add(parser.Parse(terms), BooleanClause.Occur.MUST);
booleanQuery.Add(new TermQuery(new Term("Status", ((int)Status.Active).ToString())), BooleanClause.Occur.MUST);

return session.CreateFullTextQuery(booleanQuery, new[] { typeof(Record) });
</code>```

Let me know if you find a cleaner solution.

Body:
I'm am using NHibernate.Search and Lucene.Net. I will ask if anyone have experienced similar problems. This is the situation regarding the following three classes.

[Indexed]
public class File
{
    [Field]
    public virtual string FileId { get; private set; }

    [ContainedIn]
    public virtual List<Record> Records { get; private set; }
}

[Indexed]
public class CaseFile : File
{
    [Field]
    public virtual int CaseYear { get; set; }
    [Field]
    public virtual int CaseSequenceNumber { get; set; }
}

[Indexed]
public class Record
{
    [IndexedEmbedded]
    public virtual File ParentFile { get; set; }
}

The problem is when I try to index the record class. The goal is to get all fields of both the File class and the subclass CaseFile contained in the Record index. But when I index the Record class I only get fields of the File superclass in my Record index. The fields of the CaseFile subclass are missing in the Record index.

I have also tried the [IndexedEmbedded(TargetElement = typeof(CaseFile))] on the ParentFile property in the Record class, but this leads to totally empty indexes, or no indexing at all.

If I index the File class, the expected subclass properties are indexed as expected in the File index.

Have anyone experienced similar problems with Hibernate/NHibernate search?

Body:
I was having the same issue, and I managed to achieve a workaround by doing something similar to the following.

It's not the nicest solution though.

[Indexed]
public class File
{
    [Field]
    public virtual string FileId { get; private set; }

    [ContainedIn]
    public virtual List<Record> Records { get; private set; }

    [Field(Index.Tokenized, Store = Store.Yes)]
    public virtual string CaseYearSearch
    {
        get
        {
            if(GetType() == typeof(CaseFile))
            {
                return ((CaseFile)this).CaseYear;
            }
            return "";
        }
    }

    [Field(Index.Tokenized, Store = Store.Yes)]
    public virtual string CaseSequenceNumberSearch
    {
        get
        {
            if(GetType() == typeof(CaseFile))
            {
                return ((CaseFile)this).CaseSequenceNumber;
            }
            return "";
        }
    }
}

public class CaseFile : File
{
    public virtual int CaseYear { get; set; }
    public virtual int CaseSequenceNumber { get; set; }
}

[Indexed]
public class Record
{
    [IndexedEmbedded]
    public virtual File ParentFile { get; set; }
}

I'm using a MultiFieldQueryParser to query.

IFullTextSession session = Search.CreateFullTextSession(Session);

var parser = new MultiFieldQueryParser(new[] { "File.CaseYearSearch", "File.CaseSequenceNumberSearch" }, new CustomAnalyzer());
parser.SetDefaultOperator(QueryParser.Operator.OR);

var booleanQuery = new BooleanQuery();
booleanQuery.Add(parser.Parse(terms), BooleanClause.Occur.MUST);
booleanQuery.Add(new TermQuery(new Term("Status", ((int)Status.Active).ToString())), BooleanClause.Occur.MUST);

return session.CreateFullTextQuery(booleanQuery, new[] { typeof(Record) });

Let me know if you find a cleaner solution.


问:
How to read status of git remote - v
I start to learn git, I would like to understand git remote -v status.
When I comfirm git remote -v some message below is displayed.

How to understand the status of remote repository?

```<code>$ git remote -v
origin  https://github.com/user/calendar.git (fetch)
origin  https://github.com/user/calendar.git (push)
</code>```

Best regards

答:
git remote just lists remote repositories, without telling you anything about the status of these repositories.

Use git status to see the status of your local repository in relation to the remote repository. E.g., this will tell you that you are ahead (local commits not yet pushed to remote) or behind (your local repository is not up-to-date).

With git fetch, git pull, and git push you can interact with the remote repository.

Also make sure to take a look on Git's good manual pages, like git help remote, git help status, and so on.

Title: How to read status of git remote - v

Body:
I start to learn git, I would like to understand git remote -v status.
When I comfirm git remote -v some message below is displayed.

How to understand the status of remote repository?

$ git remote -v
origin  https://github.com/user/calendar.git (fetch)
origin  https://github.com/user/calendar.git (push)

Best regards


问:
Items on left to be added in the box on the right upon clicked
I have a list of items placed on the left (itemDrop) and would like to add it in the box on the right (itemList) when selected. Terms: unable to select the same item, unable to select more than 3 items. Can only edit javascript file, HTML file untouchable.

HTML:

```<code><div id="itemSelectHeader"> <H2>Item List</H2>
<div id="itemSelect">SELECT FROM HERE
<div id="itemDrop" class="itemSetup">
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>
</div>
</div>
</div>
<div id="itemListSection">
    <H3>Items Selected</H3>
    <div id="itemList" class="itemSetup"> <ul></ul></div>
</div>
</code>```

Add ons:
- clear box when clear button clicked
- submit only when there are 3 items selected

```<code>    <div id="itemBtn">
         <button type="button" id="clearItem">CLEAR ALL</button>
         <button type="button" id="selectItem">SUBMIT</button>
    </div>
</code>```

tried the following for clear button but it doesn't work. But worked for alert

```<code>    $("#clearItem").click(function(){
        //alert("try");
        $("#itemList").reset();
    });
</code>```

答:
this will serve your terms.
Terms: unable to select the same item, unable to select more than 3 items. Can only edit javascript file

    let counter = 0;
let selectedItem = [];
let drop = document.querySelector("#itemList ul");
let lists = document.querySelectorAll("#itemDrop ul li");
for (let i = 0; i < lists.length; i++) {
     lists[i].addEventListener("click", function() {
        appendPlace(i, lists[i]);
     });
}

function appendPlace(itemNo, item) {
 if(!selectedItem[itemNo] && counter < 3)
 {
  let x = document.createElement("LI");
    let t = document.createTextNode(item.innerHTML);
    x.appendChild(t);
  drop.appendChild(x);
  selectedItem[itemNo] = 1;
  counter++;
 }
}```

Body:
I have a list of items placed on the left (itemDrop) and would like to add it in the box on the right (itemList) when selected. Terms: unable to select the same item, unable to select more than 3 items. Can only edit javascript file, HTML file untouchable.

HTML:

Item List

SELECT FROM HERE

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Items Selected

Add ons:
- clear box when clear button clicked
- submit only when there are 3 items selected

         <button type="button" id="clearItem">CLEAR ALL</button>
         <button type="button" id="selectItem">SUBMIT</button>

tried the following for clear button but it doesn't work. But worked for alert

    $("#clearItem").click(function(){
        //alert("try");
        $("#itemList").reset();
    });


问:
Counting elements in a list that only occur once: how do I optimise my performance? It's very slow
I have a large list that contains usernames (about 60,000 strings). Each username represents a submission. Some users have made only one submission i.e. they are "one-time users", so their username appears only once in this list. Others have made multiple submission (returning users) so their username can appear many times in this list. I want to count how many of these one-time users there are and get some stats based on that. Here are the variables I'm currently grabbing:

import time

start_time = time.time()

users = ["UserA", "UserB", "UserC", "UserA", "UserA", "UserA", "UserB", "UserB", "UserD"] # ...just a sample, this goes up to ~60,000 elements
print(f"1: got users list. Time elapsed: {time.time() - start_time}")

one_time_users = [user for user in users if users.count(user) == 1]
print(f"2: got one-time users list. Time elapsed: {time.time() - start_time}")

returning_users = [user for user in users if users.count(user) != 1]
print(f"3: got returning users list. Time elapsed: {time.time() - start_time}")

frequencies = [users.count(user) for user in set(users)]
print(f"4: calculated frequencies list. Time elapsed: {time.time() - start_time}")

sorted_frequencies = sorted(frequencies, reverse=True) # Descending order, largest first
print(f"5: got sorted frequencies list. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_sum = sum(sorted_frequencies[:10])
print(f"6: got top 10 frequencies sum. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_percentage = round(((top_ten_frequencies_sum / len(users)) * 100), 2)
print(f"7: got top 10 frequencies percentage. Time elapsed: {time.time() - start_time}")

average_submissions_per_user = round(len(users) / len(set(users)), 2)
print(f"8: got average submissions per user. Time elapsed: {time.time() - start_time}")
```

<p>This operation is <strong>very slow.</strong> Here is my output:</p>

```1: got users list. Time elapsed: 0.41695237159729004
2: got one-time users list. Time elapsed: 48.26731848716736
3: got returning users list. Time elapsed: 101.88410639762878
4: calculated frequencies list. Time elapsed: 104.39784860610962
5: got sorted frequencies list. Time elapsed: 104.39850783348083
6: got top 10 frequencies sum. Time elapsed: 104.39853930473328
7: got top 10 frequencies percentage. Time elapsed: 104.39856457710266
8: got average submissions per user. Time elapsed: 104.4005241394043
```

As you can see the list comprehensions are taking the most time. Can someone explain to me:

Why it's so slow in terms of time complexity.

Whether collections.Counter() will be a better choice and how best to apply it here.

Thank you!

答:
You can improve by using a Counter, in 2. for each element you are iterating the whole list, and you are doing this multiple times for the same user if an user occurs more than once.

Note that when you use users.count(user) you iterate all the list of users to count how many times the user occurs. This means quadratic complexity with respect to the length of the list.

Using a counter, you can solve it in linear complexity.

Also, in 4. you are iterating and counting again, while you could just remove the ones you just computed from the whole users.

Example.

```<code>>>> one_time_users = {user for user,cnt in Counter(users).items() if cnt == 1}
{'UserC', 'UserD'}
>>> returning_users = set(users) - one_time_users
>>> returning_users
{'UserB', 'UserA'}
</code>```

or more directly

```<code>one_time_users, returning_users  = [], []
for user,cnt in Counter(users).items():
   if cnt==1:
      one_time_users.append(user)
   else:
      returning_users.append(user)
</code>```

Here a comparison of l.count(el) vs a Counter(l).

```<code>>>> l = random.choices(range(500), k=60000)
>>> timeit.timeit('[el for el in l if l.count(el) == 1]',setup='from __main__ import l',number=1)
71.70409394335002
>>> timeit.timeit('[el for el,cnt in Counter(l).items() if cnt == 1]',setup='from __main__ import l, Counter',number=1)
0.005492186639457941
</code>```

Body:
I have a large list that contains usernames (about 60,000 strings). Each username represents a submission. Some users have made only one submission i.e. they are "one-time users", so their username appears only once in this list. Others have made multiple submission (returning users) so their username can appear many times in this list. I want to count how many of these one-time users there are and get some stats based on that. Here are the variables I'm currently grabbing:

import time

start_time = time.time()

users = ["UserA", "UserB", "UserC", "UserA", "UserA", "UserA", "UserB", "UserB", "UserD"] # ...just a sample, this goes up to ~60,000 elements
print(f"1: got users list. Time elapsed: {time.time() - start_time}")

one_time_users = [user for user in users if users.count(user) == 1]
print(f"2: got one-time users list. Time elapsed: {time.time() - start_time}")

returning_users = [user for user in users if users.count(user) != 1]
print(f"3: got returning users list. Time elapsed: {time.time() - start_time}")

frequencies = [users.count(user) for user in set(users)]
print(f"4: calculated frequencies list. Time elapsed: {time.time() - start_time}")

sorted_frequencies = sorted(frequencies, reverse=True) # Descending order, largest first
print(f"5: got sorted frequencies list. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_sum = sum(sorted_frequencies[:10])
print(f"6: got top 10 frequencies sum. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_percentage = round(((top_ten_frequencies_sum / len(users)) * 100), 2)
print(f"7: got top 10 frequencies percentage. Time elapsed: {time.time() - start_time}")

average_submissions_per_user = round(len(users) / len(set(users)), 2)
print(f"8: got average submissions per user. Time elapsed: {time.time() - start_time}")

This operation is very slow. Here is my output:

1: got users list. Time elapsed: 0.41695237159729004
2: got one-time users list. Time elapsed: 48.26731848716736
3: got returning users list. Time elapsed: 101.88410639762878
4: calculated frequencies list. Time elapsed: 104.39784860610962
5: got sorted frequencies list. Time elapsed: 104.39850783348083
6: got top 10 frequencies sum. Time elapsed: 104.39853930473328
7: got top 10 frequencies percentage. Time elapsed: 104.39856457710266
8: got average submissions per user. Time elapsed: 104.4005241394043

As you can see the list comprehensions are taking the most time. Can someone explain to me:

Why it's so slow in terms of time complexity.

Whether collections.Counter() will be a better choice and how best to apply it here.

Thank you!

Body:
You can improve by using a Counter, in 2. for each element you are iterating the whole list, and you are doing this multiple times for the same user if an user occurs more than once.

Note that when you use users.count(user) you iterate all the list of users to count how many times the user occurs. This means quadratic complexity with respect to the length of the list.

Using a counter, you can solve it in linear complexity.

Also, in 4. you are iterating and counting again, while you could just remove the ones you just computed from the whole users.

Example.

>>> one_time_users = {user for user,cnt in Counter(users).items() if cnt == 1}
{'UserC', 'UserD'}
>>> returning_users = set(users) - one_time_users
>>> returning_users
{'UserB', 'UserA'}

or more directly

one_time_users, returning_users  = [], []
for user,cnt in Counter(users).items():
   if cnt==1:
      one_time_users.append(user)
   else:
      returning_users.append(user)

Here a comparison of l.count(el) vs a Counter(l).

>>> l = random.choices(range(500), k=60000)
>>> timeit.timeit('[el for el in l if l.count(el) == 1]',setup='from __main__ import l',number=1)
71.70409394335002
>>> timeit.timeit('[el for el,cnt in Counter(l).items() if cnt == 1]',setup='from __main__ import l, Counter',number=1)
0.005492186639457941


问:
Move image behind the main content CSS
I have a problem with some css in my website

```<code>this is the main CSS source :
/* html selectors ---- */

html, body {
    font-family: 'Arial Unicode MS';
    margin: 0;
    padding: 0;
    background-repeat: repeat-x;
    background-color: white;
    direction: rtl;
    font-size: 10.3pt;
}

h1, h2, h3, h4, h5, h6 {
    margin: 0;
}

h1 {
    font-size: 17pt;
    text-decoration: underline;
    top: 3px;
    padding-bottom: 10px;
    line-height: 25px;
}

h2 {
    font-family: david;
    font-size: 11pt;
    color: #191970;
}

h3 {
    font-size: 16pt;
    color: white;
    margin-left: 15px;
    font-weight: bold;
    margin-bottom: 20px;
    padding-right: 30px;
    padding-top: -55px;
    font-family: 'Arial Unicode MS';
}

/*page -----------*/
#page {
    width: 900px;
    padding: 0px;
    margin: 0 auto;
    direction: rtl;
    position: relative;
    z-index: 100;
    z-index: 5;
    background-image: url("images/bgimage.png");
}

#leftshadow {
    width: 100px;
    height: 900px;
    background-image: url("images/leftshadow.png");
    position: absolute;
    right: 840px;
    z-index: none;
    top: -25px;
}

#rightshadow {
    width: 100px;
    height: 900px;
    background-image: url("images/rightshadow.png");
    position: absolute;
    right: -45px;
    z-index: none;
    top: -25px;
}
</code>```

My question is how can I move the image-shdow back, behind the main content?

I tried a lot with z-index but I couldn't find a solution, can you help me solve thos problem pleas?

答:
You need both a position command, and "none" is not a valid z-index value.  -1 works for me.</p>

```<code>style="position:relative; z-index:-1;"
</code>```

Title: Move image behind the main content CSS

Body:
I have a problem with some css in my website

this is the main CSS source :
/* html selectors ---- */

html, body {
    font-family: 'Arial Unicode MS';
    margin: 0;
    padding: 0;
    background-repeat: repeat-x;
    background-color: white;
    direction: rtl;
    font-size: 10.3pt;
}

h1, h2, h3, h4, h5, h6 {
    margin: 0;
}

h1 {
    font-size: 17pt;
    text-decoration: underline;
    top: 3px;
    padding-bottom: 10px;
    line-height: 25px;
}

h2 {
    font-family: david;
    font-size: 11pt;
    color: #191970;
}

h3 {
    font-size: 16pt;
    color: white;
    margin-left: 15px;
    font-weight: bold;
    margin-bottom: 20px;
    padding-right: 30px;
    padding-top: -55px;
    font-family: 'Arial Unicode MS';
}

/*page -----------*/
#page {
    width: 900px;
    padding: 0px;
    margin: 0 auto;
    direction: rtl;
    position: relative;
    z-index: 100;
    z-index: 5;
    background-image: url("images/bgimage.png");
}

#leftshadow {
    width: 100px;
    height: 900px;
    background-image: url("images/leftshadow.png");
    position: absolute;
    right: 840px;
    z-index: none;
    top: -25px;
}

#rightshadow {
    width: 100px;
    height: 900px;
    background-image: url("images/rightshadow.png");
    position: absolute;
    right: -45px;
    z-index: none;
    top: -25px;
}

My question is how can I move the image-shdow back, behind the main content?

I tried a lot with z-index but I couldn't find a solution, can you help me solve thos problem pleas?

Body:
You need both a position command, and "none" is not a valid z-index value.  -1 works for me.

style="position:relative; z-index:-1;"


问:
Get path of executable
I know this question has been asked before but I still haven't seen a satisfactory answer, or a definitive "no, this cannot be done", so I'll ask again!

All I want to do is get the path to the currently running executable, either as an absolute path or relative to where the executable is invoked from, in a platform-independent fashion. I though boost::filesystem::initial_path was the answer to my troubles but that seems to only handle the 'platform-independent' part of the question - it still returns the path from which the application was invoked.

For a bit of background, this is a game using Ogre, which I'm trying to profile using Very Sleepy, which runs the target executable from its own directory, so of course on load the game finds no configuration files etc. and promptly crashes. I want to be able to pass it an absolute path to the configuration files, which I know will always live alongside the executable. The same goes for debugging in Visual Studio - I'd like to be able to run $(TargetPath) without having to set the working directory.

答:
This is what I ended up with

The header file looks like this:

#pragma once

#include <string>
namespace MyPaths {

  std::string getExecutablePath();
  std::string getExecutableDir();
  std::string mergePaths(std::string pathA, std::string pathB);
  bool checkIfFileExists (const std::string& filePath);

}

```

<p>Implementation</p>

<pre class="lang-cpp prettyprint-override"><code>
#if defined(_WIN32)
    #include <windows.h>
    #include <Shlwapi.h>
    #include <io.h>

    #define access _access_s
#endif

#ifdef __APPLE__
    #include <libgen.h>
    #include <limits.h>
    #include <mach-o/dyld.h>
    #include <unistd.h>
#endif

#ifdef __linux__
    #include <limits.h>
    #include <libgen.h>
    #include <unistd.h>

    #if defined(__sun)
        #define PROC_SELF_EXE "/proc/self/path/a.out"
    #else
        #define PROC_SELF_EXE "/proc/self/exe"
    #endif

#endif

namespace MyPaths {

#if defined(_WIN32)

std::string getExecutablePath() {
   char rawPathName[MAX_PATH];
   GetModuleFileNameA(NULL, rawPathName, MAX_PATH);
   return std::string(rawPathName);
}

std::string getExecutableDir() {
    std::string executablePath = getExecutablePath();
    char* exePath = new char[executablePath.length()];
    strcpy(exePath, executablePath.c_str());
    PathRemoveFileSpecA(exePath);
    std::string directory = std::string(exePath);
    delete[] exePath;
    return directory;
}

std::string mergePaths(std::string pathA, std::string pathB) {
  char combined[MAX_PATH];
  PathCombineA(combined, pathA.c_str(), pathB.c_str());
  std::string mergedPath(combined);
  return mergedPath;
}

#endif

#ifdef __linux__

std::string getExecutablePath() {
   char rawPathName[PATH_MAX];
   realpath(PROC_SELF_EXE, rawPathName);
   return  std::string(rawPathName);
}

std::string getExecutableDir() {
    std::string executablePath = getExecutablePath();
    char *executablePathStr = new char[executablePath.length() + 1];
    strcpy(executablePathStr, executablePath.c_str());
    char* executableDir = dirname(executablePathStr);
    delete [] executablePathStr;
    return std::string(executableDir);
}

std::string mergePaths(std::string pathA, std::string pathB) {
  return pathA+"/"+pathB;
}

#endif

#ifdef __APPLE__
    std::string getExecutablePath() {
        char rawPathName[PATH_MAX];
        char realPathName[PATH_MAX];
        uint32_t rawPathSize = (uint32_t)sizeof(rawPathName);

        if(!_NSGetExecutablePath(rawPathName, &rawPathSize)) {
            realpath(rawPathName, realPathName);
        }
        return  std::string(realPathName);
    }

    std::string getExecutableDir() {
        std::string executablePath = getExecutablePath();
        char *executablePathStr = new char[executablePath.length() + 1];
        strcpy(executablePathStr, executablePath.c_str());
        char* executableDir = dirname(executablePathStr);
        delete [] executablePathStr;
        return std::string(executableDir);
    }

    std::string mergePaths(std::string pathA, std::string pathB) {
        return pathA+"/"+pathB;
    }
#endif

bool checkIfFileExists (const std::string& filePath) {
   return access( filePath.c_str(), 0 ) == 0;
}

}

</code>```

ContentLicense: CC BY-SA 2.5

Title: Get path of executable

Body:
This is what I ended up with

The header file looks like this:

#pragma once

#include <string>
namespace MyPaths {

  std::string getExecutablePath();
  std::string getExecutableDir();
  std::string mergePaths(std::string pathA, std::string pathB);
  bool checkIfFileExists (const std::string& filePath);

}

Implementation

#if defined(_WIN32)
    #include <windows.h>
    #include <Shlwapi.h>
    #include <io.h>

    #define access _access_s
#endif

#ifdef __APPLE__
    #include <libgen.h>
    #include <limits.h>
    #include <mach-o/dyld.h>
    #include <unistd.h>
#endif

#ifdef __linux__
    #include <limits.h>
    #include <libgen.h>
    #include <unistd.h>

    #if defined(__sun)
        #define PROC_SELF_EXE "/proc/self/path/a.out"
    #else
        #define PROC_SELF_EXE "/proc/self/exe"
    #endif

#endif

namespace MyPaths {

#if defined(_WIN32)

std::string getExecutablePath() {
   char rawPathName[MAX_PATH];
   GetModuleFileNameA(NULL, rawPathName, MAX_PATH);
   return std::string(rawPathName);
}

std::string getExecutableDir() {
    std::string executablePath = getExecutablePath();
    char* exePath = new char[executablePath.length()];
    strcpy(exePath, executablePath.c_str());
    PathRemoveFileSpecA(exePath);
    std::string directory = std::string(exePath);
    delete[] exePath;
    return directory;
}

std::string mergePaths(std::string pathA, std::string pathB) {
  char combined[MAX_PATH];
  PathCombineA(combined, pathA.c_str(), pathB.c_str());
  std::string mergedPath(combined);
  return mergedPath;
}

#endif

#ifdef __linux__

std::string getExecutablePath() {
   char rawPathName[PATH_MAX];
   realpath(PROC_SELF_EXE, rawPathName);
   return  std::string(rawPathName);
}

std::string getExecutableDir() {
    std::string executablePath = getExecutablePath();
    char *executablePathStr = new char[executablePath.length() + 1];
    strcpy(executablePathStr, executablePath.c_str());
    char* executableDir = dirname(executablePathStr);
    delete [] executablePathStr;
    return std::string(executableDir);
}

std::string mergePaths(std::string pathA, std::string pathB) {
  return pathA+"/"+pathB;
}

#endif

#ifdef __APPLE__
    std::string getExecutablePath() {
        char rawPathName[PATH_MAX];
        char realPathName[PATH_MAX];
        uint32_t rawPathSize = (uint32_t)sizeof(rawPathName);

        if(!_NSGetExecutablePath(rawPathName, &rawPathSize)) {
            realpath(rawPathName, realPathName);
        }
        return  std::string(realPathName);
    }

    std::string getExecutableDir() {
        std::string executablePath = getExecutablePath();
        char *executablePathStr = new char[executablePath.length() + 1];
        strcpy(executablePathStr, executablePath.c_str());
        char* executableDir = dirname(executablePathStr);
        delete [] executablePathStr;
        return std::string(executableDir);
    }

    std::string mergePaths(std::string pathA, std::string pathB) {
        return pathA+"/"+pathB;
    }
#endif

bool checkIfFileExists (const std::string& filePath) {
   return access( filePath.c_str(), 0 ) == 0;
}

}


问:
Why does training my Naive Bayes Classifier take so much memory?
Recently, I have been working on a project which requires Sentiment analysis of twitter data. I am using a Naive Bayes Classifier from the Textblob library, and am trying to train it with 1.6 million tweets (which can be found here if anyone is wondering: https://www.kaggle.com/kazanova/sentiment140). Just outright passing in the 1.6 million tweets causes a Memory Error, so I decided to chunk it so only 1000 tweets get trained at a time. This has minor success as I can only get to about 10,000 tweets on my local machine until my computer freezes up, because I am using too much ram. I then tried it on Google colab, so I could run my code in the cloud. With both the TPU, and the GPU, the max I have gotten too is 28,000 tweets, before the session crashed and I had to restart the runtime. Here is my code:

```<code>with open("shuffledlist.pickle", 'rb') as f: #Loading in my list of 1.6 million tweets
    full_data = pickle.load(f)

training_data = (tweet for tweet in full_data[:1500000])

try:
    with open("sentimentclassifier.pickle", "rb") as file: #makes a new classifier if one doesnt exist
        classifier = pickle.load(file)
        print("Got existing classifier")
except EOFError:
    classifier = NaiveBayesClassifier(full_data[:1000])
    print("Made new classifier")
del full_data

feeding_size = 1000
left_splice = 0
right_splice = feeding_size + left_splice

count = 0
new_start_time = time.time()
past_times = 0

while right_splice < 1500000:
    loop_time = time.time()
    data = itertools.islice(training_data,left_splice,right_splice)
    try:
        classifier.update(data)
    except Exception:
        print("Houston we got a problem")
        with open("sentimentclassifier.pickle", "wb") as sentiment:
             pickle.dump(classifier, sentiment, protocol = -1)
        sys.exit("Yo it ended at {} and {}".format(left_splice, right_splice))
    past_times += time.time() - loop_time
    count += 1
    string = "Left: {} Right: {}. Took {} seconds. Total Time Elapsed: {}. Average Time for each: {}. Count: {}."\
        .format(left_splice, right_splice, time.time()-loop_time, time.time() - new_start_time, past_times/count, count)
    sys.stdout.write('\r' + string)
    left_splice += feeding_size
    right_splice += feeding_size
    with open("sentimentclassifier.pickle", "wb") as sentiment:
        pickle.dump(classifier, sentiment, protocol = -1)
        print("Done dumping cycle {}!".format(count))

print("Done! Right: {}, Left: {}!".format(left_splice, right_splice))

with open("sentimentclassifier.pickle", "wb") as sentiment:
    pickle.dump(classifier, sentiment, protocol = -1)

print("Training took {} seconds!".format(time.time()-new_start_time))
</code>```

Some notes:

Since my primary problem is how big my sentimentclassifier.pickle file gets, I have tried using gzip, but it just takes way too long to open and close the file, and this is especially bad because I need to open the file every loop since I do not want to lose any progress if the program crashes.

I switched from using lists to using generators, which did improve the speed quite significantly.

In google colab I tried passing in 10,000 at a time, which was sort of a last ditch effort, and unsurprisingly, it did not work out for the best.

I am not sure if nltk's Naive Bayes Classifier is more efficient, but I really want that to be a last resort, as reformatting my list of tweets may take a few hours. But if it really is more efficient I will happily redo my code if it means I can get this working.

Thank you and any advice will be greatly appreciated!

答:
I'd try splitting the training data into manageable chunks in separate training files. Instead of opening a file of 1.5 million tweets, split that file into a few thousand tweets per file. Make a loop to train on one file, close that file, then train on the next. That way you're not loading so much into ram at once. It has to hold the entire 1.5 million tweets in memory the way you're doing it. That's bogging down your RAM.

To be clear:

This:

with open("shuffledlist.pickle", 'rb') as f: #Loading in my list of 1.6 million tweets
     full_data = pickle.load(f)

```<code>    >training_data = (tweet for tweet in full_data[:1500000])
</code>```

is loading the entire file into RAM. So, chunking after this line isn't lessening the amount of ram you're using, though it is decreasing the amount of GPU cores you're utilizing because you're only feeding the GPU x amount per iteration. If you load a smaller file in the first place, you'll decrease the amount of RAM utilized from the get-go.

Body:
Recently, I have been working on a project which requires Sentiment analysis of twitter data. I am using a Naive Bayes Classifier from the Textblob library, and am trying to train it with 1.6 million tweets (which can be found here if anyone is wondering: https://www.kaggle.com/kazanova/sentiment140). Just outright passing in the 1.6 million tweets causes a Memory Error, so I decided to chunk it so only 1000 tweets get trained at a time. This has minor success as I can only get to about 10,000 tweets on my local machine until my computer freezes up, because I am using too much ram. I then tried it on Google colab, so I could run my code in the cloud. With both the TPU, and the GPU, the max I have gotten too is 28,000 tweets, before the session crashed and I had to restart the runtime. Here is my code:

with open("shuffledlist.pickle", 'rb') as f: #Loading in my list of 1.6 million tweets
    full_data = pickle.load(f)

training_data = (tweet for tweet in full_data[:1500000])

try:
    with open("sentimentclassifier.pickle", "rb") as file: #makes a new classifier if one doesnt exist
        classifier = pickle.load(file)
        print("Got existing classifier")
except EOFError:
    classifier = NaiveBayesClassifier(full_data[:1000])
    print("Made new classifier")
del full_data

feeding_size = 1000
left_splice = 0
right_splice = feeding_size + left_splice

count = 0
new_start_time = time.time()
past_times = 0

while right_splice < 1500000:
    loop_time = time.time()
    data = itertools.islice(training_data,left_splice,right_splice)
    try:
        classifier.update(data)
    except Exception:
        print("Houston we got a problem")
        with open("sentimentclassifier.pickle", "wb") as sentiment:
             pickle.dump(classifier, sentiment, protocol = -1)
        sys.exit("Yo it ended at {} and {}".format(left_splice, right_splice))
    past_times += time.time() - loop_time
    count += 1
    string = "Left: {} Right: {}. Took {} seconds. Total Time Elapsed: {}. Average Time for each: {}. Count: {}."\
        .format(left_splice, right_splice, time.time()-loop_time, time.time() - new_start_time, past_times/count, count)
    sys.stdout.write('\r' + string)
    left_splice += feeding_size
    right_splice += feeding_size
    with open("sentimentclassifier.pickle", "wb") as sentiment:
        pickle.dump(classifier, sentiment, protocol = -1)
        print("Done dumping cycle {}!".format(count))

print("Done! Right: {}, Left: {}!".format(left_splice, right_splice))

with open("sentimentclassifier.pickle", "wb") as sentiment:
    pickle.dump(classifier, sentiment, protocol = -1)

print("Training took {} seconds!".format(time.time()-new_start_time))

Some notes:

Since my primary problem is how big my sentimentclassifier.pickle file gets, I have tried using gzip, but it just takes way too long to open and close the file, and this is especially bad because I need to open the file every loop since I do not want to lose any progress if the program crashes.

I switched from using lists to using generators, which did improve the speed quite significantly.

In google colab I tried passing in 10,000 at a time, which was sort of a last ditch effort, and unsurprisingly, it did not work out for the best.

I am not sure if nltk's Naive Bayes Classifier is more efficient, but I really want that to be a last resort, as reformatting my list of tweets may take a few hours. But if it really is more efficient I will happily redo my code if it means I can get this working.

Thank you and any advice will be greatly appreciated!

Body:
I'd try splitting the training data into manageable chunks in separate training files. Instead of opening a file of 1.5 million tweets, split that file into a few thousand tweets per file. Make a loop to train on one file, close that file, then train on the next. That way you're not loading so much into ram at once. It has to hold the entire 1.5 million tweets in memory the way you're doing it. That's bogging down your RAM.

To be clear:

This:

with open("shuffledlist.pickle", 'rb') as f: #Loading in my list of 1.6 million tweets
     full_data = pickle.load(f)

    >training_data = (tweet for tweet in full_data[:1500000])

is loading the entire file into RAM. So, chunking after this line isn't lessening the amount of ram you're using, though it is decreasing the amount of GPU cores you're utilizing because you're only feeding the GPU x amount per iteration. If you load a smaller file in the first place, you'll decrease the amount of RAM utilized from the get-go.


问:
How to bypass the message-"your connection is not private" on non-secure page using Selenium?
I'm trying to interact with the page "Your connection is not private".

The solution of using options.add_argument('--ignore-certificate-errors') is not helpful for two reasons:

I'm using an already open window.

Even if I was using a "selenium opened window" the script runs non stop, and the issue I'm trying to solve is when my browser disconnects from a splunk dashboard and I want it to automatically connect again(and it pops the private connection window).

How do I click on "Advanced" and then click on "Proceed to splunk_server (unsafe)?

答:
For chrome:

```<code>from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Chrome(options=options)
</code>```

If not work then this:

```<code>from selenium import webdriver
from selenium.webdriver import DesiredCapabilities

options = webdriver.ChromeOptions()
options.add_argument('--allow-insecure-localhost') # differ on driver version. can ignore.
caps = options.to_capabilities()
caps["acceptInsecureCerts"] = True
driver = webdriver.Chrome(desired_capabilities=caps)
</code>```

For firefox:

```<code>from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True

driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://cacert.org/')

driver.close()
</code>```

If not work then this:

```<code>capabilities = webdriver.DesiredCapabilities().FIREFOX
capabilities['acceptSslCerts'] = True
driver = webdriver.Firefox(capabilities=capabilities)
driver.get('https://cacert.org/')
driver.close()
</code>```

Above all worked for me!

Body:
For chrome:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Chrome(options=options)

If not work then this:

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities

options = webdriver.ChromeOptions()
options.add_argument('--allow-insecure-localhost') # differ on driver version. can ignore.
caps = options.to_capabilities()
caps["acceptInsecureCerts"] = True
driver = webdriver.Chrome(desired_capabilities=caps)

For firefox:

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True

driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://cacert.org/')

driver.close()

If not work then this:

capabilities = webdriver.DesiredCapabilities().FIREFOX
capabilities['acceptSslCerts'] = True
driver = webdriver.Firefox(capabilities=capabilities)
driver.get('https://cacert.org/')
driver.close()

Above all worked for me!


问:
What's the file path of d8.jar used by Android Studio?
I know that Android Studio switch to D8 dexer by default. But I wonder what's the file path of d8.jar ? I can't found d8.jar in SDK like dx.jar.

A typical dx.jar located in Android/Sdk/build-tools/<VERSION>/lib/:

```<code>xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib$ ls
apksigner.jar  dx.jar  shrinkedAndroid.jar
xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib$
</code>```

My first thought is dx.jar means d8.jar, but seems like not the case.

The old dx.jar source code:

```<code>xb@dnxb:~/Downloads/dalvik/dx/src/com/android$ ls
dex  dx  multidex
xb@dnxb:~/Downloads/dalvik/dx/src/com/android$ ls -1 dex
Annotation.java
CallSiteId.java
ClassData.java
ClassDef.java
Code.java
DexException.java
DexFormat.java
DexIndexOverflowException.java
Dex.java
EncodedValueCodec.java
EncodedValue.java
EncodedValueReader.java
FieldId.java
Leb128.java
MethodHandle.java
MethodId.java
Mutf8.java
ProtoId.java
SizeOf.java
TableOfContents.java
TypeList.java
util
xb@dnxb:~/Downloads/dalvik/dx/src/com/android$
</code>```

Is exactly the same as the .classes of dx.jar in 27.0.3 or older(e.g. 25.0.0) SDK (I unzip it):

```<code>xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib/dx/com/android$ ls
dex  dx  multidex
xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib/dx/com/android$ ls -1 dex | grep -v '\$'
Annotation.class
CallSiteId.class
ClassData.class
ClassDef.class
Code.class
Dex.class
DexException.class
DexFormat.class
DexIndexOverflowException.class
EncodedValue.class
EncodedValueCodec.class
EncodedValueReader.class
FieldId.class
Leb128.class
MethodHandle.class
MethodId.class
Mutf8.class
ProtoId.class
SizeOf.class
TableOfContents.class
TypeList.class
util
xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib/dx/com/android$
</code>```

But the new d8.jar has totally difference structure:

```<code>xb@dnxb:~/Downloads/r8/build/libs/d8/com/android/tools/r8$ ls
annotations                                           ExtractMarkerCommand.class
ApiLevelException.class                               ExtractMarker$VdexOrigin.class
ArchiveClassFileProvider.class                        GenerateMainDexList.class
ArchiveProgramResourceProvider.class                  GenerateMainDexListCommand$1.class
ArchiveProgramResourceProvider$ZipFileSupplier.class  GenerateMainDexListCommand$Builder.class
BaseCommand$Builder.class                             GenerateMainDexListCommand.class
BaseCommand.class                                     graph
BaseCompilerCommand$Builder.class                     InternalProgramOutputPathConsumer.class
... omit
</code>```

And I search filename with d8 keyword in both sdk and Android Studio, but no luck:

```<code>xb@dnxb:~$ find /home/xiaobai/Android/ -iname '*d8*'
xb@dnxb:~$ find ~/Downloads/AS/android-studio -iname '*d8*'
xb@dnxb:~$
</code>```

So where's the file path of d8.jar in Android Studio ? My Android Studio version is 3.2 Canary 12 already, but how Android Studio invoke d8 by default if d8.jar not exist ? Or it hide in somewhere ?

答:
After a default installation of Android Studio I just made, I have a d8.jar here (size 4 MB):

```<code>~/Android/Sdk/build-tools/29.0.3/lib/d8.jar
</code>```

To invoke it BTW, you need to run

java -cp d8.jar com.android.tools.r8.D8 ...

Body:
I know that Android Studio switch to D8 dexer by default. But I wonder what's the file path of d8.jar ? I can't found d8.jar in SDK like dx.jar.

A typical dx.jar located in Android/Sdk/build-tools/<VERSION>/lib/:

xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib$ ls
apksigner.jar  dx.jar  shrinkedAndroid.jar
xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib$

My first thought is dx.jar means d8.jar, but seems like not the case.

The old dx.jar source code:

xb@dnxb:~/Downloads/dalvik/dx/src/com/android$ ls
dex  dx  multidex
xb@dnxb:~/Downloads/dalvik/dx/src/com/android$ ls -1 dex
Annotation.java
CallSiteId.java
ClassData.java
ClassDef.java
Code.java
DexException.java
DexFormat.java
DexIndexOverflowException.java
Dex.java
EncodedValueCodec.java
EncodedValue.java
EncodedValueReader.java
FieldId.java
Leb128.java
MethodHandle.java
MethodId.java
Mutf8.java
ProtoId.java
SizeOf.java
TableOfContents.java
TypeList.java
util
xb@dnxb:~/Downloads/dalvik/dx/src/com/android$

Is exactly the same as the .classes of dx.jar in 27.0.3 or older(e.g. 25.0.0) SDK (I unzip it):

xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib/dx/com/android$ ls
dex  dx  multidex
xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib/dx/com/android$ ls -1 dex | grep -v '\$'
Annotation.class
CallSiteId.class
ClassData.class
ClassDef.class
Code.class
Dex.class
DexException.class
DexFormat.class
DexIndexOverflowException.class
EncodedValue.class
EncodedValueCodec.class
EncodedValueReader.class
FieldId.class
Leb128.class
MethodHandle.class
MethodId.class
Mutf8.class
ProtoId.class
SizeOf.class
TableOfContents.class
TypeList.class
util
xb@dnxb:~/Android/Sdk/build-tools/27.0.3/lib/dx/com/android$

But the new d8.jar has totally difference structure:

xb@dnxb:~/Downloads/r8/build/libs/d8/com/android/tools/r8$ ls
annotations                                           ExtractMarkerCommand.class
ApiLevelException.class                               ExtractMarker$VdexOrigin.class
ArchiveClassFileProvider.class                        GenerateMainDexList.class
ArchiveProgramResourceProvider.class                  GenerateMainDexListCommand$1.class
ArchiveProgramResourceProvider$ZipFileSupplier.class  GenerateMainDexListCommand$Builder.class
BaseCommand$Builder.class                             GenerateMainDexListCommand.class
BaseCommand.class                                     graph
BaseCompilerCommand$Builder.class                     InternalProgramOutputPathConsumer.class
... omit

And I search filename with d8 keyword in both sdk and Android Studio, but no luck:

xb@dnxb:~$ find /home/xiaobai/Android/ -iname '*d8*'
xb@dnxb:~$ find ~/Downloads/AS/android-studio -iname '*d8*'
xb@dnxb:~$

So where's the file path of d8.jar in Android Studio ? My Android Studio version is 3.2 Canary 12 already, but how Android Studio invoke d8 by default if d8.jar not exist ? Or it hide in somewhere ?

Body:
After a default installation of Android Studio I just made, I have a d8.jar here (size 4 MB):

~/Android/Sdk/build-tools/29.0.3/lib/d8.jar

To invoke it BTW, you need to run

java -cp d8.jar com.android.tools.r8.D8 ...


问:
i keep geting eror "Uncaught SyntaxError: Unexpected token ';' " in javascript switch statement
i have tried to delete ';' and retype case command but nothing happen and still just getting uncaught error. iam get this from tutorial please help iam so new for programming :)
can somebody tell me why the eror still poppin??
heres the code

```<code>//SWITCH STATEMMENT
var job = 'teacher';
switch (job) {
    case 'teacher';
    case 'instructor';
        console.log(firstName + ' teachs kids how to code.');
        break;
    case 'driver';
        console.log(firstName + ' drives an uber in Bekasi.');
        break;
    case 'designer';
        console.log(firstName + ' design beautiiful website.');
        break;
    default;
        console.log(firstName + ' does something else');
}
</code>```

this is the code and the error on the console

答:
You're using ; after your case "something" instead of :.

```<code>var job = 'teacher';
switch (job) {
    case 'teacher':
    case 'instructor':
        console.log(firstName + ' teachs kids how to code.');
        break;
    case 'driver':
        console.log(firstName + ' drives an uber in Bekasi.');
        break;
    case 'designer':
        console.log(firstName + ' design beautiiful website.');
        break;
    default:
        console.log(firstName + ' does something else');
}
</code>```

Body:
i have tried to delete ';' and retype case command but nothing happen and still just getting uncaught error. iam get this from tutorial please help iam so new for programming :)
can somebody tell me why the eror still poppin??
heres the code

//SWITCH STATEMMENT
var job = 'teacher';
switch (job) {
    case 'teacher';
    case 'instructor';
        console.log(firstName + ' teachs kids how to code.');
        break;
    case 'driver';
        console.log(firstName + ' drives an uber in Bekasi.');
        break;
    case 'designer';
        console.log(firstName + ' design beautiiful website.');
        break;
    default;
        console.log(firstName + ' does something else');
}

this is the code and the error on the console

Body:
You're using ; after your case "something" instead of :.

var job = 'teacher';
switch (job) {
    case 'teacher':
    case 'instructor':
        console.log(firstName + ' teachs kids how to code.');
        break;
    case 'driver':
        console.log(firstName + ' drives an uber in Bekasi.');
        break;
    case 'designer':
        console.log(firstName + ' design beautiiful website.');
        break;
    default:
        console.log(firstName + ' does something else');
}


问:
How to I add gradient color or image to Text in iPhone dev
I want to add a gradient color to my UILabel or any text on my iPhone screen. I want to know the ways to do it. Both Using interface and programatically.

tnx

答:
EDIT:

I expanded on my previous comment after all and created a little subclass of UILabel for this purpose. You can read about it here where you can also get the code.

This is the result:

Old reply:

Please see my reply to this question: How do I add a gradient to the text of a UILabel, but not the background?

Shows the code needed to achieve what you are after.


问:
How to get all the strings after a specific index?
Suppose I have this string: /ban 1d hello world which is essentially a command sended to a bot, meaning:

/ban specify to ban the user

1d represents the time

hello world is the reason

I need to get the reason, so I did:

let c = '/ban 1d hello world';
let arr = c.split(' ');
let result = c.replace(arr[0], '');
result = result.replace(arr[1], '')
alert(result);```

this is working, but I would like to ask if there is a better way to achieve this.

Kind regards.

答:
A regular expression is a good way to match a known format.
You can match against a slash \/ followed by two words separated by spaces \S+ \S+ and then match the remaining characters (.*).

let c = '/ban 1d hello world';
let match = /\/\S+ \S+ (.*)/.exec(c);
let result = match[1];
console.log(result);```

Body:
Suppose I have this string: /ban 1d hello world which is essentially a command sended to a bot, meaning:

/ban specify to ban the user

1d represents the time

hello world is the reason

I need to get the reason, so I did:

let c = '/ban 1d hello world';
let arr = c.split(' ');
let result = c.replace(arr[0], '');
result = result.replace(arr[1], '')
alert(result);

this is working, but I would like to ask if there is a better way to achieve this.

Kind regards.


问:
How to show exactly 4 numbers after decimal point without rounding in Python?
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers

```<code>num="%.4f" % num
</code>```

and this one doesn't show 1.0000 or numbers like this.

```<code>num=math.floor(num * 10000)/10000
</code>```

答:
Here is an option if you wish printing / just showing the 4 numbers after decimal point:

```<code> num = 0.553252
'{:.4f}'.format(num)
</code>```

You can find more information on presenting strings / values here -
https://pyformat.info/#number

Body:
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers

num="%.4f" % num

and this one doesn't show 1.0000 or numbers like this.

num=math.floor(num * 10000)/10000

Body:
Here is an option if you wish printing / just showing the 4 numbers after decimal point:

 num = 0.553252
'{:.4f}'.format(num)

You can find more information on presenting strings / values here -
https://pyformat.info/#number


问:
Why is getattr(self, "x") not the same as self.x in this example?
I found a case where getattr(self, "x") behaves different from self.x. Sorry about the length of the post - I didn't know how to reproduce the behavior without the PySide2 around. So with this example.qml file:

```<code>import QtQuick 2.10
import QtQuick.Controls 2.1
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3

ApplicationWindow {
    id: applicationWindow
    Material.theme: Material.Dark
    title: qsTr("Test Invoke")
    visible: true

    width: 600
    height: 500

    Slider {
        id: slider1
        x: 69
        y: 215
        value: Manager.xyz
        property bool updateValueWhileDragging: true
        onMoved: Manager.xyz = value
    }
}
</code>```

and this example.py file:

```<code>import sys
import os

from PySide2.QtCore import Qt, QObject, Signal, Slot, Property
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtWidgets import QSlider, QPushButton, QCheckBox

class Manager(QObject):
    xyz_slot = Signal()
    def __init__(self):
        QObject.__init__(self)
        self.__xyz = None
        self.xyz_slot.connect(self.on_xyz_changed)
        self.xyz = 0.3

    @Property(float, notify=xyz_slot) # (6)
    def xyz(self):
        # (1) This works
        # return self.__xyz
        # (2) This doesn't work and produces the error:
        # Error: 'Manager' object has no attribute '__xyz'
        return getattr(self, "__xyz")

    @xyz.setter
    def set_xyz(self, val):
        if self.__xyz == val:
            return
        self.__xyz = val
        self.xyz_slot.emit()

    @Slot()
    def on_xyz_changed(self):
        print(self.__xyz)

if __name__ == "__main__":
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    manager = Manager()
    ctx = engine.rootContext()
    ctx.setContextProperty("Manager", manager)
    engine.load('example.qml')
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
</code>```

using Python 3.7.

Why is the getattr (2) version not working?

Note that I need a version with the getattr because I want to decorate other classes. In that case it is not possible to use the dot-calling version.
In the documentation, there is an example that claims both to be the same. I can imagine that maybe the C++ code of PySide2 causes the difference. However I don't know how to proceed from here.

答:
Because you are using double-underscore name mangling.

From the docs

Notice that code passed to exec() or eval() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.

You probably don't need to use double-underscore name mangling so just don't use it.

Body:
I found a case where getattr(self, "x") behaves different from self.x. Sorry about the length of the post - I didn't know how to reproduce the behavior without the PySide2 around. So with this example.qml file:

import QtQuick 2.10
import QtQuick.Controls 2.1
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3

ApplicationWindow {
    id: applicationWindow
    Material.theme: Material.Dark
    title: qsTr("Test Invoke")
    visible: true

    width: 600
    height: 500

    Slider {
        id: slider1
        x: 69
        y: 215
        value: Manager.xyz
        property bool updateValueWhileDragging: true
        onMoved: Manager.xyz = value
    }
}

and this example.py file:

import sys
import os

from PySide2.QtCore import Qt, QObject, Signal, Slot, Property
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtWidgets import QSlider, QPushButton, QCheckBox

class Manager(QObject):
    xyz_slot = Signal()
    def __init__(self):
        QObject.__init__(self)
        self.__xyz = None
        self.xyz_slot.connect(self.on_xyz_changed)
        self.xyz = 0.3

    @Property(float, notify=xyz_slot) # (6)
    def xyz(self):
        # (1) This works
        # return self.__xyz
        # (2) This doesn't work and produces the error:
        # Error: 'Manager' object has no attribute '__xyz'
        return getattr(self, "__xyz")

    @xyz.setter
    def set_xyz(self, val):
        if self.__xyz == val:
            return
        self.__xyz = val
        self.xyz_slot.emit()

    @Slot()
    def on_xyz_changed(self):
        print(self.__xyz)

if __name__ == "__main__":
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    manager = Manager()
    ctx = engine.rootContext()
    ctx.setContextProperty("Manager", manager)
    engine.load('example.qml')
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

using Python 3.7.

Why is the getattr (2) version not working?

Note that I need a version with the getattr because I want to decorate other classes. In that case it is not possible to use the dot-calling version.
In the documentation, there is an example that claims both to be the same. I can imagine that maybe the C++ code of PySide2 causes the difference. However I don't know how to proceed from here.


问:
jQuery variable scope within each
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

```<code>  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });
</code>```

Many thanks for your time,

答: You're trying to make an object (new Object() or { }), not an array.

Title: jQuery variable scope within each

Body:
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });

Many thanks for your time,


问:
How to change line color based on data - chartist or chart.js
Been looking for a solution to this with either chartist or chart.js, but keep coming up empty. I'm looking for a way to create a line graph and change the color of the line based on the data.

Example data set:

```<code>[
    {time: '3:00:00', speed: 20, direction: 345},
    {time: '3:01:00', speed: 0, direction: 0},
    {time: '3:02:00', speed: 25, direction: 90},
    {time: '3:03:00', speed: 10, direction: 180},
    {time: '3:04:00', speed: 5, direction: 0}
]
</code>```

I'm looking for the time to be the x axis, the speed to be the y axis, and then to change the color of the line segment based on the direction. Seems like most of the charting libraries (unless I start digging into d3) when they create line graphs create one big line for the whole series and doesn't let you style the individual segments of the line. There's a great chartjs example here, but the color isn't based on the data (it's just an arbitrary set of colors):

https://blog.vanila.io/chart-js-tutorial-how-to-make-gradient-line-chart-af145e5c92f9

答: uminder has an interesting solution. In another thread, someone posted a solution which I went with - they just created an array of colors that's the same size as the dataset (and just feed that in with the data). That worked great and was much simpler than I think I was trying to make it.</p>

Body:
Been looking for a solution to this with either chartist or chart.js, but keep coming up empty. I'm looking for a way to create a line graph and change the color of the line based on the data.

Example data set:

[
    {time: '3:00:00', speed: 20, direction: 345},
    {time: '3:01:00', speed: 0, direction: 0},
    {time: '3:02:00', speed: 25, direction: 90},
    {time: '3:03:00', speed: 10, direction: 180},
    {time: '3:04:00', speed: 5, direction: 0}
]

I'm looking for the time to be the x axis, the speed to be the y axis, and then to change the color of the line segment based on the direction. Seems like most of the charting libraries (unless I start digging into d3) when they create line graphs create one big line for the whole series and doesn't let you style the individual segments of the line. There's a great chartjs example here, but the color isn't based on the data (it's just an arbitrary set of colors):

https://blog.vanila.io/chart-js-tutorial-how-to-make-gradient-line-chart-af145e5c92f9


问:
Executing .py file also runs another .py file
I have three files in one dir:

```<code># Untitled-1.py

print("UTITLEDPY")

if __name__== "__main__":
    from telegram.ext import Updater, CommandHandler, InlineQueryHandler
    import logging
    from telegram import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent
</code>```

and

```<code># test.py
import google_image_search

print("TESTPY")
</code>```

and this one

```<code># google_image_search.py

print("IMAGESPY")
</code>```

When I run python3 Untitled-1.py, I have the following output:

```<code>UTITLEDPY
IMAGESPY
TESTPY
</code>```

Please, explain why. The expected output is UTITLEDPY only.

[EDIT]

I added raise ValueError() to test.py:

```<code># test.py
import google_image_search

print("TESTPY")

raise ValueError()
</code>```

After that running python3 Untitled-1.py gives the following output:

```<code>UTITLEDPY
IMAGESPY
TESTPY
Traceback (most recent call last):
  File "Untitled-1.py", line 5, in <module>
    from telegram.ext import Updater, CommandHandler, InlineQueryHandler
  File "/usr/local/lib/python3.7/site-packages/telegram/__init__.py", line 47, in <module>
    from .files.file import File
  File "/usr/local/lib/python3.7/site-packages/telegram/files/file.py", line 24, in <module>
    from future.backports.urllib import parse as urllib_parse
  File "/usr/local/lib/python3.7/site-packages/future/backports/__init__.py", line 14, in <module>
    import_top_level_modules()
  File "/usr/local/lib/python3.7/site-packages/future/standard_library/__init__.py", line 810, in import_top_level_modules
    with exclude_local_folder_imports(*TOP_LEVEL_MODULES):
  File "/usr/local/lib/python3.7/site-packages/future/standard_library/__init__.py", line 781, in __enter__
    module = __import__(m, level=0)
  File "/Users/arturzielinski/Desktop/ibodi_bot/test.py", line 5, in <module>
    raise ValueError()
ValueError
</code>```

[EDIT2]

Renaming test.py to test1.py solved the issue. I now get the expected output.

Body:
I have three files in one dir:

# Untitled-1.py

print("UTITLEDPY")

if __name__== "__main__":
    from telegram.ext import Updater, CommandHandler, InlineQueryHandler
    import logging
    from telegram import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent

and

# test.py
import google_image_search

print("TESTPY")

and this one

# google_image_search.py

print("IMAGESPY")

When I run python3 Untitled-1.py, I have the following output:

UTITLEDPY
IMAGESPY
TESTPY

Please, explain why. The expected output is UTITLEDPY only.

[EDIT]

I added raise ValueError() to test.py:

# test.py
import google_image_search

print("TESTPY")

raise ValueError()

After that running python3 Untitled-1.py gives the following output:

UTITLEDPY
IMAGESPY
TESTPY
Traceback (most recent call last):
  File "Untitled-1.py", line 5, in <module>
    from telegram.ext import Updater, CommandHandler, InlineQueryHandler
  File "/usr/local/lib/python3.7/site-packages/telegram/__init__.py", line 47, in <module>
    from .files.file import File
  File "/usr/local/lib/python3.7/site-packages/telegram/files/file.py", line 24, in <module>
    from future.backports.urllib import parse as urllib_parse
  File "/usr/local/lib/python3.7/site-packages/future/backports/__init__.py", line 14, in <module>
    import_top_level_modules()
  File "/usr/local/lib/python3.7/site-packages/future/standard_library/__init__.py", line 810, in import_top_level_modules
    with exclude_local_folder_imports(*TOP_LEVEL_MODULES):
  File "/usr/local/lib/python3.7/site-packages/future/standard_library/__init__.py", line 781, in __enter__
    module = __import__(m, level=0)
  File "/Users/arturzielinski/Desktop/ibodi_bot/test.py", line 5, in <module>
    raise ValueError()
ValueError

[EDIT2]

Renaming test.py to test1.py solved the issue. I now get the expected output.


问:
what is the use of route 53 in aws when ISPs can also route traffic into our instances
I know route 53 can route dns traffic into our instances . but  why specially need to use route 53 when ISPs  can also provide same routing.</p>

答:
You don't need to use route 53, especially if you are just, for example, routing http/https traffic to your web application - any dns provider will work just fine.

I have about 1/2 my domains with AWS, and 1/2 still outside - some of the aws specific features are easier if the domain is within AWS, but most of the time it really doesn't matter much at all - but more and more I am moving them into AWS just to keep the billing simpler (one bill).


Title: How to show exactly 4 numbers after decimal point without rounding in Python?

Body:
Try this:

>>> num = 5.12129
>>> num = f'{num:.5f}'[:-1]
>>> num
'5.1212'


问:
Create a dictionary inside nested lists
Can someone explain how can I construct a dictionary inside lists? For example, I have this dictionary:

```<code>A = {'typeA': [12], 'typeB': [12, 13]}
</code>```

and I want to get this:

```<code>A = {'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}
</code>```

I have tried something like this:

```<code>listFinal = []
for key in A.keys
---- newDict = {}
---- for value in A[key]:
--------- newDict[value] = []
newDict[key].append(value)
</code>```

But this isn't right...
This can be a little confusing and I believe it isn't that elegant. I'm sorry if this isn't a relevant question.

答:
You can do it with dict comprehensions

```<code>a = {key: [{v: []} for v in A[key]] for key in A.keys()}

# outout {'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}
</code>```

Another version

```<code>a = {key: [{v: []} for v in value] for key, value in A.items()}
</code>```

Title: Create a dictionary inside nested lists

Body:
Can someone explain how can I construct a dictionary inside lists? For example, I have this dictionary:

A = {'typeA': [12], 'typeB': [12, 13]}

and I want to get this:

A = {'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}

I have tried something like this:

listFinal = []
for key in A.keys
---- newDict = {}
---- for value in A[key]:
--------- newDict[value] = []
newDict[key].append(value)

But this isn't right...
This can be a little confusing and I believe it isn't that elegant. I'm sorry if this isn't a relevant question.

Body:
You can do it with dict comprehensions

a = {key: [{v: []} for v in A[key]] for key in A.keys()}

# outout {'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}

Another version

a = {key: [{v: []} for v in value] for key, value in A.items()}


问:
how can i get the selected item in tableview pyqt4
how can i get or print clicked item in a tableview?
here is sample code</p>

```<code>def connectSlots(self):
    # this does not work ..
    QtCore.QObject.connect(self.tableView, QtCore.SIGNAL("clicked(const QModelIndex&"), self._onClick)
    QtCore.QObject.connect(self.tableView, QtCore.SIGNAL("clicked(QModelIndex"), self._onClick)

def _onClick(self, *args):
    print "_onClick", args
</code>```

答:
i found the answer :)

```<code>def connectSlots(self):
    QtCore.QObject.connect(self.ui.tableView, QtCore.SIGNAL("clicked(QModelIndex)"), self.cellClicked)

def cellClicked( self, qmodelindex ):
    self.item = qmodelindex.data(QtCore.Qt.DisplayRole).toString()
    print self.item
</code>```

this will get and print the items that was clicked in the qtableview
just got hard time searching for examples

thx Stephen ..

Body:
how can i get or print clicked item in a tableview?
here is sample code

def connectSlots(self):
    # this does not work ..
    QtCore.QObject.connect(self.tableView, QtCore.SIGNAL("clicked(const QModelIndex&"), self._onClick)
    QtCore.QObject.connect(self.tableView, QtCore.SIGNAL("clicked(QModelIndex"), self._onClick)

def _onClick(self, *args):
    print "_onClick", args

Body:
i found the answer :)

def connectSlots(self):
    QtCore.QObject.connect(self.ui.tableView, QtCore.SIGNAL("clicked(QModelIndex)"), self.cellClicked)

def cellClicked( self, qmodelindex ):
    self.item = qmodelindex.data(QtCore.Qt.DisplayRole).toString()
    print self.item

this will get and print the items that was clicked in the qtableview
just got hard time searching for examples

thx Stephen ..


问:
Could not attach to pid : “41851”?
When running app in iOS simulator through Xcode 7.3. It's giving error with message - Could not attach to pid : “41851”. </p>

答:
Try running this in the terminal:</p>

```<code>sudo DevToolsSecurity -enable
</code>```

Title: Could not attach to pid : “41851”?

Body:
Try running this in the terminal:

sudo DevToolsSecurity -enable


问:
Compile Unreal Lightmass. Error with Unreal 4.24 build from source on Linux
I get the following error when I am trying to build a project in Unreal, that I have included some lightning. "Lighting Build Failed. Swarm failed to Kick off. Compile Unreal Lightmass".

I have build Unreal Engine 4.24.1 from source on Linux with the setup instructions from the documentations.

Any ideas how to proceed. How would I go and compile Unreal Lightmass for the Engine?

答:
If you did the full source build setup process, Lightmass should have compiled as well. Here is a probably-foolproof solution:

Run Setup.sh

Run GenerateProjectFiles.sh

Once the Visual Studio .sln is finished generating, open that.

Wait for the option to appear, then (Toolbar) Build->Build Solution

The UEBuildTool should then compile everything in the project, including Lightmass.


问:
Define generic decoder in scala using circe

I'm trying to switch my JsonUtils class from Json4s to circe
and i find it hard to solve the generic implementation for the decoder.

my Json4s func look like this:

```<code>implicit val formats = DefaultFormats
  def extractValueFromJson[T](json: String, key: String)(implicit m: Manifest[T]): T = {
    val parsed = parse(json).asInstanceOf[JObject]
    val value =(parsed \ key).extract[T]
    value
  }
</code>```

example of usage:

```<code>extractValueFromJson[String](jsonStr, keyInJson)
</code>```

and it is working perfectly

now i have tried the same func with circe:

```<code> implicit def decodeGeneric[A: Decoder](json: Json): Either[Error, A] = Decoder[A].decodeJson(json)
    def extractValueFromJson[A: ClassTag, T](jsonStr: String, key: String)(implicit m: Manifest[T]): T = {
            val json: String = jsonStr.asJson.noSpaces
            decode[A](json) match {
              case Left(error: Error) => throw error
              case Right(value) => {
                value.getClass.getDeclaredField(key).get(value).asInstanceOf[T]
              }
            }
          }
</code>```

and i get the following error while compiling:

```<code>could not find implicit value for evidence parameter of type io.circe.Decoder[A]
[error]         decode[A](json) match {
[error]                  ^
</code>```

This is the desired output for a given input

input:

```<code>case class Bar(str: String)
val bar = Bar("just a string")
</code>```

usage:

```<code>val test = extractValueFromJson[Bar,String](bar.asJson.noSpaces,"str")
</code>```

output:

```<code>just a string
</code>```

What am i doing wrong here?
Is there a way to define a generic decoder?
i have read some similar questions here but haven't found a solution that fit my needs

答:
You can do this:

```<code>def extractValueFromJson[A](jsonStr: String, key: String)(implicit decoder: Decoder[A]): A =
  io.circe.parser.decode(jsonStr)(decoder.at(field = key)) match {
    case Right(result) => result
    case Left(error) => throw error
  }
</code>```

Which you can use like this:

```<code>extractValueFromJson[String](jsonStr = bar.asJson.noSpaces, key = "str")
// res: String = "just a string"
</code>```

Body:
I'm trying to switch my JsonUtils class from Json4s to circe
and i find it hard to solve the generic implementation for the decoder.

my Json4s func look like this:

implicit val formats = DefaultFormats
  def extractValueFromJson[T](json: String, key: String)(implicit m: Manifest[T]): T = {
    val parsed = parse(json).asInstanceOf[JObject]
    val value =(parsed \ key).extract[T]
    value
  }

example of usage:

extractValueFromJson[String](jsonStr, keyInJson)

and it is working perfectly

now i have tried the same func with circe:

 implicit def decodeGeneric[A: Decoder](json: Json): Either[Error, A] = Decoder[A].decodeJson(json)
    def extractValueFromJson[A: ClassTag, T](jsonStr: String, key: String)(implicit m: Manifest[T]): T = {
            val json: String = jsonStr.asJson.noSpaces
            decode[A](json) match {
              case Left(error: Error) => throw error
              case Right(value) => {
                value.getClass.getDeclaredField(key).get(value).asInstanceOf[T]
              }
            }
          }

and i get the following error while compiling:

could not find implicit value for evidence parameter of type io.circe.Decoder[A]
[error]         decode[A](json) match {
[error]                  ^

This is the desired output for a given input

input:

case class Bar(str: String)
val bar = Bar("just a string")

usage:

val test = extractValueFromJson[Bar,String](bar.asJson.noSpaces,"str")

output:

just a string

What am i doing wrong here?
Is there a way to define a generic decoder?
i have read some similar questions here but haven't found a solution that fit my needs

Body:
You can do this:

def extractValueFromJson[A](jsonStr: String, key: String)(implicit decoder: Decoder[A]): A =
  io.circe.parser.decode(jsonStr)(decoder.at(field = key)) match {
    case Right(result) => result
    case Left(error) => throw error
  }

Which you can use like this:

extractValueFromJson[String](jsonStr = bar.asJson.noSpaces, key = "str")
// res: String = "just a string"


答:
i hope this will meet your requirement</p>

```<code>A = {'typeA': [12], 'typeB': [12, 13]}
result = {}
for item in A.items():
    result[item[0]] = [dict.fromkeys(item[1], [])]
print(result)
# {'typeA': [{12: []}], 'typeB': [{12: [], 13: []}]}
</code>```

Title: Create a dictionary inside nested lists

Body:
i hope this will meet your requirement

A = {'typeA': [12], 'typeB': [12, 13]}
result = {}
for item in A.items():
    result[item[0]] = [dict.fromkeys(item[1], [])]
print(result)
# {'typeA': [{12: []}], 'typeB': [{12: [], 13: []}]}


问:
WebAssembly language with small footprint
I'm looking for a language that is compiled to wasm (or to something else that's not human-readable and run through web assembly, like a dll), with a small footprint. I need to be able to interact with it from javascript.

What I need it for is to perform hashing of a string in a way a user wouldn't be able to easily figure out. I know anything that runs on the client is not secure, but it's a deterrent, not a security feature (like a captcha).

I have already done this with Blazor, but the download size is too large, so I'm looking for something that has a smaller footprint.

Thanks!

答:
One lightweight way to target WebAssebmly is https://github.com/AssemblyScript/assemblyscript.   It's low level but more easy to write that raw WebAssembly.    if you are careful to avoid dependencies on the larger parts of libc, then emscripten can also produce very small binary files.

However, if your goal is obfuscation then WebAssebmly is really not better than JavaScript.  WebAssembly was not designed for this purpose.  As with something like the JVM bytecode there are tools out there are do good job of decompiling WebAssembly binaries.  See wasm-deompile which is part of https://github.com/WebAssembly/wabt.  These tools will only get better over time.


问:
How to Check If a Value Already Exists in a Text Field in Javascript
I have a set of users. Each time the delete button is click it is added up to the input text field which I already implemented. If the users is already on the deleted_user field, how can I display the remaining unselected users.

Ex. If Jan and Mike are already on deleted_user field. Next is clicking the submit users button, only Sam will appear

```<code>        <td><button onclick="deleteVal('Jan');" > Delete </button></td>
        <td><input type="text" name="users[]" value="Jan"> </td>

        <td><button onclick="deleteVal('Mike');"> Delete </button></td>
        <td> <input type="text" name="users[]" value="Mike"> </td>

        <td><button onclick="deleteVal('Sam');"> Delete </button></td>
        <td> <input type="text" name="users[]" value="Sam"> </td>

Deleted Users: <input type="text" id="deleted_user">

<button type="button" id="submit_users"> Submit Users </button>
Final Users:<input type="text" id="final_users">
</code>```

This is my code.

```<code> function deleteVal(val) {
    var delete_id = val;
    var deleted_user = document.getElementById('deleted_user').value

    if(!deleted_user.includes(delete_id)) {
       var tempVal = document.getElementById('deleted_user').value += val + ',';
    }
  }
</code>```

答:
I used pure Javascript:

function deleteVal(val) {
 var delete_id = val;
    var deleted_user = document.getElementById('deleted_user').value;

    if(!deleted_user.includes(delete_id)) {
       var tempVal = document.getElementById('deleted_user').value += val + ',';
       for(var j=0; j<list.length; j++){
         if(list[j]==delete_id){
           list[j]=null;
            document.getElementById('final_users').value=list.join(" ");
          }
       }
    }
  }
  var list=[];
 for(var i=0; i<document.querySelectorAll(".names").length; i++){
  list[i] =document.querySelectorAll(".names")[i].value;
 }
document.getElementById('final_users').value=list.join(" ");

function checker(){
  for(k=0; k<list.length; k++){
    if(list[k]!=null){
      alert("There are remaining unselected users : "+list.join(" "));
      return;
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <td><button onclick="deleteVal('Jan');" > Delete </button></td>
        <td><input class="names" type="text" name="users[]" value="Jan"> </td>

        <td><button onclick="deleteVal('Mike');"> Delete </button></td>
        <td> <input class="names" type="text" name="users[]" value="Mike"> </td>

        <td><button onclick="deleteVal('Sam');"> Delete </button></td>
        <td> <input class="names" type="text" name="users[]" value="Sam"> </td>

Deleted Users: <input type="text" id="deleted_user">

<button onclick="checker()" type="button" id="submit_users"> Submit Users </button>
Final Users:<input type="text" id="final_users"></code>```

That is what I understood.

Body:
I have a set of users. Each time the delete button is click it is added up to the input text field which I already implemented. If the users is already on the deleted_user field, how can I display the remaining unselected users.

Ex. If Jan and Mike are already on deleted_user field. Next is clicking the submit users button, only Sam will appear

        <button onclick="deleteVal('Jan');" > Delete </button>
        <input type="text" name="users[]" value="Jan">

        <button onclick="deleteVal('Mike');"> Delete </button>
         <input type="text" name="users[]" value="Mike">

        <button onclick="deleteVal('Sam');"> Delete </button>
         <input type="text" name="users[]" value="Sam">

Deleted Users: <input type="text" id="deleted_user">

<button type="button" id="submit_users"> Submit Users </button>
Final Users:<input type="text" id="final_users">

This is my code.

 function deleteVal(val) {
    var delete_id = val;
    var deleted_user = document.getElementById('deleted_user').value

    if(!deleted_user.includes(delete_id)) {
       var tempVal = document.getElementById('deleted_user').value += val + ',';
    }
  }

Body:
I used pure Javascript:

function deleteVal(val) {
 var delete_id = val;
    var deleted_user = document.getElementById('deleted_user').value;

    if(!deleted_user.includes(delete_id)) {
       var tempVal = document.getElementById('deleted_user').value += val + ',';
       for(var j=0; j<list.length; j++){
         if(list[j]==delete_id){
           list[j]=null;
            document.getElementById('final_users').value=list.join(" ");
          }
       }
    }
  }
  var list=[];
 for(var i=0; i<document.querySelectorAll(".names").length; i++){
  list[i] =document.querySelectorAll(".names")[i].value;
 }
document.getElementById('final_users').value=list.join(" ");

function checker(){
  for(k=0; k<list.length; k++){
    if(list[k]!=null){
      alert("There are remaining unselected users : "+list.join(" "));
      return;
    }
  }
}

        <td><button onclick="deleteVal('Jan');" > Delete </button></td>
        <td><input class="names" type="text" name="users[]" value="Jan"> </td>

        <td><button onclick="deleteVal('Mike');"> Delete </button></td>
        <td> <input class="names" type="text" name="users[]" value="Mike"> </td>

        <td><button onclick="deleteVal('Sam');"> Delete </button></td>
        <td> <input class="names" type="text" name="users[]" value="Sam"> </td>

Deleted Users: <input type="text" id="deleted_user">

<button onclick="checker()" type="button" id="submit_users"> Submit Users </button>
Final Users:<input type="text" id="final_users">

That is what I understood.