问:
Cursor Array into ListView but multiple columns
I currently get cursor data via a database query, put each selection into an array to then show in one of my three list views.

```<code>public void insertData() {
    ListView listView = (ListView) findViewById(R.id.listWorkouts1);
    ListView listView2 = (ListView) findViewById(R.id.listWorkouts2);
    ListView listView3 = (ListView) findViewById(R.id.listWorkouts3);
    SQLiteController db = new SQLiteController(this);
    String username = ma.id;
    //populate an ArrayList<String> from the database and then view it
    ArrayList<String> theList1 = new ArrayList<>();
    ArrayList<String> theList2 = new ArrayList<>();
    ArrayList<String> theList3 = new ArrayList<>();
    ArrayList<String> finalList = new ArrayList<>();
    Cursor data = db.getUserListContents(username);

    if (data.getCount() == 0) {
        Toast.makeText(this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            theList1.add(data.getString(0));
            theList2.add(data.getString(1));
            theList3.add(data.getString(2));

            ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList1);
            listView.setAdapter(listAdapter);

            ListAdapter listAdapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList2);
            listView2.setAdapter(listAdapter2);

            ListAdapter listAdapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList3);
            listView3.setAdapter(listAdapter3);
        }
    }
}
</code>```

The issue is the user can separately scroll through each of the three listviews.

How can I only use one listView but separate the data to be seen in separate columns?

At default, it lists everything under the previous value.

Each While loop performed I want that data to be shown on the same line, not one under the other.

Any help is appreciated.

答:
You can use RecyclerView with a GridLayoutManager in your case. Here is a basic implementation example. You can also look into this tutorial as well.

Instead of separate lists, you can actually create an object and pass the list of that object into your adapter to load the items from there. For example, consider the following class.

```<code>public class Workout {
    public String name;
    public String date;
    public String weight;
}
</code>```

Now when reading values from the cursor, create an object of Workout class and create a List<Workout> and then modify your adapter to pass this list.

I hope I could give you an idea of implementing this gracefully.

Body:
I currently get cursor data via a database query, put each selection into an array to then show in one of my three list views.

public void insertData() {
    ListView listView = (ListView) findViewById(R.id.listWorkouts1);
    ListView listView2 = (ListView) findViewById(R.id.listWorkouts2);
    ListView listView3 = (ListView) findViewById(R.id.listWorkouts3);
    SQLiteController db = new SQLiteController(this);
    String username = ma.id;
    //populate an ArrayList<String> from the database and then view it
    ArrayList<String> theList1 = new ArrayList<>();
    ArrayList<String> theList2 = new ArrayList<>();
    ArrayList<String> theList3 = new ArrayList<>();
    ArrayList<String> finalList = new ArrayList<>();
    Cursor data = db.getUserListContents(username);

    if (data.getCount() == 0) {
        Toast.makeText(this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            theList1.add(data.getString(0));
            theList2.add(data.getString(1));
            theList3.add(data.getString(2));

            ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList1);
            listView.setAdapter(listAdapter);

            ListAdapter listAdapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList2);
            listView2.setAdapter(listAdapter2);

            ListAdapter listAdapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList3);
            listView3.setAdapter(listAdapter3);
        }
    }
}

The issue is the user can separately scroll through each of the three listviews.

How can I only use one listView but separate the data to be seen in separate columns?

At default, it lists everything under the previous value.

Each While loop performed I want that data to be shown on the same line, not one under the other.

Any help is appreciated.

Body:
You can use RecyclerView with a GridLayoutManager in your case. Here is a basic implementation example. You can also look into this tutorial as well.

Instead of separate lists, you can actually create an object and pass the list of that object into your adapter to load the items from there. For example, consider the following class.

public class Workout {
    public String name;
    public String date;
    public String weight;
}

Now when reading values from the cursor, create an object of Workout class and create a List<Workout> and then modify your adapter to pass this list.

I hope I could give you an idea of implementing this gracefully.


来源: stackexchange

问:
Request throwing An existing connection was forcibly closed by the remote host only on C# request
I'm having a hard time trying to consume a REST service from Cielo (credit/debit card gateway company). If I use postman it works:

```<code>POST /1/sales/ HTTP/1.1
Host: apisandbox.cieloecommerce.cielo.com.br
MerchantKey: my_key
Content-Type: application/json
MerchantId: merc_id
Cache-Control: no-cache
Postman-Token: 6643cc5a-173a-f5db-8924-85ea8b7bbb55

{"MerchantId":"00000000-0000-0000-0000-000000000000","MerchantKey":null,"RequestId":"00000000-0000-0000-0000-000000000000","MerchantOrderId":"1223","Customer":{"Name":"Emerson Fitchy"},"Payment":{"PaymentId":"00000000-0000-0000-0000-000000000000","Type":"CreditCard","Amount":15700,"Installments":1,"Provider":null,"ProofOfSale":null,"Tid":null,"AuthorizationCode":null,"SoftDescriptor":null,"ECI":null,"Status":0,"ReturnCode":null,"ReturnMessage":null,"CreditCard":{"CardNumber":"0000000000000001","Holder":"Emerson Fitchy Santis","ExpirationDate":"12/2022","SecurityCode":"154","Brand":"Visa"}}}
</code>```

And this is the C# code (at the moment, I tried also with RestSharp and HttpClient with the same results):

```<code>var webrequest = (HttpWebRequest)WebRequest.Create(Constants.Cielo.GetSalesUrl());

webrequest.ContentType = "application/json";
webrequest.Method = "POST";
webrequest.Headers.Add("MerchantId", Constants.Cielo.Sandbox.MerchantId.ToString());
webrequest.Headers.Add("MerchantKey", Constants.Cielo.Sandbox.MerchantKey);

using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
    var json = JsonConvert.SerializeObject(sale);
    streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
    var x = result;
}
</code>```

Any ideas on what am I doing wrong? I tried using Fiddler 4 but it's not picking up this request (I don't know why) and WireShark picks it up, but doesn't show the information the way Fiddler does (Maybe it's because I'm using https?).

Any ideas?

Thanks!

EDIT

Response/Exception

答:
I just had the same issue where I suddenly was unable to make calls to a specific website from a Windows Server where I was running a console application on .NET 4.7.2. I was able to make the call in Postman from the same machine, but started getting the An existing connection was forcibly closed by the remote host.

It turns out that the sever had TLS 1.2 disabled. I was able to resolve it following the steps in this answer. I still am not sure if this setting was changed on the server or if the website started enforcing it, but it resolved the issue for me.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a hard time trying to consume a REST service from Cielo (credit/debit card gateway company). If I use postman it works:

POST /1/sales/ HTTP/1.1
Host: apisandbox.cieloecommerce.cielo.com.br
MerchantKey: my_key
Content-Type: application/json
MerchantId: merc_id
Cache-Control: no-cache
Postman-Token: 6643cc5a-173a-f5db-8924-85ea8b7bbb55

{"MerchantId":"00000000-0000-0000-0000-000000000000","MerchantKey":null,"RequestId":"00000000-0000-0000-0000-000000000000","MerchantOrderId":"1223","Customer":{"Name":"Emerson Fitchy"},"Payment":{"PaymentId":"00000000-0000-0000-0000-000000000000","Type":"CreditCard","Amount":15700,"Installments":1,"Provider":null,"ProofOfSale":null,"Tid":null,"AuthorizationCode":null,"SoftDescriptor":null,"ECI":null,"Status":0,"ReturnCode":null,"ReturnMessage":null,"CreditCard":{"CardNumber":"0000000000000001","Holder":"Emerson Fitchy Santis","ExpirationDate":"12/2022","SecurityCode":"154","Brand":"Visa"}}}

And this is the C# code (at the moment, I tried also with RestSharp and HttpClient with the same results):

var webrequest = (HttpWebRequest)WebRequest.Create(Constants.Cielo.GetSalesUrl());

webrequest.ContentType = "application/json";
webrequest.Method = "POST";
webrequest.Headers.Add("MerchantId", Constants.Cielo.Sandbox.MerchantId.ToString());
webrequest.Headers.Add("MerchantKey", Constants.Cielo.Sandbox.MerchantKey);

using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
    var json = JsonConvert.SerializeObject(sale);
    streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
    var x = result;
}

Any ideas on what am I doing wrong? I tried using Fiddler 4 but it's not picking up this request (I don't know why) and WireShark picks it up, but doesn't show the information the way Fiddler does (Maybe it's because I'm using https?).

Any ideas?

Thanks!

EDIT

Response/Exception

ContentLicense: CC BY-SA 4.0


问:
Postman and Browser have different behavior with my middleware
I'm getting into the backend with Node and express , I wanted to create a middleware that show on the console that the route was not found if you try to do a request to a route that does not exist , so I did this way

```<code>server.get('/' , (req,res) => {
    res.render('index.html')
})

server.use((req,res,next) => {
    console.log('NOT FOUND')
})

</code>```

If i'm not wrong , this middleware should just execute if I do the request to a route that is not / since it is the only that exist , and when I try in postman it have exactly the behavior that it should , but when I try on the browser it execute the middleware even if the request is to / and my view is render and sometimes it even execute it two times and it show NOT FOUND two times on the console

I don't know why Postman and the Browser are doing different things , Am I doing something wrong?

Thanks for the help

答:
There is not a lot of information here, but my best guess would be that maybe index.html references som other resources (js,css, favicon, ++) that it tries to load, but it does not find.
Whereas postman does not try to load these resources?

Update:
as per OPs comment, to "disable" favicons, have a look at this post:
How to prevent favicon.ico requests?

Body:
I'm getting into the backend with Node and express , I wanted to create a middleware that show on the console that the route was not found if you try to do a request to a route that does not exist , so I did this way

server.get('/' , (req,res) => {
    res.render('index.html')
})

server.use((req,res,next) => {
    console.log('NOT FOUND')
})

If i'm not wrong , this middleware should just execute if I do the request to a route that is not / since it is the only that exist , and when I try in postman it have exactly the behavior that it should , but when I try on the browser it execute the middleware even if the request is to / and my view is render and sometimes it even execute it two times and it show NOT FOUND two times on the console

I don't know why Postman and the Browser are doing different things , Am I doing something wrong?

Thanks for the help


问:
Why, when adding two or more identical objects to state in a row, they always generate the same key?
I'm learning React and i'm stuck on this problem. I've looked for answers but couldn't find why this exact thing was happening.

When i fill in a form and submit it, a new object gets added to the state. No matter how i generate random key (for example in code below i do it with date object and getTime method), when i add two or more identical objects to the state in a row (one exactly after the other), they always generate the same key, same with math.random and all other methods i've tried.

If i add one object and then change any data even a little bit and add another and then add the same as the first one, everything works perfectly. The only problem is when i try to add the same ones in a row.

By identical objects i mean that all their {key: value} pairs contain the same data and they have the same keys.

This is how my state objects like like:

```<code>state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }
</code>```

Note that when i have this initial state already hard coded, when i add a new object that's the same as the 3rd one, the error doesn't occur. It's just when creating new ones.

newDmd object that is passed to addDmd method would not have id at first and would look like this:

```<code>{name: 'john', age: 22, rich: 'yes'}
</code>```

Method used to change state:

```<code>  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }
</code>```

The image below is to show you when the keys become the same (my key is 'id'). You can see that on the last 3 additions, the key is the same, starting to repeat after the second one:

I don't have enough reputation points to post an image, so here's a link: https://i.imgur.com/WQrVHlp.png

I would like to know:

Why this happens

How to fix this

Best practices regarding changing state and generating unique keys

Edit:
Adding code from where addDmd method is called.

```<code>class AddDmd extends Component {
    state = {
        name: null,
        age: null,
        rich: null
    };

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addDmd(this.state);
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="name">Name:</label>
                    <input type="text" id="name" onChange={this.handleChange}></input>
                    <label htmlFor="age">Age:</label>
                    <input type="text" id="age" onChange={this.handleChange}></input>
                    <label htmlFor="rich">rich?:</label>
                    <input type="text" id="rich" onChange={this.handleChange}></input>
                    <button>Submit</button>
                </form>
            </div>
        )
    }
}
</code>```

Edit 2: added full code of class where addDmd method resides.

```<code>class App extends Component {
  state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }

  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }

  render() {
    return (
      <div className="App" >
        <AddDmd addDmd={this.addDmd} />
      </div>
    );
  }
}
</code>```

答:
Most likely your issue is related to accidental mutation of nested objects by reference.

1. Why this happens:

I can only speculate for now. If you want to share the usage of addDmd I can confirm. I believe newDmd is populated from a previous entry. Which means doing newDmd.id =  will mutate both objects in state.

You can confirm this yourself by checking the id each time a new entry is added. The new id should be different since its based on time, but watch and see if the previous entries are changing along with it.

2. How to fix it:

Change your function to this so that it makes deep copies of the state:

addDmd = (newDmd) => {
  newDmd.id = new Date().getTime();
  let newArray = [...this.state.dmd.map(nestedObj => ({...nestedObj})), newDmd];
  this.setState({
    dmd: newArray
  });
}
```
<p><strong>3. Best practices:</strong></p>
<p>As far as I can tell your method of generating unique keys should work fine. The best practice I would recommend is to make sure you make deep copies of state when necessary.</p>
<h2>Update</h2>
<p>I was pretty close. The issue is you're passing <code>this.state</code> directly to <code>addDmd</code>. <code>this.state</code> gets a new object reference every time the component re-renders, but if you don't change any values in the form and submit again - it doesn't need to re-render. This means you pass <code>addDmd</code> the same object reference.</p>
<p>Simple fix:</p>
<pre class="lang-js prettyprint-override"><code>handleSubmit = (e) => {
  e.preventDefault();
  this.props.addDmd({...this.state}); // Create new object out of state
}
</code>```

Now you can submit the same form as many times as you want and it will always submit a new object reference and will not mutate the previous submission.

Body:
I'm learning React and i'm stuck on this problem. I've looked for answers but couldn't find why this exact thing was happening.

When i fill in a form and submit it, a new object gets added to the state. No matter how i generate random key (for example in code below i do it with date object and getTime method), when i add two or more identical objects to the state in a row (one exactly after the other), they always generate the same key, same with math.random and all other methods i've tried.

If i add one object and then change any data even a little bit and add another and then add the same as the first one, everything works perfectly. The only problem is when i try to add the same ones in a row.

By identical objects i mean that all their {key: value} pairs contain the same data and they have the same keys.

This is how my state objects like like:

state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }

Note that when i have this initial state already hard coded, when i add a new object that's the same as the 3rd one, the error doesn't occur. It's just when creating new ones.

newDmd object that is passed to addDmd method would not have id at first and would look like this:

{name: 'john', age: 22, rich: 'yes'}

Method used to change state:

  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }

The image below is to show you when the keys become the same (my key is 'id'). You can see that on the last 3 additions, the key is the same, starting to repeat after the second one:

I don't have enough reputation points to post an image, so here's a link: https://i.imgur.com/WQrVHlp.png

I would like to know:

Why this happens

How to fix this

Best practices regarding changing state and generating unique keys

Edit:
Adding code from where addDmd method is called.

class AddDmd extends Component {
    state = {
        name: null,
        age: null,
        rich: null
    };

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addDmd(this.state);
    }

    render() {
        return (

                <form onSubmit={this.handleSubmit}>
                    Name:
                    <input type="text" id="name" onChange={this.handleChange}></input>
                    Age:
                    <input type="text" id="age" onChange={this.handleChange}></input>
                    rich?:
                    <input type="text" id="rich" onChange={this.handleChange}></input>
                    <button>Submit</button>
                </form>

        )
    }
}

Edit 2: added full code of class where addDmd method resides.

class App extends Component {
  state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }

  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }

  render() {
    return (

        <AddDmd addDmd={this.addDmd} />

    );
  }
}

Body:
Most likely your issue is related to accidental mutation of nested objects by reference.

1. Why this happens:

I can only speculate for now. If you want to share the usage of addDmd I can confirm. I believe newDmd is populated from a previous entry. Which means doing newDmd.id =  will mutate both objects in state.

You can confirm this yourself by checking the id each time a new entry is added. The new id should be different since its based on time, but watch and see if the previous entries are changing along with it.

2. How to fix it:

Change your function to this so that it makes deep copies of the state:

addDmd = (newDmd) => {
  newDmd.id = new Date().getTime();
  let newArray = [...this.state.dmd.map(nestedObj => ({...nestedObj})), newDmd];
  this.setState({
    dmd: newArray
  });
}

3. Best practices:

As far as I can tell your method of generating unique keys should work fine. The best practice I would recommend is to make sure you make deep copies of state when necessary.

Update

I was pretty close. The issue is you're passing this.state directly to addDmd. this.state gets a new object reference every time the component re-renders, but if you don't change any values in the form and submit again - it doesn't need to re-render. This means you pass addDmd the same object reference.

Simple fix:

handleSubmit = (e) => {
  e.preventDefault();
  this.props.addDmd({...this.state}); // Create new object out of state
}

Now you can submit the same form as many times as you want and it will always submit a new object reference and will not mutate the previous submission.


问:
How would I vectorize a function in pandas that returns a list?
I've been reading about how to optimize pandas code for speed, and I'm trying to refactor my code, changing from iterrows() to vectorization. Here is an example of the old code and its result:

Old Code

```<code>import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
for index, row in df.iterrows():
    df.at[index,"repeatedAsList"] = repeatAsList(row['values'])
df
</code>```

Old Result

```<code>+--------+----------------+
| values | repeatedAsList |
+--------+----------------+
|      1 | [1, 1]         |
|      2 | [2, 2]         |
|      3 | [3, 3]         |
+--------+----------------+
</code>```

New Code

```<code>import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
df["repeatedAsList"] = repeatAsList(df["values"])
</code>```

New Result

```<code>ValueError: Length of values does not match length of index
</code>```

I'd like to understand why the new code above fails, and if it's possible to run a different way and achieve speed improvements from the old code. I feel like I'm missing a key point of vectorization, and it would be nice to learn why the values have to be scalar.

答:
You could try map:

```<code>df['repeatedAsList'] = list(map(lambda x: [x,x], df['values'].values))
#df['repeatedAsList'] = list(map(lambda x: [x,x], df['values']) #seems slow

   values repeatedAsList
0       1         [1, 1]
1       2         [2, 2]
2       3         [3, 3]
</code>```

Body:
I've been reading about how to optimize pandas code for speed, and I'm trying to refactor my code, changing from iterrows() to vectorization. Here is an example of the old code and its result:

Old Code

import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
for index, row in df.iterrows():
    df.at[index,"repeatedAsList"] = repeatAsList(row['values'])
df

Old Result

+--------+----------------+
| values | repeatedAsList |
+--------+----------------+
|      1 | [1, 1]         |
|      2 | [2, 2]         |
|      3 | [3, 3]         |
+--------+----------------+

New Code

import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
df["repeatedAsList"] = repeatAsList(df["values"])

New Result

ValueError: Length of values does not match length of index

I'd like to understand why the new code above fails, and if it's possible to run a different way and achieve speed improvements from the old code. I feel like I'm missing a key point of vectorization, and it would be nice to learn why the values have to be scalar.

Body:
You could try map:

df['repeatedAsList'] = list(map(lambda x: [x,x], df['values'].values))
#df['repeatedAsList'] = list(map(lambda x: [x,x], df['values']) #seems slow

   values repeatedAsList
0       1         [1, 1]
1       2         [2, 2]
2       3         [3, 3]


问:
Parameter with that position [1] did not exist after moving the native query into a NamedNativeQuery?
Why do I get the following error when I move a JPA native query no longer work when I move it into a named one?

```<code>java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
</code>```

Not working query:

```<code>@NamedNativeQuery(
                name = Test.TEST,
                query = "SELECT * FROM test_table where id = ?",

Query q = entityManager.createNativeQuery(Test.TEST);
q.setParameter(1, 362L);
List<Object> result = q.getResultList();
</code>```

This works:

```<code>Query q = entityManager.createNativeQuery("SELECT * FROM test_table where id = ?");
q.setParameter(1, 362L);
List<Object> result = q.getResultList();
</code>```

答:
Because you should be calling:

```<code>Query q = entityManager.createNamedQuery(Test.TEST);
</code>```

and not

```<code>Query q = entityManager.createNativeQuery(Test.TEST);
</code>```

Body:
Why do I get the following error when I move a JPA native query no longer work when I move it into a named one?

java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

Not working query:

@NamedNativeQuery(
                name = Test.TEST,
                query = "SELECT * FROM test_table where id = ?",

Query q = entityManager.createNativeQuery(Test.TEST);
q.setParameter(1, 362L);
List<Object> result = q.getResultList();

This works:

Query q = entityManager.createNativeQuery("SELECT * FROM test_table where id = ?");
q.setParameter(1, 362L);
List<Object> result = q.getResultList();

Body:
Because you should be calling:

Query q = entityManager.createNamedQuery(Test.TEST);

and not

Query q = entityManager.createNativeQuery(Test.TEST);


问:
Using classes to print out instance attributes based on user input in Python
I am new to programming and would like to practice by creating a small app, using Python.
The app asks the user to enter a level and a term and the app will return the curriculum for the said level and term.

I have tried before without using classes and only using nested dictionaries but it got really messy really quick as some classes have a different curriculum.

How could I check if the users input is inside an instance then return the instance attributes in which it contains?

Thanks!

```<code>class PacketClasses:

    def __init__(self, level, term, song, story, act1, act2):
        self.level = level
        self.term = term
        self.song = song
        self.story = story
        self.act1 = act1
        self.ac2 = act2

class HeadWayClasses:

    def __init__(self, level, term, song, review, expression, gs):
        self.level = level
        self.term = term
        self.song = song
        self.review = review
        self.expression = expression
        self.gs = gs

p1 = Packet("Pink", 1, "heads shoulders knees and toes", "The giant grass-hopper", "bowling", "craft")
p2 = Packet("Pink", 2, "ABC song", "The giant grass-hopper part 2", "shopping", "craft")
g1 = Packet("Green", 1, "ABC song", "Snow White", "Animals", "craft")
g2 = Packet("Green", 2, "ABC song", "Snow White part 2", "At the zoo", "craft")

o1 = HeadWay("Orange", 1, "song 1", "review 1", "expression 1", "gs 1")
o2 = HeadWay("Orange", 2, "song 2", "review 2", "expression 2", "gs 2")
a1 = HeadWay("Aqua", 2, "song 1", "review 1", "expression 1", "gs 1")
a2 = HeadWay("Aqua", 2, "song 2", "review 2", "expression 2", "gs 2")

users_level = input("Please enter the level you wish to check: ")
users_term = int(input("Please enter the term level you wish to check: "))

# if users_level & users_term in a class, print the curriculum
</code>```

答:
This is a classic example of how inheritance and object-oriented programming can really help you out. We're going to create a parent class Classes and extend it. This will reduce a lot of code.

class Classes:

    def __init__(self, level, term, song):
        self.level = level
        self.term = term
        self.song = song
```

<p>Now, we're going to extend it with the classes you already have:</p>

<pre class="lang-py prettyprint-override"><code>class Packet(Classes):

    def __init__(self, level, term, song, story, act1, act2):
        super().__init__(level, term, song)
        self.story = story
        self.act1 = act1
        self.ac2 = act2

class HeadWay(Classes):

    def __init__(self, level, term, song, review, expression, gs):
        super().__init__(level, term, song)
        self.review = review
        self.expression = expression
        self.gs = gs
</code>```

Not much has changed, but now you can be sure that any time you use either PacketClasses or HeadWayClasses interchangably, they'll always have a level, term, and song.

Now it's a simple matter of searching through classes for level and term. For really large amount of data, you'd actually want to use a real database. However, for small data like this, simply looping through is adequate.

Put the classes into an array:

classes = [
    Packet("Pink", 1, "heads shoulders knees and toes", "The giant grass-hopper", "bowling", "craft"),
    Packet("Pink", 2, "ABC song", "The giant grass-hopper part 2", "shopping", "craft"),
    Packet("Green", 1, "ABC song", "Snow White", "Animals", "craft"),
    Packet("Green", 2, "ABC song", "Snow White part 2", "At the zoo", "craft"),
    HeadWay("Orange", 1, "song 1", "review 1", "expression 1", "gs 1"),
    HeadWay("Orange", 2, "song 2", "review 2", "expression 2", "gs 2"),
    HeadWay("Aqua", 2, "song 1", "review 1", "expression 1", "gs 1"),
    HeadWay("Aqua", 2, "song 2", "review 2", "expression 2", "gs 2")
]
```

<p>Now we can loop over them. Let's put the logic into a small function:</p>

<pre class="lang-py prettyprint-override"><code>def findByLevelAndTerm(classes, level, term):
    for c in classes:
        if c.level == level and c.term == term:
            return c
    return None
</code>```

And we're done! Now you can search the classes by level and term:

users_level = input("Please enter the level you wish to check: ")
users_term = int(input("Please enter the term you wish to check: "))
found_class = findByLevelAndTerm( classes, users_level, users_term )
if found_class is None: print("Unable to find the class!")
```

It's important to note that findByLevelAndTerm() will return only the first result. If multiple exist, you may want it to return a list instead.

Body:
I am new to programming and would like to practice by creating a small app, using Python.
The app asks the user to enter a level and a term and the app will return the curriculum for the said level and term.

I have tried before without using classes and only using nested dictionaries but it got really messy really quick as some classes have a different curriculum.

How could I check if the users input is inside an instance then return the instance attributes in which it contains?

Thanks!

class PacketClasses:

    def __init__(self, level, term, song, story, act1, act2):
        self.level = level
        self.term = term
        self.song = song
        self.story = story
        self.act1 = act1
        self.ac2 = act2

class HeadWayClasses:

    def __init__(self, level, term, song, review, expression, gs):
        self.level = level
        self.term = term
        self.song = song
        self.review = review
        self.expression = expression
        self.gs = gs

p1 = Packet("Pink", 1, "heads shoulders knees and toes", "The giant grass-hopper", "bowling", "craft")
p2 = Packet("Pink", 2, "ABC song", "The giant grass-hopper part 2", "shopping", "craft")
g1 = Packet("Green", 1, "ABC song", "Snow White", "Animals", "craft")
g2 = Packet("Green", 2, "ABC song", "Snow White part 2", "At the zoo", "craft")

o1 = HeadWay("Orange", 1, "song 1", "review 1", "expression 1", "gs 1")
o2 = HeadWay("Orange", 2, "song 2", "review 2", "expression 2", "gs 2")
a1 = HeadWay("Aqua", 2, "song 1", "review 1", "expression 1", "gs 1")
a2 = HeadWay("Aqua", 2, "song 2", "review 2", "expression 2", "gs 2")

users_level = input("Please enter the level you wish to check: ")
users_term = int(input("Please enter the term level you wish to check: "))

# if users_level & users_term in a class, print the curriculum

Body:
This is a classic example of how inheritance and object-oriented programming can really help you out. We're going to create a parent class Classes and extend it. This will reduce a lot of code.

class Classes:

    def __init__(self, level, term, song):
        self.level = level
        self.term = term
        self.song = song

Now, we're going to extend it with the classes you already have:

class Packet(Classes):

    def __init__(self, level, term, song, story, act1, act2):
        super().__init__(level, term, song)
        self.story = story
        self.act1 = act1
        self.ac2 = act2

class HeadWay(Classes):

    def __init__(self, level, term, song, review, expression, gs):
        super().__init__(level, term, song)
        self.review = review
        self.expression = expression
        self.gs = gs

Not much has changed, but now you can be sure that any time you use either PacketClasses or HeadWayClasses interchangably, they'll always have a level, term, and song.

Now it's a simple matter of searching through classes for level and term. For really large amount of data, you'd actually want to use a real database. However, for small data like this, simply looping through is adequate.

Put the classes into an array:

classes = [
    Packet("Pink", 1, "heads shoulders knees and toes", "The giant grass-hopper", "bowling", "craft"),
    Packet("Pink", 2, "ABC song", "The giant grass-hopper part 2", "shopping", "craft"),
    Packet("Green", 1, "ABC song", "Snow White", "Animals", "craft"),
    Packet("Green", 2, "ABC song", "Snow White part 2", "At the zoo", "craft"),
    HeadWay("Orange", 1, "song 1", "review 1", "expression 1", "gs 1"),
    HeadWay("Orange", 2, "song 2", "review 2", "expression 2", "gs 2"),
    HeadWay("Aqua", 2, "song 1", "review 1", "expression 1", "gs 1"),
    HeadWay("Aqua", 2, "song 2", "review 2", "expression 2", "gs 2")
]

Now we can loop over them. Let's put the logic into a small function:

def findByLevelAndTerm(classes, level, term):
    for c in classes:
        if c.level == level and c.term == term:
            return c
    return None

And we're done! Now you can search the classes by level and term:

users_level = input("Please enter the level you wish to check: ")
users_term = int(input("Please enter the term you wish to check: "))
found_class = findByLevelAndTerm( classes, users_level, users_term )
if found_class is None: print("Unable to find the class!")

It's important to note that findByLevelAndTerm() will return only the first result. If multiple exist, you may want it to return a list instead.


问:
How to access to a child method from the parent in vue.js
I have two nested components, what is the proper way to access to the child methods from the parent ?

this.$children[0].myMethod() seems to do the trick but it is pretty ugly, isn't it, what can be better way:

```<code><script>
import child from './my-child'

export default {
  components: {
   child
  },
  mounted () {
    this.$children[0].myMethod()
  }
}
</script>
</code>```

答:
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:

```<code>this.$refs.childRef.childMethod()
</code>```

childRef is the reference of your child component and childMethod can just be replaced with whatever method you have in your child component.

And from the other child I've called the root method:

```<code>this.$root.theParentMethod() // It works with Bootstrap Vue
this.$parent.theParentMethod()
</code>```

It worked for me.

Body:
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:

this.$refs.childRef.childMethod()

childRef is the reference of your child component and childMethod can just be replaced with whatever method you have in your child component.

And from the other child I've called the root method:

this.$root.theParentMethod() // It works with Bootstrap Vue
this.$parent.theParentMethod()

It worked for me.


问:
how to make a Text prevent the inputs more than 'x' number of digits?
My question is:

I want the Text field in Eclipse RCP to allow only the digits to be keyed in as inputs and the requirement is that it should allow only up to 'x' (let's say x=5) characters.

How can I accomplish it in RCP ?

I've tried the code like:

```<code>txtInput.addListener(SWT.Verify, new DecimalText(
                txtInsuranceValue, 8, 1000.00));
</code>```

where txtInputis a Text field. But this listener failed when I made repeated input into this field at run time.

Any alternatives please ?

答:
In general, solutions like adding verifyListeners/focusListeners are not complete and won't work with all situations. For example, what happens when the user copy-pastes some text into this text box?

If all you want is to get numerical inputs from the user, you should be using Spinner widget instead of Text widget. You could easily set the minimum and maximum limits on the Spinner.

See the snippets for more usage.

Body:
My question is:

I want the Text field in Eclipse RCP to allow only the digits to be keyed in as inputs and the requirement is that it should allow only up to 'x' (let's say x=5) characters.

How can I accomplish it in RCP ?

I've tried the code like:

txtInput.addListener(SWT.Verify, new DecimalText(
                txtInsuranceValue, 8, 1000.00));

where txtInputis a Text field. But this listener failed when I made repeated input into this field at run time.

Any alternatives please ?


问:
Can't Save same entry multiple times in MongoDB
What i'm trying to do is save a room object multiple times in a database but MongoDB shows only 1 entry no matter how many times i insert it. i'm guessing its because the object is same so i was hoping if there is any way around it. </p>

```<code> let room = new Room({
  rent,
  roomType,
  NoOfRooms,
  roomMaxOccupancy,
});

for(let i=0;i<NoOfRooms;i++){
  await room.save();
}
</code>```

答:
What you are doing is creating a room with a unique _id and then save it multiple times. It is one and the same room. In order to save multiple different rooms you need to have rooms with unique _ids each.</p>

```<code>for(let i=0;i<NoOfRooms;i++){
  let room = new Room({
    rent,
    roomType,
    NoOfRooms,
    roomMaxOccupancy,
  });
await room.save();
}
</code>```

Body:
What i'm trying to do is save a room object multiple times in a database but MongoDB shows only 1 entry no matter how many times i insert it. i'm guessing its because the object is same so i was hoping if there is any way around it.

 let room = new Room({
  rent,
  roomType,
  NoOfRooms,
  roomMaxOccupancy,
});

for(let i=0;i<NoOfRooms;i++){
  await room.save();
}

Body:
What you are doing is creating a room with a unique _id and then save it multiple times. It is one and the same room. In order to save multiple different rooms you need to have rooms with unique _ids each.

for(let i=0;i<NoOfRooms;i++){
  let room = new Room({
    rent,
    roomType,
    NoOfRooms,
    roomMaxOccupancy,
  });
await room.save();
}


问:
C# Azure AppendBlob AppendBlock adding a file larger than the 4mb limit
I've searched and searched and have not found any examples.

I'm using the Azure.Storage.Blobs nuget packages in C# .NET Core.

Here is an example of my current code that doesn't work.

I get a Status: 413 (The request body is to large and exceeds the maximum permissible limit.)

Searching seems to indicate there is either a 4mb limit or a 100mb limit it's not clear but I think it's 4mb on Append Blobs and 100mb limit on Block Blobs.

```<code>var appendBlobClient = containerClient.GetAppendBlobClient(string.Format("{0}/{1}", tenantName, Path.GetFileName(filePath)));

using FileStream uploadFileStream = File.OpenRead(filePath);
appendBlobClient.CreateIfNotExists();
appendBlobClient.AppendBlock(uploadFileStream);
uploadFileStream.Close();
</code>```

This doesn't work because of the 4mb limit so I need to append 4mb chunks of my file but I've not found examples of the best way to do this.

So what I'm trying to figure out is the best way to upload large files it seems it has to be done in chunks maybe 4mb for append blobs and 100mb for block blobs but the documentation isn't clear and doesn't have examples.

答:
I want to thank @silent for responding since he provided enough info to work out what I needed.  Sometimes just having someone to talk through things helps me figure things out.

What I found in on the BlockBlobClient.Upload method it chunks your file stream for you.  I believe this to be 100mb blocks from my research.  It appears it has a limit of 100mb blocks and 50,000 of them

For AppendBlockClient.AppendBlock it does not chunk your stream for you.  It has a limit of 4mb blocks and 50,000 of them.

Here is part of my code that allowed me to upload a 6gb file as a block blob and a 200mb file as an append blob.

```<code>BlobServiceClient blobServiceClient = new BlobServiceClient(azureStorageAccountConnectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(azureStorageAccountContainerName);
containerClient.CreateIfNotExists();

if (appendData)
{
    var appendBlobClient = containerClient.GetAppendBlobClient(string.Format("{0}/{1}", tenantName, Path.GetFileName(filePath)));

    appendBlobClient.CreateIfNotExists();

    var appendBlobMaxAppendBlockBytes = appendBlobClient.AppendBlobMaxAppendBlockBytes;
    using (var file = File.OpenRead(filePath))
    {
        int bytesRead;
        var buffer = new byte[appendBlobMaxAppendBlockBytes];
        while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
        {
            //Stream stream = new MemoryStream(buffer);
            var newArray = new Span<byte>(buffer, 0, bytesRead).ToArray();
            Stream stream = new MemoryStream(newArray);
            stream.Position = 0;
            appendBlobClient.AppendBlock(stream);
        }
    }
}
else
{
    var blockBlobClient = containerClient.GetBlockBlobClient(string.Format("{0}/{1}", tenantName, Path.GetFileName(filePath)));

    using FileStream uploadFileStream = File.OpenRead(filePath);
    blockBlobClient.DeleteIfExists();
    blockBlobClient.Upload(uploadFileStream);
    uploadFileStream.Close();
}
</code>```

Body:
I've searched and searched and have not found any examples.

I'm using the Azure.Storage.Blobs nuget packages in C# .NET Core.

Here is an example of my current code that doesn't work.

I get a Status: 413 (The request body is to large and exceeds the maximum permissible limit.)

Searching seems to indicate there is either a 4mb limit or a 100mb limit it's not clear but I think it's 4mb on Append Blobs and 100mb limit on Block Blobs.

var appendBlobClient = containerClient.GetAppendBlobClient(string.Format("{0}/{1}", tenantName, Path.GetFileName(filePath)));

using FileStream uploadFileStream = File.OpenRead(filePath);
appendBlobClient.CreateIfNotExists();
appendBlobClient.AppendBlock(uploadFileStream);
uploadFileStream.Close();

This doesn't work because of the 4mb limit so I need to append 4mb chunks of my file but I've not found examples of the best way to do this.

So what I'm trying to figure out is the best way to upload large files it seems it has to be done in chunks maybe 4mb for append blobs and 100mb for block blobs but the documentation isn't clear and doesn't have examples.

Body:
I want to thank @silent for responding since he provided enough info to work out what I needed.  Sometimes just having someone to talk through things helps me figure things out.

What I found in on the BlockBlobClient.Upload method it chunks your file stream for you.  I believe this to be 100mb blocks from my research.  It appears it has a limit of 100mb blocks and 50,000 of them

For AppendBlockClient.AppendBlock it does not chunk your stream for you.  It has a limit of 4mb blocks and 50,000 of them.

Here is part of my code that allowed me to upload a 6gb file as a block blob and a 200mb file as an append blob.

BlobServiceClient blobServiceClient = new BlobServiceClient(azureStorageAccountConnectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(azureStorageAccountContainerName);
containerClient.CreateIfNotExists();

if (appendData)
{
    var appendBlobClient = containerClient.GetAppendBlobClient(string.Format("{0}/{1}", tenantName, Path.GetFileName(filePath)));

    appendBlobClient.CreateIfNotExists();

    var appendBlobMaxAppendBlockBytes = appendBlobClient.AppendBlobMaxAppendBlockBytes;
    using (var file = File.OpenRead(filePath))
    {
        int bytesRead;
        var buffer = new byte[appendBlobMaxAppendBlockBytes];
        while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
        {
            //Stream stream = new MemoryStream(buffer);
            var newArray = new Span<byte>(buffer, 0, bytesRead).ToArray();
            Stream stream = new MemoryStream(newArray);
            stream.Position = 0;
            appendBlobClient.AppendBlock(stream);
        }
    }
}
else
{
    var blockBlobClient = containerClient.GetBlockBlobClient(string.Format("{0}/{1}", tenantName, Path.GetFileName(filePath)));

    using FileStream uploadFileStream = File.OpenRead(filePath);
    blockBlobClient.DeleteIfExists();
    blockBlobClient.Upload(uploadFileStream);
    uploadFileStream.Close();
}


问:
How to reverse a dictionary that has repeated values
I have a dictionary with almost 100,000 (key, value) pairs and the majority of the keys map to the same values. For example:

```<code>mydict =  {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}
</code>```

What I want to do, is to reverse the dictionary so that each value in mydict is going to be a key at the reverse_dict and is going to map to a list of all the mydict.keys() that used to map to that value in mydict. So based on the example above I would get:

```<code>reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'] , 3: ['d', 'j']}
</code>```

I came up with a solution that is very expensive and I want to hear any ideas for doing this more efficiently than this:

```<code>reversed_dict = {}
for value in mydict.values():
    reversed_dict[value] = []
    for key in mydict.keys():
        if mydict[key] == value:
            if key not in reversed_dict[value]:
                reversed_dict[value].append(key)
</code>```

答:
```<code>reversed_dict = {}
for key, value in mydict.items():
    reversed_dict.setdefault(value, [])
    reversed_dict[value].append(key)
</code>```

Body:
I have a dictionary with almost 100,000 (key, value) pairs and the majority of the keys map to the same values. For example:

mydict =  {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}

What I want to do, is to reverse the dictionary so that each value in mydict is going to be a key at the reverse_dict and is going to map to a list of all the mydict.keys() that used to map to that value in mydict. So based on the example above I would get:

reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'] , 3: ['d', 'j']}

I came up with a solution that is very expensive and I want to hear any ideas for doing this more efficiently than this:

reversed_dict = {}
for value in mydict.values():
    reversed_dict[value] = []
    for key in mydict.keys():
        if mydict[key] == value:
            if key not in reversed_dict[value]:
                reversed_dict[value].append(key)


问:
Custom Campaign tracking Cross-Domain Google Analytics
I have successfully implemented Cross-Domain tracking with Google Analytics (1 session as user jumps across domain, same _ga cookie on both domains, etc.) However, when the user jumps to the second domain and completes a purchase, the eCommerce transaction is not getting attributed to the utm custom campaign from the first page. It seems you can't pass the utm custom campaign information cross-domain. Is this true? Has anyone ran into this before?</p>

答:
I found my issue, cache. I have done hard refreshes before every test, but I went into Chrome tools and clear EVERYTHING. Cookie, cache, everything. And Cross-Domain tracking for Custom Campaigns started working! For reference here are the scripts for the two sites:

Site 1:

ga('create','UA-xxxxxxx-x'','auto', { 'allowLinker': true });
ga('require', 'linker');
ga('linker:autoLink', ['site2.com']);
ga('require','ecommerce','ecommerce.js');
ga('send','pageview');

Site2:

ga('create', 'UA-xxxxxxx-x', 'auto', { 'name': 'client', 'allowLinker': true });
ga('client.require', 'linker');
ga('client.linker:autoLink', ['site1.com']);
ga('client.require', 'ecommerce', 'ecommerce.js');
ga('client.send', 'pageview');```

Also, I added site1.com and site2.com to the Referral Exclusion List in GA and the UA key for site 1 and site 2 are the same.

Body:
I found my issue, cache. I have done hard refreshes before every test, but I went into Chrome tools and clear EVERYTHING. Cookie, cache, everything. And Cross-Domain tracking for Custom Campaigns started working! For reference here are the scripts for the two sites:

Site 1:

ga('create','UA-xxxxxxx-x'','auto', { 'allowLinker': true });
ga('require', 'linker');
ga('linker:autoLink', ['site2.com']);
ga('require','ecommerce','ecommerce.js');
ga('send','pageview');

Site2:

ga('create', 'UA-xxxxxxx-x', 'auto', { 'name': 'client', 'allowLinker': true });
ga('client.require', 'linker');
ga('client.linker:autoLink', ['site1.com']);
ga('client.require', 'ecommerce', 'ecommerce.js');
ga('client.send', 'pageview');

Also, I added site1.com and site2.com to the Referral Exclusion List in GA and the UA key for site 1 and site 2 are the same.


问:
Options for sharing dashboards with sensitive information with PowerBI
I have a dashboard I've built using Power BI, that contains sensitive information.  I want to share this dashboard with external users outside of my organization, that do not and will not have PowerBI.

From everything I've read, it appears I have a few options:

The external recipient of the dashboard would need to download Power BI Pro (from my understanding, they won't be able to view my dashboard with anything other than Power BI Pro?)

I somehow embed my dashboard in a Sharepoint which the external recipients have access to - but from what I've read, this seems likely to fail since they don't have Power BI.

I publish dashboard to the web, and have no way to password protect or restrict access.

Are these my only options?  Am I correct in that anyone I wish to share the dashboard with needs Power BI Pro to view, or I need to publish it to the open web and let it be publicly available?

If this is the case.. this is just one more reason I am disenchanted by Power BI.

答:
There are other options in addition to these you mentioned already (i.e. directly sharing through adding users to the workspace, embed in SharePoint and Publish to web).

Sharing (except Publish to web, which is public) require both the publisher and the consumer to have Power BI Pro licenses (which is not the case for you). Purchasing Power BI Premium (P SKUs only) will allow you to share reports with non-Pro (i.e. Power BI free users), but they still needs Power BI licenses (although free). Also this will costs you thousands per month and has annual commitment, which means you can't buy this for a month or two.

If this doesn't work for you, you can also:

Export these reports to PDF or PowerPoint and share the files with them.

If the report imports the data (see Dataset modes in the Power BI service), you can send them the .pbix file directly. It can be opened in Power BI Desktop even without having no Power BI account at all.

Publish the report to local instance of Power BI Report Server, where you can control who can access the report. You need either Power BI Premium (P SKUs) or SQL Server Enterprise with software assurance for that.

Embed the report using Power BI's API into custom written application, implementing app owns data scenario (see Tutorial: Embed Power BI content into an application for your customers and for example this answer).


问:
Automake include all libraries
My directory structure looks like the following :

```<code>-misc
-- misc.h
-- misc.c
-- misc.la

-dict
-- dict.h
-- dict.c
-- dict.la

-main
-- main.c
</code>```

I'm trying to build main.c into a program. main.c contains a reference to a function in dict.c and dict.c contains references to misc.c

How do I tell automake to include dict.la, misc.la to build main ?
In other words, I want to include all the *.la files that were built by the top level make.

This is of course just an example, in the real scenario, i'm dealing with more than 20 such libraries each in a directory similar to the above.

答:
the recursive make case

You sound as if you were using recursive make with one top level Makefile.am, one main/Makefile.am and one FOO/Makefile.am for FOO in misc, dict, and the 20 other such libraries.

If possible, I would try to change to using non-recursive make for this use case (see below).

In that recursive make case, you will need to adapt main/Makefile.am to link main with all those libraries, and to make sure those libraries are actually (re)built if necessary:

```<code>bin_PROGRAMS     = mainprog
mainprog_SOURCES = main.c
mainprog_LDADD   =

mainprog_LDADD += $(top_builddir)/misc/libmisc.la
$(top_builddir)/misc/libmisc.la:
        cd $(top_builddir)/misc && $(MAKE) libmisc.la
</code>```

You will need to repeat that _LDADD += and build rule pattern for each and every of those 20+ libraries.

the non-recursive make case

Personally, I would switch to using non-recursive make with one single top level Makefile.am, while putting both the mainprog executable and the 20+ libfoo.la files into the $(top_builddir). Then adding a library to the main program can be reduced to adding a single line

```<code>mainprog_LDADD += libmisc.la
</code>```

without any extra rules being required. This also parallelizes building of those 20+ libraries, which is a very welcome side effect.

The new top level Makefile.am would contain one line per library like

```<code>include misc/Makefile-files
</code>```

ending with one line

```<code>include main/Makefile-files
</code>```

and the file misc/Makefile-files would contain something like

```<code># -*- Makefile -*-
lib_LTLIBRARIES   += libmisc.la
libmisc_la_SOURCES = %reldir%/misc.c
</code>```

while main/Makefile-files would look like

```<code># -*- Makefile -*-
bin_PROGRAMS      += mainprog
mainprog_SOURCES   = main.c
mainprog_CPPFLAGS  =
mainprog_LDADD     =

# repeat for 20+ libraries
mainprog_LDADD += dict/libdict.la
mainprog_LDADD += misc/libmisc.la
</code>```

If your main program uses #include "misc.h", you will need 20+ per library mainprog_CPPFLAGS += -I$(top_srcdir)/misc additions. If you could change that to #include "misc/misc.h", a single mainprog_CPPFLAGS = -I$(top_srcdir) will do instead.

You could also include main/Makefile-files in before all those library Makefile-files and consistently add the respective library to mainprog in the library Makefile-files:

```<code>bin_PROGRAMS      += mainprog
mainprog_SOURCES   = main.c
mainprog_CPPFLAGS  =
mainprog_LDADD     =
</code>```

with misc/Makefile-files containing

```<code>lib_LTLIBRARIES    += libmisc.la
libmisc_la_SOURCES  = %reldir%/misc.c
mainprog_CPPFLAGS  += -I$(top_srcdir)/%reldir%
mainprog_LDADD     += libmisc.la
</code>```

If you can guarantee that all the lib_LTLIBRARIES built from the top level Makefile.am are to be linked to the main program, and that the main program sources can use #include "misc/misc.h", the following top level Makefile.am will do:

```<code>include main/Makefile-files

# 20+ library includes
include dict/Makefile-files
include misc/Makefile-files

mainprog_LDADD += $(lib_LTLIBRARIES)
</code>```

with main/Makefile-files being

```<code>bin_PROGRAMS     += mainprog
mainprog_SOURCES  = main.c
mainprog_LDADD    =
</code>```

and misc/Makefile-files and the other libraries:

```<code>mainprog_LDADD += libmisc.la
</code>```0

For a complete working example of a single library and a main program using non-recursive make for inspiration, see my answer https://stackoverflow.com/a/60306382/182675 and the github example I built for that.

Title: Automake include all libraries

Body:
My directory structure looks like the following :

-misc
-- misc.h
-- misc.c
-- misc.la

-dict
-- dict.h
-- dict.c
-- dict.la

-main
-- main.c

I'm trying to build main.c into a program. main.c contains a reference to a function in dict.c and dict.c contains references to misc.c

How do I tell automake to include dict.la, misc.la to build main ?
In other words, I want to include all the *.la files that were built by the top level make.

This is of course just an example, in the real scenario, i'm dealing with more than 20 such libraries each in a directory similar to the above.

Body:
the recursive make case

You sound as if you were using recursive make with one top level Makefile.am, one main/Makefile.am and one FOO/Makefile.am for FOO in misc, dict, and the 20 other such libraries.

If possible, I would try to change to using non-recursive make for this use case (see below).

In that recursive make case, you will need to adapt main/Makefile.am to link main with all those libraries, and to make sure those libraries are actually (re)built if necessary:

bin_PROGRAMS     = mainprog
mainprog_SOURCES = main.c
mainprog_LDADD   =

mainprog_LDADD += $(top_builddir)/misc/libmisc.la
$(top_builddir)/misc/libmisc.la:
        cd $(top_builddir)/misc && $(MAKE) libmisc.la

You will need to repeat that _LDADD += and build rule pattern for each and every of those 20+ libraries.

the non-recursive make case

Personally, I would switch to using non-recursive make with one single top level Makefile.am, while putting both the mainprog executable and the 20+ libfoo.la files into the $(top_builddir). Then adding a library to the main program can be reduced to adding a single line

mainprog_LDADD += libmisc.la

without any extra rules being required. This also parallelizes building of those 20+ libraries, which is a very welcome side effect.

The new top level Makefile.am would contain one line per library like

include misc/Makefile-files

ending with one line

include main/Makefile-files

and the file misc/Makefile-files would contain something like

# -*- Makefile -*-
lib_LTLIBRARIES   += libmisc.la
libmisc_la_SOURCES = %reldir%/misc.c

while main/Makefile-files would look like

# -*- Makefile -*-
bin_PROGRAMS      += mainprog
mainprog_SOURCES   = main.c
mainprog_CPPFLAGS  =
mainprog_LDADD     =

# repeat for 20+ libraries
mainprog_LDADD += dict/libdict.la
mainprog_LDADD += misc/libmisc.la

If your main program uses #include "misc.h", you will need 20+ per library mainprog_CPPFLAGS += -I$(top_srcdir)/misc additions. If you could change that to #include "misc/misc.h", a single mainprog_CPPFLAGS = -I$(top_srcdir) will do instead.

You could also include main/Makefile-files in before all those library Makefile-files and consistently add the respective library to mainprog in the library Makefile-files:

bin_PROGRAMS      += mainprog
mainprog_SOURCES   = main.c
mainprog_CPPFLAGS  =
mainprog_LDADD     =

with misc/Makefile-files containing

lib_LTLIBRARIES    += libmisc.la
libmisc_la_SOURCES  = %reldir%/misc.c
mainprog_CPPFLAGS  += -I$(top_srcdir)/%reldir%
mainprog_LDADD     += libmisc.la

If you can guarantee that all the lib_LTLIBRARIES built from the top level Makefile.am are to be linked to the main program, and that the main program sources can use #include "misc/misc.h", the following top level Makefile.am will do:

include main/Makefile-files

# 20+ library includes
include dict/Makefile-files
include misc/Makefile-files

mainprog_LDADD += $(lib_LTLIBRARIES)

with main/Makefile-files being

bin_PROGRAMS     += mainprog
mainprog_SOURCES  = main.c
mainprog_LDADD    =

and misc/Makefile-files and the other libraries:

lib_LTLIBRARIES    += libmisc.la
libmisc_la_SOURCES  = misc.c

For a complete working example of a single library and a main program using non-recursive make for inspiration, see my answer https://stackoverflow.com/a/60306382/182675 and the github example I built for that.


问:
Group by count take top 3
I have a database with source and destination, I would like to apply the group by returning only the top 3 destinations per source.

Like this.

答:
Try with </p>

```<code>s=df.groupby(['Origin','Destinations']).size().sort_values().groupby(level=0).head(3).sort_index(level=0)
</code>```

Title: Group by count take top 3

Body:
Try with

s=df.groupby(['Origin','Destinations']).size().sort_values().groupby(level=0).head(3).sort_index(level=0)


问:
Failing to display image from server directory file
I'm failing to display the contents of "uploads" folder.

On the website I've uploaded the image and it goes into the server directory file/ the uploads folder, and then it should fetch and display the image, but it doesn't. Thanks for reading this, I'm happy to hear your suggestions.

```<code>    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

//This is me trying to display the image (all this is in the index.file <main> where my server.php file is included (<?php require_once 'server.php'; ?>)) -
    <td><?php echo '<img src="'.$target_dir.'" width="100" height="100">'; ?></td>

<main>
<?php require_once 'edit-carteri-server.php'; ?>

<?php

if (isset($_SESSION['message'])): ?>

<div class="alert alert-<?=$_SESSION['msg_type']?>">

    <?php
        echo $_SESSION['message'];
        unset($_SESSION['message']);
    ?>
</div>
<?php endif ?>

<div class="container">
<?php
    $mysqli = new mysqli('localhost', 'root', '', 'id12522465_admin') or die(mysqli_error($mysqli));        //Savieno ar datubāzi
    $result = $mysqli->query("SELECT * FROM carteri") or die($mysqli->error);
 ?>

<div class="row justify-content-center">
    <table class="table">
        <thead>
            <tr>
                <th>Bilde</th>
                <th>Valsts</th>
                <th>Teksts</th>
                <th colspan="2">Action</th>
            </tr>
<?php

    while ($row = $result->fetch_assoc()): ?>
        <tr>
            <td><?php echo '<img src="'.$target_file.'" width="100" height="100">'; ?></td>
            <td><?php echo $row['valsts']; ?></td>
            <td><?php echo $row['teksts']; ?></td>
            <td>
                <a href="edit-carteri.php?edit=<?php echo $row['id']; ?>"
                    class="btn btn-info">Edit</a>
                <a href="edit-carteri-server.php?delete=<?php echo $row['id']; ?>"
                    class="btn btn-danger">Delete</a>
            </td>
        </tr>
<?php endwhile; ?>
        </thead>
    </table>
</div>
</code>```

答:
I think you want:

```<code><td><?php echo '<img src="'.$target_file.'" width="100" height="100">'; ?></td>
</code>```

Not:

```<code><td><?php echo '<img src="'.$target_dir.'" width="100" height="100">'; ?></td>
</code>```

Body:
I'm failing to display the contents of "uploads" folder.

On the website I've uploaded the image and it goes into the server directory file/ the uploads folder, and then it should fetch and display the image, but it doesn't. Thanks for reading this, I'm happy to hear your suggestions.

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

//This is me trying to display the image (all this is in the index.file  where my server.php file is included (<?php require_once 'server.php'; ?>)) -
    <?php echo ''; ?>

<?php require_once 'edit-carteri-server.php'; ?>

<?php

if (isset($_SESSION['message'])): ?>

<div class="alert alert-<?=$_SESSION['msg_type']?>">

    <?php
        echo $_SESSION['message'];
        unset($_SESSION['message']);
    ?>

<?php endif ?>

<?php
    $mysqli = new mysqli('localhost', 'root', '', 'id12522465_admin') or die(mysqli_error($mysqli));        //Savieno ar datubāzi
    $result = $mysqli->query("SELECT * FROM carteri") or die($mysqli->error);
 ?>

                Bilde
                Valsts
                Teksts
                Action

<?php

    while ($row = $result->fetch_assoc()): ?>

            <?php echo ''; ?>
            <?php echo $row['valsts']; ?>
            <?php echo $row['teksts']; ?>

                <a href="edit-carteri.php?edit=<?php echo $row['id']; ?>"
                    class="btn btn-info">Edit
                <a href="edit-carteri-server.php?delete=<?php echo $row['id']; ?>"
                    class="btn btn-danger">Delete

<?php endwhile; ?>

Body:
I think you want:

<td><?php echo '<img src="'.$target_file.'" width="100" height="100">'; ?></td>

Not:

<td><?php echo '<img src="'.$target_dir.'" width="100" height="100">'; ?></td>


问:
MySQL Error 1093 - Can't specify target table for update in FROM clause (two joins)
I'm trying to update the unit_price in a sales_order_parts detail table with calculation from the  applied_discount field from sales_orders.  Also, the price is in the master_part_list table as price.  When I run from the select statement down, it runs fine and returns the list of values from order_number 209 with the correct calculation.  When I run it complete from the update line, it returns "Error Code: 1093. You can't specify target table 'sop' for update in FROM clause" Any ideas?</p>

```<code>update sales_order_parts as sop
    set unit_price =
    (select (master_part_list.price * (1-(so.applied_discount/100)))
    from sales_orders as so
        inner join sales_order_parts as sop2
            on so.id = sop2.order_id
        inner join master_part_list
            on sop2.part_id = master_part_list.id
        where so.order_number = 209);

</code>```

答:
Use a subquery for sales_order_parts. mysql then treats as new temporary table

Like

```<code>update sales_order_parts as sop
    set unit_price =
    (select (master_part_list.price * (1-(so.applied_discount/100)))
    from sales_orders as so
        inner join (SELECT * FROM sales_order_parts) as sop2
            on so.id = sop2.order_id
        inner join master_part_list
            on sop2.part_id = master_part_list.id
        where so.order_number = 209);
</code>```

Body:
I'm trying to update the unit_price in a sales_order_parts detail table with calculation from the  applied_discount field from sales_orders.  Also, the price is in the master_part_list table as price.  When I run from the select statement down, it runs fine and returns the list of values from order_number 209 with the correct calculation.  When I run it complete from the update line, it returns "Error Code: 1093. You can't specify target table 'sop' for update in FROM clause" Any ideas?

update sales_order_parts as sop
    set unit_price =
    (select (master_part_list.price * (1-(so.applied_discount/100)))
    from sales_orders as so
        inner join sales_order_parts as sop2
            on so.id = sop2.order_id
        inner join master_part_list
            on sop2.part_id = master_part_list.id
        where so.order_number = 209);

Body:
Use a subquery for sales_order_parts. mysql then treats as new temporary table

Like

update sales_order_parts as sop
    set unit_price =
    (select (master_part_list.price * (1-(so.applied_discount/100)))
    from sales_orders as so
        inner join (SELECT * FROM sales_order_parts) as sop2
            on so.id = sop2.order_id
        inner join master_part_list
            on sop2.part_id = master_part_list.id
        where so.order_number = 209);