问:
JMeter: Connect to PostGresSQL in JSR using groovy and then compare values from multiple tables in DB with API response
Sorry for the long post, but I really need some guidance here. I need to compare values from an API response with the values from multiple tables in the DB.

Currently, I am doing it as follows:

Use a JDBC Connect Configuration to connect to Postgres DB and then use the JDBC Sampler to execute queries. I use it three times to query 3 different tables.  I store this data in variables (lets call them DBVariables). Please see this image for current Jmeter setup. https://i.stack.imgur.com/GZJyF.png

In JSR Assertion, I have written code that takes data from various DBVariables and compares it against the API response.

However, my issue is the API response can have an array of records and then nested arrays inside each (please see API response sample below). And these array elements can be sorted in any order. This is where I have issues.

I was wondering what would be the most efficient way of writing this JSR Assertion to validate all data elements returned by the API are the same as what is in the DB.

I am very new to groovy, but I think if I can query the DB inside the JSR assertion (instead of using the JDBC sampler), then the comparison can be done by storing API response in a map and then the DBResponse in another map and sorting both and comparing the items.
My questions are:

How can I connect to postgressql using groovy and then execute query statements in it? I have not done that before and was hoping if someone can provide a sample code.

How can I store API response and DB responses in Map and sort them and compare them in groovy?

The API response is of the following type:

```<code>    {
  "data":{
    "response":{
      "employeeList":[
        {
          "employeeNumber":"11102",
          "addressList":[
            {
              "addrType":"Home",
              "street_1":"123 Any street"
            },
            {
              "addrType":"Alternate",
              "street_1":"123 Any street"
            }
          ],
          "departmentList":[
            {
              "deptName":"IT"
            },
            {
              "deptName":"Finance"
            },
            {
              "deptName":"IT"
            }
          ]
        },
        {
          "employeeNumber":"11103",
          "addressList":[
            {
              "addrType":"Home",
              "street_1":"123 Any street"
            },
            {
              "addrType":"Alternate",
              "street_1":"123 Any street"
            }
          ],
          "departmentList":[
            {
              "deptName":"IT"
            },
            {
              "deptName":"Finance"
            },
            {
              "deptName":"IT"
            }
          ]
        }
      ]
    }
  }
}
</code>```

答:
Have you seen Working with a relational database chapter of Groovy documentation? Alternatively you can obtain a Connection instance from the JDBC Configuration Element like

```<code>def connection = org.apache.jmeter.protocol.jdbc.config.getConnection('your-pool-name')
</code>```

With regards to "sort" There is DefaultGroovyMethods class which provides sort() function for any "sortable" entity. With regards to "compare" - we don't know how the object from the database looks like hence cannot provide a comprehensive solution.

Maybe an easier option would be converting the response from the JDBC Sampler to JSON using JsonBuilder and once you have 2 JSON structures use the library like JSONassert which doesn't care about order and depth

You haven't asked, but if you're "very new to groovy" maybe it worth extracting individual values from API using JSON Extractor, do the same for the database with the JDBC elements and compare individual JMeter Variables using Response Assertion?

Body:
Sorry for the long post, but I really need some guidance here. I need to compare values from an API response with the values from multiple tables in the DB.

Currently, I am doing it as follows:

Use a JDBC Connect Configuration to connect to Postgres DB and then use the JDBC Sampler to execute queries. I use it three times to query 3 different tables.  I store this data in variables (lets call them DBVariables). Please see this image for current Jmeter setup. https://i.stack.imgur.com/GZJyF.png

In JSR Assertion, I have written code that takes data from various DBVariables and compares it against the API response.

However, my issue is the API response can have an array of records and then nested arrays inside each (please see API response sample below). And these array elements can be sorted in any order. This is where I have issues.

I was wondering what would be the most efficient way of writing this JSR Assertion to validate all data elements returned by the API are the same as what is in the DB.

I am very new to groovy, but I think if I can query the DB inside the JSR assertion (instead of using the JDBC sampler), then the comparison can be done by storing API response in a map and then the DBResponse in another map and sorting both and comparing the items.
My questions are:

How can I connect to postgressql using groovy and then execute query statements in it? I have not done that before and was hoping if someone can provide a sample code.

How can I store API response and DB responses in Map and sort them and compare them in groovy?

The API response is of the following type:

    {
  "data":{
    "response":{
      "employeeList":[
        {
          "employeeNumber":"11102",
          "addressList":[
            {
              "addrType":"Home",
              "street_1":"123 Any street"
            },
            {
              "addrType":"Alternate",
              "street_1":"123 Any street"
            }
          ],
          "departmentList":[
            {
              "deptName":"IT"
            },
            {
              "deptName":"Finance"
            },
            {
              "deptName":"IT"
            }
          ]
        },
        {
          "employeeNumber":"11103",
          "addressList":[
            {
              "addrType":"Home",
              "street_1":"123 Any street"
            },
            {
              "addrType":"Alternate",
              "street_1":"123 Any street"
            }
          ],
          "departmentList":[
            {
              "deptName":"IT"
            },
            {
              "deptName":"Finance"
            },
            {
              "deptName":"IT"
            }
          ]
        }
      ]
    }
  }
}

Body:
Have you seen Working with a relational database chapter of Groovy documentation? Alternatively you can obtain a Connection instance from the JDBC Configuration Element like

def connection = org.apache.jmeter.protocol.jdbc.config.getConnection('your-pool-name')

With regards to "sort" There is DefaultGroovyMethods class which provides sort() function for any "sortable" entity. With regards to "compare" - we don't know how the object from the database looks like hence cannot provide a comprehensive solution.

Maybe an easier option would be converting the response from the JDBC Sampler to JSON using JsonBuilder and once you have 2 JSON structures use the library like JSONassert which doesn't care about order and depth

You haven't asked, but if you're "very new to groovy" maybe it worth extracting individual values from API using JSON Extractor, do the same for the database with the JDBC elements and compare individual JMeter Variables using Response Assertion?


来源: stackexchange

问:
If data is undefined, at least one attribute must be present pubsub
I'm trying to use Google Cloud's Pub/Sub API to send messages to topic subscribers, but I'm having a problem where it's returning the message "If data is undefined, at least one attribute must be present.". I'm going to use it with Cloud Functions. I have the following code which is the same as the official Pub/Sub NodeJS documentation with minor changes:

```<code>exports.helloWorld = async (req, res) => {

    const parse = require('url-parse');
    const punycode = require('punycode');
    const {PubSub} = require('@google-cloud/pubsub');

    let message = req.query.message || req.body.message || 'Hello World!';

    let referHeader = req.headers.referer;
    let userIP = req.socket.remoteAddress;
    let originHeader = req.headers.origin;
    let userAgenteHeader = req.useragent;
    let a = req.query.a;
    let s = req.query.s;
    let e = req.query.e;

    try {

        const pubSubClient = new PubSub({
            project_id: 'my-project',
            credentials: {
                private_key: "my_private_key",
                client_email: 'email_project@myemail.com',
            }
        });

        a = 123; //Change for test

        let topicNameOrId = 'MY_TOPIC_ID';

        const data = JSON.stringify({
            "data": "analytics",
            "attributes": {
              "a": a
            }
          });

        const dataBuffer = Buffer.from(data);

        const messageId = await pubSubClient
          .topic(topicNameOrId)
          .publishMessage(dataBuffer);

        res.status(200).send(`Message ${messageId} published.`);

      } catch (error) {

        console.error();
        res.status(403).send(`${error.message}`);

        process.exitCode = 1;
      }
};
</code>```

I've tried to do it with JSON.stringify, without it, directly in the function, but nothing worked, it always gives the same error and I'm passing the data parameter normally.

答:
I tried your code and I was able to reproduce your error. After debugging your code, it was stuck when it uses publishMessage(). Apparently publishMessage() accepts a message object.

publishMessage(message: MessageOptions): Promise<[string]>;

Use publish() instead, it accepts buffer object.

publish(data: Buffer, attributes?: Attributes): Promise;

Apply publish() in your code, use the fix below:

```<code>const messageId = await pubSubClient.topic(topicNameOrId).publish(dataBuffer);
</code>```

Cloud Function output:

Actual Pubsub message:

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use Google Cloud's Pub/Sub API to send messages to topic subscribers, but I'm having a problem where it's returning the message "If data is undefined, at least one attribute must be present.". I'm going to use it with Cloud Functions. I have the following code which is the same as the official Pub/Sub NodeJS documentation with minor changes:

exports.helloWorld = async (req, res) => {

    const parse = require('url-parse');
    const punycode = require('punycode');
    const {PubSub} = require('@google-cloud/pubsub');

    let message = req.query.message || req.body.message || 'Hello World!';

    let referHeader = req.headers.referer;
    let userIP = req.socket.remoteAddress;
    let originHeader = req.headers.origin;
    let userAgenteHeader = req.useragent;
    let a = req.query.a;
    let s = req.query.s;
    let e = req.query.e;

    try {

        const pubSubClient = new PubSub({
            project_id: 'my-project',
            credentials: {
                private_key: "my_private_key",
                client_email: 'email_project@myemail.com',
            }
        });

        a = 123; //Change for test

        let topicNameOrId = 'MY_TOPIC_ID';

        const data = JSON.stringify({
            "data": "analytics",
            "attributes": {
              "a": a
            }
          });

        const dataBuffer = Buffer.from(data);

        const messageId = await pubSubClient
          .topic(topicNameOrId)
          .publishMessage(dataBuffer);

        res.status(200).send(`Message ${messageId} published.`);

      } catch (error) {

        console.error();
        res.status(403).send(`${error.message}`);

        process.exitCode = 1;
      }
};

I've tried to do it with JSON.stringify, without it, directly in the function, but nothing worked, it always gives the same error and I'm passing the data parameter normally.

Body:
I tried your code and I was able to reproduce your error. After debugging your code, it was stuck when it uses publishMessage(). Apparently publishMessage() accepts a message object.

publishMessage(message: MessageOptions): Promise<[string]>;

Use publish() instead, it accepts buffer object.

publish(data: Buffer, attributes?: Attributes): Promise;

Apply publish() in your code, use the fix below:

const messageId = await pubSubClient.topic(topicNameOrId).publish(dataBuffer);

Cloud Function output:

Actual Pubsub message:


问:
How to calculate the perimeter from the intersection of the mesh and the cut line in Unity 3D?
I want to calculate the perimeter of various irregular 3D objects, how can I do this in Unity 3D using C#?

My idea is:
Get a plane by inputting the coordinates of 3 points, then get the intersection of the plane and the object to be calculated, and then calculate the perimeter of the cumulative distance of these intersections.

But I have no idea to do this.

答:
I don't think there is one answer for every 3D object, if you want to find the perimeter for a particular shape you have to find the formula for that.
In case of a sphere:

c is position of the plane.
c0 is position of the sphere.
p is distance between c and c0.
r = sqrt(R2 - p2).
Then the perimeter of the intersection is: 2rpi.


问:
onChange Not Updating State At Correct Time
I'm trying to save the value of the input field to state. When the defaultValue is 'projectName', and I delete the word 'Name' from the input field, I want the state to update so that the defaultValue is 'project'. When I console.log e.target.value in the onChange, I can see the change happening when I make the deletion, and my code in the onChange is saving the value to state, but unfortunately, the state does not update. Any thoughts as to why?

Here is a Code Sandbox: https://codesandbox.io/s/amazing-river-o15h4?file=/src/Child.js

... And here is a screenshot of the console.log in the onChange and the setState call not updating:

App.js

import "./styles.css";

import Child from "./Child";

export default function App() {
  const thisIsState = {
    id: 1,
    projectName: "projectName",
    description: "description"
  };

  return (

      <Child project={thisIsState} />

  );
}

```
<p>Child.js</p>
<pre class="lang-js prettyprint-override"><code>import { useState, useEffect } from "react";
import "./styles.css";

export default function Child(props) {
  console.log(props);
  const [state, setState] = useState({
    projectName: "",
    description: ""
  });

  let project = props.project;
  let errors = props.errors;
  useEffect(
    (state) => {
      setState({
        ...state,
        projectName: project.projectName,
        description: project.description
      });
      console.log("useEffect1 state: ", state);
    },
    [project, errors]
  );

  const onChange = (e) => {
    console.log("e.target.value in onChange: ", e.target.value);
    setState((state) => ({
      ...state,
      [e.target.name]: e.target.value
    }));
    console.log("onChange() state: ", state);
  };
  return (
    <div className="App">
      <form>
        <input
          type="text"
          placeholder="Project Name"
          name="projectName"
          defaultValue={props.project.projectName}
          onChange={onChange}
          style={{ marginBottom: "15px" }}
        />
        <br />
        <input
          type="text"
          placeholder="Project Name"
          name="projectDescription"
          defaultValue={props.project.description}
          onChange={onChange}
        />
      </form>
    </div>
  );
}

</code>```

答:
This question has already been answered in a different question. The thing is setstate function is asynchronous. To overcome this you can use callback functions to print the state after it is updated. The link to the original answer is below
State not updating when printing on same function where updating in React Js</p>

Body:
I'm trying to save the value of the input field to state. When the defaultValue is 'projectName', and I delete the word 'Name' from the input field, I want the state to update so that the defaultValue is 'project'. When I console.log e.target.value in the onChange, I can see the change happening when I make the deletion, and my code in the onChange is saving the value to state, but unfortunately, the state does not update. Any thoughts as to why?

Here is a Code Sandbox: https://codesandbox.io/s/amazing-river-o15h4?file=/src/Child.js

... And here is a screenshot of the console.log in the onChange and the setState call not updating:

App.js

import "./styles.css";

import Child from "./Child";

export default function App() {
  const thisIsState = {
    id: 1,
    projectName: "projectName",
    description: "description"
  };

  return (

      <Child project={thisIsState} />

  );
}

Child.js

import { useState, useEffect } from "react";
import "./styles.css";

export default function Child(props) {
  console.log(props);
  const [state, setState] = useState({
    projectName: "",
    description: ""
  });

  let project = props.project;
  let errors = props.errors;
  useEffect(
    (state) => {
      setState({
        ...state,
        projectName: project.projectName,
        description: project.description
      });
      console.log("useEffect1 state: ", state);
    },
    [project, errors]
  );

  const onChange = (e) => {
    console.log("e.target.value in onChange: ", e.target.value);
    setState((state) => ({
      ...state,
      [e.target.name]: e.target.value
    }));
    console.log("onChange() state: ", state);
  };
  return (

      <form>
        <input
          type="text"
          placeholder="Project Name"
          name="projectName"
          defaultValue={props.project.projectName}
          onChange={onChange}
          style={{ marginBottom: "15px" }}
        />

        <input
          type="text"
          placeholder="Project Name"
          name="projectDescription"
          defaultValue={props.project.description}
          onChange={onChange}
        />
      </form>

  );
}


问:
How to create "read more" button for a text without having the text content?
I am building a website that fetches images from NASA's API. Now, I would like to add description to those images but I don't want all the description to be shown. Thus, I want to add a read more button/link to it. The text content(or description of the image) will change every day. And so I don't know at which word to put the button. Is there any way that I can put button after certain number of rows?

Any help or input is highly appreciated, thanks.

答:
Add 2  element and put part of the text up until the row you want the button to be at using JavaScript (I'll tell that later), add visibility:"hidden" as one of the properties of the div2 after you use the Javascript, add the read more button after the first div and before the second div, add an onclick:"document.getElementById("idOfThe2ndDiv).visibility = "visible"; "
to the button.
Now I'll tell how to use the JavaScript.</p>
```<code>var text = "lorem ipsum dolor sit amet" //make the text the description of the image
var part1 = text.slice(0, num); //replace num with the amount of characters you want
var part2 = text.slice(num);
document.getElementById("idOfThe1stDiv").InnerHTML = part1;
document.getElementById("idOfThe2ndDiv").innerHTML = part2;
</code>```

Body:
Add 2  element and put part of the text up until the row you want the button to be at using JavaScript (I'll tell that later), add visibility:"hidden" as one of the properties of the div2 after you use the Javascript, add the read more button after the first div and before the second div, add an onclick:"document.getElementById("idOfThe2ndDiv).visibility = "visible"; "
to the button.
Now I'll tell how to use the JavaScript.

var text = "lorem ipsum dolor sit amet" //make the text the description of the image
var part1 = text.slice(0, num); //replace num with the amount of characters you want
var part2 = text.slice(num);
document.getElementById("idOfThe1stDiv").InnerHTML = part1;
document.getElementById("idOfThe2ndDiv").innerHTML = part2;


问:
Azure Data Factory Calculate Percent Revenue
I need to calculate billing percentage with respect to the total in Azure Data Factory WorkFlow. I used the expression:

```<code>Total_amount/sum(Total_amount)
</code>```

But it doesn´t work. How could I calculate percentages using aggregate transformation inside a data flow?

答: Create a data flow with 2 sources. They can both be the same source, in your example. The first stream will have Source->aggregate [sum(total amount)]->Sink (cached). The second stream will have Source->derived column (total amount/lookup from the cached sink above). My example screenshot below does this exact same thing with loan data. This is what my formula in the derived column looks like: loan_amnt / sink1#output().total_amount

Body:
I need to calculate billing percentage with respect to the total in Azure Data Factory WorkFlow. I used the expression:

Total_amount/sum(Total_amount)

But it doesn´t work. How could I calculate percentages using aggregate transformation inside a data flow?


问:
Simpler interface for SQL Server analysis services cubes for end users
Is there a simpler interface for end users to run "queries" on pre-existing SqlServer Analysis Service cubes?  I'm looking for a way to deploy the cubes and allow the users to work with the data through a simpler interface than BIDS.  Is this even possible?</p>

答:
Another option is Report Builder, that comes for free with SQL Server.
Though the SQL Server 2005 version is a bit cranky, the new release with SQL Server 2008 seems to work much better.

Although it isn't as flexible as excel for ad-hoc queries,it comes very handy for some scenarios.

OwnerDisplayName: Barry

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: santiiiii


问:
Is the function name in the extension should be really unique or not in swift
I'd like to ask about naming the Swift extension function.
I have an extension file for a UIViewController and created a function called showAlert in the file. I thought the name showAlert might (or might not) be used as the method of default Swift UIViewController in the future update, and I was wondering if I need to change the name of the function to something really unique or I don't really need to change the name at all.
If the UIViewController has a function called showAlert with the same parameters in the future Swift update, (which I guess it's not gonna happen) and I have the same name function in the extension file, is it going to be a compiler error? If so, I may need to change the name of the method to something very exclusive to the project.

in case, my code is like

```<code>extension UIViewController {

    func showAlert(title: String?, message: String?, actions: [UIAlertAction], style: UIAlertController.Style, completion: (() -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach { alert.addAction($0)}
        present(alert, animated: true, completion: completion)
    }
}
</code>```

something like this.

答:
and I have the same name function in the extension file, is it going to be a compiler error?

Yes

I was wondering if I need to change the name of the function to something really unique

Nah, just write it in the way that makes your code best. Don’t make your code ugly just to make it defensive.

I think the only issue you might run into is if two libraries both declare the same extension. If the extension is one that you wrote yourself, you should get an error if it’s redeclaring a method that already exists.

Body:
I'd like to ask about naming the Swift extension function.
I have an extension file for a UIViewController and created a function called showAlert in the file. I thought the name showAlert might (or might not) be used as the method of default Swift UIViewController in the future update, and I was wondering if I need to change the name of the function to something really unique or I don't really need to change the name at all.
If the UIViewController has a function called showAlert with the same parameters in the future Swift update, (which I guess it's not gonna happen) and I have the same name function in the extension file, is it going to be a compiler error? If so, I may need to change the name of the method to something very exclusive to the project.

in case, my code is like

extension UIViewController {

    func showAlert(title: String?, message: String?, actions: [UIAlertAction], style: UIAlertController.Style, completion: (() -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach { alert.addAction($0)}
        present(alert, animated: true, completion: completion)
    }
}

something like this.


问:
Webpack Including Files in Unexpected Directory
I have two webpack configs that are intended to target two different things in the following directory structure

```<code>./scripts/react/TestA.tsx
./scripts/typescript/TestB.tsx
</code>```

They are seemingly isolated from each other with no imports in each but when I run the build with my webpack.config.js

```<code>module.exports = {
  entry:{
    typescript:[__dirname + "/../scripts/typescript/TestB.tsx"]
  },
  module:{
    rules:[
      {
        test:/\.tsx$/,
        exclude:[__dirname + "/../node_modules"],
        use:{ loader:"ts-loader" }
      }
    ]
  }
}
</code>```

It handles the build fine but it's bringing up errors in the folder I was not expecting

```<code>asset typescript.js 1.54 KiB [emitted] (name: typescript)
./scripts/typescript/TestB.tsx 69 bytes [built] [code generated]

ERROR in ***/scripts/react/TestA.tsx
</code>```

Why is this happening and is there anyway to stop this? I tried to add it to the excludes options but it didn't seem to make any difference (I'm probably doing it wrong)

```<code>        exclude:[__dirname + "/../node_modules", __dirname + "/../scripts/react/"],
</code>```

答:
Webpack has nothing to do with this. It is the TypeScript type checker that is causing the issue. TypeScript compilation works on folder level. So, even if your Webpack doesn't really include that other file in the dependency graph, the TypeScript type checker will still type check all the files in the project.

TypeScript's type checks begins at the root folder where tsconfig.json file is detected. It checks all the files. That's the default behavior. You can change that behavior using baseUrl option.

As a quick solution, since you intend to generate two different builds, it means you can consider them as a composite build and it means you should have two projects in two different folders and use two different tsconfig.json files for two projects. By doing this, type checking of one project won't affect the other project.

Body:
I have two webpack configs that are intended to target two different things in the following directory structure

./scripts/react/TestA.tsx
./scripts/typescript/TestB.tsx

They are seemingly isolated from each other with no imports in each but when I run the build with my webpack.config.js

module.exports = {
  entry:{
    typescript:[__dirname + "/../scripts/typescript/TestB.tsx"]
  },
  module:{
    rules:[
      {
        test:/\.tsx$/,
        exclude:[__dirname + "/../node_modules"],
        use:{ loader:"ts-loader" }
      }
    ]
  }
}

It handles the build fine but it's bringing up errors in the folder I was not expecting

asset typescript.js 1.54 KiB [emitted] (name: typescript)
./scripts/typescript/TestB.tsx 69 bytes [built] [code generated]

ERROR in ***/scripts/react/TestA.tsx

Why is this happening and is there anyway to stop this? I tried to add it to the excludes options but it didn't seem to make any difference (I'm probably doing it wrong)

        exclude:[__dirname + "/../node_modules", __dirname + "/../scripts/react/"],


问:
Efficient and scalable storage for JSON data with NoSQL databases
We are working on a project which should collect journal and audit data and store it in a datastore for archive purposes and some views. We are not quite sure which datastore would work for us.

we need to store small JSON documents, about 150 bytes, e.g. "audit:{timestamp: '86346512',host':'foo',username:'bar',task:'foo',result:0}" or "journal:{timestamp:'86346512',host':'foo',terminalid:1,type='bar',rc=0}"

we are expecting about one million entries per day, about 150 MB data

data will be stored and read but never modified

data should stored in an efficient way, e.g. binary format used by Apache Avro

after a retention time data may be deleted

custom queries, such as 'get audit for user and time period' or 'get journal for terminalid and time period'

replicated data base for failsafe

scalable

Currently we are evaluating NoSQL databases like Hadoop/Hbase, CouchDB, MongoDB and Cassandra. Are these databases the right datastore for us? Which of them would fit best?
Are there better options?

答:
We're using Hadoop/HBase, and I've looked at Cassandra, and they generally use the row key as the means to retrieve data the fastest, although of course (in HBase at least) you can still have it apply filters on the column data, or do it client side. For example, in HBase, you can say "give me all rows starting from key1 up to, but not including, key2".

So if you design your keys properly, you could get everything for 1 user, or 1 host, or 1 user on 1 host, or things like that. But, it takes a properly designed key. If most of your queries need to be run with a timestamp, you could include that as part of the key, for example.

How often do you need to query the data/write the data? If you expect to run your reports and it's fine if it takes 10, 15, or more minutes (potentially), but you do a lot of small writes, then HBase w/Hadoop doing MapReduce (or using Hive or Pig as higher level query languages) would work very well.

ContentLicense: CC BY-SA 3.0


问:
Post Increment has high precedence than Pre increment but doesn't execute first
I have trouble understanding operator precedence in post increment and pre increment operators. I did my research and found below article in StackOverFlow

Precedence of ++ and -- operators in Java

But it does not answer my questions.

In the code below

```<code>d = 1; System.out.println(++d * d++);
</code>```

According to one of the answer by @Paŭlo Ebermann  the above expression is evaluated as
 ++d * d++ => (++d) * (d++)
and then evaluated from left to right which gives answer as 2*2=4 which is ofcourse what the java says when I print it.

My understanding is I believe that the expression is evaluated as   ++d * d++ => (++d * (d++)) since d++ has higher precedence than ++d which gives answer as 3*1=3.

EDIT: Another example to support my claim-
Consider expression 2+3*5 which gets evaluated to (2+(3*5)) and evaluation happens in that manner(Multiplication followed by addition). But consider this expression int i=1;sysout(i+i++); Here i+i++ must change to (i+(i++)). The post increment must increase i by two(similar to multiplication) which is assigned to i which makes 2+1=3 but the output is 2.

Please clarify what I am thinking wrong here in relation to precedence to evaluation order

答:
Precedence only appear when there is a conflict on operants. For 3 + 7 * 9, both + and * are binary operator, having a conflict because they both they act on the same operand 7. According to the precedence order, it equals to 3 + (7 * 9).

But in your case ++d * d++, the pre-increment and post-increment are unary operaters. They act on different variables d, not having a conflict or share a common operand. So the higher precedence rule doesn't work here. Just calculate with left to right order.

Refer this website for more details about the conception of Precedence order and Associativity and Order of operand evaluation. https://introcs.cs.princeton.edu/java/11precedence/

Body:
I have trouble understanding operator precedence in post increment and pre increment operators. I did my research and found below article in StackOverFlow

Precedence of ++ and -- operators in Java

But it does not answer my questions.

In the code below

d = 1; System.out.println(++d * d++);

According to one of the answer by @Paŭlo Ebermann  the above expression is evaluated as
 ++d * d++ => (++d) * (d++)
and then evaluated from left to right which gives answer as 2*2=4 which is ofcourse what the java says when I print it.

My understanding is I believe that the expression is evaluated as   ++d * d++ => (++d * (d++)) since d++ has higher precedence than ++d which gives answer as 3*1=3.

EDIT: Another example to support my claim-
Consider expression 2+3*5 which gets evaluated to (2+(3*5)) and evaluation happens in that manner(Multiplication followed by addition). But consider this expression int i=1;sysout(i+i++); Here i+i++ must change to (i+(i++)). The post increment must increase i by two(similar to multiplication) which is assigned to i which makes 2+1=3 but the output is 2.

Please clarify what I am thinking wrong here in relation to precedence to evaluation order


问:
how to convert array to dataframe in column only
i have tried to convert array to dataframe, and follow the documentation how to convert them.

here my script;

```<code>M = pd.DataFrame(a, columns=col)
c0 = M.quantile(0)
c1 = M.quantile(0.2)
c2 = M.quantile(0.4)
c3 = M.quantile(0.6)
c4 = M.quantile(0.8)
c5 = M.quantile(1)
d = np.array([c0,c1,c2,c3,c4,c5])
output_table_1 = pd.DataFrame(d)
</code>```

the ouput has 6 rows, is not my expected that i want convert it to 6 columns.
anyone can help me to solve this issue?

Body:
i have tried to convert array to dataframe, and follow the documentation how to convert them.

here my script;

M = pd.DataFrame(a, columns=col)
c0 = M.quantile(0)
c1 = M.quantile(0.2)
c2 = M.quantile(0.4)
c3 = M.quantile(0.6)
c4 = M.quantile(0.8)
c5 = M.quantile(1)
d = np.array([c0,c1,c2,c3,c4,c5])
output_table_1 = pd.DataFrame(d)

the ouput has 6 rows, is not my expected that i want convert it to 6 columns.
anyone can help me to solve this issue?

Body:
Check the shape of d:

In [186]: d.shape
Out[186]: (6, 1)
In [187]: pd.DataFrame(d)
Out[187]:
     0
0  0.0
1  0.6
2  1.2
3  1.8
4  2.4
5  3.0

With a (1,6) shape:

In [188]: pd.DataFrame(d.T)
Out[188]:
     0    1    2    3    4    5
0  0.0  0.6  1.2  1.8  2.4  3.0


问:
boolean mask for similarity between tensors
I have two tensors and would like to check if elements of row in a, are in the same row in b

```<code>a = [[1,2,3], [7,8,4]]
b = [[2,1,1], [4,5,6]]
c = [[T,T,F], [F,F,T]]
</code>```

I would like this to be done in pure Pytorch in the fastest way possible.

答:
Found the solution (https://stackoverflow.com/a/67870684/12216433)

In my case it would work like this.

```<code>AA = a.reshape(2, 3, 1)
BB = b.reshape(2, 1, 3)
mask = (AA == BB).sum(-1).bool()
</code>```

Body:
I have two tensors and would like to check if elements of row in a, are in the same row in b

a = [[1,2,3], [7,8,4]]
b = [[2,1,1], [4,5,6]]
c = [[T,T,F], [F,F,T]]

I would like this to be done in pure Pytorch in the fastest way possible.

Body:
Found the solution (https://stackoverflow.com/a/67870684/12216433)

In my case it would work like this.

AA = a.reshape(2, 3, 1)
BB = b.reshape(2, 1, 3)
mask = (AA == BB).sum(-1).bool()


问:
python how to generate permutations of putting a singular character into a word
No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

```<code>c-ats
ca-ts
-c-ats
etc,
</code>```

Is anybody able to help me?

答:
I assume that you want to generate all possible ways to insert zero or more hyphens into your word s.t. no two hyphens are adjacent. Here is one way to do this with itertools.product:

```<code>from itertools import product

def hyphens(word):
  # create template, each {} is to be filled with "" or "-"
  template = "{}" + "{}".join(word) + "{}"
  # iterate over all possible ways to fill empty braces
  for chars in product(["", "-"], repeat=len(word) + 1):
    yield template.format(*chars)

list(hyphens('cats'))
# ['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s', 'ca-t-s-',
# 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-a-ts-', 'c-a-t-s',
# 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-cat-s-', '-ca-ts', '-ca-ts-',
# '-ca-t-s', '-ca-t-s-', '-c-ats', '-c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts',
# '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']
</code>```

Body:
No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

c-ats
ca-ts
-c-ats
etc,

Is anybody able to help me?

Body:
I assume that you want to generate all possible ways to insert zero or more hyphens into your word s.t. no two hyphens are adjacent. Here is one way to do this with itertools.product:

from itertools import product

def hyphens(word):
  # create template, each {} is to be filled with "" or "-"
  template = "{}" + "{}".join(word) + "{}"
  # iterate over all possible ways to fill empty braces
  for chars in product(["", "-"], repeat=len(word) + 1):
    yield template.format(*chars)

list(hyphens('cats'))
# ['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s', 'ca-t-s-',
# 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-a-ts-', 'c-a-t-s',
# 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-cat-s-', '-ca-ts', '-ca-ts-',
# '-ca-t-s', '-ca-t-s-', '-c-ats', '-c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts',
# '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']


问:
How can I make my VBA error handling more efficient
I've written this for each loop that gives me the result I am looking for, but when I step through the code it seems to be repeating the error handler, and is therefore running pretty slow. Is there a way to make it run more efficiently?

The reason I needed error handling at all is because it is looping through values from a VLOOKUP and some cells contain an error.

```<code>For Each cell In maxStockRange
        On Error GoTo ErrorValue
        If cell.value = "0" Then
            cell.value = ""
        End If
ErrorValue:
            If cell.Text = "#N/A" Then
                cell.value = ""
            End If
            Resume Next
    Next cell
</code>```

答:
Erroring Cells

Why not change the formula?

```<code>=IFERROR(IF(VLOOKUP(...)=0,"",VLOOKUP(...)),"")
</code>```

Think about how you never ever want to have mixed formulas and values in a data column.

' This works for values.
maxStockRange.Replace 0, "", xlWhole
maxStockRange.Replace "#N/A", "", xlWhole

' This also works for formulas.
For Each cell In maxStockRange
    Select Case True
    Case IsError(cell), CStr(cell.Value) = "0"
        cell.Value = ""
    Case Else
    End Select
Next cell
```

Body:
I've written this for each loop that gives me the result I am looking for, but when I step through the code it seems to be repeating the error handler, and is therefore running pretty slow. Is there a way to make it run more efficiently?

The reason I needed error handling at all is because it is looping through values from a VLOOKUP and some cells contain an error.

For Each cell In maxStockRange
        On Error GoTo ErrorValue
        If cell.value = "0" Then
            cell.value = ""
        End If
ErrorValue:
            If cell.Text = "#N/A" Then
                cell.value = ""
            End If
            Resume Next
    Next cell

Body:
Erroring Cells

Why not change the formula?

=IFERROR(IF(VLOOKUP(...)=0,"",VLOOKUP(...)),"")

Think about how you never ever want to have mixed formulas and values in a data column.

' This works for values.
maxStockRange.Replace 0, "", xlWhole
maxStockRange.Replace "#N/A", "", xlWhole

' This also works for formulas.
For Each cell In maxStockRange
    Select Case True
    Case IsError(cell), CStr(cell.Value) = "0"
        cell.Value = ""
    Case Else
    End Select
Next cell


问:
How to overload |= operator on scoped enum?
How can I overload the |= operator on a strongly typed (scoped) enum (in C++11, GCC)?

I want to test, set and clear bits on strongly typed enums. Why strongly typed? Because my books say it is good practice. But this means I have to static_cast<int> everywhere. To prevent this, I overload the | and & operators, but I can't figure out how to overload the |= operator on an enum. For a class you'd simply put the operator definition in the class, but for enums that doesn't seem to work syntactically.

This is what I have so far:

```<code>enum class NumericType
{
    None                    = 0,

    PadWithZero             = 0x01,
    NegativeSign            = 0x02,
    PositiveSign            = 0x04,
    SpacePrefix             = 0x08
};

inline NumericType operator |(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) | static_cast<int>(b));
}

inline NumericType operator &(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) & static_cast<int>(b));
}
</code>```

The reason I do this: this is the way it works in strongly-typed C#: an enum there is just a struct with a field of its underlying type, and a bunch of constants defined on it. But it can have any integer value that fits in the enum's hidden field.

And it seems that C++ enums work in the exact same way. In both languages casts are required to go from enum to int or vice versa. However, in C# the bitwise operators are overloaded by default, and in C++ they aren't.

答:
After reading this question, I have overloaded the bitwise operators valid for all enums.</p>
```<code>template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator~(const T& value)
{
    return static_cast<T>(~static_cast<int>(value));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator|(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) | static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator|=(T& left, const T& right)
{
    return left = left | right;
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator&(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) & static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator&=(T& left, const T& right)
{
    return left = left & right;
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator^(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) ^ static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator^=(T& left, const T& right)
{
    return left = left ^ right;
}
</code>```

Body:
How can I overload the |= operator on a strongly typed (scoped) enum (in C++11, GCC)?

I want to test, set and clear bits on strongly typed enums. Why strongly typed? Because my books say it is good practice. But this means I have to static_cast<int> everywhere. To prevent this, I overload the | and & operators, but I can't figure out how to overload the |= operator on an enum. For a class you'd simply put the operator definition in the class, but for enums that doesn't seem to work syntactically.

This is what I have so far:

enum class NumericType
{
    None                    = 0,

    PadWithZero             = 0x01,
    NegativeSign            = 0x02,
    PositiveSign            = 0x04,
    SpacePrefix             = 0x08
};

inline NumericType operator |(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) | static_cast<int>(b));
}

inline NumericType operator &(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) & static_cast<int>(b));
}

The reason I do this: this is the way it works in strongly-typed C#: an enum there is just a struct with a field of its underlying type, and a bunch of constants defined on it. But it can have any integer value that fits in the enum's hidden field.

And it seems that C++ enums work in the exact same way. In both languages casts are required to go from enum to int or vice versa. However, in C# the bitwise operators are overloaded by default, and in C++ they aren't.

Body:
After reading this question, I have overloaded the bitwise operators valid for all enums.

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator~(const T& value)
{
    return static_cast<T>(~static_cast<int>(value));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator|(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) | static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator|=(T& left, const T& right)
{
    return left = left | right;
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator&(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) & static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator&=(T& left, const T& right)
{
    return left = left & right;
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator^(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) ^ static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator^=(T& left, const T& right)
{
    return left = left ^ right;
}


问:
How to specify each index number - Python
I'm writing this program that is supposed to convert binary to hex. I have to use the for loop. The part I need is how do I get the program to get the integer and its index number.

my code so far

```<code>q = raw_input('asdf ')
p = list(q)
t = [int(x) for x in p]
for i in t:
    if i == 1:
    w=i*(2**(3-t[x]))
    print w
</code>```

the t[x] part is supposed to be the index number. So what is happening is if its a one then it will multiply by 2^3-(its index number)

How do I refer to the index number?

And how do I get it to sum all the values it gets

答:
You can use the enumerate function.

```<code>for rank, item in enumerate(my_list):
   # here you have the index of the item (rank)
   # and the item ( the same as my_list[rank] )
</code>```

for your example you can do something like this :

```<code> inital_binary = raw_input("polop")
 for rank, letter in enumerate(inital_binary):
    print int(letter) * 2**(len(inital_binary) - (rank+1))
</code>```

that will give for an input of 1100 :

```<code>8
4
0
0
</code>```

Body:
I'm writing this program that is supposed to convert binary to hex. I have to use the for loop. The part I need is how do I get the program to get the integer and its index number.

my code so far

q = raw_input('asdf ')
p = list(q)
t = [int(x) for x in p]
for i in t:
    if i == 1:
    w=i*(2**(3-t[x]))
    print w

the t[x] part is supposed to be the index number. So what is happening is if its a one then it will multiply by 2^3-(its index number)

How do I refer to the index number?

And how do I get it to sum all the values it gets

Body:
You can use the enumerate function.

for rank, item in enumerate(my_list):
   # here you have the index of the item (rank)
   # and the item ( the same as my_list[rank] )

for your example you can do something like this :

 inital_binary = raw_input("polop")
 for rank, letter in enumerate(inital_binary):
    print int(letter) * 2**(len(inital_binary) - (rank+1))

that will give for an input of 1100 :

8
4
0
0


问:
Prismic embedded url for a video does not load
```<code>  <video
    controls
    className={"w-full h-full object-contain"}
    loop
    autoPlay
    muted
  >
    <source
      src={videoUrl.embed_url}
      type="video/mp4"
      className={"relative z-[100000]"}
    />
  </video>
</code>```

If I put static(local) video src -> it works. But external video URL - doesn't.

What can cause this problem?

答:
i would try creating a frame. and sorry im not sure of the cause of the problem</p>
```<code><iframe width="420" height="315" src="https://www.youtube.com"> </iframe>
</code>```

Body:
  <video
    controls
    className={"w-full h-full object-contain"}
    loop
    autoPlay
    muted
  >
    <source
      src={videoUrl.embed_url}
      type="video/mp4"
      className={"relative z-[100000]"}
    />
  </video>

If I put static(local) video src -> it works. But external video URL - doesn't.

What can cause this problem?

Body:
i would try creating a frame. and sorry im not sure of the cause of the problem

<iframe width="420" height="315" src="https://www.youtube.com"> </iframe>


问:
name 'target' is not defined Feature Selection
I am working on feature selection based on the LOFO Importance selection algorithm. I have defined the target value but it gives an error that the target value is not defined.

```<code>import pandas as pd
from sklearn.model_selection import KFold
from lofo import LOFOImportance, Dataset, plot_importance
%matplotlib inline

# import data
train_df = pd.read_csv("/content/heat_pipe.csv")

train_df.head()

# # extract a sample of the data
sample_df = train_df.sample(frac=0.01, random_state=0)
sample_df.sort_values("Date", inplace=True)

# # define the validation scheme
cv = KFold(n_splits=4, shuffle=True, random_state=0)

# # define the binary target and the features
dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])

# # define the validation scheme and scorer. The default model is LightGBM
lofo_imp = LOFOImportance(dataset, cv=cv, scoring="roc_auc")

# # # get the mean and standard deviation of the importances in pandas format
importance_df = lofo_imp.get_importance()

# # # plot the means and standard deviations of the importances
plot_importance(importance_df, figsize=(12, 20))
</code>```

Error

```<code>NameError                                 Traceback (most recent call last)
<ipython-input-33-cca2efb2dc97> in <module>()
     34
     35 # # define the binary target and the features
---> 36 dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])
     37
     38 # # # define the validation scheme and scorer. The default model is LightGBM

<ipython-input-33-cca2efb2dc97> in <listcomp>(.0)
     34
     35 # # define the binary target and the features
---> 36 dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])
     37
     38 # # # define the validation scheme and scorer. The default model is LightGBM

NameError: name 'target' is not defined
</code>```

答:
There is a confusion with your usage of

```<code>dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])
</code>```

The target="day_of_the_week" is a kwarg (a named parameter for the Dataset() class.  It isn't assigning the value of "day_of_the_week" to target.

Try adding target = "day_of_the_week" before that line:

```<code>
import pandas as pd
from sklearn.model_selection import KFold
from lofo import LOFOImportance, Dataset, plot_importance
%matplotlib inline

# import data
train_df = pd.read_csv("/content/heat_pipe.csv")

train_df.head()

# # extract a sample of the data
sample_df = train_df.sample(frac=0.01, random_state=0)
sample_df.sort_values("Date", inplace=True)

# # define the validation scheme
cv = KFold(n_splits=4, shuffle=True, random_state=0)

# set target
target = "day_of_the_week"

# # define the binary target and the features
dataset = Dataset(df=sample_df, target=target, features=[col for col in train_df.columns if col != target])

# # define the validation scheme and scorer. The default model is LightGBM
lofo_imp = LOFOImportance(dataset, cv=cv, scoring="roc_auc")

# # # get the mean and standard deviation of the importances in pandas format
importance_df = lofo_imp.get_importance()

# # # plot the means and standard deviations of the importances
plot_importance(importance_df, figsize=(12, 20))
</code>```

Body:
I am working on feature selection based on the LOFO Importance selection algorithm. I have defined the target value but it gives an error that the target value is not defined.

import pandas as pd
from sklearn.model_selection import KFold
from lofo import LOFOImportance, Dataset, plot_importance
%matplotlib inline

# import data
train_df = pd.read_csv("/content/heat_pipe.csv")

train_df.head()

# # extract a sample of the data
sample_df = train_df.sample(frac=0.01, random_state=0)
sample_df.sort_values("Date", inplace=True)

# # define the validation scheme
cv = KFold(n_splits=4, shuffle=True, random_state=0)

# # define the binary target and the features
dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])

# # define the validation scheme and scorer. The default model is LightGBM
lofo_imp = LOFOImportance(dataset, cv=cv, scoring="roc_auc")

# # # get the mean and standard deviation of the importances in pandas format
importance_df = lofo_imp.get_importance()

# # # plot the means and standard deviations of the importances
plot_importance(importance_df, figsize=(12, 20))

Error

NameError                                 Traceback (most recent call last)
<ipython-input-33-cca2efb2dc97> in <module>()
     34
     35 # # define the binary target and the features
---> 36 dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])
     37
     38 # # # define the validation scheme and scorer. The default model is LightGBM

<ipython-input-33-cca2efb2dc97> in <listcomp>(.0)
     34
     35 # # define the binary target and the features
---> 36 dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])
     37
     38 # # # define the validation scheme and scorer. The default model is LightGBM

NameError: name 'target' is not defined

Body:
There is a confusion with your usage of

dataset = Dataset(df=sample_df, target="day_of_the_week", features=[col for col in train_df.columns if col != target])

The target="day_of_the_week" is a kwarg (a named parameter for the Dataset() class.  It isn't assigning the value of "day_of_the_week" to target.

Try adding target = "day_of_the_week" before that line:

import pandas as pd
from sklearn.model_selection import KFold
from lofo import LOFOImportance, Dataset, plot_importance
%matplotlib inline

# import data
train_df = pd.read_csv("/content/heat_pipe.csv")

train_df.head()

# # extract a sample of the data
sample_df = train_df.sample(frac=0.01, random_state=0)
sample_df.sort_values("Date", inplace=True)

# # define the validation scheme
cv = KFold(n_splits=4, shuffle=True, random_state=0)

# set target
target = "day_of_the_week"

# # define the binary target and the features
dataset = Dataset(df=sample_df, target=target, features=[col for col in train_df.columns if col != target])

# # define the validation scheme and scorer. The default model is LightGBM
lofo_imp = LOFOImportance(dataset, cv=cv, scoring="roc_auc")

# # # get the mean and standard deviation of the importances in pandas format
importance_df = lofo_imp.get_importance()

# # # plot the means and standard deviations of the importances
plot_importance(importance_df, figsize=(12, 20))


问:
Python nested dictionary comprehension with file objects
Fairly new to Python. I'm working on making a code more eloquent by trying to minimally write a nested for loop within a nested for loop to ultimate create a dictionary, where the dictionary includes the words as key and the frequency of words as values in a file. I believe I figured out how to do the inner for loop using dictionary comprehension but am having trouble figuring out the syntax for the outer for loop. I am guessing the outer for loop would be set up as a list comprehension expression. Currently I am not going to worry about what type of character is being considered a word (symbol, number, alphabet), and am trying to avoid importing any additional libraries. Could you maybe show me some examples, or point me to a resource I could read up more into nested comprehensions/advanced comprehensions?

The "brute force" fundamental method I originally developed looks along the lines of this:

```<code>word_cache = {}
# Some code here

with open('myfile.txt') as lines:
    for line in lines:
        for word in line.split():
            word_cache[word]=word_cache.get(word,0)+1

    '''
    Below is alternatively what I have for dictionary comprehension.
    The "for line in lines" is what I am having difficulty trying to nest which I believe would replace the "line in the dictionary comprehension". Part of the issue I see is lines is considered a file object.
    '''
    word_cache.update({word:word_cache.get(word,0)+1 for word in line.split()})

    # Tried the below but did not work because this is the (line for line in lines) is a generator expression
    word_cache.update({word:word_cache.get(word,0)+1 for word in (line for line in lines).split()})
</code>```

Could someone help me understand what is the correct syntax for nested comprehensions of file objects (assuming the object file comes from a txt file)?

答:
Just put the for loops one after another:

```<code>{word: word_cache.get(word,0) + 1 for word in line .split() for line in lines}
</code>```

See the last example of PEP 274

As mentioned in the comments, a comprehension doesn't really help in your context as the assignment will only occur when the loops are completed.

Comprehensions are sometimes very useful, but they're only syntactic sugar. Nothing that a plain for loop can't do.

Body:
Fairly new to Python. I'm working on making a code more eloquent by trying to minimally write a nested for loop within a nested for loop to ultimate create a dictionary, where the dictionary includes the words as key and the frequency of words as values in a file. I believe I figured out how to do the inner for loop using dictionary comprehension but am having trouble figuring out the syntax for the outer for loop. I am guessing the outer for loop would be set up as a list comprehension expression. Currently I am not going to worry about what type of character is being considered a word (symbol, number, alphabet), and am trying to avoid importing any additional libraries. Could you maybe show me some examples, or point me to a resource I could read up more into nested comprehensions/advanced comprehensions?

The "brute force" fundamental method I originally developed looks along the lines of this:

word_cache = {}
# Some code here

with open('myfile.txt') as lines:
    for line in lines:
        for word in line.split():
            word_cache[word]=word_cache.get(word,0)+1

    '''
    Below is alternatively what I have for dictionary comprehension.
    The "for line in lines" is what I am having difficulty trying to nest which I believe would replace the "line in the dictionary comprehension". Part of the issue I see is lines is considered a file object.
    '''
    word_cache.update({word:word_cache.get(word,0)+1 for word in line.split()})

    # Tried the below but did not work because this is the (line for line in lines) is a generator expression
    word_cache.update({word:word_cache.get(word,0)+1 for word in (line for line in lines).split()})

Could someone help me understand what is the correct syntax for nested comprehensions of file objects (assuming the object file comes from a txt file)?

Body:
Just put the for loops one after another:

{word: word_cache.get(word,0) + 1 for word in line .split() for line in lines}

See the last example of PEP 274

As mentioned in the comments, a comprehension doesn't really help in your context as the assignment will only occur when the loops are completed.

Comprehensions are sometimes very useful, but they're only syntactic sugar. Nothing that a plain for loop can't do.


问:
async function in Python not working as expected
I have the following code snippet:

```<code>import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()
</code>```

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.

Ideal output is:

```<code>BEFORE
AFTER
</code>```

Right now it's

```<code>AFTER
BEFORE
</code>```

答:
run seems to be blocking, so you might want to just use gather here:

```<code>import asyncio

async def main():
    await asyncio.gather(work(), setup())
    print('After gather')

async def work():
    await asyncio.sleep(2)
    print("AFTER")

async def setup():
    print("BEFORE")

asyncio.run(main())
</code>```

This correctly prints

```<code>BEFORE
AFTER
After gather
</code>```

The entire gather statement itself is blocking as well, but all of the functions specified in the gather statement can run asynchronously.

Body:
I have the following code snippet:

import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.

Ideal output is:

BEFORE
AFTER

Right now it's

AFTER
BEFORE

Body:
run seems to be blocking, so you might want to just use gather here:

import asyncio

async def main():
    await asyncio.gather(work(), setup())
    print('After gather')

async def work():
    await asyncio.sleep(2)
    print("AFTER")

async def setup():
    print("BEFORE")

asyncio.run(main())

This correctly prints

BEFORE
AFTER
After gather

The entire gather statement itself is blocking as well, but all of the functions specified in the gather statement can run asynchronously.


问:
Does "new char[]" need to be release resources manually?
For this:
m_sFilename = new char [len+1];

Should I call delete[] m_sFilename; sometime?

And:

should I use delete[] m_sFilename or delete m_sFilename;?

答:
Yes, if you don't want the memory allocated by the new[] to leak, you should delete[] it when you're done using that memory.

To avoid having to keep track of that memory, I recommend you use std::string or std::vector instead.


问:
Pandas json_Normalize Outputs only 1 Huge Row
I am trying to turn JSON data into a Pandas dataframe in Python.

Whenever I use df = pd.json_normalize(data)

The output is 1 rows x 285750 columns.
Screenshot of output in Jupyter Notebook

I am ultimately trying to get a dataframe that has a row for each item 'name'

This is a sample of the JSON:

```<code>    {
        "success": true,
        "currency": "USD",
        "timestamp": 1644687375,
        "items_list": {
            "&#39Blueberries&#39 Buckshot | NSWC SEAL": {
                "name": "&#39Blueberries&#39 Buckshot | NSWC SEAL",
                "price": {
                    "7_days": {
                        "average": 1.46,
                        "median": 1.45,
                        "sold": "50",
                        "standard_deviation": "5.38",
                        "lowest_price": 1.33,
                        "highest_price": 1.54
                    },
                    "30_days": {
                        "average": 1.43,
                        "median": 1.43,
                        "sold": "3157",
                        "standard_deviation": "5.51",
                        "lowest_price": 1.06,
                        "highest_price": 1.58
                    },
                    "all_time": {
                        "average": 1.2,
                        "median": 1.39,
                        "sold": "123024",
                        "standard_deviation": "14.02",
                        "lowest_price": 0.83,
                        "highest_price": 1.74
                    }
                },
                "first_sale_date": "1607036400"
            },
            "&#39Medium Rare&#39 Crasswater | Guerrilla Warfare": {
                "name": "&#39Medium Rare&#39 Crasswater | Guerrilla Warfare",
                "price": {
                    "7_days": {
                        "average": 4.68,
                        "median": 4.66,
                        "sold": "49",
                        "standard_deviation": "1.68",
                        "lowest_price": 4.55,
                        "highest_price": 4.81
                    },
                    "30_days": {
                        "average": 4.58,
                        "median": 4.58,
                        "sold": "4584",
                        "standard_deviation": "5.15",
                        "lowest_price": 3.71,
                        "highest_price": 5.21
                    },
                    "all_time": {
                        "average": 7.24,
                        "median": 4.76,
                        "sold": "30250",
                        "standard_deviation": "22.02",
                        "lowest_price": 3.71,
                        "highest_price": 15.16
                    }
                },
                "first_sale_date": "1632348000"
            }
    }
}
</code>```

I'm very new to coding in general, so I opted to not include the other solutions I've tried incase they are erroneous or don't make sense. Thanks in advance for any help!

答:
data["items_list"] is a dict where the .values() is a "list" of the data you need. This can be passed directly to pandas.json_normalize() to produce the needed output.

```<code>>>> pd.json_normalize(data["items_list"].values())
                                                name first_sale_date  ...  price.all_time.lowest_price  price.all_time.highest_price
0           &#39Blueberries&#39 Buckshot | NSWC SEAL      1607036400  ...                         0.83                          1.74
1  &#39Medium Rare&#39 Crasswater | Guerrilla War...      1632348000  ...                         3.71                         15.16

[2 rows x 20 columns]
</code>```

Body:
I am trying to turn JSON data into a Pandas dataframe in Python.

Whenever I use df = pd.json_normalize(data)

The output is 1 rows x 285750 columns.
Screenshot of output in Jupyter Notebook

I am ultimately trying to get a dataframe that has a row for each item 'name'

This is a sample of the JSON:

    {
        "success": true,
        "currency": "USD",
        "timestamp": 1644687375,
        "items_list": {
            "&#39Blueberries&#39 Buckshot | NSWC SEAL": {
                "name": "&#39Blueberries&#39 Buckshot | NSWC SEAL",
                "price": {
                    "7_days": {
                        "average": 1.46,
                        "median": 1.45,
                        "sold": "50",
                        "standard_deviation": "5.38",
                        "lowest_price": 1.33,
                        "highest_price": 1.54
                    },
                    "30_days": {
                        "average": 1.43,
                        "median": 1.43,
                        "sold": "3157",
                        "standard_deviation": "5.51",
                        "lowest_price": 1.06,
                        "highest_price": 1.58
                    },
                    "all_time": {
                        "average": 1.2,
                        "median": 1.39,
                        "sold": "123024",
                        "standard_deviation": "14.02",
                        "lowest_price": 0.83,
                        "highest_price": 1.74
                    }
                },
                "first_sale_date": "1607036400"
            },
            "&#39Medium Rare&#39 Crasswater | Guerrilla Warfare": {
                "name": "&#39Medium Rare&#39 Crasswater | Guerrilla Warfare",
                "price": {
                    "7_days": {
                        "average": 4.68,
                        "median": 4.66,
                        "sold": "49",
                        "standard_deviation": "1.68",
                        "lowest_price": 4.55,
                        "highest_price": 4.81
                    },
                    "30_days": {
                        "average": 4.58,
                        "median": 4.58,
                        "sold": "4584",
                        "standard_deviation": "5.15",
                        "lowest_price": 3.71,
                        "highest_price": 5.21
                    },
                    "all_time": {
                        "average": 7.24,
                        "median": 4.76,
                        "sold": "30250",
                        "standard_deviation": "22.02",
                        "lowest_price": 3.71,
                        "highest_price": 15.16
                    }
                },
                "first_sale_date": "1632348000"
            }
    }
}

I'm very new to coding in general, so I opted to not include the other solutions I've tried incase they are erroneous or don't make sense. Thanks in advance for any help!

Body:
data["items_list"] is a dict where the .values() is a "list" of the data you need. This can be passed directly to pandas.json_normalize() to produce the needed output.

>>> pd.json_normalize(data["items_list"].values())
                                                name first_sale_date  ...  price.all_time.lowest_price  price.all_time.highest_price
0           &#39Blueberries&#39 Buckshot | NSWC SEAL      1607036400  ...                         0.83                          1.74
1  &#39Medium Rare&#39 Crasswater | Guerrilla War...      1632348000  ...                         3.71                         15.16

[2 rows x 20 columns]


问:
Refresh Pivot Table without opening Excel wiht Python
i can refresh pivot tables with Python but i don't wanna to see excel, i wanna refresh as invisible on background.

```<code>import win32com.client

office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(r"path\to\excel\file\to\print.xlsm")

count = wb.Sheets.Count
for i in range(count):
    ws = wb.Worksheets[i]

    pivotCount = ws.PivotTables().Count
    for j in range(1, pivotCount+1):
        ws.PivotTables(j).PivotCache().Refresh()
wb.Save()
wb.Close()
</code>```

it didn't show up when I tried yesterday. but i am trying now, excel has been showing up, refresh and close. how can i refresh as invisible?

答:
```<code>    xl = win32.gencache.EnsureDispatch("Excel.Application")
    xl.Visible = False
    xl.DisplayAlerts = False
</code>```

Set Visible = False to let the refresh happen in the background, Excel will not be visible on the screen. You may also consider setting DisplayAlerts = False to suppress any alert window which require any user action.

Body:
i can refresh pivot tables with Python but i don't wanna to see excel, i wanna refresh as invisible on background.

import win32com.client

office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(r"path\to\excel\file\to\print.xlsm")

count = wb.Sheets.Count
for i in range(count):
    ws = wb.Worksheets[i]

    pivotCount = ws.PivotTables().Count
    for j in range(1, pivotCount+1):
        ws.PivotTables(j).PivotCache().Refresh()
wb.Save()
wb.Close()

it didn't show up when I tried yesterday. but i am trying now, excel has been showing up, refresh and close. how can i refresh as invisible?

Body:
    xl = win32.gencache.EnsureDispatch("Excel.Application")
    xl.Visible = False
    xl.DisplayAlerts = False

Set Visible = False to let the refresh happen in the background, Excel will not be visible on the screen. You may also consider setting DisplayAlerts = False to suppress any alert window which require any user action.


问:
How to hanlde concurrency in Mongo DB when we have multiple instances
We are running a Microservice architectire with multiple instances. I have a  mongo document which consisits of list of names.If the document is not present in the collection I create a new document. But if the document is present in the collection I add the name in the existing array. But since I am using multiple instances there could be a race condition. How do I handle this, any help would be appreciated.

Skeleton of code is given below:

```<code>A a = repo.findById("");

if(Objects.nonNull(a))
    do some operation
else{
     a= new A();
}
a.getList.add("");
repo.save(a);
</code>```

How do I handle concurrency in this case when multiple instances are present?

答: Use an upsert update where the doc is modified if it exists or created if not.</p>

Body:
We are running a Microservice architectire with multiple instances. I have a  mongo document which consisits of list of names.If the document is not present in the collection I create a new document. But if the document is present in the collection I add the name in the existing array. But since I am using multiple instances there could be a race condition. How do I handle this, any help would be appreciated.

Skeleton of code is given below:

A a = repo.findById("");

if(Objects.nonNull(a))
    do some operation
else{
     a= new A();
}
a.getList.add("");
repo.save(a);

How do I handle concurrency in this case when multiple instances are present?


问:
I try to separate 2 box layouts but instead they fuse together
I want to separate these 2 box layouts but when I run it, they are literally one over another. I've looked through kivy documents and still didn't find an answer.

Here is my code:

```<code><BoxLayout>:
    spacing:"0dp"
    orientation:"vertical"
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:1,1
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos

<BoxLayout>:
    orientation:"vertical"
    spacing:"10dp"
    TextInput:
        text: "type enemy name"
        size_hint:1,3
        id: starta
    Button:
        text:"Start"
        on_press: root.on_button_click()
        size_hint:1,3
        font_size:40
        id: startb
    Label:
        id: label
        text: "Enter enemy name and press 'start'"
        text_size: self.width-100, None
        font_size:27
    Button:
        text:"Fight"
        size_hint: 1,.3
        color:1,0,0,1
        background_color:.5,0,0
        font_size:40
        opacity:0
        id: thingy
    Button:
        text:"Guard"
        size_hint: 1,.3
        color:0,0,1,1
        background_color:0,0,.5
        font_size:40
        opacity:0
        id: thingys
    Button:
        text:"Heal"
        size_hint: 1,.3
        color:0,1,0,1
        background_color:0,.5,0
        font_size:40
        opacity:0
        id: thingyss
</code>```
```<code>from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import (NumericProperty, StringProperty)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from random import randint
from time import sleep
from threading import Thread
import time
from kivy.core.audio import SoundLoader
turn=False
started=False
attacking=False
healing=False
guard=False
guardcor=False
enemycharge=False
enemyhp=200
playerhp=200
maxmana=50
mana=50
enemydamage=20
playerdamage=13
testify=[]

Builder.load_string("""
<BoxLayout>:
    spacing:"0dp"
    orientation:"vertical"
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:1,1
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos

<BoxLayout>:
    orientation:"vertical"
    spacing:"10dp"
    TextInput:
        text: "type enemy name"
        size_hint:1,3
        id: starta
    Button:
        text:"Start"
        on_press: root.on_button_click()
        size_hint:1,3
        font_size:40
        id: startb
    Label:
        id: label
        text: "Enter enemy name and press 'start'"
        text_size: self.width-100, None
        font_size:27
    Button:
        text:"Fight"
        size_hint: 1,.3
        color:1,0,0,1
        background_color:.5,0,0
        font_size:40
        opacity:0
        id: thingy
    Button:
        text:"Guard"
        size_hint: 1,.3
        color:0,0,1,1
        background_color:0,0,.5
        font_size:40
        opacity:0
        id: thingys
    Button:
        text:"Heal"
        size_hint: 1,.3
        color:0,1,0,1
        background_color:0,.5,0
        font_size:40
        opacity:0
        id: thingyss

""")

from time import sleep
from threading import Thread

class ProcessingThread(Thread):
    global testify
    global enemyhp
    global playerhp
    global maxmana
    global mana
    global enemydamage
    global playerdamage
    global attacking
    global healing
    global guard
    global turn
    global enemycharge
    global guardcor
    def run(self):
        global attacking
        global healing
        global guard
        global turn
        global testify
        global enemyhp
        global playerhp
        global maxmana
        global mana
        global enemydamage
        global playerdamage
        global enemycharge
        global guardcor
        label = testify[0]
        fightb = testify[1]
        guardb = testify[2]
        healb = testify[3]
        enemyname=testify[4]
        rootui=testify[5]
        #enemyhpui=testify[6]
        #playerhpui=testify[7]
        #manaui=testify[8]
        fightb.opacity = 1
        guardb.opacity = 1
        healb.opacity = 1

        TextBox.type_text(rootui, "who you are fighting againist is %s, be careful. they are strong."% enemyname)
        sleep(7)
        label.color=1,0,0,1
        TextBox.type_text(rootui, "FIGHT makes you deal 13 damage to the enemy.")
        sleep(5)
        label.color=0,0,1,1
        TextBox.type_text(rootui,"GUARD makes you not get hit when the enemy attacks.")
        sleep(5.5)
        label.color=0,1,0,1
        TextBox.type_text(rootui, "and lastly, HEAL makes you heal 30 health.")
        sleep(5)
        label.color=1,1,1,1
        TextBox.type_text(rootui, "good luck, player.")
        sleep(3)
        soundyeye = SoundLoader.load('battlesong.mp3')
        soundyeye.loop=True
        soundyeye.play()
        TextBox.type_text(rootui, "%s jumps into the battlefield!"% enemyname)
        while True:
            dialoguerng=randint(1,4)
            if dialoguerng==1:
                TextBox.type_text(rootui,"%s looks around him and then looks back to you."% enemyname)
                sleep(6)
            elif dialoguerng==2:
                TextBox.type_text(rootui,"%s readies itself."% enemyname)
                sleep(3)
            elif dialoguerng==3:
                TextBox.type_text(rootui,"%s is too excited to beat you up"% enemyname)
                sleep(5)
            elif dialoguerng==4:
                TextBox.type_text(rootui, "%s is sick of this battling system"% enemyname)
                sleep(5)
            label.text="what are you going to do?"
            turn=True
            while True:
                sleep(0.1)
                if attacking==True:
                    turn=False
                    attacking==False
                    TextBox.type_text()
                    break
                elif guard==True:
                    turn=False
                    guard=False
                    guardcor==True
                    break
                elif healing==True:
                    turn=False
                    healing==False

                    break

class TextBox(BoxLayout):
    cache_text = StringProperty("") # For storing the entered text.
    index = NumericProperty(0) # For iteration over cache_text.
    global started
    global testify
    def hide_widget(self, wid, dohide=True):
        if hasattr(wid, 'saved_attrs'):
            if not dohide:
                wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs
                del wid.saved_attrs
        elif dohide:
            wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled
            wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True

    def type_text(self, txt, time=0.06):
        global testify
        self.ids.label.text = ""  # Comment it out to retain the text.
        self.cache_text = txt # Store the entered text here.
        # For more control you may use method Clock.create_trigger.
        self.ev = Clock.schedule_interval(self.update_text, time) # Update text after every 0.25 sec.

    def update_text(self, *args):
            global testify
            if self.index < len(self.cache_text):
                val = self.cache_text[self.index]
                self.ids.label.text += val # Appending to existing text.
                self.index += 1
            else:
                self.index = 0 # Reset index.
                self.cache_text = "" # Clear cache.
                self.ev.cancel() # Cancel text updation.

    def on_button_click(self):
        global testify
        global started
        if started==False:
            started=True
            enemyname = self.ids.starta.text
            self.hide_widget(self.ids.starta)
            self.hide_widget(self.ids.startb)
            testify.insert(0,self.ids.label)
            testify.insert(1,self.ids.thingy)
            testify.insert(2,self.ids.thingys)
            testify.insert(3,self.ids.thingyss)
            testify.insert(4,enemyname)
            testify.insert(5,self)
            p = ProcessingThread()
            p.start()

class TestApp(App):
    def build(self):
        return TextBox()

TestApp().run()
</code>```

also dont blame me if the script sucks I am new I started like 5 days ago (if you ask why one of the 3 labels from the "first" boxlayout's size is different other than the 2 other, it is for testing purposes)
gui layout output
gui layout output 2

答:
When you define a rule in a kv file using <SomeClass>, that rule gets applied to every instance of that SomeClass that gets created after the kv file is loaded. If you have two different rules like <SomeClass>, then the second set of properties from the second rule just get added to the first.

If you want different properties, you can create different classes and define different <> rules. Or, you can define a single rule that contains two instances of the original SomeClass.

In your case you can do something like:

```<code>FloatLayout:
    TextBox:
        # properties of the first TextBox
        .
        .
        .
    TextBox:
        # properties of the second TextBox
        .
        .
        .
</code>```

Of course, you will need to position and size the TextBox instances.

You can use a <TextBox> rule to define properties that will be common to all instances of TextBox.

Body:
I want to separate these 2 box layouts but when I run it, they are literally one over another. I've looked through kivy documents and still didn't find an answer.

Here is my code:

<BoxLayout>:
    spacing:"0dp"
    orientation:"vertical"
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:1,1
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos

<BoxLayout>:
    orientation:"vertical"
    spacing:"10dp"
    TextInput:
        text: "type enemy name"
        size_hint:1,3
        id: starta
    Button:
        text:"Start"
        on_press: root.on_button_click()
        size_hint:1,3
        font_size:40
        id: startb
    Label:
        id: label
        text: "Enter enemy name and press 'start'"
        text_size: self.width-100, None
        font_size:27
    Button:
        text:"Fight"
        size_hint: 1,.3
        color:1,0,0,1
        background_color:.5,0,0
        font_size:40
        opacity:0
        id: thingy
    Button:
        text:"Guard"
        size_hint: 1,.3
        color:0,0,1,1
        background_color:0,0,.5
        font_size:40
        opacity:0
        id: thingys
    Button:
        text:"Heal"
        size_hint: 1,.3
        color:0,1,0,1
        background_color:0,.5,0
        font_size:40
        opacity:0
        id: thingyss

from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import (NumericProperty, StringProperty)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from random import randint
from time import sleep
from threading import Thread
import time
from kivy.core.audio import SoundLoader
turn=False
started=False
attacking=False
healing=False
guard=False
guardcor=False
enemycharge=False
enemyhp=200
playerhp=200
maxmana=50
mana=50
enemydamage=20
playerdamage=13
testify=[]

Builder.load_string("""
<BoxLayout>:
    spacing:"0dp"
    orientation:"vertical"
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:1,1
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos
    Label:
        text:"test"
        background_color: (64/255, 64/255, 64/255,1)
        size_hint:.2,.3
        canvas.before:
            Color:
                rgba: self.background_color
            Rectangle:
                size: self.size
                pos: self.pos

<BoxLayout>:
    orientation:"vertical"
    spacing:"10dp"
    TextInput:
        text: "type enemy name"
        size_hint:1,3
        id: starta
    Button:
        text:"Start"
        on_press: root.on_button_click()
        size_hint:1,3
        font_size:40
        id: startb
    Label:
        id: label
        text: "Enter enemy name and press 'start'"
        text_size: self.width-100, None
        font_size:27
    Button:
        text:"Fight"
        size_hint: 1,.3
        color:1,0,0,1
        background_color:.5,0,0
        font_size:40
        opacity:0
        id: thingy
    Button:
        text:"Guard"
        size_hint: 1,.3
        color:0,0,1,1
        background_color:0,0,.5
        font_size:40
        opacity:0
        id: thingys
    Button:
        text:"Heal"
        size_hint: 1,.3
        color:0,1,0,1
        background_color:0,.5,0
        font_size:40
        opacity:0
        id: thingyss

""")

from time import sleep
from threading import Thread

class ProcessingThread(Thread):
    global testify
    global enemyhp
    global playerhp
    global maxmana
    global mana
    global enemydamage
    global playerdamage
    global attacking
    global healing
    global guard
    global turn
    global enemycharge
    global guardcor
    def run(self):
        global attacking
        global healing
        global guard
        global turn
        global testify
        global enemyhp
        global playerhp
        global maxmana
        global mana
        global enemydamage
        global playerdamage
        global enemycharge
        global guardcor
        label = testify[0]
        fightb = testify[1]
        guardb = testify[2]
        healb = testify[3]
        enemyname=testify[4]
        rootui=testify[5]
        #enemyhpui=testify[6]
        #playerhpui=testify[7]
        #manaui=testify[8]
        fightb.opacity = 1
        guardb.opacity = 1
        healb.opacity = 1

        TextBox.type_text(rootui, "who you are fighting againist is %s, be careful. they are strong."% enemyname)
        sleep(7)
        label.color=1,0,0,1
        TextBox.type_text(rootui, "FIGHT makes you deal 13 damage to the enemy.")
        sleep(5)
        label.color=0,0,1,1
        TextBox.type_text(rootui,"GUARD makes you not get hit when the enemy attacks.")
        sleep(5.5)
        label.color=0,1,0,1
        TextBox.type_text(rootui, "and lastly, HEAL makes you heal 30 health.")
        sleep(5)
        label.color=1,1,1,1
        TextBox.type_text(rootui, "good luck, player.")
        sleep(3)
        soundyeye = SoundLoader.load('battlesong.mp3')
        soundyeye.loop=True
        soundyeye.play()
        TextBox.type_text(rootui, "%s jumps into the battlefield!"% enemyname)
        while True:
            dialoguerng=randint(1,4)
            if dialoguerng==1:
                TextBox.type_text(rootui,"%s looks around him and then looks back to you."% enemyname)
                sleep(6)
            elif dialoguerng==2:
                TextBox.type_text(rootui,"%s readies itself."% enemyname)
                sleep(3)
            elif dialoguerng==3:
                TextBox.type_text(rootui,"%s is too excited to beat you up"% enemyname)
                sleep(5)
            elif dialoguerng==4:
                TextBox.type_text(rootui, "%s is sick of this battling system"% enemyname)
                sleep(5)
            label.text="what are you going to do?"
            turn=True
            while True:
                sleep(0.1)
                if attacking==True:
                    turn=False
                    attacking==False
                    TextBox.type_text()
                    break
                elif guard==True:
                    turn=False
                    guard=False
                    guardcor==True
                    break
                elif healing==True:
                    turn=False
                    healing==False

                    break

class TextBox(BoxLayout):
    cache_text = StringProperty("") # For storing the entered text.
    index = NumericProperty(0) # For iteration over cache_text.
    global started
    global testify
    def hide_widget(self, wid, dohide=True):
        if hasattr(wid, 'saved_attrs'):
            if not dohide:
                wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs
                del wid.saved_attrs
        elif dohide:
            wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled
            wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True

    def type_text(self, txt, time=0.06):
        global testify
        self.ids.label.text = ""  # Comment it out to retain the text.
        self.cache_text = txt # Store the entered text here.
        # For more control you may use method Clock.create_trigger.
        self.ev = Clock.schedule_interval(self.update_text, time) # Update text after every 0.25 sec.

    def update_text(self, *args):
            global testify
            if self.index < len(self.cache_text):
                val = self.cache_text[self.index]
                self.ids.label.text += val # Appending to existing text.
                self.index += 1
            else:
                self.index = 0 # Reset index.
                self.cache_text = "" # Clear cache.
                self.ev.cancel() # Cancel text updation.

    def on_button_click(self):
        global testify
        global started
        if started==False:
            started=True
            enemyname = self.ids.starta.text
            self.hide_widget(self.ids.starta)
            self.hide_widget(self.ids.startb)
            testify.insert(0,self.ids.label)
            testify.insert(1,self.ids.thingy)
            testify.insert(2,self.ids.thingys)
            testify.insert(3,self.ids.thingyss)
            testify.insert(4,enemyname)
            testify.insert(5,self)
            p = ProcessingThread()
            p.start()

class TestApp(App):
    def build(self):
        return TextBox()

TestApp().run()

also dont blame me if the script sucks I am new I started like 5 days ago (if you ask why one of the 3 labels from the "first" boxlayout's size is different other than the 2 other, it is for testing purposes)
gui layout output
gui layout output 2

Body:
When you define a rule in a kv file using <SomeClass>, that rule gets applied to every instance of that SomeClass that gets created after the kv file is loaded. If you have two different rules like <SomeClass>, then the second set of properties from the second rule just get added to the first.

If you want different properties, you can create different classes and define different <> rules. Or, you can define a single rule that contains two instances of the original SomeClass.

In your case you can do something like:

FloatLayout:
    TextBox:
        # properties of the first TextBox
        .
        .
        .
    TextBox:
        # properties of the second TextBox
        .
        .
        .

Of course, you will need to position and size the TextBox instances.

You can use a <TextBox> rule to define properties that will be common to all instances of TextBox.


问:
Given center, dimensions and orientation of a box, whats the quickest way of calculating its vertices?
suppose I have a box characterized by

```<code>box = [cx,cy,cz,length,width,height,tx,ty,tz]
</code>```

where cx,cy,cz is the coordinate of the center of the box. and tx,ty,tz are the angles the box is rotated w.r.t to each axis, for example, yaw can be calculated by arctan(ty/tx).

What is the quickest way one can calculate the 8 vertices of this box? A google search yielded no algorithm. Although not too difficult of a task, would appreciate someone sharing an algorithm if known.

A simplifying assumption is that the pitch and roll angles can be ignored.

EDIT: basically asking for the reverse of Convert 3D box vertices to center, dimensions and rotation

答:
With only yaw to use, the directions of the edges are (tx, ty, 0), (-ty, tx, 0), (0, 0, 1). Normalized to unit length they are nx = (tx, ty, 0)/sqrt(tx²+ty²) ny = (-ty, tx, 0)/sqrt(tx²+ty²) and nz = (0, 0, 1).

Then the positions of the vertices are (cx, cy, cz) + (±.5*length, ±.5*width, ±.5*height) * (nx, ny, nz).

The three ± signs lead to 8 combinations for the 8 vertices of the rotated box.

Please check that in your application the rotation around the yaw axis has the correct sign. Normally it is defined as positive rotation with  the axis going up. And yaw = arctan ty/tx also confirms this.

Depending on how tx and ty are given, sqrt(tx²+ty²) could already/always be normalized to 1, which would simplify the first formula for the normalized edge directions.

Body:
suppose I have a box characterized by

box = [cx,cy,cz,length,width,height,tx,ty,tz]

where cx,cy,cz is the coordinate of the center of the box. and tx,ty,tz are the angles the box is rotated w.r.t to each axis, for example, yaw can be calculated by arctan(ty/tx).

What is the quickest way one can calculate the 8 vertices of this box? A google search yielded no algorithm. Although not too difficult of a task, would appreciate someone sharing an algorithm if known.

A simplifying assumption is that the pitch and roll angles can be ignored.

EDIT: basically asking for the reverse of Convert 3D box vertices to center, dimensions and rotation


问:
Append data from another page with jquery
I have a div with content, and clicking on a button will call a page where more data is pulled from the database.

How can I append that new info to the same div?

I was going to use .load(), but that rewrites the data in the div. I thought about loading the content into a hidden div, then using .append() to put it in the right place. But felt like that was an awkward work around.

Is there a better solution?

答:
You can use $.get:

```<code>$.get('path_to/file.php', function (data) {
    $('#div_to_append_to').append('<p>' + data + '</p>');
});
</code>```

This appends the data from your ajax call to the div rather than overwrite its contents all together.

Documentation on $.get - http://api.jquery.com/jQuery.get/

Body:
You can use $.get:

$.get('path_to/file.php', function (data) {
    $('#div_to_append_to').append('<p>' + data + '</p>');
});

This appends the data from your ajax call to the div rather than overwrite its contents all together.

Documentation on $.get - http://api.jquery.com/jQuery.get/