问:
Select some rows from a XML file with Python
I have an XML that i want to export some rows, base in attribute 1 content.

My File is like that:

```<code><Root>
  <First_Level_Node>
    <Element_Name>
      <attribute1>1</attribute1>
      <attribute2>2</attribute2>
      <attribute3>3</attribute3>
      <attribute4>4</attribute4>
      <attribute5>5</attribute5>
      <attribute6>6</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>41</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random value</attribute5>
      <attribute6>18th Jun 2014  07:09:18 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>23rd Jul 2014  02:47:10 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>43</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>08th Nov 2014  23:53:31 GMT</attribute6>
    </Element_Name>
  </First_Level_Node>
</Root>
</code>```

And based on the value of the attribute 1, I want to get all the rows from that element.
For example, I want attribute 1 = 42 or attribute 1 = 43, so the output will be like:

```<code><Root>
  <First_Level_Node>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>23rd Jul 2014  02:47:10 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>43</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>08th Nov 2014  23:53:31 GMT</attribute6>
    </Element_Name>
  </First_Level_Node>
</Root>
</code>```

I want to use Python for this.

I tried to use ElementTree, but was unsuccessful. That's what I tried so far

```<code>with open("output.xml", 'r') as f3:
        root = ET.parse(f3)

    tree=root.getroot()
    with open("list_xxx", 'r') as f2:
        for line in f2:
            line = line.rstrip()
            print (line)
            #get all subnet nodes containing certain ManagedElementId
            subnet_path = './/*[attribute1="{0}"]'
            subnet_path = subnet_path.format(line)
            for subnet in tree.findall(subnet_path):
                #reconstruct subnet node:
                parent = ET.Element(subnet.tag, attrib=subnet.attrib)
                #path to find all ManagedElement containing certain ManagedElementId
                content_path = ".//*[attribute1='{0}']".format(line)
                print (content_path)

                #append all ManagedElement found to the new subnet:
                for content in subnet.findall(content_path):
                    parent.append(content)
                #print new subnet:
                print (ET.tostring(parent))
</code>```

And list xxx has the values of attribute 1 that I am looking for:

```<code>41
42
</code>```

答:
You've already pre-selected the Element_Name elements which have the specified attribute1 contents (41 and 42).  There is no need to re-select them a second time, which is causing the entire Element_Name element to be returned by findall().

You just need to select the child attribute1 elements at that point.

Therefore, if you change

```<code>content_path = ".//*[attribute1='{0}']".format(line)
</code>```

to

```<code> content_path = "attribute1"
</code>```

your program will print:

```<code>41
attribute1
b'<Element_Name><attribute1>41</attribute1>\n      </Element_Name>'
42
attribute1
b'<Element_Name><attribute1>42</attribute1>\n      </Element_Name>'
</code>```

Body:
I have an XML that i want to export some rows, base in attribute 1 content.

My File is like that:

<Root>
  <First_Level_Node>
    <Element_Name>
      <attribute1>1</attribute1>
      <attribute2>2</attribute2>
      <attribute3>3</attribute3>
      <attribute4>4</attribute4>
      <attribute5>5</attribute5>
      <attribute6>6</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>41</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random value</attribute5>
      <attribute6>18th Jun 2014  07:09:18 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>23rd Jul 2014  02:47:10 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>43</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>08th Nov 2014  23:53:31 GMT</attribute6>
    </Element_Name>
  </First_Level_Node>
</Root>

And based on the value of the attribute 1, I want to get all the rows from that element.
For example, I want attribute 1 = 42 or attribute 1 = 43, so the output will be like:

<Root>
  <First_Level_Node>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>23rd Jul 2014  02:47:10 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>43</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>08th Nov 2014  23:53:31 GMT</attribute6>
    </Element_Name>
  </First_Level_Node>
</Root>

I want to use Python for this.

I tried to use ElementTree, but was unsuccessful. That's what I tried so far

with open("output.xml", 'r') as f3:
        root = ET.parse(f3)

    tree=root.getroot()
    with open("list_xxx", 'r') as f2:
        for line in f2:
            line = line.rstrip()
            print (line)
            #get all subnet nodes containing certain ManagedElementId
            subnet_path = './/*[attribute1="{0}"]'
            subnet_path = subnet_path.format(line)
            for subnet in tree.findall(subnet_path):
                #reconstruct subnet node:
                parent = ET.Element(subnet.tag, attrib=subnet.attrib)
                #path to find all ManagedElement containing certain ManagedElementId
                content_path = ".//*[attribute1='{0}']".format(line)
                print (content_path)

                #append all ManagedElement found to the new subnet:
                for content in subnet.findall(content_path):
                    parent.append(content)
                #print new subnet:
                print (ET.tostring(parent))

And list xxx has the values of attribute 1 that I am looking for:

41
42

Body:
You've already pre-selected the Element_Name elements which have the specified attribute1 contents (41 and 42).  There is no need to re-select them a second time, which is causing the entire Element_Name element to be returned by findall().

You just need to select the child attribute1 elements at that point.

Therefore, if you change

content_path = ".//*[attribute1='{0}']".format(line)

to

 content_path = "attribute1"

your program will print:

41
attribute1
b'<Element_Name><attribute1>41</attribute1>\n      </Element_Name>'
42
attribute1
b'<Element_Name><attribute1>42</attribute1>\n      </Element_Name>'


来源: stackexchange

问:
Core data taking time to insert records with fetching entity & set as relationship
I have 2 entities: Components & SurveyReadingWeb that have a one-to-many relationship.
I have saved Components data in core data database; but while saving SurveyReadingWeb -- in a for loop -- I have to fetch Components data entity by passing component id and setting the surveyreadings isComponentexists relationship, like in the code below for 8000 records. This process is taking too much time, nearly 7 minutes.  How can I reduce the time?</p>

```<code>for item in items {
            autoIncrementId = autoIncrementId + 1
            print("reading items parsed:- \(item.SurveyReadingId), \(autoIncrementId)")

            let reading : SurveyReadingWeb? = NSEntityDescription.insertNewObject(forEntityName: Constants.EntityNames.kSURVEYREADINGWEB, into: self.managedContext) as? SurveyReadingWeb
            reading?.surveyId1 = Int32(autoIncrementId)
            reading?.surveyId = Int32(item.SurveyId) ?? 0
            reading?.readingData = item.CH4
            reading?.surveyDateTime = item.SurveyReadingDateTime
            reading?.latitude = item.Latitude
            reading?.longitude = item.Longitude
            reading?.serialNumber = item.SerialNumber
            reading?.descriptionText = item.Description
            reading?.componentName = item.Description
            reading?.componentId = Int32(item.ComponentId) ?? 0
            reading?.readingTypeId = Int32(item.ReadingTypeID) ?? 0
            reading?.readingTypeDetails = item.ReadingTypeDetails

            reading?.currentLatitude = item.CurrentLatitude
            reading?.currentLongitude = item.CurrentLongitude
            reading?.hdop = item.HDOP
            reading?.vdop = item.VDOP
            reading?.componentDistance = item.ComponentDistance
            reading?.facilityId = Int32(item.ProjectId) ?? 0
            reading?.posted = 1
            reading?.readyToSync = 1

            reading?.isComponentExists = DatabaseManager.sharedManager.getCompNameFromID(compID: Int32(item.ComponentId) ?? 0)
        }
        saveContext()

func getCompNameFromID(compID : Int32) -> Components? {
    var component : Components? = nil
    let fetchRequest : NSFetchRequest<Components> = Components.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "componentId == %ld", compID)

    do {
        let searchResults = try managedContext.fetch(fetchRequest)
        component =  (searchResults.first) ?? nil
    } catch {
    }
    return component ?? nil
}
</code>```

答:
You can reduce the time dramatically if you add an NSCache instance to cache compID:Components key value pairs.

In getCompNameFromID check if the compID exists in the cache. If yes get the value from the cache (very fast), if not fetch the record and save it for the compID in the cache.

And use the convenient SurveyReadingWeb(context: initializer to get rid of all the ugly question marks, however the performance benefit is rather tiny.

ContentLicense: CC BY-SA 4.0

Body:
I have 2 entities: Components & SurveyReadingWeb that have a one-to-many relationship.
I have saved Components data in core data database; but while saving SurveyReadingWeb -- in a for loop -- I have to fetch Components data entity by passing component id and setting the surveyreadings isComponentexists relationship, like in the code below for 8000 records. This process is taking too much time, nearly 7 minutes.  How can I reduce the time?

for item in items {
            autoIncrementId = autoIncrementId + 1
            print("reading items parsed:- \(item.SurveyReadingId), \(autoIncrementId)")

            let reading : SurveyReadingWeb? = NSEntityDescription.insertNewObject(forEntityName: Constants.EntityNames.kSURVEYREADINGWEB, into: self.managedContext) as? SurveyReadingWeb
            reading?.surveyId1 = Int32(autoIncrementId)
            reading?.surveyId = Int32(item.SurveyId) ?? 0
            reading?.readingData = item.CH4
            reading?.surveyDateTime = item.SurveyReadingDateTime
            reading?.latitude = item.Latitude
            reading?.longitude = item.Longitude
            reading?.serialNumber = item.SerialNumber
            reading?.descriptionText = item.Description
            reading?.componentName = item.Description
            reading?.componentId = Int32(item.ComponentId) ?? 0
            reading?.readingTypeId = Int32(item.ReadingTypeID) ?? 0
            reading?.readingTypeDetails = item.ReadingTypeDetails

            reading?.currentLatitude = item.CurrentLatitude
            reading?.currentLongitude = item.CurrentLongitude
            reading?.hdop = item.HDOP
            reading?.vdop = item.VDOP
            reading?.componentDistance = item.ComponentDistance
            reading?.facilityId = Int32(item.ProjectId) ?? 0
            reading?.posted = 1
            reading?.readyToSync = 1

            reading?.isComponentExists = DatabaseManager.sharedManager.getCompNameFromID(compID: Int32(item.ComponentId) ?? 0)
        }
        saveContext()

func getCompNameFromID(compID : Int32) -> Components? {
    var component : Components? = nil
    let fetchRequest : NSFetchRequest<Components> = Components.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "componentId == %ld", compID)

    do {
        let searchResults = try managedContext.fetch(fetchRequest)
        component =  (searchResults.first) ?? nil
    } catch {
    }
    return component ?? nil
}


问:
Unity iOS app crashes for unclear reasons
I'm trying to fix a crash which occurs in my app a lot. The crash alert shows after killing the app's process (by hitting device's home button twice and swiping up the process) and reopening the app. After closing the Apple's crash popup, the app launches without problems. Sometimes the app crashes in background, even though some time passed since it was closed. Here are the logs I found on the device (I had to replace strings containing company name).

First log, this is related to crash on app start after killing the process (I had to paste links due to SO's character limit):

```<code>Crash log#1
https://pastebin.com/kuPSAqJY
</code>```

Second log, this is related to the second, unclear crash:

```<code>Crash log#2
https://pastebin.com/zcjdLpHq
</code>```

Do you know what may cause these crashes?

The exception raised in both cases is:

Exception Type:  EXC_CRASH (SIGKILL)
      Exception Codes: 0x0000000000000000, 0x0000000000000000
      Exception Note:  EXC_CORPSE_NOTIFY
      Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d
      Termination Description: SPRINGBOARD, scene-update watchdog transgression: application:4258 exhausted real (wall clock) time allowance of 10.00 seconds | ProcessVisibility: Foreground | ProcessState: Running | WatchdogEvent: scene-update | WatchdogVisibility: Background | WatchdogCPUStatistics: ( | "Elapsed total CPU time (seconds): 6.200 (user 6.200, system 0.000), 63% CPU", | "Elapsed application CPU time (seconds): 4.853, 49% CPU" | )

[edit] I noticed that when I build and run the app on the device through xCode (instead of using Testflight), the crash alert doesn't show up (but the app takes longer to launch). However, an exception in xCode: exc_bad_access is being displayed.

Is there any way I could "translate" these addresses into something more helpful? I noticed that NullReferenceException is being thrown as well (it shows in the output). May these two be related?

答: For anyone wondering: I haven't found a solution for this problem. Instead, I just submitted the app to App Store and it has been accepted. The crash popup doesn't show up outside of Testflight.</p>

Body:
I'm trying to fix a crash which occurs in my app a lot. The crash alert shows after killing the app's process (by hitting device's home button twice and swiping up the process) and reopening the app. After closing the Apple's crash popup, the app launches without problems. Sometimes the app crashes in background, even though some time passed since it was closed. Here are the logs I found on the device (I had to replace strings containing company name).

First log, this is related to crash on app start after killing the process (I had to paste links due to SO's character limit):

Crash log#1
https://pastebin.com/kuPSAqJY

Second log, this is related to the second, unclear crash:

Crash log#2
https://pastebin.com/zcjdLpHq

Do you know what may cause these crashes?

The exception raised in both cases is:

Exception Type:  EXC_CRASH (SIGKILL)
      Exception Codes: 0x0000000000000000, 0x0000000000000000
      Exception Note:  EXC_CORPSE_NOTIFY
      Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d
      Termination Description: SPRINGBOARD, scene-update watchdog transgression: application:4258 exhausted real (wall clock) time allowance of 10.00 seconds | ProcessVisibility: Foreground | ProcessState: Running | WatchdogEvent: scene-update | WatchdogVisibility: Background | WatchdogCPUStatistics: ( | "Elapsed total CPU time (seconds): 6.200 (user 6.200, system 0.000), 63% CPU", | "Elapsed application CPU time (seconds): 4.853, 49% CPU" | )

[edit] I noticed that when I build and run the app on the device through xCode (instead of using Testflight), the crash alert doesn't show up (but the app takes longer to launch). However, an exception in xCode: exc_bad_access is being displayed.

Is there any way I could "translate" these addresses into something more helpful? I noticed that NullReferenceException is being thrown as well (it shows in the output). May these two be related?


问:
Mysql error: Column count doesn't match value count at row 1; code appears to match suggestions of guides,
I'm working on the website for a mmo-rpg game-based group, and I'm having trouble on the insert form for their 'hitlist'; my code is as follows:

function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

$Pri = check_input($_GET['Pri']);
$Pir = check_input($_GET['Pir']);
$Lvl = check_input($_GET['Lvl']);
$XCd = check_input($_GET['XCd']);
$YCd = check_input($_GET['YCd']);
$Nts = mysql_real_escape_string(check_input($_GET['Nts']));
$Opl = check_input($_GET['Opl']);
$Kwl = check_input($_GET['Kwl']);
$Ktl = check_input($_GET['Ktl']);
$Tty = mysql_real_escape_string(check_input($_GET['Tty']));
$Grp = check_input($_GET['Grp']);

$sql="INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error() . ' ' . $sql);
  }
```

<p>Yes, I've looked elsewhere, and yes, here is a printout of the query:</p>

<pre class="lang-php prettyprint-override"><code>INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`) VALUES ('','1','Eri','13','13751','408','?','?','?','?','?','Coming Soon.','Sector 23')
</code>```

I really don't understand what I'm doing wrong.  The Id is auto-incremented, and this query works in phpMyAdmin

A new set of eyes would really be appreciated here.

答:
If it still doesn't work, avoid the id. </p>

```<code>INSERT INTO modattacklist ( `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('$Pri','$Pir','$Lvl','$KnownFltLvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on the website for a mmo-rpg game-based group, and I'm having trouble on the insert form for their 'hitlist'; my code is as follows:

function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

$Pri = check_input($_GET['Pri']);
$Pir = check_input($_GET['Pir']);
$Lvl = check_input($_GET['Lvl']);
$XCd = check_input($_GET['XCd']);
$YCd = check_input($_GET['YCd']);
$Nts = mysql_real_escape_string(check_input($_GET['Nts']));
$Opl = check_input($_GET['Opl']);
$Kwl = check_input($_GET['Kwl']);
$Ktl = check_input($_GET['Ktl']);
$Tty = mysql_real_escape_string(check_input($_GET['Tty']));
$Grp = check_input($_GET['Grp']);

$sql="INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error() . ' ' . $sql);
  }

Yes, I've looked elsewhere, and yes, here is a printout of the query:

INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`) VALUES ('','1','Eri','13','13751','408','?','?','?','?','?','Coming Soon.','Sector 23')

I really don't understand what I'm doing wrong.  The Id is auto-incremented, and this query works in phpMyAdmin

A new set of eyes would really be appreciated here.

Body:
If it still doesn't work, avoid the id.

INSERT INTO modattacklist ( `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('$Pri','$Pir','$Lvl','$KnownFltLvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')


问:
Additional parameter in oauth2 token request
I'm developing backend for oauth2 client. I'm using authorization_grant flow with PKCE extension. I'm trying to implement it in such way that code verifier and code challenge is generated on clients side. So i have to add additional parameters to my token request (the second request, when input is authorization code and my application exchange it for access token).
My app will have to take this code_verifier from request param and pass it to authorization server with authorization code, client id, and client secret.

So now I'm struggling with customizing spring-security-oauth2-client to add additional parameter. There is way to add such parameters to authorization request by implementing OAuth2AuthorizationRequestResolver, but is there analogical way for adding parameters to token request?

Or maybe should i implement this endpoint manually?

答: I feel your pain, since Spring OAuth Security is often poorly documented for common use cases. One option you might consider is to provide a custom Spring filter that uses the open source nimbusds libraries, which have very good documentation and are easy to use.</p>


问:
build aborted: no such package '@antlr4_tool//jar'
So I am trying to replicate the textmining usecase of biograkn in the biograkn repo. I am trying to migrate the data in schema, for which i was supposed to do bazel build. so i ran the following command:

bazel build  //migrator:migrator-bin

inside the textmining folder of biograkn. Now, the build fails and I am getting error:

Here is the traceback

```<code>DEBUG: Rule 'io_bazel_rules_python' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1545256788 -0500"
DEBUG: Rule 'com_github_grpc_grpc' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1550231355 +0300"
DEBUG: Rule 'stackb_rules_proto' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1561665037 -0600"
DEBUG: Rule 'graknlabs_grakn_core' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870526 +0000"
DEBUG: Rule 'graknlabs_benchmark' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1571391871 +0100"
DEBUG: Rule 'graknlabs_graql' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870025 +0000"
DEBUG: Rule 'rules_antlr' indicated that a canonical reproducible form can be obtained by modifying arguments commit = "397361a4d252a7186bc33add33144f4ede2a3899", shallow_since = "1559662328 +0200" and dropping ["tag"]
DEBUG: Rule 'graknlabs_client_python' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1569623464 +0000"
DEBUG: Rule 'graknlabs_bazel_distribution' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572869706 +0300"
DEBUG: Rule 'com_github_google_bazel_common' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1551104077 +0300"
DEBUG: Rule 'graknlabs_protocol' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870033 +0000"
INFO: Call stack for the definition of repository 'antlr4_tool' which is a http_jar (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/bazel_tools/tools/build_defs/repo/http.bzl:347:12):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/rules_antlr/antlr/deps.bzl:49:5
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/rules_antlr/antlr/deps.bzl:27:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:120:1
ERROR: An error occurred during the fetch of repository 'antlr4_tool':
   java.io.IOException: Error downloading [http://central.maven.org/maven2/org/antlr/antlr4/4.7.2/antlr4-4.7.2.jar] to /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/antlr4_tool/jar/downloaded.jar: Unknown host: central.maven.org
INFO: Call stack for the definition of repository 'remotejdk11_linux' which is a http_archive (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/bazel_tools/tools/build_defs/repo/http.bzl:229:16):
 - /DEFAULT.WORKSPACE.SUFFIX:199:1
INFO: Call stack for the definition of repository 'com_google_protobuf' which is a http_archive (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/bazel_tools/tools/build_defs/repo/http.bzl:229:16):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/com_github_grpc_grpc/bazel/grpc_deps.bzl:125:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:83:1
INFO: Call stack for the definition of repository 'com-google-protobuf-protobuf-java' which is a jar_artifact (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:667:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:103:1
INFO: Call stack for the definition of repository 'org-apache-lucene-lucene-analyzers-common' which is a jar_artifact (rule definition at /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:120:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:72:1
INFO: Call stack for the definition of repository 'io-netty-netty-all' which is a jar_artifact (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:667:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:103:1
INFO: Call stack for the definition of repository 'edu-stanford-nlp-stanford-corenlp-java-models' which is a jar_artifact (rule definition at /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:120:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:72:1
ERROR: /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_graql/grammar/BUILD:24:1: every rule of type antlr4 implicitly depends upon the target '@antlr4_tool//jar:jar', but this target could not be found because of: no such package '@antlr4_tool//jar': java.io.IOException: Error downloading [http://central.maven.org/maven2/org/antlr/antlr4/4.7.2/antlr4-4.7.2.jar] to /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/antlr4_tool/jar/downloaded.jar: Unknown host: central.maven.org
Documentation for implicit attribute deps of rules of type antlr4:

The dependencies to use. Defaults to the official ANTLR 4 release, but if
you need to use a different version, you can specify the dependencies here.

DEBUG: Rule 'graknlabs_common' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870041 +0000"
DEBUG: Rule 'graknlabs_client_java' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1570795516 +0000"
ERROR: Analysis of target '//migrator:migrator-bin' failed; build aborted: no such package '@antlr4_tool//jar': java.io.IOException: Error downloading [http://central.maven.org/maven2/org/antlr/antlr4/4.7.2/antlr4-4.7.2.jar] to /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/antlr4_tool/jar/downloaded.jar: Unknown host: central.maven.org
INFO: Elapsed time: 7.458s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (4 packages loaded, 0 targets configured)
</code>```

I suspect its some antlr4 package issue on maven servers. How to resolve it, if there are any good workarounds?

答:
Yes it looks like the link being depended upon is dead. You are trying to manually migrate the data yourself. To use BioGrakn in the most basic case, you can just download a pre-loaded set of data by following the link in the README/releases page.

If you want to customise things or use it as a basis for your own work, and you want to use Bazel, then the dependencies in the WORKSPACE file should point to more recent commits the relevant repos. In general this repo needs an update.

Body:
So I am trying to replicate the textmining usecase of biograkn in the biograkn repo. I am trying to migrate the data in schema, for which i was supposed to do bazel build. so i ran the following command:

bazel build  //migrator:migrator-bin

inside the textmining folder of biograkn. Now, the build fails and I am getting error:

Here is the traceback

DEBUG: Rule 'io_bazel_rules_python' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1545256788 -0500"
DEBUG: Rule 'com_github_grpc_grpc' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1550231355 +0300"
DEBUG: Rule 'stackb_rules_proto' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1561665037 -0600"
DEBUG: Rule 'graknlabs_grakn_core' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870526 +0000"
DEBUG: Rule 'graknlabs_benchmark' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1571391871 +0100"
DEBUG: Rule 'graknlabs_graql' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870025 +0000"
DEBUG: Rule 'rules_antlr' indicated that a canonical reproducible form can be obtained by modifying arguments commit = "397361a4d252a7186bc33add33144f4ede2a3899", shallow_since = "1559662328 +0200" and dropping ["tag"]
DEBUG: Rule 'graknlabs_client_python' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1569623464 +0000"
DEBUG: Rule 'graknlabs_bazel_distribution' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572869706 +0300"
DEBUG: Rule 'com_github_google_bazel_common' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1551104077 +0300"
DEBUG: Rule 'graknlabs_protocol' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870033 +0000"
INFO: Call stack for the definition of repository 'antlr4_tool' which is a http_jar (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/bazel_tools/tools/build_defs/repo/http.bzl:347:12):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/rules_antlr/antlr/deps.bzl:49:5
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/rules_antlr/antlr/deps.bzl:27:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:120:1
ERROR: An error occurred during the fetch of repository 'antlr4_tool':
   java.io.IOException: Error downloading [http://central.maven.org/maven2/org/antlr/antlr4/4.7.2/antlr4-4.7.2.jar] to /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/antlr4_tool/jar/downloaded.jar: Unknown host: central.maven.org
INFO: Call stack for the definition of repository 'remotejdk11_linux' which is a http_archive (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/bazel_tools/tools/build_defs/repo/http.bzl:229:16):
 - /DEFAULT.WORKSPACE.SUFFIX:199:1
INFO: Call stack for the definition of repository 'com_google_protobuf' which is a http_archive (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/bazel_tools/tools/build_defs/repo/http.bzl:229:16):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/com_github_grpc_grpc/bazel/grpc_deps.bzl:125:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:83:1
INFO: Call stack for the definition of repository 'com-google-protobuf-protobuf-java' which is a jar_artifact (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:667:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:103:1
INFO: Call stack for the definition of repository 'org-apache-lucene-lucene-analyzers-common' which is a jar_artifact (rule definition at /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:120:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:72:1
INFO: Call stack for the definition of repository 'io-netty-netty-all' which is a jar_artifact (rule definition at /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_grakn_core/dependencies/maven/dependencies.bzl:667:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:103:1
INFO: Call stack for the definition of repository 'edu-stanford-nlp-stanford-corenlp-java-models' which is a jar_artifact (rule definition at /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:40:16):
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:58:5
 - /home/aditya/Projects/RD/biograkn/dependencies/maven/dependencies.bzl:120:9
 - /home/aditya/Projects/RD/biograkn/WORKSPACE:72:1
ERROR: /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/graknlabs_graql/grammar/BUILD:24:1: every rule of type antlr4 implicitly depends upon the target '@antlr4_tool//jar:jar', but this target could not be found because of: no such package '@antlr4_tool//jar': java.io.IOException: Error downloading [http://central.maven.org/maven2/org/antlr/antlr4/4.7.2/antlr4-4.7.2.jar] to /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/antlr4_tool/jar/downloaded.jar: Unknown host: central.maven.org
Documentation for implicit attribute deps of rules of type antlr4:

The dependencies to use. Defaults to the official ANTLR 4 release, but if
you need to use a different version, you can specify the dependencies here.

DEBUG: Rule 'graknlabs_common' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1572870041 +0000"
DEBUG: Rule 'graknlabs_client_java' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1570795516 +0000"
ERROR: Analysis of target '//migrator:migrator-bin' failed; build aborted: no such package '@antlr4_tool//jar': java.io.IOException: Error downloading [http://central.maven.org/maven2/org/antlr/antlr4/4.7.2/antlr4-4.7.2.jar] to /home/aditya/.cache/bazel/_bazel_aditya/1271badea2afdf63b6fcb04c93a3b0e2/external/antlr4_tool/jar/downloaded.jar: Unknown host: central.maven.org
INFO: Elapsed time: 7.458s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (4 packages loaded, 0 targets configured)

I suspect its some antlr4 package issue on maven servers. How to resolve it, if there are any good workarounds?


问:
Converting JSONarray to ArrayList
I am downloading a JSON string and converting it to JSONArray.  Im putting it into a listview and need to be able to delete from that listview later, and since JSONArray has no .remove method (Thanks Obama), I am trying to convert it to an arraylist.

here is my JSON (the array.toString()):

```<code>[
    {
         "thumb_url":"tb1370913834.jpg",
         "event_id":"15","count":"44",
         "event_tagline":"this is a tagline",
         "event_name":"5th birthday",
         "event_end":"1370919600",
         "event_start":"1370876400"
    }
]
</code>```

I need to get it into an array and be able to call the strings by their respective keys.  Appreciate any help!

答:
Just going by the original subject of the thread:

converting jsonarray to list (used jackson jsonarray and object mapper here):

```<code>ObjectMapper mapper = new ObjectMapper();
JSONArray array = new JSONArray();
array.put("IND");
array.put("CHN");
List<String> list = mapper.readValue(array.toString(), List.class);
</code>```

Title: Converting JSONarray to ArrayList

Body:
I am downloading a JSON string and converting it to JSONArray.  Im putting it into a listview and need to be able to delete from that listview later, and since JSONArray has no .remove method (Thanks Obama), I am trying to convert it to an arraylist.

here is my JSON (the array.toString()):

[
    {
         "thumb_url":"tb1370913834.jpg",
         "event_id":"15","count":"44",
         "event_tagline":"this is a tagline",
         "event_name":"5th birthday",
         "event_end":"1370919600",
         "event_start":"1370876400"
    }
]

I need to get it into an array and be able to call the strings by their respective keys.  Appreciate any help!

Body:
Just going by the original subject of the thread:

converting jsonarray to list (used jackson jsonarray and object mapper here):

ObjectMapper mapper = new ObjectMapper();
JSONArray array = new JSONArray();
array.put("IND");
array.put("CHN");
List<String> list = mapper.readValue(array.toString(), List.class);


问:
Cumulative Sum of 2 Columns
I am using Postgresql 11.

I have 2 tables - txn_table and summary_table

```<code>create table txn_table(id int, txn_date timestamp, amount decimal);

create table summary_table(id int, txn_date date, day_Total decimal, Cumulative_Total decimal);
</code>```

Sample data for txn_table is

```<code>insert into txn_table values (1, '2020-05-28 10:05:05', 100.00);
insert into txn_table values(2, '2020-05-28 11:45:10', 200.00);
insert into txn_table values(3, '2020-05-29 10:05:05', 300.00);
insert into txn_table values(4, '2020-05-29 12:10:01', 400.00);
</code>```

I want to insert the data in summary_table like below

day_total contains sum of particular day

Cumulative_total contains cumulative sum of day_total

```<code>| id  | txn_date                 | day_total | cumulative_total |
| --- | ------------------------ | --------- | ---------------- |
| 1   | 2020-05-28               | 300       | 300              |
| 2   | 2020-05-29               | 700       | 1000             |
</code>```

答:
do following:

Add unique constraint to txn_date column of summary_table.

```<code>create table summary_table(id SERIAL PRIMARY KEY, txn_date date unique, day_total decimal, cumulative_total decimal);
</code>```

if you want to ignore the duplicates. use below mentioned query

```<code>insert into summary_table(txn_date,day_total,cumulative_total)
(select  txn_date, day_total, sum(day_total) over (order by txn_date) as cumulative_total from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
order by txn_date)
on conflict(txn_date)
do nothing;
</code>```

if you want to update the duplicate values in summary_table. use below mentioned query

```<code>insert into summary_table(txn_date,day_total,cumulative_total)
(select  txn_date, day_total, sum(day_total) over (order by txn_date) as cumulative_total from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
order by txn_date)
on conflict(txn_date)
do update set day_total=EXCLUDED.day_total,
cumulative_total=EXCLUDED.cumulative_total;
</code>```

Title: Cumulative Sum of 2 Columns

Body:
I am using Postgresql 11.

I have 2 tables - txn_table and summary_table

create table txn_table(id int, txn_date timestamp, amount decimal);

create table summary_table(id int, txn_date date, day_Total decimal, Cumulative_Total decimal);

Sample data for txn_table is

insert into txn_table values (1, '2020-05-28 10:05:05', 100.00);
insert into txn_table values(2, '2020-05-28 11:45:10', 200.00);
insert into txn_table values(3, '2020-05-29 10:05:05', 300.00);
insert into txn_table values(4, '2020-05-29 12:10:01', 400.00);

I want to insert the data in summary_table like below

day_total contains sum of particular day

Cumulative_total contains cumulative sum of day_total

| id  | txn_date                 | day_total | cumulative_total |
| --- | ------------------------ | --------- | ---------------- |
| 1   | 2020-05-28               | 300       | 300              |
| 2   | 2020-05-29               | 700       | 1000             |

Body:
do following:

Add unique constraint to txn_date column of summary_table.

create table summary_table(id SERIAL PRIMARY KEY, txn_date date unique, day_total decimal, cumulative_total decimal);

if you want to ignore the duplicates. use below mentioned query

insert into summary_table(txn_date,day_total,cumulative_total)
(select  txn_date, day_total, sum(day_total) over (order by txn_date) as cumulative_total from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
order by txn_date)
on conflict(txn_date)
do nothing;

if you want to update the duplicate values in summary_table. use below mentioned query

insert into summary_table(txn_date,day_total,cumulative_total)
(select  txn_date, day_total, sum(day_total) over (order by txn_date) as cumulative_total from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
order by txn_date)
on conflict(txn_date)
do update set day_total=EXCLUDED.day_total,
cumulative_total=EXCLUDED.cumulative_total;


问:
Code Coverage Results periodically gives: Empty results generated
I've run into a recurring problem with a few different projects using MSTest in VS2012, where every now and then my code coverage stops working (seemingly at random) and instead gives me:

Empty results generated: No binaries were instrumented. Make sure the
  tests ran, required binaries were loaded, had matching symbol files,
  and were not excluded through custom settings. For more information
  see http://go.microsoft.com/fwlink/?LinkID=253731

I've checked the obvious (what it's suggested) but can't seem to figure out what is causing it.

Here is my runsettings file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="Code Coverage"
                     uri="datacollector://Microsoft/CodeCoverage/2.0"
                     assemblyQualifiedName=" Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector,
                                             Microsoft.VisualStudio.TraceCollector,
                                             Version=11.0.0.0,
                                             Culture=neutral,
                                             PublicKeyToken=b03f5f7f11d50a3a">
        <Configuration>
          <CodeCoverage>
            <ModulePaths>
              <Include>
                <ModulePath>.*\.dll$</ModulePath>
              </Include>
              <Exclude>
                <ModulePath>.*\.tests.dll</ModulePath>
              </Exclude>
            </ModulePaths>
            <Attributes>
              <Exclude>
                <Attribute>.*ExcludeFromCodeCoverageAttribute$</Attribute>
                <Attribute>.*GeneratedCodeAttribute$</Attribute>
              </Exclude>
            </Attributes>

            <UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
            <AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
            <CollectFromChildProcesses>True</CollectFromChildProcesses>
            <CollectAspDotNet>False</CollectAspDotNet>
          </CodeCoverage>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>
</code>```

答: Configure Test -> Processor Architecture >> AnyCPU Projects setting >>> X86 to X64.This works for me</p>

Body:
I've run into a recurring problem with a few different projects using MSTest in VS2012, where every now and then my code coverage stops working (seemingly at random) and instead gives me:

Empty results generated: No binaries were instrumented. Make sure the
  tests ran, required binaries were loaded, had matching symbol files,
  and were not excluded through custom settings. For more information
  see http://go.microsoft.com/fwlink/?LinkID=253731

I've checked the obvious (what it's suggested) but can't seem to figure out what is causing it.

Here is my runsettings file:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="Code Coverage"
                     uri="datacollector://Microsoft/CodeCoverage/2.0"
                     assemblyQualifiedName=" Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector,
                                             Microsoft.VisualStudio.TraceCollector,
                                             Version=11.0.0.0,
                                             Culture=neutral,
                                             PublicKeyToken=b03f5f7f11d50a3a">
        <Configuration>
          <CodeCoverage>
            <ModulePaths>
              <Include>
                <ModulePath>.*\.dll$</ModulePath>
              </Include>
              <Exclude>
                <ModulePath>.*\.tests.dll</ModulePath>
              </Exclude>
            </ModulePaths>
            <Attributes>
              <Exclude>
                <Attribute>.*ExcludeFromCodeCoverageAttribute$</Attribute>
                <Attribute>.*GeneratedCodeAttribute$</Attribute>
              </Exclude>
            </Attributes>

            <UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
            <AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
            <CollectFromChildProcesses>True</CollectFromChildProcesses>
            <CollectAspDotNet>False</CollectAspDotNet>
          </CodeCoverage>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>


问:
Unable to insert rows of a CSV file into a MYSQL database through python
I need to read a CSV file that contains the number of infected people per country and per day and insert the rows into a MYSQL database using python. I have already created the database and it contains the same amount of columns as the CSV file. When I try to run the code below, I get the following error message: "ValueError: Could not process parameters". Can you please have a look and let me know if there is something wrong with he code? Many thanks!

```<code>import pandas as pd
import mysql.connector

mydb = mysql.connector.connect(
  host="127.0.0.1",
  user="root",
  passwd="xxxx",
  database="covid19_ca"
)

mycursor = mydb.cursor()

dataframe = pd.read_csv('total_cases_modified.csv')
print(dataframe)

for row in dataframe:
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan) VALUES("%s", "%s", "%s"")', row)
    mydb.commit()
    cursor.close()
</code>```

```<code>for _, row in dataframe.iterrows():
    values = (row['date'], row['World'], row['Afghanistan'], row['Albania'], row['Algeria'], row['Andorra'], row['Angola'], row['Anguilla'], row['AntiguaAndBarbuda'], row['Argentina'], row['Armenia'], row['Aruba'], row['Australia'], row['Austria'], row['Azerbaijan'], row['Bahamas'], row['Bahrain'], row['Bangladesh'], row['Barbados'], row['Belarus'], row['Belgium'], row['Belize'], row['Benin'], row['Bermuda'], row['Bhutan'], row['Bolivia'], row['BonaireSintEustatiusAndSaba'], row['BosniaAndHerzegovina'], row['Botswana'], row['Brazil'], row['BritishVirginIslands'], row['Brunei'], row['Bulgaria'], row['BurkinaFaso'], row['Burundi'], row['Cambodia'], row['Cameroon'], row['Canada'], row['CapeVerde'], row['CaymanIslands'], row['CentralAfricanRepublic'], row['Chad'], row['Chile'], row['China'], row['Colombia'], row['Comoros'], row['Congo'], row['CostaRica'], row['CotedIvoire'], row['Croatia'], row['Cuba'], row['Curacao'], row['Cyprus'], row['CzechRepublic'], row['DemocraticRepublicCongo'], row['Denmark'], row['Djibouti'], row['Dominica'], row['DominicanRepublic'], row['Ecuador'], row['Egypt'], row['ElSalvador'], row['EquatorialGuinea'], row['Eritrea'], row['Estonia'], row['Ethiopia'], row['FaeroeIslands'], row['FalklandIslands'], row['Fiji'], row['Finland'], row['France'], row['FrenchPolynesia'], row['Gabon'], row['Gambia'], row['Georgia'], row['Germany'], row['Ghana'], row['Gibraltar'], row['Greece'], row['Greenland'], row['Grenada'], row['Guam'], row['Guatemala'], row['Guernsey'], row['Guinea'], row['GuineaBissau'], row['Guyana'], row['Haiti'], row['Honduras'], row['Hungary'], row['Iceland'], row['India'], row['Indonesia'], row['International'], row['Iran'], row['Iraq'], row['Ireland'], row['IsleofMan'], row['Israel'], row['Italy'], row['Jamaica'], row['Japan'], row['Jersey'], row['Jordan'], row['Kazakhstan'], row['Kenya'], row['Kosovo'], row['Kuwait'], row['Kyrgyzstan'], row['Laos'], row['Latvia'], row['Lebanon'], row['Lesotho'], row['Liberia'], row['Libya'], row['Liechtenstein'], row['Lithuania'], row['Luxembourg'], row['Macedonia'], row['Madagascar'], row['Malawi'], row['Malaysia'], row['Maldives'], row['Mali'], row['Malta'], row['Mauritania'], row['Mauritius'], row['Mexico'], row['Moldova'], row['Monaco'], row['Mongolia'], row['Montenegro'], row['Montserrat'], row['Morocco'], row['Mozambique'], row['Myanmar'], row['Namibia'], row['Nepal'], row['Netherlands'], row['NewCaledonia'], row['NewZealand'], row['Nicaragua'], row['Niger'], row['Nigeria'], row['NorthernMarianaIslands'], row['Norway'], row['Oman'], row['Pakistan'], row['Palestine'], row['Panama'], row['PapuaNewGuinea'], row['Paraguay'], row['Peru'], row['Philippines'], row['Poland'], row['Portugal'], row['PuertoRico'], row['Qatar'], row['Romania'], row['Russia'], row['Rwanda'], row['SaintKittsAndNevis'], row['SaintLucia'], row['SaintVincentAndtheGrenadines'], row['SanMarino'], row['SaoTomeAndPrincipe'], row['SaudiArabia'], row['Senegal'], row['Serbia'], row['Seychelles'], row['SierraLeone'], row['Singapore'], row['SintMaarten'], row['Slovakia'], row['Slovenia'], row['Somalia'], row['SouthAfrica'], row['SouthKorea'], row['SouthSudan'], row['Spain'], row['SriLanka'], row['Sudan'], row['Suriname'], row['Swaziland'], row['Sweden'], row['Switzerland'], row['Syria'], row['Taiwan'], row['Tajikistan'], row['Tanzania'], row['Thailand'], row['Timor'], row['Togo'], row['TrinidadAndTobago'], row['Tunisia'], row['Turkey'], row['TurksAndCaicosIslands'], row['Uganda'], row['Ukraine'], row['UnitedArabEmirates'], row['UnitedKingdom'], row['UnitedStates'], row['UnitedStatesVirginIslands'], row['Uruguay'], row['Uzbekistan'], row['Vatican'], row['Venezuela', row['Vietnam'], row['WesternSahara'], row['Yemen'], row['Zambia'], row['Zimbabwe'])
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan, Albania, Algeria, Andorra, Angola, Anguilla, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, Brazil, BritishVirginIslands, Brunei, Bulgaria, BurkinaFaso, Burundi, Cambodia, Cameroon, Canada, CapeVerde, CaymanIslands, CentralAfricanRepublic,Chad, Chile, China, Colombia, Comoros, Congo, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, CzechRepublic, DemocraticRepublicCongo, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FaeroeIslands, FalklandIslands, Fiji, Finland, France, FrenchPolynesia,Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, Honduras, Hungary, Iceland, India, Indonesia, International, Iran, Iraq, Ireland, IsleofMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Mauritania, Mauritius, Mexico, Moldova, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, NorthernMarianaIslands, Norway, Oman, Pakistan, Palestine, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Poland, Portugal, PuertoRico, Qatar, Romania, Russia, Rwanda, SaintKittsAndNevis, SaintLucia, SaintVincentAndtheGrenadines, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaarten, Slovakia, Slovenia, Somalia, SouthAfrica, SouthKorea, SouthSudan, Spain, SriLanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tajikistan, Tanzania, Thailand, Timor, Togo, TrinidadAndTobago, Tunisia, Turkey, TurksAndCaicosIslands, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdom, UnitedStates, UnitedStatesVirginIslands, Uruguay, Uzbekistan, Vatican, Venezuela, Vietnam, WesternSahara, Yemen, Zambia, Zimbabwe) VALUES("%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s")', values)
</code>```

mydb.commit()

```<code>values = (row['Antigua and Barbuda'])
mycursor.execute('INSERT INTO covid_per_day_per_country (Antigua and Barbuda) VALUES ("%s")', values)
</code>```

ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and Barbuda) VALUES ("%s")' at line 1

答:
The preferred pandas way is to use the to_sql function. Install the sqlalchemy package first. Try this code then. The column names in the table and the dataframe have to be the same.

```<code>from sqlalchemy import create_engine

engine = create_engine('mysql://root:xxxx@127.0.0.1/')
dataframe.to_sql('covid19_ca', engine)
</code>```

If you want to keep using your code and iterate through the dataframe (note it's not recommended), you can try something like this:

```<code>for _, row in dataframe.iterrows():
    values = (row['date'], row['World'], row['Afghanistan'])
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan) VALUES("%s", "%s", "%s")', values)
    mydb.commit()
</code>```

Body:
I need to read a CSV file that contains the number of infected people per country and per day and insert the rows into a MYSQL database using python. I have already created the database and it contains the same amount of columns as the CSV file. When I try to run the code below, I get the following error message: "ValueError: Could not process parameters". Can you please have a look and let me know if there is something wrong with he code? Many thanks!

import pandas as pd
import mysql.connector

mydb = mysql.connector.connect(
  host="127.0.0.1",
  user="root",
  passwd="xxxx",
  database="covid19_ca"
)

mycursor = mydb.cursor()

dataframe = pd.read_csv('total_cases_modified.csv')
print(dataframe)

for row in dataframe:
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan) VALUES("%s", "%s", "%s"")', row)
    mydb.commit()
    cursor.close()

for _, row in dataframe.iterrows():
    values = (row['date'], row['World'], row['Afghanistan'], row['Albania'], row['Algeria'], row['Andorra'], row['Angola'], row['Anguilla'], row['AntiguaAndBarbuda'], row['Argentina'], row['Armenia'], row['Aruba'], row['Australia'], row['Austria'], row['Azerbaijan'], row['Bahamas'], row['Bahrain'], row['Bangladesh'], row['Barbados'], row['Belarus'], row['Belgium'], row['Belize'], row['Benin'], row['Bermuda'], row['Bhutan'], row['Bolivia'], row['BonaireSintEustatiusAndSaba'], row['BosniaAndHerzegovina'], row['Botswana'], row['Brazil'], row['BritishVirginIslands'], row['Brunei'], row['Bulgaria'], row['BurkinaFaso'], row['Burundi'], row['Cambodia'], row['Cameroon'], row['Canada'], row['CapeVerde'], row['CaymanIslands'], row['CentralAfricanRepublic'], row['Chad'], row['Chile'], row['China'], row['Colombia'], row['Comoros'], row['Congo'], row['CostaRica'], row['CotedIvoire'], row['Croatia'], row['Cuba'], row['Curacao'], row['Cyprus'], row['CzechRepublic'], row['DemocraticRepublicCongo'], row['Denmark'], row['Djibouti'], row['Dominica'], row['DominicanRepublic'], row['Ecuador'], row['Egypt'], row['ElSalvador'], row['EquatorialGuinea'], row['Eritrea'], row['Estonia'], row['Ethiopia'], row['FaeroeIslands'], row['FalklandIslands'], row['Fiji'], row['Finland'], row['France'], row['FrenchPolynesia'], row['Gabon'], row['Gambia'], row['Georgia'], row['Germany'], row['Ghana'], row['Gibraltar'], row['Greece'], row['Greenland'], row['Grenada'], row['Guam'], row['Guatemala'], row['Guernsey'], row['Guinea'], row['GuineaBissau'], row['Guyana'], row['Haiti'], row['Honduras'], row['Hungary'], row['Iceland'], row['India'], row['Indonesia'], row['International'], row['Iran'], row['Iraq'], row['Ireland'], row['IsleofMan'], row['Israel'], row['Italy'], row['Jamaica'], row['Japan'], row['Jersey'], row['Jordan'], row['Kazakhstan'], row['Kenya'], row['Kosovo'], row['Kuwait'], row['Kyrgyzstan'], row['Laos'], row['Latvia'], row['Lebanon'], row['Lesotho'], row['Liberia'], row['Libya'], row['Liechtenstein'], row['Lithuania'], row['Luxembourg'], row['Macedonia'], row['Madagascar'], row['Malawi'], row['Malaysia'], row['Maldives'], row['Mali'], row['Malta'], row['Mauritania'], row['Mauritius'], row['Mexico'], row['Moldova'], row['Monaco'], row['Mongolia'], row['Montenegro'], row['Montserrat'], row['Morocco'], row['Mozambique'], row['Myanmar'], row['Namibia'], row['Nepal'], row['Netherlands'], row['NewCaledonia'], row['NewZealand'], row['Nicaragua'], row['Niger'], row['Nigeria'], row['NorthernMarianaIslands'], row['Norway'], row['Oman'], row['Pakistan'], row['Palestine'], row['Panama'], row['PapuaNewGuinea'], row['Paraguay'], row['Peru'], row['Philippines'], row['Poland'], row['Portugal'], row['PuertoRico'], row['Qatar'], row['Romania'], row['Russia'], row['Rwanda'], row['SaintKittsAndNevis'], row['SaintLucia'], row['SaintVincentAndtheGrenadines'], row['SanMarino'], row['SaoTomeAndPrincipe'], row['SaudiArabia'], row['Senegal'], row['Serbia'], row['Seychelles'], row['SierraLeone'], row['Singapore'], row['SintMaarten'], row['Slovakia'], row['Slovenia'], row['Somalia'], row['SouthAfrica'], row['SouthKorea'], row['SouthSudan'], row['Spain'], row['SriLanka'], row['Sudan'], row['Suriname'], row['Swaziland'], row['Sweden'], row['Switzerland'], row['Syria'], row['Taiwan'], row['Tajikistan'], row['Tanzania'], row['Thailand'], row['Timor'], row['Togo'], row['TrinidadAndTobago'], row['Tunisia'], row['Turkey'], row['TurksAndCaicosIslands'], row['Uganda'], row['Ukraine'], row['UnitedArabEmirates'], row['UnitedKingdom'], row['UnitedStates'], row['UnitedStatesVirginIslands'], row['Uruguay'], row['Uzbekistan'], row['Vatican'], row['Venezuela', row['Vietnam'], row['WesternSahara'], row['Yemen'], row['Zambia'], row['Zimbabwe'])
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan, Albania, Algeria, Andorra, Angola, Anguilla, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, Brazil, BritishVirginIslands, Brunei, Bulgaria, BurkinaFaso, Burundi, Cambodia, Cameroon, Canada, CapeVerde, CaymanIslands, CentralAfricanRepublic,Chad, Chile, China, Colombia, Comoros, Congo, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, CzechRepublic, DemocraticRepublicCongo, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FaeroeIslands, FalklandIslands, Fiji, Finland, France, FrenchPolynesia,Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, Honduras, Hungary, Iceland, India, Indonesia, International, Iran, Iraq, Ireland, IsleofMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Mauritania, Mauritius, Mexico, Moldova, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, NorthernMarianaIslands, Norway, Oman, Pakistan, Palestine, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Poland, Portugal, PuertoRico, Qatar, Romania, Russia, Rwanda, SaintKittsAndNevis, SaintLucia, SaintVincentAndtheGrenadines, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaarten, Slovakia, Slovenia, Somalia, SouthAfrica, SouthKorea, SouthSudan, Spain, SriLanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tajikistan, Tanzania, Thailand, Timor, Togo, TrinidadAndTobago, Tunisia, Turkey, TurksAndCaicosIslands, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdom, UnitedStates, UnitedStatesVirginIslands, Uruguay, Uzbekistan, Vatican, Venezuela, Vietnam, WesternSahara, Yemen, Zambia, Zimbabwe) VALUES("%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s")', values)

mydb.commit()

values = (row['Antigua and Barbuda'])
mycursor.execute('INSERT INTO covid_per_day_per_country (Antigua and Barbuda) VALUES ("%s")', values)

ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and Barbuda) VALUES ("%s")' at line 1

Body:
The preferred pandas way is to use the to_sql function. Install the sqlalchemy package first. Try this code then. The column names in the table and the dataframe have to be the same.

from sqlalchemy import create_engine

engine = create_engine('mysql://root:xxxx@127.0.0.1/')
dataframe.to_sql('covid19_ca', engine)

If you want to keep using your code and iterate through the dataframe (note it's not recommended), you can try something like this:

for _, row in dataframe.iterrows():
    values = (row['date'], row['World'], row['Afghanistan'])
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan) VALUES("%s", "%s", "%s")', values)
    mydb.commit()


问:
Converting ConfigParser values to python data types
ConfigParser requires all sections, keys and values to be strings; no surprise. It has methods to convert the values to datatypes with getfloat, getint, getboolean.  If you don't know the datatype, you can wrap the get() with an eval() to get have the string evaluated such as:

```<code>>>> from ConfigParser import SafeConfigParser
>>> cp = SafeConfigParser()
>>> cp.add_section('one')
>>> cp.set('one', 'key', '42')
>>> print cp.get('one', 'key')
'42'
>>> print eval(cp.get('one', 'key'))
42
>>> cp.set('one', 'key', 'None')
>>> print eval(cp.get('one', 'key'))
None
>>>
</code>```

Is there a better way? I assume there some grave security concerns with evaluating text from a file- which I acknowledge; I completely trust the file.

I thought I would use pickle for this, but I would really like to keep the config file human readable.

How would you do it?

答:
If you are using Python 2.6 or above you can use ast.literal_eval:

ast.literal_eval(node_or_string)

  Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

This will work like eval when the string is safe:

```<code>>>> literal_eval("{'key': 10}")
{'key': 10}
</code>```

But it will fail if anything besides the types listed in the documentation appear:

```<code>>>> literal_eval("import os; os.system('rm -rf somepath')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/ast.py", line 49, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib64/python2.6/ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    import os; os.system('rm -rf somepath')
         ^
SyntaxError: invalid syntax
</code>```

Body:
ConfigParser requires all sections, keys and values to be strings; no surprise. It has methods to convert the values to datatypes with getfloat, getint, getboolean.  If you don't know the datatype, you can wrap the get() with an eval() to get have the string evaluated such as:

>>> from ConfigParser import SafeConfigParser
>>> cp = SafeConfigParser()
>>> cp.add_section('one')
>>> cp.set('one', 'key', '42')
>>> print cp.get('one', 'key')
'42'
>>> print eval(cp.get('one', 'key'))
42
>>> cp.set('one', 'key', 'None')
>>> print eval(cp.get('one', 'key'))
None
>>>

Is there a better way? I assume there some grave security concerns with evaluating text from a file- which I acknowledge; I completely trust the file.

I thought I would use pickle for this, but I would really like to keep the config file human readable.

How would you do it?

Body:
If you are using Python 2.6 or above you can use ast.literal_eval:

ast.literal_eval(node_or_string)

  Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

This will work like eval when the string is safe:

>>> literal_eval("{'key': 10}")
{'key': 10}

But it will fail if anything besides the types listed in the documentation appear:

>>> literal_eval("import os; os.system('rm -rf somepath')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/ast.py", line 49, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib64/python2.6/ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    import os; os.system('rm -rf somepath')
         ^
SyntaxError: invalid syntax


问:
How to disable auto-play for local video in iframe
How to disable auto-play for video when src is from my local pc?

```<code><iframe width="465" height="315" src="videos/example.mp4"></iframe>
</code>```

I have tried the following, but it doesn't work:

src="videos/example.mp4?autoplay=0"

src="videos/example.mp4?autoplay=false"

src="videos/example.mp4?autostart=0"

src="videos/example.mp4?autostart=false"

答:
Just replace

```<code><iframe width="465" height="315" src="videos/example.mp4"></iframe>
</code>```

by

```<code><video src="videos/example.mp4" controls></video>
</code>```

Here is an example using bootstrap 4:

```<code> <div class="embed-responsive embed-responsive-4by3">
      <video src="videos/example.mp4" controls></video>
 </div>
</code>```

Body:
How to disable auto-play for video when src is from my local pc?

I have tried the following, but it doesn't work:

src="videos/example.mp4?autoplay=0"

src="videos/example.mp4?autoplay=false"

src="videos/example.mp4?autostart=0"

src="videos/example.mp4?autostart=false"

Body:
Just replace

<iframe width="465" height="315" src="videos/example.mp4"></iframe>

by

<video src="videos/example.mp4" controls></video>

Here is an example using bootstrap 4:

 <div class="embed-responsive embed-responsive-4by3">
      <video src="videos/example.mp4" controls></video>
 </div>


问:
How do I divide integers and not get a 1
Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.</p>

```<code>        Console.Write("Ange dagskassa (kr): ");
        string inlasning = Console.ReadLine();
        int dagskassa = int.Parse(inlasning);

        Console.Write("Ange nuvarande lunchpris (kr): ");
        string inlasning2 = Console.ReadLine();
        int lunchpris = int.Parse(inlasning);

        double antalGaster = dagskassa / lunchpris;

        Console.WriteLine("Antal gäster: " + antalGaster + "st.");
</code>```

答:
You'll need to cast your ints to double in order for the above to work. For example,

```<code>int i = 1;
int j = 2;
double _int = i / j; // without casting, your result will be of type (int) and is rounded
double _double = (double) i / j; // with casting, you'll get the expected result
</code>```

In the case of your code, this would be

```<code>double antalGaster = (double) dagskassa / lunchpris;
</code>```

To round to the lowest whole number for a head count, use Math.Floor()

```<code>double antalGaster = Math.Floor((double) dagskassa / lunchpris);
</code>```

Body:
Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.

        Console.Write("Ange dagskassa (kr): ");
        string inlasning = Console.ReadLine();
        int dagskassa = int.Parse(inlasning);

        Console.Write("Ange nuvarande lunchpris (kr): ");
        string inlasning2 = Console.ReadLine();
        int lunchpris = int.Parse(inlasning);

        double antalGaster = dagskassa / lunchpris;

        Console.WriteLine("Antal gäster: " + antalGaster + "st.");

Body:
You'll need to cast your ints to double in order for the above to work. For example,

int i = 1;
int j = 2;
double _int = i / j; // without casting, your result will be of type (int) and is rounded
double _double = (double) i / j; // with casting, you'll get the expected result

In the case of your code, this would be

double antalGaster = (double) dagskassa / lunchpris;

To round to the lowest whole number for a head count, use Math.Floor()

double antalGaster = Math.Floor((double) dagskassa / lunchpris);


问:
Can't understand how to get rid of goto
This question probably is kind of silly, but I really need help.

I'm pretty new in programming and as far as I know, goto is a thing that I should avoid in my code. And a couple of days ago I wrote this for my school task:

```<code>bool create_way(int start_index) {
if (start_index == members.get_size() - 1) {
    flowToDrain.push_back(start_index);
    return true;
}

find_any_way:
int max_index = INT_MIN;
int max_bandwidth = INT_MIN;

for (int i = 0; i < network[start_index].routes.get_size(); i++) {

    int index = network[start_index].routes.find(i);
    int bandwidth = network[index].bandwidth.find(start_index);

    if (bandwidth > max_bandwidth && !network[index].visited) {
        max_index = index;
        max_bandwidth = bandwidth;
    }
}

network[start_index].visited = true;

if (max_index != INT_MIN) {
    if (!create_way(max_index)) goto find_any_way;
    else {
        flowToDrain.push_back(start_index);
        return true;
    }
}
else return false; }
</code>```

I wrote goto to keep in mind the logic of the algorithm, but now I'm really stuck with it. And since then I haven't came up with any idea how to get rid of this. I understand, that it should be a loop, probably with continue, but I can't understand what expression to check in it.

答:
This should work, though you should test it:</p>

```<code>while(1) {
    int max_index = INT_MIN;
    int max_bandwidth = INT_MIN;

    for (int i = 0; i < network[start_index].routes.get_size(); i++) {

        int index = network[start_index].routes.find(i);
        int bandwidth = network[index].bandwidth.find(start_index);

        if (bandwidth > max_bandwidth && !network[index].visited) {
            max_index = index;
            max_bandwidth = bandwidth;
        }
    }

    network[start_index].visited = true;

    if (max_index != INT_MIN) {
        if (!create_way(max_index)) continue;
        else {
            flowToDrain.push_back(start_index);
            return true;
        }
    }
    else return false;
}
</code>```

Title: Can't understand how to get rid of goto

Body:
This question probably is kind of silly, but I really need help.

I'm pretty new in programming and as far as I know, goto is a thing that I should avoid in my code. And a couple of days ago I wrote this for my school task:

bool create_way(int start_index) {
if (start_index == members.get_size() - 1) {
    flowToDrain.push_back(start_index);
    return true;
}

find_any_way:
int max_index = INT_MIN;
int max_bandwidth = INT_MIN;

for (int i = 0; i < network[start_index].routes.get_size(); i++) {

    int index = network[start_index].routes.find(i);
    int bandwidth = network[index].bandwidth.find(start_index);

    if (bandwidth > max_bandwidth && !network[index].visited) {
        max_index = index;
        max_bandwidth = bandwidth;
    }
}

network[start_index].visited = true;

if (max_index != INT_MIN) {
    if (!create_way(max_index)) goto find_any_way;
    else {
        flowToDrain.push_back(start_index);
        return true;
    }
}
else return false; }

I wrote goto to keep in mind the logic of the algorithm, but now I'm really stuck with it. And since then I haven't came up with any idea how to get rid of this. I understand, that it should be a loop, probably with continue, but I can't understand what expression to check in it.

Body:
This should work, though you should test it:

while(1) {
    int max_index = INT_MIN;
    int max_bandwidth = INT_MIN;

    for (int i = 0; i < network[start_index].routes.get_size(); i++) {

        int index = network[start_index].routes.find(i);
        int bandwidth = network[index].bandwidth.find(start_index);

        if (bandwidth > max_bandwidth && !network[index].visited) {
            max_index = index;
            max_bandwidth = bandwidth;
        }
    }

    network[start_index].visited = true;

    if (max_index != INT_MIN) {
        if (!create_way(max_index)) continue;
        else {
            flowToDrain.push_back(start_index);
            return true;
        }
    }
    else return false;
}


问:
Problem with reasigning value to a list in Angular
hello I have a list of projects listOfPhasesWithTasks which I get from backEnd. I assigned it to a local variable filteredPhasesWithTasks which I'm using in the rest of the project. It is supposed to work as a backup. When I'm doing filtering like this :

```<code> this.filteredPhasesWithTasks.forEach((phase) => {
                    phase.tasks = phase.tasks.filter(task => task.taskName !== null && task.taskName.toUpperCase().includes(filterParam.taskName.toUpperCase()));
                });
</code>```

I don't get why this changes my listOfPhasesWithTasks as well. I'm expecting that it would change only filteredPhasesWithTasks as code says.

答:
In Javascript (and Typescript) objects are passed by reference.

This means if you have an object and you assign it to a new one, you don't duplicate the object, you just have reference to the first object from both variables. Hence, changing a field in one of the variables you assigned "changes it for both". Actually, changes it to the only existing object that is pointed by both your variables :P

You could consider using the cloneDeep method offered by the library Lodash. You'll find a lot of other useful shortcuts there :)

Body:
hello I have a list of projects listOfPhasesWithTasks which I get from backEnd. I assigned it to a local variable filteredPhasesWithTasks which I'm using in the rest of the project. It is supposed to work as a backup. When I'm doing filtering like this :

 this.filteredPhasesWithTasks.forEach((phase) => {
                    phase.tasks = phase.tasks.filter(task => task.taskName !== null && task.taskName.toUpperCase().includes(filterParam.taskName.toUpperCase()));
                });

I don't get why this changes my listOfPhasesWithTasks as well. I'm expecting that it would change only filteredPhasesWithTasks as code says.


问:
mongodb-error validating settings: only one positional argument is allowed
I just moved to a new laptop which had mongo 3.0.0 I believe.
On the new laptop I have mongo 3.0.4. and trying the script that was working on the old laptop is giving me errors. This line is giving me the error.

```<code>mongoimport --host localhost \
            -db roudy123_q \
            -collection LebaneseAmericanUniversity\(Lebanon\).json \
            --file LebaneseAmericanUniversity\(Lebanon\).json \
            --jsonArray
</code>```

error validating settings: only one positional argument is allowed.

I googled the error and the only relevant result was the source code of mongoimport. So I guess it has something to do with the new version.

答:
None of the above mentioned answers solved my problem but they indeed helped me in figuring out what I was doing wrong.(I am using windows)

1)using -d instead of --d (shorthand only require one - not two --)

2)using "" for absolute file path.

3)Changing \ to / in file path location.

For example my files location in windows is:
C:\kp github\other projects\projectXyz\myFile.csv

So for me the command that worked was:

mongoimport -d users -c contacts --type=csv --headerline --file="C:/kp github/other projects/projectXyz/myFile.csv" or

mongoimport -d users -c contacts --type csv --headerline --file "C:/kp github/other projects/projectXyz/myFile.csv"

where users is my db name and contacts is my collection name

Body:
I just moved to a new laptop which had mongo 3.0.0 I believe.
On the new laptop I have mongo 3.0.4. and trying the script that was working on the old laptop is giving me errors. This line is giving me the error.

mongoimport --host localhost \
            -db roudy123_q \
            -collection LebaneseAmericanUniversity\(Lebanon\).json \
            --file LebaneseAmericanUniversity\(Lebanon\).json \
            --jsonArray

error validating settings: only one positional argument is allowed.

I googled the error and the only relevant result was the source code of mongoimport. So I guess it has something to do with the new version.


问:
Integer to Integer Array C#
I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way :
My solution was :</p>

```<code>public static int[] intToArray(int num){
    String holder = num.ToString();
    int[] numbers = new int[Holder.ToString().Length];
    for(int i=0;i<numbers.length;i++){
        numbers[i] = Convert.toInt32(holder.CharAt(i));
    }
    return numbers;
}
</code>```

答:
Integer or Long to Integer Array C#
Convert it to char array and subtract 48.</p>

```<code> public static int[] IntToArray(int value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }

    public static int[] LongToIntArray(long value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }
</code>```

Title: Integer to Integer Array C#

Body:
I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way :
My solution was :

public static int[] intToArray(int num){
    String holder = num.ToString();
    int[] numbers = new int[Holder.ToString().Length];
    for(int i=0;i<numbers.length;i++){
        numbers[i] = Convert.toInt32(holder.CharAt(i));
    }
    return numbers;
}

Body:
Integer or Long to Integer Array C#
Convert it to char array and subtract 48.

 public static int[] IntToArray(int value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }

    public static int[] LongToIntArray(long value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }


问:
Create an array of id's in cookie JS
I want to update the cookie from my WP page with the post id's that the user is visiting. But my problem is that each time the value from the array is deleted and the array contains always just on id, and the next id's are just overwited.

```<code> let post_id = my_script_vars.postID; // this is a variable with some id's
 let arr = [] // i create an array

 function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}

index = arr.indexOf(post_id);
if (index == -1) { // if the id is not in the array the push it
  arr.push(post_id);
  } else { // if it is in array then keep all of them
    arr.splice(index, 1);
  }
setCookie("id_film",JSON.stringify(arr),30);
</code>```

and i want my array to keep all the id's and not just one.

答:
Follow these steps:

Don't create your arr variable until you need it

Add a function to read cookie and return contents as JSON

On page load, read the cookie, update your array, then save new contents

Final code should see like this:

```<code> let post_id = my_script_vars.postID; // this is a variable with some id's

 function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}
// Function to read cookie and return as JSON
function getCookie(name) {
    let a = `; ${document.cookie}`.match(`;\\s*${name}=([^;]+)`);
    return a ? JSON.parse(a[1]) : [];
}

// Be sure to execute after DOM is loaded
window.addEventListener('load', function() {
    // Get saved IDs
    let arr = getCookie('id_film');
    index = arr.indexOf(post_id);
    if (index == -1) {
        // if the id is not in the array the push it
        arr.push(post_id);
    }
    setCookie("id_film",JSON.stringify(arr),30);
});
</code>```

Title: Create an array of id's in cookie JS

Body:
I want to update the cookie from my WP page with the post id's that the user is visiting. But my problem is that each time the value from the array is deleted and the array contains always just on id, and the next id's are just overwited.

 let post_id = my_script_vars.postID; // this is a variable with some id's
 let arr = [] // i create an array

 function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}

index = arr.indexOf(post_id);
if (index == -1) { // if the id is not in the array the push it
  arr.push(post_id);
  } else { // if it is in array then keep all of them
    arr.splice(index, 1);
  }
setCookie("id_film",JSON.stringify(arr),30);

and i want my array to keep all the id's and not just one.

Body:
Follow these steps:

Don't create your arr variable until you need it

Add a function to read cookie and return contents as JSON

On page load, read the cookie, update your array, then save new contents

Final code should see like this:

 let post_id = my_script_vars.postID; // this is a variable with some id's

 function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}
// Function to read cookie and return as JSON
function getCookie(name) {
    let a = `; ${document.cookie}`.match(`;\\s*${name}=([^;]+)`);
    return a ? JSON.parse(a[1]) : [];
}

// Be sure to execute after DOM is loaded
window.addEventListener('load', function() {
    // Get saved IDs
    let arr = getCookie('id_film');
    index = arr.indexOf(post_id);
    if (index == -1) {
        // if the id is not in the array the push it
        arr.push(post_id);
    }
    setCookie("id_film",JSON.stringify(arr),30);
});


问:
SQL Server - drop multiple columns with IF EXISTS at once
SQL Server supports syntax that allows to remove more than one column at a time. How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

Though it seems to be impossible to force it to work with IF EXISTS clasue for each occurence.

ALTER TABLE

```<code>DROP
| COLUMN [ IF EXISTS ]
      {
          column_name
      } [ ,...n ]
</code>```

Conditionally drops the column or constraint only if it already exists.

Example:

```<code>CREATE TABLE t(i INT, col1 INT, col2 INT);

ALTER TABLE t DROP COLUMN IF EXISTS col1, col2;
-- col1, col2 were successfully removed

ALTER TABLE t DROP COLUMN IF EXISTS col1,  col2;
-- Msg 4924 Level 16 State 1 Line 1
-- ALTER TABLE DROP COLUMN failed because column 'col2' does not exist in table 't'.
</code>```

Based on error message IF EXISTS takes effect only for first column.

db<>fiddle demo

Is there a limitation of this clause when combined with multiple columns at once?

答:
The syntax is a bit cumbersome but

```<code>ALTER TABLE t DROP COLUMN IF EXISTS col1,
                   COLUMN IF EXISTS col2;
</code>```

works fine

Body:
SQL Server supports syntax that allows to remove more than one column at a time. How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

Though it seems to be impossible to force it to work with IF EXISTS clasue for each occurence.

ALTER TABLE

DROP
| COLUMN [ IF EXISTS ]
      {
          column_name
      } [ ,...n ]

Conditionally drops the column or constraint only if it already exists.

Example:

CREATE TABLE t(i INT, col1 INT, col2 INT);

ALTER TABLE t DROP COLUMN IF EXISTS col1, col2;
-- col1, col2 were successfully removed

ALTER TABLE t DROP COLUMN IF EXISTS col1,  col2;
-- Msg 4924 Level 16 State 1 Line 1
-- ALTER TABLE DROP COLUMN failed because column 'col2' does not exist in table 't'.

Based on error message IF EXISTS takes effect only for first column.

db<>fiddle demo

Is there a limitation of this clause when combined with multiple columns at once?

Body:
The syntax is a bit cumbersome but

ALTER TABLE t DROP COLUMN IF EXISTS col1,
                   COLUMN IF EXISTS col2;

works fine


问:
Overlay Image over view corner
I am attempting to draw the medal overlaying the corner of the score screen shown here

There is an transparent layout holding the buttons and a RelativeLayout (black edge box), which holds the interior box (grey box) that contains the rest of the data. I tried adding the medal to the top left corner of the interior RelativeLayout and giving it negative margins, but that just cuts it off at the edge of the view. Adding it to the transparent layout puts it behind the corner.

How can I force the medal to overlay that corner? I'd prefer to do it in xml if possible, but any suggestions are welcome.

答:
merge them ...

http://developer.android.com/resources/articles/layout-tricks-merge.html would help

Title: Overlay Image over view corner


问:
How to fix <class 'AttributeError'> error?
I don't know why ım get attribute error. My code looks like clean.
Im using pyqt5. My ui codes link: ui codes

Im trying for make ui calculator.
My idle:PyCharm 2020

Backend codes:

```<code>from PyQt5 import QtWidgets
from calculatorui import Ui_MainWindow
import sys
class myApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(myApp, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btn_bolme.clicked.connect(self.hesapla)
        self.ui.btn_carpma.clicked.connect(self.hesapla)
        self.ui.btn_toplama.clicked.connect(self.hesapla)
        self.ui.btn_cikarma.clicked.connect(self.hesapla)

    def hesapla(self):
        sender=self.sender().text()
        result=0
        try:

            if sender.text()=="Toplama":
                result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Çıkarma":
                result = int(self.ui.lbl_sayi1.text()) - int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Çarpma":
                result = int(self.ui.lbl_sayi1.text()) * int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Bölme":
                result = int(self.ui.lbl_sayi1.text()) / int(self.ui.lbl_sayi2.text())
            self.ui.txt_sonuc.setText("Sonuç: "+str(result))
        except ZeroDivisionError:
            self.ui.txt_sonuc.setText("0'a bölemezsin")
        except:
            print("Unexpected error:", sys.exc_info()[0])
def app():
    app=QtWidgets.QApplication(sys.argv)
    win=myApp()
    win.show()
    sys.exit(app.exec_())
app() ```
```

答:
First, if you're struggling to figure out what an error is, make sure you include it in the error message. I edited it to look like the following and got a more detailed traceback:

```<code>except Exception as e:
    print(f"Unexpected error:{e}", sys.exc_info()[0])
</code>```

The traceback shows where you're having your attribute error:

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-13-387a1e8e21c9> in hesapla(self)
     81         try:
---> 82             if sender.text()=="Toplama":
     83                 result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())

AttributeError: 'str' object has no attribute 'text'

</code>```

On closer inspection, this is where it looks like the problem is:

```<code>    def hesapla(self):
        sender=self.sender().text() <------!!!
        result=0
        try:
            if sender.text()=="Toplama": <---------!!!
                result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())
</code>```

You call text() on self.sender(), which returns a string. Then, you try to call text() again on the results of the first time you call it. If you get rid of .text() in either the first line of hesapla or in the if statements, that should fix your AttributeError problem. It looks like there's another problem after that, but it appears to be unrelated to the original problem.

Body:
I don't know why ım get attribute error. My code looks like clean.
Im using pyqt5. My ui codes link: ui codes

Im trying for make ui calculator.
My idle:PyCharm 2020

Backend codes:

from PyQt5 import QtWidgets
from calculatorui import Ui_MainWindow
import sys
class myApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(myApp, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btn_bolme.clicked.connect(self.hesapla)
        self.ui.btn_carpma.clicked.connect(self.hesapla)
        self.ui.btn_toplama.clicked.connect(self.hesapla)
        self.ui.btn_cikarma.clicked.connect(self.hesapla)

    def hesapla(self):
        sender=self.sender().text()
        result=0
        try:

            if sender.text()=="Toplama":
                result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Çıkarma":
                result = int(self.ui.lbl_sayi1.text()) - int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Çarpma":
                result = int(self.ui.lbl_sayi1.text()) * int(self.ui.lbl_sayi2.text())
            elif sender.text()=="Bölme":
                result = int(self.ui.lbl_sayi1.text()) / int(self.ui.lbl_sayi2.text())
            self.ui.txt_sonuc.setText("Sonuç: "+str(result))
        except ZeroDivisionError:
            self.ui.txt_sonuc.setText("0'a bölemezsin")
        except:
            print("Unexpected error:", sys.exc_info()[0])
def app():
    app=QtWidgets.QApplication(sys.argv)
    win=myApp()
    win.show()
    sys.exit(app.exec_())
app() ```

Body:
First, if you're struggling to figure out what an error is, make sure you include it in the error message. I edited it to look like the following and got a more detailed traceback:

except Exception as e:
    print(f"Unexpected error:{e}", sys.exc_info()[0])

The traceback shows where you're having your attribute error:

AttributeError                            Traceback (most recent call last)
<ipython-input-13-387a1e8e21c9> in hesapla(self)
     81         try:
---> 82             if sender.text()=="Toplama":
     83                 result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())

AttributeError: 'str' object has no attribute 'text'

On closer inspection, this is where it looks like the problem is:

    def hesapla(self):
        sender=self.sender().text() <------!!!
        result=0
        try:
            if sender.text()=="Toplama": <---------!!!
                result = int(self.ui.lbl_sayi1.text()) + int(self.ui.lbl_sayi2.text())

You call text() on self.sender(), which returns a string. Then, you try to call text() again on the results of the first time you call it. If you get rid of .text() in either the first line of hesapla or in the if statements, that should fix your AttributeError problem. It looks like there's another problem after that, but it appears to be unrelated to the original problem.