问:
What is the LIMIT clause alternative in JPQL?
I'm working with PostgreSQL query implementing in JPQL.

This is a sample native psql query which works fine,

```<code>SELECT * FROM students ORDER BY id DESC LIMIT 1;
</code>```

The same query in JPQL doesnt work,

```<code>@Query("SELECT s FROM Students s ORDER BY s.id DESC LIMIT 1")

Students getLastStudentDetails();
</code>```

seems like LIMIT clause doesn't work in JPQL.

According to JPA documentation we can use setMaxResults/setFirstResult, Can anyone tell me how can I use that in my above query?

答:
JPQL does not allow to add the limit keyword to the query generated by the HQL. You would get the following exception.

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
  LIMIT near line 1

But don't worry there is an alternative to use the limit keyword in the query generated by the HQL by using the following steps.

Sort.by(sortBy).descending() // fetch the records in descending order

pageSize = 1 // fetch the first record from the descending order result set.

Refer the following service class

Service:

```<code>@Autowired
StudentRepository repository;

public List<Student> getLastStudentDetails(Integer pageNo, Integer pageSize, String sortBy)
{
    Integer pageNo = 0;
    Integer pageSize = 1;
    String sortBy = "id";
    Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(sortBy).descending());

    Slice<Student> pagedResult = repository.findLastStudent(paging);

    return pagedResult.getContent();
}
</code>```

Your repository interface should implement the PagingAndSortingRepository

Repository:

```<code>public interface StudentRepository extends JpaRepository<Student,Long>, PagingAndSortingRepository<Student,Long>{

    @Query("select student from Student student")
    Slice<Student> findLastStudent(Pageable paging);
}
</code>```

This will add the limit keyword to you query which you can see in the console. Hope this helps.

Body:
I'm working with PostgreSQL query implementing in JPQL.

This is a sample native psql query which works fine,

SELECT * FROM students ORDER BY id DESC LIMIT 1;

The same query in JPQL doesnt work,

@Query("SELECT s FROM Students s ORDER BY s.id DESC LIMIT 1")

Students getLastStudentDetails();

seems like LIMIT clause doesn't work in JPQL.

According to JPA documentation we can use setMaxResults/setFirstResult, Can anyone tell me how can I use that in my above query?

Body:
JPQL does not allow to add the limit keyword to the query generated by the HQL. You would get the following exception.

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
  LIMIT near line 1

But don't worry there is an alternative to use the limit keyword in the query generated by the HQL by using the following steps.

Sort.by(sortBy).descending() // fetch the records in descending order

pageSize = 1 // fetch the first record from the descending order result set.

Refer the following service class

Service:

@Autowired
StudentRepository repository;

public List<Student> getLastStudentDetails(Integer pageNo, Integer pageSize, String sortBy)
{
    Integer pageNo = 0;
    Integer pageSize = 1;
    String sortBy = "id";
    Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(sortBy).descending());

    Slice<Student> pagedResult = repository.findLastStudent(paging);

    return pagedResult.getContent();
}

Your repository interface should implement the PagingAndSortingRepository

Repository:

public interface StudentRepository extends JpaRepository<Student,Long>, PagingAndSortingRepository<Student,Long>{

    @Query("select student from Student student")
    Slice<Student> findLastStudent(Pageable paging);
}

This will add the limit keyword to you query which you can see in the console. Hope this helps.


来源: stackexchange

问:
Nesting Defaultdictionaries in Python3
I'm working on a piece of code and this is my first time implementing defaultdict from collections.
Currently, I have a piece of code that works just fine as a defaultdict, but I'd really like to nest my dictionaries.

This is the code I have currently:

```<code>from collections import defaultdict, Counter
from re import findall

class Class:
    def __init__(self, n, file):
        self.counts = defaultdict(lambda: defaultdict(int))
        self.__n = n
        self.__file = file

    def function(self, starting_text, charas):
        self.__starting_text = starting_text
        self.__charas = charas

        with open(self.__file) as file:
            text = file.read().lower().replace('\n', ' ')

        ngrams = [text[i : i + self.__n] for i in range(len(text))]

        out = self.counts
        for item in ngrams:
            data = []
            for word in findall( item+".", text):
                data.append(word[-1])
            self.counts = { item : data.count(item) for item in data }
            out[item] = self.counts
        self.counts = out
</code>```

Some of the things in the code aren't yet implemented because I'm at a bit of a standstill, so please ignore anything that isn't applicable to this particular question!

If I run print(self.counts) at the end, my program runs something that looks like this:

```<code>defaultdict(<function Class.__init__.<locals>.<lambda> at 0x7f8c4a94bea0>, {'t': {'h': 1, ' ': 1, 'e': 1}, 'h': {'i': 1, 'o': 1}, 'i': {'s': 2}, 's': {' ': 2, 'h': 1, 'e': 1}, ' ': {'i': 1, 'a': 1, 's': 2}, 'a': {' ': 1}, 'o': {'r': 1}, 'r': {'t': 1}, 'e': {'n': 2, ' ': 1}, 'n': {'t': 1, 'c': 1}, 'c': {'e': 1}})
</code>```

Which is great! But I'd really like to have those inner dictionaries be defaultdicts as well. In particular, if I run self.counts['t']['h'], I get 1, as expected.
However, a benefit of the defaultdict is having it give you 0 if a key is not available. Currently, if I run self.counts['t']['x'] I get a keyerror, but I'd live to get 0 instead by having each inner list be a defaultdict as well.

I'm assuming this can be done somewhere in the chunk of code beginning with out=self.counts, but I'm a little unsure how I can achieve this.

答:
You should change this two lines:

```<code>self.counts = { item : data.count(item) for item in data }
out[item] = self.counts
</code>```

You don't need the out variable. the problem is that you are creating a "normal" dict and assign it to self.count. Just use:

```<code>self.counts[item].update({ item : data.count(item) for item in data })
</code>```

ContentLicense: CC BY-SA 4.0

Title: Nesting Defaultdictionaries in Python3

Body:
I'm working on a piece of code and this is my first time implementing defaultdict from collections.
Currently, I have a piece of code that works just fine as a defaultdict, but I'd really like to nest my dictionaries.

This is the code I have currently:

from collections import defaultdict, Counter
from re import findall

class Class:
    def __init__(self, n, file):
        self.counts = defaultdict(lambda: defaultdict(int))
        self.__n = n
        self.__file = file

    def function(self, starting_text, charas):
        self.__starting_text = starting_text
        self.__charas = charas

        with open(self.__file) as file:
            text = file.read().lower().replace('\n', ' ')

        ngrams = [text[i : i + self.__n] for i in range(len(text))]

        out = self.counts
        for item in ngrams:
            data = []
            for word in findall( item+".", text):
                data.append(word[-1])
            self.counts = { item : data.count(item) for item in data }
            out[item] = self.counts
        self.counts = out

Some of the things in the code aren't yet implemented because I'm at a bit of a standstill, so please ignore anything that isn't applicable to this particular question!

If I run print(self.counts) at the end, my program runs something that looks like this:

defaultdict(<function Class.__init__.<locals>.<lambda> at 0x7f8c4a94bea0>, {'t': {'h': 1, ' ': 1, 'e': 1}, 'h': {'i': 1, 'o': 1}, 'i': {'s': 2}, 's': {' ': 2, 'h': 1, 'e': 1}, ' ': {'i': 1, 'a': 1, 's': 2}, 'a': {' ': 1}, 'o': {'r': 1}, 'r': {'t': 1}, 'e': {'n': 2, ' ': 1}, 'n': {'t': 1, 'c': 1}, 'c': {'e': 1}})

Which is great! But I'd really like to have those inner dictionaries be defaultdicts as well. In particular, if I run self.counts['t']['h'], I get 1, as expected.
However, a benefit of the defaultdict is having it give you 0 if a key is not available. Currently, if I run self.counts['t']['x'] I get a keyerror, but I'd live to get 0 instead by having each inner list be a defaultdict as well.

I'm assuming this can be done somewhere in the chunk of code beginning with out=self.counts, but I'm a little unsure how I can achieve this.

Body:
You should change this two lines:

self.counts = { item : data.count(item) for item in data }
out[item] = self.counts

You don't need the out variable. the problem is that you are creating a "normal" dict and assign it to self.count. Just use:

self.counts[item].update({ item : data.count(item) for item in data })


问:
Function not sending alert in browser HTML, JavaScript
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

```<code><!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>
  <script>
    'use strict';
    function getNumber(cardNum) {
        if (cardNum.length > 16 || cardNum.length < 13) {
            alert(‘This is not valid.’);
            return false;}
        else {
            alert(‘This is valid.’);
            return true;}
    }
  </script>
</head>

<body onload=“document.cardNum()”>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>
    <br>
    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

</body>
</html>
</code>```

答:
There was 3 things i fixed; 1- onload=“document.cardNum()” , there is no function like that so your page crashes immediately so no further script executes 2- I dont know if it is spoilt during paste but some of your quotes are not valid, you should use " and ' 3- This one just prevents working right; In your function you pass input's reference and check HTML element's length you need to check input's value

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type='text/css'/>

 Enter Credit Card Number:

<form>
    <input type='text' id='cardNum' name='cardNum'/>

    <input type="submit" value='Submit' onclick="getNumber(document.getElementById('cardNum').value)"/>
</form>

```

Body:
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>

 Enter Credit Card Number:

<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>

    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

Body:
There was 3 things i fixed; 1- onload=“document.cardNum()” , there is no function like that so your page crashes immediately so no further script executes 2- I dont know if it is spoilt during paste but some of your quotes are not valid, you should use " and ' 3- This one just prevents working right; In your function you pass input's reference and check HTML element's length you need to check input's value

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type='text/css'/>
  <script>
    'use strict';
    function getNumber(cardNum) {
        if (cardNum.length <= 16 && cardNum.length >= 13) {
            alert('This is valid.');
            return false;
          }
        else {
            alert('This is not valid.');
            return true;
          }
    }
  </script>
</head>

<body>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id='cardNum' name='cardNum'/>
    <br>
    <input type="submit" value='Submit' onclick="getNumber(document.getElementById('cardNum').value)"/>
</form>

</body>
</html>


问:
How does Interval keyword work in Oracle?
I have 2 queries :

```<code>SELECT 300*interval '1' HOUR FROM DUAL  --   0 5:0:0.0 (Output)

SELECT 300* interval '1' minute FROM DUAL -- 12 12:0:0.0(Output)
</code>```

I am unable to get how is the interval Keyword working and what is the format of the Output produced ?

答:
Your first query :

```<code>--300 * 1 hour => 12 days 12 hours which is +000000012 12:00:00.000000000
SELECT 300 * ( INTERVAL '1' HOUR ) FROM DUAL;

-- 300 * 1 minute => 300 Minute which is 300 / 60 = 5 Hours =>  +000000000 05:00:00.000000000
SELECT 300 * (interval '1' minute) FROM DUAL
</code>```

Hope it helps

Body:
I have 2 queries :

SELECT 300*interval '1' HOUR FROM DUAL  --   0 5:0:0.0 (Output)

SELECT 300* interval '1' minute FROM DUAL -- 12 12:0:0.0(Output)

I am unable to get how is the interval Keyword working and what is the format of the Output produced ?

Body:
Your first query :

--300 * 1 hour => 12 days 12 hours which is +000000012 12:00:00.000000000
SELECT 300 * ( INTERVAL '1' HOUR ) FROM DUAL;

-- 300 * 1 minute => 300 Minute which is 300 / 60 = 5 Hours =>  +000000000 05:00:00.000000000
SELECT 300 * (interval '1' minute) FROM DUAL

Hope it helps


问:
Show all options selected by default in a dropdown list
I would like to know (by request of our client) if it is possible to modify the behavior of a drop-down list filter. The idea is to see all the options selected by default when the current value is All. Something like this:

答: In Power BI Desktop click on Select all, save the report and publish it. This will be the default selection and it will be shown to the user. Just to note, that the result of both selections is equivalent.


答:
make data a collections.Counter or a defaultdict instead of a list (since you strictly don't care about the sequence of bits, only their occurrences count)

then update your self.counts[item] with the counter instead of assigning a dict

you could even do the update straight:

for item in ngrams:
    data = self.counts[item]
    for word in findall( item+".", text):
        data[word[-1]] += 1
```

and that's about it, this will update the relevant counts straight into the defaultdict as originally defined</li>
</ol>

<p>That aside much of the code is... not ideal, or odd</p>

<h3>seems unnecessarily complex</h3>

<p>You're getting each codepoint following your ngram, why not straight extract pseudo-ngrams of n+1 and split that up? Something along the lines of (untested, may be slightly off):</p>

<pre class="lang-py prettyprint-override"><code>for i in range(0, len(text)-n):
    ngram, follower = text[i:i+n], text[i+n]
    self.counts[ngram][follower] += 1
</code>```

That also avoids the at-least quadratic complexity of your code (and the various constant complexities) which is a nice side-effect, though note that the original would implicitly skip followers of \n (a newline / line break) as wihout re.DOTALL, . "matches any character except a newline". So if you want to keep that behaviour you'll have to specifically test for and skip on follower == '\n'.

Reusing member variables as locals?

You're reusing self.counts as a local variable for some weird reason, saving it to out, setting it to weird stuff then re-loading it after having set it on itself, why isn't out the inner variable?

        for item in ngrams:
            data = []
            for word in findall( item+".", text):
                data.append(word[-1])
            out = { item : data.count(item) for item in data }
            self.counts[item] = out
```

Not that that's very useful (possibly aside from printf-debugging utility), you can assign to self.counts[item] straight.

I also have no idea whatsoever what utility __starting_text and __charas have

double underscore prefixes

Don't. It doesn't matter what you're using them for, I'm reasonably sure you're wrong (because I've rarely encountered people who knew what these are for) and you should stop it.

If you want to hint to callers that something is an internal detail of the object, use a single underscore prefix. Though you probably don't need to do that either.

always pass an encoding to text-mode open

Seriously. open(path) works in text mode (automatically decodes the raw on-disk data to str), but the encoding it picks is whatever getdefaultencoding() returns which is as likely as not to be garbage. You don't want to use it to read the user's file, and you really absolutely never want to use it to read your own file. Explicitly provide encoding='utf-8', it will avoid lots of grief down the line. If you need to infer encoding maybe use chardet.

Title: Nesting Defaultdictionaries in Python3

Body:
make data a collections.Counter or a defaultdict instead of a list (since you strictly don't care about the sequence of bits, only their occurrences count)

then update your self.counts[item] with the counter instead of assigning a dict

you could even do the update straight:

for item in ngrams:
    data = self.counts[item]
    for word in findall( item+".", text):
        data[word[-1]] += 1

and that's about it, this will update the relevant counts straight into the defaultdict as originally defined

That aside much of the code is... not ideal, or odd

seems unnecessarily complex

You're getting each codepoint following your ngram, why not straight extract pseudo-ngrams of n+1 and split that up? Something along the lines of (untested, may be slightly off):

for i in range(0, len(text)-n):
    ngram, follower = text[i:i+n], text[i+n]
    self.counts[ngram][follower] += 1

That also avoids the at-least quadratic complexity of your code (and the various constant complexities) which is a nice side-effect, though note that the original would implicitly skip followers of \n (a newline / line break) as wihout re.DOTALL, . "matches any character except a newline". So if you want to keep that behaviour you'll have to specifically test for and skip on follower == '\n'.

Reusing member variables as locals?

You're reusing self.counts as a local variable for some weird reason, saving it to out, setting it to weird stuff then re-loading it after having set it on itself, why isn't out the inner variable?

        for item in ngrams:
            data = []
            for word in findall( item+".", text):
                data.append(word[-1])
            out = { item : data.count(item) for item in data }
            self.counts[item] = out

Not that that's very useful (possibly aside from printf-debugging utility), you can assign to self.counts[item] straight.

I also have no idea whatsoever what utility __starting_text and __charas have

double underscore prefixes

Don't. It doesn't matter what you're using them for, I'm reasonably sure you're wrong (because I've rarely encountered people who knew what these are for) and you should stop it.

If you want to hint to callers that something is an internal detail of the object, use a single underscore prefix. Though you probably don't need to do that either.

always pass an encoding to text-mode open

Seriously. open(path) works in text mode (automatically decodes the raw on-disk data to str), but the encoding it picks is whatever getdefaultencoding() returns which is as likely as not to be garbage. You don't want to use it to read the user's file, and you really absolutely never want to use it to read your own file. Explicitly provide encoding='utf-8', it will avoid lots of grief down the line. If you need to infer encoding maybe use chardet.


问:
How to avoid evaluating an GString
I'm working on extending a legacy script system using groovy. The source scripts are "java-like", so it mostly parses as a groovy script with a little pre-processing.

I'm using invokeMethod() and missingMethod() to pass-through the legacy code, enabling me to use closures and other groovy features to enhance the scripts. However, the original script uses strings of the type "$foo" to refer to variables. When a legacy method is caught by missingMethod(), I need it to not evaluate this string as a GString, but simply outputting it verbatim. Is this possible in any way?

答:
there are two way to escape the $foo:

escape the '$' as '\$'

use ' instead of " as string delimiter

example:

```<code> def test = "bad"
 def s0 = "$test"
 def s1 = "\$test"
 assert s1 != s0
 def s2 = '$test'
 assert s2 == s1
 println s0
 println s1
 println s2
</code>```

So I guess you have to use your preprocessor in order to escape your strings

ContentLicense: CC BY-SA 3.0

Title: How to avoid evaluating an GString

Body:
there are two way to escape the $foo:

escape the '$' as '\$'

use ' instead of " as string delimiter

example:

 def test = "bad"
 def s0 = "$test"
 def s1 = "\$test"
 assert s1 != s0
 def s2 = '$test'
 assert s2 == s1
 println s0
 println s1
 println s2

So I guess you have to use your preprocessor in order to escape your strings


问:
Conditionally include the branch name in an Azure DevOps build name
I'm using Azure DevOps to build a pipeline, but I wish to change the name of the build. This is entirely possible according to the documentation.

With that in mind, I tested the following, which worked. So far so good...

```<code>name: '1.0.$(Rev:r)-$(Build.SourceBranchName)'
</code>```

1.0.1-master

However, one of my requirements is to exclude the branch name if it's 'master', so I tried the following. This seemed to work in the first instance, as a 'master' did not have a branch name appended, but when I ran a feature branch I found that $(Build.SourceBranchName) was not being expanded.

```<code>variables:
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    branchName: ''
  ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
    branchName: '-$(Build.SourceBranchName)'

name: '1.0.$(Rev:r)$(branchName)'
</code>```

I've since tried ${{ variables.Build.SourceBranchName }} and $[variables.Build.SourceBranchName] as described in the documentation, but as written they token is either ignored or returns an empty string. The three formats leave me with the following build names.

1.0.1-$(Build.SourceBranchName)

  1.0.1-

  1.0.1-$[variables.Build.SourceBranchName]

The documentation around custom naming makes mention of a variable $(SourceBranchName), but I've tried this and it also fails.

What I find confusing is that the expressions in the variables: segment can access the variable values as described here, but seemingly the variables: segment itself is unable to.

Is it possible to conditionally name the build so that I can include/exclude the branch name as required?

答:
The problem is how you are referencing $(Build.SourceBranchName) in the parse time expression. It is not available in that format under the context. Additional info here

This works for me!

```<code>variables:
  system.debug: true
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    branchName: ''
  ${{ if ne( variables['Build.SourceBranchName'], 'master') }}:
    branchName: -${{ variables['Build.SourceBranchName'] }}

name: '1.0.$(Rev:r)$(branchName)'
</code>```

Some good additional info in Lance's answer ##vso[build.updatebuildnumber] might be a good path, or you could use GitVersion.

Body:
I'm using Azure DevOps to build a pipeline, but I wish to change the name of the build. This is entirely possible according to the documentation.

With that in mind, I tested the following, which worked. So far so good...

name: '1.0.$(Rev:r)-$(Build.SourceBranchName)'

1.0.1-master

However, one of my requirements is to exclude the branch name if it's 'master', so I tried the following. This seemed to work in the first instance, as a 'master' did not have a branch name appended, but when I ran a feature branch I found that $(Build.SourceBranchName) was not being expanded.

variables:
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    branchName: ''
  ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
    branchName: '-$(Build.SourceBranchName)'

name: '1.0.$(Rev:r)$(branchName)'

I've since tried ${{ variables.Build.SourceBranchName }} and $[variables.Build.SourceBranchName] as described in the documentation, but as written they token is either ignored or returns an empty string. The three formats leave me with the following build names.

1.0.1-$(Build.SourceBranchName)

  1.0.1-

  1.0.1-$[variables.Build.SourceBranchName]

The documentation around custom naming makes mention of a variable $(SourceBranchName), but I've tried this and it also fails.

What I find confusing is that the expressions in the variables: segment can access the variable values as described here, but seemingly the variables: segment itself is unable to.

Is it possible to conditionally name the build so that I can include/exclude the branch name as required?

Body:
The problem is how you are referencing $(Build.SourceBranchName) in the parse time expression. It is not available in that format under the context. Additional info here

This works for me!

variables:
  system.debug: true
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    branchName: ''
  ${{ if ne( variables['Build.SourceBranchName'], 'master') }}:
    branchName: -${{ variables['Build.SourceBranchName'] }}

name: '1.0.$(Rev:r)$(branchName)'

Some good additional info in Lance's answer ##vso[build.updatebuildnumber] might be a good path, or you could use GitVersion.


问:
How to transform nested dictionary from BeautifulSoup to pandas dataframe
I used BeautifulSoup to get this data. It seems like a nested dictionary but I failed to transform them into dataframe. The type is .

```<code>{"page":1,"rows":[{"id":"160128","cell":{"fund_id":"160128","bond_ratio":"132.04","report_dt":"2019-12-31","is_outdate":false,"maturity_dt_tips":""}},{"id":"160130","cell":{"fund_id":"160130","bond_ratio":"165.29","report_dt":"2019-12-31","is_outdate":false,"maturity_dt_tips":""}},{"id":"160131","cell":{"fund_id":"160131","bond_ratio":"94.93","report_dt":"2019-12-31","is_outdate":false,"maturity_dt_tips":""}}],"total":3}
</code>```

How should I get 'values' under each key of 'cell'? Thanks.

```<code>    fund_id     bond_ratio     report_dt     is_outdate     maturity_dt_tips
0    160128         132.04    2019-12-31          false
1    160130         165.29    2019-12-31          false
2    160131          94.93    2019-12-31          false
</code>```

答:
Use json.json_normalize:

```<code>d = {"page":1,"rows":[{"id":"160128","cell":{"fund_id":"160128","bond_ratio":"132.04","report_dt":"2019-12-31","is_outdate":False,"maturity_dt_tips":""}},{"id":"160130","cell":{"fund_id":"160130","bond_ratio":"165.29","report_dt":"2019-12-31","is_outdate":False,"maturity_dt_tips":""}},{"id":"160131","cell":{"fund_id":"160131","bond_ratio":"94.93","report_dt":"2019-12-31","is_outdate":False,"maturity_dt_tips":""}}],"total":3}
</code>```

```<code>from pandas.io.json import json_normalize

df = json_normalize(d['rows'])
print (df)
       id cell.fund_id cell.bond_ratio cell.report_dt  cell.is_outdate  \
0  160128       160128          132.04     2019-12-31            False
1  160130       160130          165.29     2019-12-31            False
2  160131       160131           94.93     2019-12-31            False

  cell.maturity_dt_tips
0
1
2
</code>```

Then if necessary remove values before . in columns names add str.split and indexing last values of lists by [-1]:

```<code>df.columns = df.columns.str.split('.').str[-1]
print (df)
       id fund_id bond_ratio   report_dt  is_outdate maturity_dt_tips
0  160128  160128     132.04  2019-12-31       False
1  160130  160130     165.29  2019-12-31       False
2  160131  160131      94.93  2019-12-31       False
</code>```

Body:
I used BeautifulSoup to get this data. It seems like a nested dictionary but I failed to transform them into dataframe. The type is .

{"page":1,"rows":[{"id":"160128","cell":{"fund_id":"160128","bond_ratio":"132.04","report_dt":"2019-12-31","is_outdate":false,"maturity_dt_tips":""}},{"id":"160130","cell":{"fund_id":"160130","bond_ratio":"165.29","report_dt":"2019-12-31","is_outdate":false,"maturity_dt_tips":""}},{"id":"160131","cell":{"fund_id":"160131","bond_ratio":"94.93","report_dt":"2019-12-31","is_outdate":false,"maturity_dt_tips":""}}],"total":3}

How should I get 'values' under each key of 'cell'? Thanks.

    fund_id     bond_ratio     report_dt     is_outdate     maturity_dt_tips
0    160128         132.04    2019-12-31          false
1    160130         165.29    2019-12-31          false
2    160131          94.93    2019-12-31          false

Body:
Use json.json_normalize:

d = {"page":1,"rows":[{"id":"160128","cell":{"fund_id":"160128","bond_ratio":"132.04","report_dt":"2019-12-31","is_outdate":False,"maturity_dt_tips":""}},{"id":"160130","cell":{"fund_id":"160130","bond_ratio":"165.29","report_dt":"2019-12-31","is_outdate":False,"maturity_dt_tips":""}},{"id":"160131","cell":{"fund_id":"160131","bond_ratio":"94.93","report_dt":"2019-12-31","is_outdate":False,"maturity_dt_tips":""}}],"total":3}

from pandas.io.json import json_normalize

df = json_normalize(d['rows'])
print (df)
       id cell.fund_id cell.bond_ratio cell.report_dt  cell.is_outdate  \
0  160128       160128          132.04     2019-12-31            False
1  160130       160130          165.29     2019-12-31            False
2  160131       160131           94.93     2019-12-31            False

  cell.maturity_dt_tips
0
1
2

Then if necessary remove values before . in columns names add str.split and indexing last values of lists by [-1]:

df.columns = df.columns.str.split('.').str[-1]
print (df)
       id fund_id bond_ratio   report_dt  is_outdate maturity_dt_tips
0  160128  160128     132.04  2019-12-31       False
1  160130  160130     165.29  2019-12-31       False
2  160131  160131      94.93  2019-12-31       False


问:
escape " regexp in dart
I'm trying to catch symbols in a dart Regexp. My regexp looks like this:

```<code>  RegExp containsSymbolRegExp = RegExp(r"[-!$%^&*()_+|~=`{}\[\]:;'<>?,.\/]");
</code>```

However, I also need to make it catch the symbol "
I can't stick " in there though, since it messes with the string. Any ideas how to do this?
Thanks.

edit: jamesdlin's answer works great for dart. But it doesn't work for my flutter app, so I'm thinking it has something to do with flutter. Here's the code I'm applying this to:

```<code>TextEditingController _passwordController = TextEditingController();
bool containsSymbol;

RegExp containsSymbolRegExp = RegExp(r"[-!$%^&*()_+|~=`{}#@\[\]:;'<>?,.\/"
      '"'
      "]");

void _handleChange(text) {
    setState(() {
        containsSymbol = containsSymbolRegExp.hasMatch(_passwordController.text);
    });
    print(containsSymbol); // always prints false for " ' \ but works for all other symbols
  }

Widget _textField(controller, labelText) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text(labelText, style: TextStyle(fontSize: 11)),
      Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: 35,
        child: TextField(
          onChanged: _handleChange,
          style: TextStyle(fontSize: 20),
          keyboardType: TextInputType.text,
          controller: _passwordController,
          cursorColor: Colors.grey,
          decoration: InputDecoration(
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey))),
        ),
      ),
    ],
  );
}
</code>```

答:
To answer to the edited part of your question being that it worked in Dart but not in Flutter...

It is because apostrophes/quotation marks from TextField values in Flutter are right quotation marks and therefore come in different Unicode.

For apostrophes, it's U+2019 (’) instead of U+0027 (')

For quotation marks, U+201D (”) instead of U+0022 (")

The Regex you were trying with is not capturing for such characters. Therefore, you just need to add those into your Regex.

RegExp containsSymbolRegExp = RegExp(
   r"[-!$%^&*()_+|~=`{}#@\[\]:;'’<>?,.\/"
   '"”'
   "]");
```

Tip: Debug! :)
I can already see some part of the value looking funny the moment it hits the breakpoint of where the value was about to be evaluated.

Title: escape " regexp in dart

Body:
I'm trying to catch symbols in a dart Regexp. My regexp looks like this:

  RegExp containsSymbolRegExp = RegExp(r"[-!$%^&*()_+|~=`{}\[\]:;'<>?,.\/]");

However, I also need to make it catch the symbol "
I can't stick " in there though, since it messes with the string. Any ideas how to do this?
Thanks.

edit: jamesdlin's answer works great for dart. But it doesn't work for my flutter app, so I'm thinking it has something to do with flutter. Here's the code I'm applying this to:

TextEditingController _passwordController = TextEditingController();
bool containsSymbol;

RegExp containsSymbolRegExp = RegExp(r"[-!$%^&*()_+|~=`{}#@\[\]:;'<>?,.\/"
      '"'
      "]");

void _handleChange(text) {
    setState(() {
        containsSymbol = containsSymbolRegExp.hasMatch(_passwordController.text);
    });
    print(containsSymbol); // always prints false for " ' \ but works for all other symbols
  }

Widget _textField(controller, labelText) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text(labelText, style: TextStyle(fontSize: 11)),
      Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: 35,
        child: TextField(
          onChanged: _handleChange,
          style: TextStyle(fontSize: 20),
          keyboardType: TextInputType.text,
          controller: _passwordController,
          cursorColor: Colors.grey,
          decoration: InputDecoration(
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey))),
        ),
      ),
    ],
  );
}

Body:
To answer to the edited part of your question being that it worked in Dart but not in Flutter...

It is because apostrophes/quotation marks from TextField values in Flutter are right quotation marks and therefore come in different Unicode.

For apostrophes, it's U+2019 (’) instead of U+0027 (')

For quotation marks, U+201D (”) instead of U+0022 (")

The Regex you were trying with is not capturing for such characters. Therefore, you just need to add those into your Regex.

RegExp containsSymbolRegExp = RegExp(
   r"[-!$%^&*()_+|~=`{}#@\[\]:;'’<>?,.\/"
   '"”'
   "]");

Tip: Debug! :)
I can already see some part of the value looking funny the moment it hits the breakpoint of where the value was about to be evaluated.


问:
Invalid syntax error in first python programming
I made my first python program of hello world.

Every time i save it,it cannot be open in the program.

And the program just blink and flashes away.

I read few line 'invalid syntax'.

here what I WROTE:

```<code>>>>print('hello world')
</code>```

then i saved it as p.py and try to run it on program and zilch.

答:
I have a feeling you are reading the book 'The self taught programmer'?   What you need to do is realize the shell and the notepad are two different things.

Do this.

Open up the IDLE shell, but then go to the file-new-new file

This should open a new window.  Now this window, simply put the Print("Hello, taxation is theft").   Now, save this window, as whatever you want.   Now, in the same window, with both the shell open, and this new window, click F5 or run 'run module'.

You'll see what you made in the notepad will run on the shell window.  It will only run once.   The next step is to practice running it 5 times, then 100 times.      You'll get there bud.

Body:
I made my first python program of hello world.

Every time i save it,it cannot be open in the program.

And the program just blink and flashes away.

I read few line 'invalid syntax'.

here what I WROTE:

>>>print('hello world')

then i saved it as p.py and try to run it on program and zilch.


问:
Javascript get status from service
I develop a web application that is getting user updates from a web service (that is in another domain) I want to get the updates every 10 seconds.

For calling the service for the first time I dynamically insert a script in the page. The service is JSONP. Then I would like to define a trigger that insert a script from 10 to 10 seconds to get the updates. Is this correct? Can I do that without affecting the user experience on the website? I mean the site performance ... it will be great if I could do the call async and when I have the results I will update the status.

Is there any better solution for accessing the remote services. Is there an efficient way of dynamically reusing the same script using a trigger? I am pretty new to Javascript. Can you give me a short sample how can I define a trigger that calls a remote web service? ... or if there is a better solution.

答:
The following will dynamically create the script tags, and delete them (and the global it requires) after being finished with a given call.

You could also use CORS to allow requests besides GET ones, though as you may be aware, that is not supported in older browsers.

To avoid race conditions or performance problems during a slow network, you could allow the JSONP callback to recursively call the function, thereby only making a new call if the callback was returned, though with an optional setTimeout call to ensure there is at least a minimum delay.

The following uses Wikipedia's API to grab a specific page revision and its user.

```<code><script>
var JSONP = function(global){
    // (C) WebReflection Essential - Mit Style ( http://webreflection.blogspot.com/2011/02/all-you-need-for-jsonp.html )
    // 202 bytes minified + gzipped via Google Closure Compiler
    function JSONP(uri, callback) {
        function JSONPResponse() {
            try { delete global[src] } catch(e) { global[src] = null }
            documentElement.removeChild(script);
            callback.apply(this, arguments);
        }
        var
            src = prefix + id++,
            script = document.createElement("script")
        ;
        global[src] = JSONPResponse;
        documentElement.insertBefore(
            script,
            documentElement.lastChild
        ).src = uri + "=" + src;
    }
    var
        id = 0,
        prefix = "__JSONP__",
        document = global.document,
        documentElement = document.documentElement
    ;
    return JSONP;
}(this);

// Be sure to include the callback parameter at the end

function startAPI (start) {
    start = start || new Date();
    var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Main%20Page&rvprop=timestamp|user|comment|content&format=json&callback';
    var minimum = 10000;
    function execute (str) {
        alert(str);
    }
    JSONP(url, function (obj) {
        for (var pageNo in obj.query.pages) {
            var page = obj.query.pages[pageNo];
            var str = 'The user ' + page.revisions[0]['user'] + ' left the page with this code ' + page.revisions[0]['*'];
            execute(str);
            var elapsed = (new Date().getTime()) - start;
            setTimeout(startAPI, (elapsed < minimum) ? (minimum - elapsed) : 0);
            break;
        }
    });
}
startAPI();
</script>
</code>```

Title: Javascript get status from service

Body:
The following will dynamically create the script tags, and delete them (and the global it requires) after being finished with a given call.

You could also use CORS to allow requests besides GET ones, though as you may be aware, that is not supported in older browsers.

To avoid race conditions or performance problems during a slow network, you could allow the JSONP callback to recursively call the function, thereby only making a new call if the callback was returned, though with an optional setTimeout call to ensure there is at least a minimum delay.

The following uses Wikipedia's API to grab a specific page revision and its user.

<script>
var JSONP = function(global){
    // (C) WebReflection Essential - Mit Style ( http://webreflection.blogspot.com/2011/02/all-you-need-for-jsonp.html )
    // 202 bytes minified + gzipped via Google Closure Compiler
    function JSONP(uri, callback) {
        function JSONPResponse() {
            try { delete global[src] } catch(e) { global[src] = null }
            documentElement.removeChild(script);
            callback.apply(this, arguments);
        }
        var
            src = prefix + id++,
            script = document.createElement("script")
        ;
        global[src] = JSONPResponse;
        documentElement.insertBefore(
            script,
            documentElement.lastChild
        ).src = uri + "=" + src;
    }
    var
        id = 0,
        prefix = "__JSONP__",
        document = global.document,
        documentElement = document.documentElement
    ;
    return JSONP;
}(this);

// Be sure to include the callback parameter at the end

function startAPI (start) {
    start = start || new Date();
    var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Main%20Page&rvprop=timestamp|user|comment|content&format=json&callback';
    var minimum = 10000;
    function execute (str) {
        alert(str);
    }
    JSONP(url, function (obj) {
        for (var pageNo in obj.query.pages) {
            var page = obj.query.pages[pageNo];
            var str = 'The user ' + page.revisions[0]['user'] + ' left the page with this code ' + page.revisions[0]['*'];
            execute(str);
            var elapsed = (new Date().getTime()) - start;
            setTimeout(startAPI, (elapsed < minimum) ? (minimum - elapsed) : 0);
            break;
        }
    });
}
startAPI();
</script>


问:
Multiprocess.pool.map() raise ValueError: No objects to concatenate
I have to run a for loop and each loop will access data from a database, do some manipulation and run the Dijkstra algorithm, then append the results to a final list. The code looks like below:

```<code>def log_transform(x):
        transformed = math.e**(-x)
        return transformed
input_region = '1.199'
t1 = '20200101'
t2 = '20200115'
candid_sale_invoices = pd.read_excel('candid_sale_invoices.xlsx')
candid_barcodes = pd.read_excel('candid_barcodes.xlsx')

weights = []
    for i in range(int(t1),(int(t2) + 1)):
        input_date = str(i)
        sql_data = """select trim(cast(p.Barcode as nvarchar(20))) Barcode ,cast(s.invoiceid as nvarchar(20)) invoiceid
        from sales s inner join Product_981115 p on s.productid = p.productid
        where s.date = """+ input_date +""" and s.qty != 0 and p.sectionid != 1691.199 and s.RegionID = """ + input_region
        data = []
        for chunk in pd.read_sql(sql_data,conn,chunksize = 1000000):
            data.append(chunk)
        data = pd.concat(data, ignore_index = True)
        data = data.merge(candid_sale_invoices)
        data = data.merge(candid_barcodes)
        final_edges_df = data.iloc[:,[2,3,4]]
        final_edges_tuples = [tuple(x) for x in final_edges_df.values]

        Gm = ig.Graph.TupleList(final_edges_tuples, directed = True, edge_attrs = ['weight'])

        longest_paths = pd.DataFrame(Gm.shortest_paths_dijkstra(None,None, weights = 'weight'))
        longest_paths = longest_paths.swifter.apply(log_transform)
        longest_paths["Date"] = input_date
        longest_paths["RegionID"] = input_region
        weights.append(longest_paths)

weights = pd.concat(weights, ignore_index = True)
</code>```

The problem is with the process time which will take hours to finish. So since each iteration is independent from other iterations, I decided to run this loop in parallel with the help of this link

```<code>import psutil
from multiprocess import Pool
pool = Pool(psutil.cpu_count(logical=False))
def graph_analysis(i):
    input_date = str(i)
    sql_data = """select trim(cast(p.Barcode as nvarchar(20))) Barcode ,cast(s.invoiceid as
    nvarchar(20)) invoiceid
    from sales s inner join Product_981115 p on s.productid = p.productid
    where s.date = """+ input_date +""" and s.qty != 0 and p.sectionid != 1691.199 and s.RegionID = """ + input_region
    data = []
    for chunk in pd.read_sql(sql_data,conn,chunksize = 1000000):
         data.append(chunk)
    data = pd.concat(data, ignore_index = True)
    data = data.merge(candid_sale_invoices)
    data = data.merge(candid_barcodes)
    final_edges_df = data.iloc[:,[2,3,4]]
    final_edges_tuples = [tuple(x) for x in final_edges_df.values]

    Gm = ig.Graph.TupleList(final_edges_tuples, directed = True, edge_attrs = ['weight'])

    longest_paths = pd.DataFrame(Gm.shortest_paths_dijkstra(None,None, weights = 'weight'))
    longest_paths = longest_paths.swifter.apply(log_transform)
    longest_paths["Date"] = input_date
    longest_paths["RegionID"] = input_region
    Return longest_paths

results = pool.map(graph_analysis,range(int(t1),(int(t2) + 1)))
pool.close()
</code>```

With running the code, it seems like the code is doing its job and compute in parallel but after a while it raise this error:

Traceback (most recent call last):

File "", line 78, in
      weights = pool.map(graph_analysis,range(int(t1),(int(t2) + 1)))

File
  "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\multiprocess\pool.py",
  line 268, in map
      return self._map_async(func, iterable, mapstar, chunksize).get()

File
  "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\multiprocess\pool.py",
  line 657, in get
      raise self._value

ValueError: No objects to concatenate

Does this error relate to gathering the "longest_paths" dataframe from all of the iterations?

答:
"No objects to concatenate" is a Pandas error returned when you call pd.concat() with an empty iterable:

```<code>>>> pd.concat([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pandas/core/reshape/concat.py", line 281, in concat
    sort=sort,
  File "pandas/core/reshape/concat.py", line 329, in __init__
    raise ValueError("No objects to concatenate")
ValueError: No objects to concatenate
>>>
</code>```

I would assume you'll just need to quit early when the SQL query does not return anything:

```<code># ...

    for chunk in pd.read_sql(sql_data, conn, chunksize=1000000):
        data.append(chunk)

    if not data: # <-- add this bit!
        return None

    data = pd.concat(data, ignore_index=True)

# ...
</code>```

I'd also suggest using pool.imap_unordered(); you also don't need psutil since Pool will default to the number of CPUs anyway.

All in all something like this – note I changed the return type to (i, x) so you get the index you passed in back too. This is still missing saving the actual results anywhere, of course. :)

from multiprocess import Pool

def log_transform(x):
    transformed = math.e ** (-x)
    return transformed

input_region = "1.199"
t1 = "20200101"
t2 = "20200115"
candid_sale_invoices = pd.read_excel("candid_sale_invoices.xlsx")
candid_barcodes = pd.read_excel("candid_barcodes.xlsx")

def graph_analysis(i):
    input_date = str(i)
    sql_data = (
        """select trim(cast(p.Barcode as nvarchar(20))) Barcode ,cast(s.invoiceid as
    nvarchar(20)) invoiceid
    from sales s inner join Product_981115 p on s.productid = p.productid
    where s.date = """
        + input_date
        + """ and s.qty != 0 and p.sectionid != 1691.199 and s.RegionID = """
        + input_region
    )
    data = []
    for chunk in pd.read_sql(sql_data, conn, chunksize=1000000):
        data.append(chunk)
    if not data:
        return (i, None)
    data = pd.concat(data, ignore_index=True)
    data = data.merge(candid_sale_invoices)
    data = data.merge(candid_barcodes)
    final_edges_df = data.iloc[:, [2, 3, 4]]
    final_edges_tuples = [tuple(x) for x in final_edges_df.values]

    Gm = ig.Graph.TupleList(final_edges_tuples, directed=True, edge_attrs=["weight"])

    longest_paths = pd.DataFrame(Gm.shortest_paths_dijkstra(None, None, weights="weight"))
    longest_paths = longest_paths.swifter.apply(log_transform)
    longest_paths["Date"] = input_date
    longest_paths["RegionID"] = input_region
    return (i, longest_paths)

if __name__ == "__main__":
    with Pool() as pool:
        for i, result in pool.imap_unordered(graph_analysis, range(int(t1), (int(t2) + 1))):
            print(i, result)
```

Body:
I have to run a for loop and each loop will access data from a database, do some manipulation and run the Dijkstra algorithm, then append the results to a final list. The code looks like below:

def log_transform(x):
        transformed = math.e**(-x)
        return transformed
input_region = '1.199'
t1 = '20200101'
t2 = '20200115'
candid_sale_invoices = pd.read_excel('candid_sale_invoices.xlsx')
candid_barcodes = pd.read_excel('candid_barcodes.xlsx')

weights = []
    for i in range(int(t1),(int(t2) + 1)):
        input_date = str(i)
        sql_data = """select trim(cast(p.Barcode as nvarchar(20))) Barcode ,cast(s.invoiceid as nvarchar(20)) invoiceid
        from sales s inner join Product_981115 p on s.productid = p.productid
        where s.date = """+ input_date +""" and s.qty != 0 and p.sectionid != 1691.199 and s.RegionID = """ + input_region
        data = []
        for chunk in pd.read_sql(sql_data,conn,chunksize = 1000000):
            data.append(chunk)
        data = pd.concat(data, ignore_index = True)
        data = data.merge(candid_sale_invoices)
        data = data.merge(candid_barcodes)
        final_edges_df = data.iloc[:,[2,3,4]]
        final_edges_tuples = [tuple(x) for x in final_edges_df.values]

        Gm = ig.Graph.TupleList(final_edges_tuples, directed = True, edge_attrs = ['weight'])

        longest_paths = pd.DataFrame(Gm.shortest_paths_dijkstra(None,None, weights = 'weight'))
        longest_paths = longest_paths.swifter.apply(log_transform)
        longest_paths["Date"] = input_date
        longest_paths["RegionID"] = input_region
        weights.append(longest_paths)

weights = pd.concat(weights, ignore_index = True)

The problem is with the process time which will take hours to finish. So since each iteration is independent from other iterations, I decided to run this loop in parallel with the help of this link

import psutil
from multiprocess import Pool
pool = Pool(psutil.cpu_count(logical=False))
def graph_analysis(i):
    input_date = str(i)
    sql_data = """select trim(cast(p.Barcode as nvarchar(20))) Barcode ,cast(s.invoiceid as
    nvarchar(20)) invoiceid
    from sales s inner join Product_981115 p on s.productid = p.productid
    where s.date = """+ input_date +""" and s.qty != 0 and p.sectionid != 1691.199 and s.RegionID = """ + input_region
    data = []
    for chunk in pd.read_sql(sql_data,conn,chunksize = 1000000):
         data.append(chunk)
    data = pd.concat(data, ignore_index = True)
    data = data.merge(candid_sale_invoices)
    data = data.merge(candid_barcodes)
    final_edges_df = data.iloc[:,[2,3,4]]
    final_edges_tuples = [tuple(x) for x in final_edges_df.values]

    Gm = ig.Graph.TupleList(final_edges_tuples, directed = True, edge_attrs = ['weight'])

    longest_paths = pd.DataFrame(Gm.shortest_paths_dijkstra(None,None, weights = 'weight'))
    longest_paths = longest_paths.swifter.apply(log_transform)
    longest_paths["Date"] = input_date
    longest_paths["RegionID"] = input_region
    Return longest_paths

results = pool.map(graph_analysis,range(int(t1),(int(t2) + 1)))
pool.close()

With running the code, it seems like the code is doing its job and compute in parallel but after a while it raise this error:

Traceback (most recent call last):

File "", line 78, in
      weights = pool.map(graph_analysis,range(int(t1),(int(t2) + 1)))

File
  "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\multiprocess\pool.py",
  line 268, in map
      return self._map_async(func, iterable, mapstar, chunksize).get()

File
  "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\multiprocess\pool.py",
  line 657, in get
      raise self._value

ValueError: No objects to concatenate

Does this error relate to gathering the "longest_paths" dataframe from all of the iterations?

Body:
"No objects to concatenate" is a Pandas error returned when you call pd.concat() with an empty iterable:

>>> pd.concat([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pandas/core/reshape/concat.py", line 281, in concat
    sort=sort,
  File "pandas/core/reshape/concat.py", line 329, in __init__
    raise ValueError("No objects to concatenate")
ValueError: No objects to concatenate
>>>

I would assume you'll just need to quit early when the SQL query does not return anything:

# ...

    for chunk in pd.read_sql(sql_data, conn, chunksize=1000000):
        data.append(chunk)

    if not data: # <-- add this bit!
        return None

    data = pd.concat(data, ignore_index=True)

# ...

I'd also suggest using pool.imap_unordered(); you also don't need psutil since Pool will default to the number of CPUs anyway.

All in all something like this – note I changed the return type to (i, x) so you get the index you passed in back too. This is still missing saving the actual results anywhere, of course. :)

from multiprocess import Pool

def log_transform(x):
    transformed = math.e ** (-x)
    return transformed

input_region = "1.199"
t1 = "20200101"
t2 = "20200115"
candid_sale_invoices = pd.read_excel("candid_sale_invoices.xlsx")
candid_barcodes = pd.read_excel("candid_barcodes.xlsx")

def graph_analysis(i):
    input_date = str(i)
    sql_data = (
        """select trim(cast(p.Barcode as nvarchar(20))) Barcode ,cast(s.invoiceid as
    nvarchar(20)) invoiceid
    from sales s inner join Product_981115 p on s.productid = p.productid
    where s.date = """
        + input_date
        + """ and s.qty != 0 and p.sectionid != 1691.199 and s.RegionID = """
        + input_region
    )
    data = []
    for chunk in pd.read_sql(sql_data, conn, chunksize=1000000):
        data.append(chunk)
    if not data:
        return (i, None)
    data = pd.concat(data, ignore_index=True)
    data = data.merge(candid_sale_invoices)
    data = data.merge(candid_barcodes)
    final_edges_df = data.iloc[:, [2, 3, 4]]
    final_edges_tuples = [tuple(x) for x in final_edges_df.values]

    Gm = ig.Graph.TupleList(final_edges_tuples, directed=True, edge_attrs=["weight"])

    longest_paths = pd.DataFrame(Gm.shortest_paths_dijkstra(None, None, weights="weight"))
    longest_paths = longest_paths.swifter.apply(log_transform)
    longest_paths["Date"] = input_date
    longest_paths["RegionID"] = input_region
    return (i, longest_paths)

if __name__ == "__main__":
    with Pool() as pool:
        for i, result in pool.imap_unordered(graph_analysis, range(int(t1), (int(t2) + 1))):
            print(i, result)


问:
Android dex2oat build:ERROR: Dex2oat failed to compile a boot image
Build Android 9.0

ERROR: Dex2oat failed to compile a boot image. The boot classpath is likely inconsistent. Rebuild with ART_BOOT_IMAGE_EXTRA_ARGS=–runtime-arg -verbose: verifier to see verification errors.

答:
when apply the below patch can reslove the dexoat,but still break build 99% and always waiting .</p>

```<code>From a177377c4f206c7c4c5463158cf83af65fae17a9 Mon Sep 17 00:00:00 2001
Date: Wed, 3 Jul 2019 14:28:40 +0800
Subject: [PATCH] Revert "Use FdFile::Copy() in dex2oat for better error
 checking."

This reverts commit b55cc6df451e7653baf6f49dce1f2a0c03ba4bc6.
---
 dex2oat/dex2oat.cc | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/dex2oat/dex2oat.cc b/dex2oat/dex2oat.cc
index fe927bbc1c..974eaec711 100644
--- a/dex2oat/dex2oat.cc
+++ b/dex2oat/dex2oat.cc
@@ -2223,14 +2223,15 @@ class Dex2Oat FINAL {
         TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
         std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
         std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
-        int64_t in_length = in->GetLength();
-        if (in_length < 0) {
-          PLOG(ERROR) << "Failed to get the length of oat file: " << in->GetPath();
-          return false;
-        }
-        if (!out->Copy(in.get(), 0, in_length)) {
-          PLOG(ERROR) << "Failed to copy oat file to file: " << out->GetPath();
-          return false;
+        size_t buffer_size = 8192;
+        std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
+        while (true) {
+          int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
+          if (bytes_read <= 0) {
+            break;
+          }
+          bool write_ok = out->WriteFully(buffer.get(), bytes_read);
+          CHECK(write_ok);
         }
         if (out->FlushCloseOrErase() != 0) {
           PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
--
2.19.1
</code>```

Body:
when apply the below patch can reslove the dexoat,but still break build 99% and always waiting .

From a177377c4f206c7c4c5463158cf83af65fae17a9 Mon Sep 17 00:00:00 2001
Date: Wed, 3 Jul 2019 14:28:40 +0800
Subject: [PATCH] Revert "Use FdFile::Copy() in dex2oat for better error
 checking."

This reverts commit b55cc6df451e7653baf6f49dce1f2a0c03ba4bc6.
---
 dex2oat/dex2oat.cc | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/dex2oat/dex2oat.cc b/dex2oat/dex2oat.cc
index fe927bbc1c..974eaec711 100644
--- a/dex2oat/dex2oat.cc
+++ b/dex2oat/dex2oat.cc
@@ -2223,14 +2223,15 @@ class Dex2Oat FINAL {
         TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
         std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
         std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
-        int64_t in_length = in->GetLength();
-        if (in_length < 0) {
-          PLOG(ERROR) << "Failed to get the length of oat file: " << in->GetPath();
-          return false;
-        }
-        if (!out->Copy(in.get(), 0, in_length)) {
-          PLOG(ERROR) << "Failed to copy oat file to file: " << out->GetPath();
-          return false;
+        size_t buffer_size = 8192;
+        std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
+        while (true) {
+          int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
+          if (bytes_read <= 0) {
+            break;
+          }
+          bool write_ok = out->WriteFully(buffer.get(), bytes_read);
+          CHECK(write_ok);
         }
         if (out->FlushCloseOrErase() != 0) {
           PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
--
2.19.1


问:
Show result from SQL SERVER using PHP in web?
I'm here to ask about how to convert MySQL query to SQL Server since this will be my first attempt on doing it. I have successfully create the connection to my SQL Server but to problem is to fetch the data from the table.

I have also read some solutions as provided from similar questions to mine here

Selecting data from SQL Serverand here how to fetch data from sql server

Following is my code:

db.php

```<code><?php

//Your sql Config
$servername = "SNAPPER";

$connectionInfo = array ("Database"=> "CDS", "UID"=>"admin", "pwd" =>"mypassword");

//Create New Database Connection
$conn =sqlsrv_connect($servername, $connectionInfo);

//Check Connection
if($conn){
    //echo "Connection Established";

}else {
     echo "Connection fail";
     die (print_r(sqlsrv_errors(), true));
}
</code>```

and here is the code that I tried to call for the data from the SQL Server database

view.php

      Count of Accident
      <?php
                      $sql = "SELECT * FROM iir_incidentmain WHERE incident_type='Accident'";
                      $result = sqlsrv_query($conn, $sql);
                      if($result->num_rows > 0) {
                        $totalno = $result->num_rows;
                      } else {
                        $totalno = 0;
                      }
                    ?>
        <?php echo $totalno; ?>

```

and here is the error that has been echoed to me

Notice: Trying to get property 'num_rows' of non-object in C:\xampp\htdocs\snapper\user\dashboard.php on line 121

答:
Please try as the following

I tried and it worked

      Count of Near Miss
      <?php
       $sql = "SELECT COUNT (*) incident_type FROM iir_incidentmain WHERE incident_type='Accident'";

  $stmt = sqlsrv_query( $conn, $sql );
   $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
       ?>
        <?php echo $row['incident_type']?>

```

Body:
I'm here to ask about how to convert MySQL query to SQL Server since this will be my first attempt on doing it. I have successfully create the connection to my SQL Server but to problem is to fetch the data from the table.

I have also read some solutions as provided from similar questions to mine here

Selecting data from SQL Serverand here how to fetch data from sql server

Following is my code:

db.php

<?php

//Your sql Config
$servername = "SNAPPER";

$connectionInfo = array ("Database"=> "CDS", "UID"=>"admin", "pwd" =>"mypassword");

//Create New Database Connection
$conn =sqlsrv_connect($servername, $connectionInfo);

//Check Connection
if($conn){
    //echo "Connection Established";

}else {
     echo "Connection fail";
     die (print_r(sqlsrv_errors(), true));
}

and here is the code that I tried to call for the data from the SQL Server database

view.php

      Count of Accident
      <?php
                      $sql = "SELECT * FROM iir_incidentmain WHERE incident_type='Accident'";
                      $result = sqlsrv_query($conn, $sql);
                      if($result->num_rows > 0) {
                        $totalno = $result->num_rows;
                      } else {
                        $totalno = 0;
                      }
                    ?>
        <?php echo $totalno; ?>

and here is the error that has been echoed to me

Notice: Trying to get property 'num_rows' of non-object in C:\xampp\htdocs\snapper\user\dashboard.php on line 121

Body:
Please try as the following

I tried and it worked

<div class="col-md-6">
  <div class="info-box bg-c-yellow">
    <span class="info-box-icon bg-red"><i class="fa fa-chart-bar"></i></span>
    <div class="info-box-content">
      <span class="info-box-text">Count of Near Miss</span>
      <?php
       $sql = "SELECT COUNT (*) incident_type FROM iir_incidentmain WHERE incident_type='Accident'";

  $stmt = sqlsrv_query( $conn, $sql );
   $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
       ?>
        <span class="info-box-number"><?php echo $row['incident_type']?></span>

    </div>
  </div>
</div>


问:
git svn fetch - Session URL does not match expected session URL
I try to execute git svn fetch on a ubuntu machine that host a svn server. (transfering svn repo to git) git svn response with the error:

```<code>Session URL does not match expected session URL: Repository moved permanently to 'http://localhost/svn/repo' at /usr/share/perl5/Git/SVN.pm line 148.
</code>```

I am able to access the svn repository over the browser:

svn co http://localhost/svn/repo/trunk also works.

The config of my git repository look like:

```<code>[svn-remote "svn"]
    url = http://localhost/svn/repo
    fetch = trunk:refs/remotes/origin/trunk
    branches = branches/branchA/*:refs/remotes/branchA/*
</code>```

Last year I do the exact same process without any issues. What should the error message tell to me?

GIT_TRACE=1:

```<code>07:30:19.957480 git.c:576               trace: exec: git-svn fetch
07:30:19.957508 run-command.c:646       trace: run_command: git-svn fetch
06:30:20.264901 git.c:344               trace: built-in: git rev-parse --git-dir
06:30:20.270689 git.c:344               trace: built-in: git rev-parse --show-cdup
06:30:20.280345 git.c:344               trace: built-in: git config --bool --get svn.useSvmProps
06:30:20.282850 git.c:344               trace: built-in: git config --get svn.ignorerefs
06:30:20.284977 git.c:344               trace: built-in: git config --bool --get svn.uselogauthor
06:30:20.289744 git.c:344               trace: built-in: git config --int --get svn.logwindowsize
06:30:20.296912 git.c:344               trace: built-in: git config --get svn.repackflags
06:30:20.302913 git.c:344               trace: built-in: git config --bool --get svn.parent
06:30:20.308843 git.c:344               trace: built-in: git config --bool --get svn.noMetadata
06:30:20.313303 git.c:344               trace: built-in: git config --get svn.authorsprog
06:30:20.315443 git.c:344               trace: built-in: git config --bool --get svn.fetchall
06:30:20.325453 git.c:344               trace: built-in: git config --get svn.configdir
06:30:20.327644 git.c:344               trace: built-in: git config --int --get svn.repack
06:30:20.336702 git.c:344               trace: built-in: git config --get svn.includepaths
06:30:20.339225 git.c:344               trace: built-in: git config --get svn.username
06:30:20.341358 git.c:344               trace: built-in: git config --bool --get svn.localtime
06:30:20.350228 git.c:344               trace: built-in: git config --bool --get svn.useSvnsyncProps
06:30:20.352446 git.c:344               trace: built-in: git config --bool --get svn.nocheckout
06:30:20.361053 git.c:344               trace: built-in: git config --get svn.authorsfile
06:30:20.365090 git.c:344               trace: built-in: git config --get svn.ignorepaths
06:30:20.367110 git.c:344               trace: built-in: git config --bool --get svn.followparent
06:30:20.376769 git.c:344               trace: built-in: git config --get svn.revision
06:30:20.378979 git.c:344               trace: built-in: git config --bool --get svn.addauthorfrom
06:30:20.384743 git.c:344               trace: built-in: git config --bool --get svn.noauthcache
06:30:20.389012 git.c:344               trace: built-in: git config --bool --get svn.quiet
06:30:20.391455 git.c:344               trace: built-in: git rev-parse --symbolic --all
06:30:20.444247 git.c:344               trace: built-in: git rev-parse --git-path svn
06:30:20.453089 git.c:344               trace: built-in: git config -l
06:30:20.465201 git.c:344               trace: built-in: git config -l
06:30:20.468112 git.c:344               trace: built-in: git config --bool svn.useSvmProps
06:30:20.474744 git.c:344               trace: built-in: git config -l
Session URL does not match expected session URL: Repository moved permanently to 'http://localhost/svn/repo' at /usr/share/perl5/Git/SVN.pm line 148.
</code>```

答:
Find an old version of my virtual machine. The correct git config should looks like:

```<code>[svn-remote "svn"]
    url = file:///localhost/svn/repo  # <-  instead of http://
    fetch = trunk:refs/remotes/origin/trunk
    branches = branches/branchA/*:refs/remotes/branchA/*
</code>```

Hope this prevent someday ppl wasting time...

Body:
I try to execute git svn fetch on a ubuntu machine that host a svn server. (transfering svn repo to git) git svn response with the error:

Session URL does not match expected session URL: Repository moved permanently to 'http://localhost/svn/repo' at /usr/share/perl5/Git/SVN.pm line 148.

I am able to access the svn repository over the browser:

svn co http://localhost/svn/repo/trunk also works.

The config of my git repository look like:

[svn-remote "svn"]
    url = http://localhost/svn/repo
    fetch = trunk:refs/remotes/origin/trunk
    branches = branches/branchA/*:refs/remotes/branchA/*

Last year I do the exact same process without any issues. What should the error message tell to me?

GIT_TRACE=1:

07:30:19.957480 git.c:576               trace: exec: git-svn fetch
07:30:19.957508 run-command.c:646       trace: run_command: git-svn fetch
06:30:20.264901 git.c:344               trace: built-in: git rev-parse --git-dir
06:30:20.270689 git.c:344               trace: built-in: git rev-parse --show-cdup
06:30:20.280345 git.c:344               trace: built-in: git config --bool --get svn.useSvmProps
06:30:20.282850 git.c:344               trace: built-in: git config --get svn.ignorerefs
06:30:20.284977 git.c:344               trace: built-in: git config --bool --get svn.uselogauthor
06:30:20.289744 git.c:344               trace: built-in: git config --int --get svn.logwindowsize
06:30:20.296912 git.c:344               trace: built-in: git config --get svn.repackflags
06:30:20.302913 git.c:344               trace: built-in: git config --bool --get svn.parent
06:30:20.308843 git.c:344               trace: built-in: git config --bool --get svn.noMetadata
06:30:20.313303 git.c:344               trace: built-in: git config --get svn.authorsprog
06:30:20.315443 git.c:344               trace: built-in: git config --bool --get svn.fetchall
06:30:20.325453 git.c:344               trace: built-in: git config --get svn.configdir
06:30:20.327644 git.c:344               trace: built-in: git config --int --get svn.repack
06:30:20.336702 git.c:344               trace: built-in: git config --get svn.includepaths
06:30:20.339225 git.c:344               trace: built-in: git config --get svn.username
06:30:20.341358 git.c:344               trace: built-in: git config --bool --get svn.localtime
06:30:20.350228 git.c:344               trace: built-in: git config --bool --get svn.useSvnsyncProps
06:30:20.352446 git.c:344               trace: built-in: git config --bool --get svn.nocheckout
06:30:20.361053 git.c:344               trace: built-in: git config --get svn.authorsfile
06:30:20.365090 git.c:344               trace: built-in: git config --get svn.ignorepaths
06:30:20.367110 git.c:344               trace: built-in: git config --bool --get svn.followparent
06:30:20.376769 git.c:344               trace: built-in: git config --get svn.revision
06:30:20.378979 git.c:344               trace: built-in: git config --bool --get svn.addauthorfrom
06:30:20.384743 git.c:344               trace: built-in: git config --bool --get svn.noauthcache
06:30:20.389012 git.c:344               trace: built-in: git config --bool --get svn.quiet
06:30:20.391455 git.c:344               trace: built-in: git rev-parse --symbolic --all
06:30:20.444247 git.c:344               trace: built-in: git rev-parse --git-path svn
06:30:20.453089 git.c:344               trace: built-in: git config -l
06:30:20.465201 git.c:344               trace: built-in: git config -l
06:30:20.468112 git.c:344               trace: built-in: git config --bool svn.useSvmProps
06:30:20.474744 git.c:344               trace: built-in: git config -l
Session URL does not match expected session URL: Repository moved permanently to 'http://localhost/svn/repo' at /usr/share/perl5/Git/SVN.pm line 148.

Body:
Find an old version of my virtual machine. The correct git config should looks like:

[svn-remote "svn"]
    url = file:///localhost/svn/repo  # <-  instead of http://
    fetch = trunk:refs/remotes/origin/trunk
    branches = branches/branchA/*:refs/remotes/branchA/*

Hope this prevent someday ppl wasting time...


问:
axios get function not working in Reactjs
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

```<code>app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

</code>```

and I call the API in my reactjs page component

```<code>class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList
</code>```

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

答:
This error rises because you are not passing array to map function please add below code and let me know is it work for you are not</p>

```<code>componentDidMount = async (e) =>{
const url = "http://localhost:4000/enduser"
try{
const res = await axios.get(url)
this.setState({
 enduser_tbl :res.data
})
}
ctach(ex){
console.log(ex)
}
}
</code>```

Body:
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

and I call the API in my reactjs page component

class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

Body:
This error rises because you are not passing array to map function please add below code and let me know is it work for you are not

componentDidMount = async (e) =>{
const url = "http://localhost:4000/enduser"
try{
const res = await axios.get(url)
this.setState({
 enduser_tbl :res.data
})
}
ctach(ex){
console.log(ex)
}
}


问:
Hot tablets problem possible when using App Engine auto-generated IDs?
The hot tablets problem is described here:
http://ikaisays.com/2011/01/25/app-engine-datastore-tip-monotonically-increasing-values-are-bad/

I think I've read before that auto-generated IDs can suffer from this, I assume it's still the case?

If so, would a simple trick like inserting a random letter in front or reversing the order of the digits would help with this ? (I'm searching for a way to work around this problem while keeping keys as short as possible...)

答:
The ID numbers generated when you put a model in the datastore don't increase monotonically when deployed to App Engine (they do in dev_appserver).  You may see short ranges, but the numbers bounce around quite a bit.  I'm not sure if they do this specifically to defeat monotonically increasing indexes, but that's a side effect.

If you don't trust that, what I often do is create a key name using uuid.uuid4() (assuming you are using Python).


问:
ModuleNotFoundError: No module named 'dataviz'
i was trying to generate clusters with dataviz got error

ModuleNotFoundError: No module named 'dataviz'

from dataviz import generate_clusters

i tried !pip install dataviz got info Requirement already satisfied but error still shows

答:
It's probably a difference in python environment between your script environment, and pip's environment.

To learn more about your environment, you can run:

```<code>>>> import sys
>>> sys.executable
'/usr/bin/python'
>>> sys.version
'2.7.12 (default, Oct  8 2019, 14:14:10) \n[GCC 5.4.0 20160609]'
>>> sys.path
['/usr/lib/python2.7',
 ...
]
</code>```

from a python prompt, if you can bring one up.

I've often found that

```<code>python -m pip install <packagename>
</code>```

is more reliable than

```<code>pip install <packagename>
</code>```

But that only works if you're executing your script at a shell level, without some other python environment being put in front.

You could also try Installing python module within code

Body:
It's probably a difference in python environment between your script environment, and pip's environment.

To learn more about your environment, you can run:

>>> import sys
>>> sys.executable
'/usr/bin/python'
>>> sys.version
'2.7.12 (default, Oct  8 2019, 14:14:10) \n[GCC 5.4.0 20160609]'
>>> sys.path
['/usr/lib/python2.7',
 ...
]

from a python prompt, if you can bring one up.

I've often found that

python -m pip install <packagename>

is more reliable than

pip install <packagename>

But that only works if you're executing your script at a shell level, without some other python environment being put in front.

You could also try Installing python module within code


问:
How to use .dll 32bit run on Excel 64bit VSTO C#
I have 2 projects in a solution :One is Console Project where communicate with PLC and another is Excel add-in project.

My Problem: using .dll (x32bit) and run on Excel 64bit. Control button by Ribbon button to connect or disconnect to PLC. So, I added Excel add-in project in Console Project's references  to use Excel add-in public class. But, i cannot call constructor of VSTO Addin

```<code>public ThisAddIn(global::Microsoft.Office.Tools.Word.ApplicationFactory factory, global::System.IServiceProvider serviceProvider) :
                base(factory, serviceProvider, "AddIn", "ThisAddIn") {
            Globals.Factory = factory;
        }
</code>```

Here my code in Console:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Microsoft.Office.Tools.Ribbon;
using PLC2EXCEL_Addin;
using DATABUILDERAXLibLB;
using Microsoft.Office.Tools.Ribbon;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

namespace PLC2EXCEL
{
    class Program
    {
        public static DBCommManager dBCommManager = new DBCommManager();

        static void Main(string[] args)
        {

            dBCommManager.PLC=DBPlcId.DBPLC_KV3000;
            dBCommManager.Peer = "USB";
            //Microsoft.Office.Tools.Excel.ApplicationFactory _fatory ;
            //_fatory.GetRibbonFactory();

            //ThisAddIn thisAddIn = new ThisAddIn(Microsoft.Office.Tools.Excel.ApplicationFactory,IServerProvider); //i am not sure about this

            PLC2EXCEL_Ribbon pLC2EXCEL_Ribbon = new PLC2EXCEL_Ribbon();
            if (pLC2EXCEL_Ribbon != null)
                pLC2EXCEL_Ribbon.connectPLC_btn.Click += new RibbonControlEventHandler(startPLC2Excel);
            dBCommManager.Connect();
            Console.WriteLine("Connect PLC OK");
            Console.ReadLine();
        }

        public event EventHandler startPLC2Excel1;
        public static void startPLC2Excel(object sender, RibbonControlEventArgs eventArgs)
        {
            //DATABUILDERAXLibLB.DBCommManager dBCommManager = new DBCommManager();
            //dBCommManager.PLC = DBPlcId.DBPLC_KV3000;
            //dBCommManager.Peer = "USB";
            dBCommManager.Connect();
            Console.WriteLine("Connect PLC OK");
            Console.ReadLine();
        }
    }
}
</code>```

And code in Ribbon of Excel Addin:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Tools.Ribbon;

namespace PLC2EXCEL_Addin
{
    public partial class PLC2EXCEL_Ribbon
    {
        private void PLC2EXCEL_Ribbon_Load(object sender, RibbonUIEventArgs e)
        {

        }

        [ComVisible(true)]
        public void connectPLC_btn_Click(object sender, RibbonControlEventArgs e)  //How to catch this event from Console project
        {

            //Catch event
            MessageBox.Show("Connect to PLC");

        }
        public void abc() { }
    }
}
</code>```

Sorry any inconvenience, this is my first post.
Thank in advance.

答:
Impossible to use .dll 32bit on 64bit Excel,So I have solved my problem by create 2 separate projects:

One is C# app adding .dll 32bit and communicate to PLC and send data
to opened excel  file.

Anther is Excel Addin with ribbon buttons,
launch/stop executive C# app when click  button

Body:
I have 2 projects in a solution :One is Console Project where communicate with PLC and another is Excel add-in project.

My Problem: using .dll (x32bit) and run on Excel 64bit. Control button by Ribbon button to connect or disconnect to PLC. So, I added Excel add-in project in Console Project's references  to use Excel add-in public class. But, i cannot call constructor of VSTO Addin

public ThisAddIn(global::Microsoft.Office.Tools.Word.ApplicationFactory factory, global::System.IServiceProvider serviceProvider) :
                base(factory, serviceProvider, "AddIn", "ThisAddIn") {
            Globals.Factory = factory;
        }

Here my code in Console:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Microsoft.Office.Tools.Ribbon;
using PLC2EXCEL_Addin;
using DATABUILDERAXLibLB;
using Microsoft.Office.Tools.Ribbon;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

namespace PLC2EXCEL
{
    class Program
    {
        public static DBCommManager dBCommManager = new DBCommManager();

        static void Main(string[] args)
        {

            dBCommManager.PLC=DBPlcId.DBPLC_KV3000;
            dBCommManager.Peer = "USB";
            //Microsoft.Office.Tools.Excel.ApplicationFactory _fatory ;
            //_fatory.GetRibbonFactory();

            //ThisAddIn thisAddIn = new ThisAddIn(Microsoft.Office.Tools.Excel.ApplicationFactory,IServerProvider); //i am not sure about this

            PLC2EXCEL_Ribbon pLC2EXCEL_Ribbon = new PLC2EXCEL_Ribbon();
            if (pLC2EXCEL_Ribbon != null)
                pLC2EXCEL_Ribbon.connectPLC_btn.Click += new RibbonControlEventHandler(startPLC2Excel);
            dBCommManager.Connect();
            Console.WriteLine("Connect PLC OK");
            Console.ReadLine();
        }

        public event EventHandler startPLC2Excel1;
        public static void startPLC2Excel(object sender, RibbonControlEventArgs eventArgs)
        {
            //DATABUILDERAXLibLB.DBCommManager dBCommManager = new DBCommManager();
            //dBCommManager.PLC = DBPlcId.DBPLC_KV3000;
            //dBCommManager.Peer = "USB";
            dBCommManager.Connect();
            Console.WriteLine("Connect PLC OK");
            Console.ReadLine();
        }
    }
}

And code in Ribbon of Excel Addin:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Tools.Ribbon;

namespace PLC2EXCEL_Addin
{
    public partial class PLC2EXCEL_Ribbon
    {
        private void PLC2EXCEL_Ribbon_Load(object sender, RibbonUIEventArgs e)
        {

        }

        [ComVisible(true)]
        public void connectPLC_btn_Click(object sender, RibbonControlEventArgs e)  //How to catch this event from Console project
        {

            //Catch event
            MessageBox.Show("Connect to PLC");

        }
        public void abc() { }
    }
}

Sorry any inconvenience, this is my first post.
Thank in advance.


问:
Can I publish app to Apple Store through iOS Developer University Program
I am trying to register In Apple developer program but apple reject my application by saying your website is not valid for your legal entity name and give me link to register through iOS Developer University Program. My question is that can I able to publish app to apple store through this program.</p>

答:
No, you will not be able to publish app to apple store through this program.

So, What included in this program?

These are:-

1) Student Development Team :
The iOS Developer University Program allows instructors and professors to create a development team with up to 200 students.

2)Development Resources :
With the suite of sophisticated and elegant tools included in the iOS SDK, and a wide-range of resources available on the Apple Developer website, students participating in the class will have everything they need to create innovative applications for iPad, iPhone, and iPod touch.

3)Test on iPad, iPhone, and iPod touch :
Students can test and debug their applications using Xcode’s graphical debugger, or collect real-time performance data in Instruments’ timeline view. To see their work in action and ensure proper functionality, students can install their applications directly on iPad, iPhone and iPod touch.

4)Sharing Applications :
The iOS Developer University Program allows students and professors within the same team to share their development applications with each other through email, or by posting them to a private website for presentation and grading purposes.


问:
How to disable Parent Directory link or restrict access to only given folder in locally created HTML code?
Below is a line of HTML code.

```<code><link rel="stylesheet" href="/static/style.css" type="text/css">
            <p style="margin-top: 1em"> <font size="6" face="sans-serif"> <marquee> ABC </marquee> </font> </p>

            <a href="C:\Users\abcde\OneDrive\Desktop\Desktop_Ruff\management\scripts"  >Go to downloads page</a>
</code>```

When I am opening it in my browser, I have to access files that are in scripts directory only but by clicking the parent directory button in the opened HTML file it'll able to access files that are in parent directory too.

答:
There is no way for an HTML document to control what files a person can access on the disk of the computer they are using.

The only way to do that would be for a local admin user to set the permissions on the file system (and I'm pretty sure you can't allow access to a subfolder without allowing access to the parent folder too).

This wouldn't be the case if you were using an HTTP server, but since the link starts with C:\Users, you clearly aren't.

Body:
Below is a line of HTML code.

<link rel="stylesheet" href="/static/style.css" type="text/css">

  <marquee> ABC </marquee>

            Go to downloads page

When I am opening it in my browser, I have to access files that are in scripts directory only but by clicking the parent directory button in the opened HTML file it'll able to access files that are in parent directory too.


问:
TextView expand animation like in Android Market
Can anyone point to solution how to make expand animation of Description TextView in Android Market animation? There are TextView wrapped into FrameLayout which expands after clicking on 'More' label.</p>

答:
Solution:

```<code>private static int measureViewHeight( View view2Expand, View view2Measure ) {
    try {
        Method m = view2Measure.getClass().getDeclaredMethod("onMeasure", int.class, int.class);
        m.setAccessible(true);
        m.invoke(view2Measure,
                    MeasureSpec.makeMeasureSpec(view2Expand.getWidth(), MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    } catch (Exception e) {
        return -1;
    }

    int measuredHeight = view2Measure.getMeasuredHeight();
    return measuredHeight;
}

static public void expandOrCollapse( View view2Expand, View view2Measure,
        int collapsedHeight ) {
    if (view2Expand.getHeight() < collapsedHeight)
        return;

    int measuredHeight = measureViewHeight(view2Expand, view2Measure);

    if (measuredHeight < collapsedHeight)
        measuredHeight = collapsedHeight;

    final int startHeight = view2Expand.getHeight();
    final int finishHeight = startHeight <= collapsedHeight ?
            measuredHeight : collapsedHeight;

    view2Expand.startAnimation(new ExpandAnimation(view2Expand, startHeight, finishHeight));
}

class ExpandAnimation extends Animation {
    private final View _view;
    private final int _startHeight;
    private final int _finishHeight;

    public ExpandAnimation( View view, int startHeight, int finishHeight ) {
        _view = view;
        _startHeight = startHeight;
        _finishHeight = finishHeight;
        setDuration(220);
    }

    @Override
    protected void applyTransformation( float interpolatedTime, Transformation t ) {
        final int newHeight = (int)((_finishHeight - _startHeight) * interpolatedTime + _startHeight);
        _view.getLayoutParams().height = newHeight;
        _view.requestLayout();
    }

    @Override
    public void initialize( int width, int height, int parentWidth, int parentHeight ) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds( ) {
        return true;
    }
};
</code>```

Body:
Solution:

private static int measureViewHeight( View view2Expand, View view2Measure ) {
    try {
        Method m = view2Measure.getClass().getDeclaredMethod("onMeasure", int.class, int.class);
        m.setAccessible(true);
        m.invoke(view2Measure,
                    MeasureSpec.makeMeasureSpec(view2Expand.getWidth(), MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    } catch (Exception e) {
        return -1;
    }

    int measuredHeight = view2Measure.getMeasuredHeight();
    return measuredHeight;
}

static public void expandOrCollapse( View view2Expand, View view2Measure,
        int collapsedHeight ) {
    if (view2Expand.getHeight() < collapsedHeight)
        return;

    int measuredHeight = measureViewHeight(view2Expand, view2Measure);

    if (measuredHeight < collapsedHeight)
        measuredHeight = collapsedHeight;

    final int startHeight = view2Expand.getHeight();
    final int finishHeight = startHeight <= collapsedHeight ?
            measuredHeight : collapsedHeight;

    view2Expand.startAnimation(new ExpandAnimation(view2Expand, startHeight, finishHeight));
}

class ExpandAnimation extends Animation {
    private final View _view;
    private final int _startHeight;
    private final int _finishHeight;

    public ExpandAnimation( View view, int startHeight, int finishHeight ) {
        _view = view;
        _startHeight = startHeight;
        _finishHeight = finishHeight;
        setDuration(220);
    }

    @Override
    protected void applyTransformation( float interpolatedTime, Transformation t ) {
        final int newHeight = (int)((_finishHeight - _startHeight) * interpolatedTime + _startHeight);
        _view.getLayoutParams().height = newHeight;
        _view.requestLayout();
    }

    @Override
    public void initialize( int width, int height, int parentWidth, int parentHeight ) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds( ) {
        return true;
    }
};


问:
Sympy: Step-by-step calculation of an ODE system using indexed objects
I currently want to implement a Hammerstein model in sympy. I have now created a small example for a simple system:

```<code>import numpy as np
from sympy import *

####HAMMERSTEIN MODEL####
#time
t = symbols("t")

#inputs
u = symbols('u')

#states
y = symbols('y',cls = Function, Function = True)

#init states
y_init =symbols('y_init')

#parameters
gain = 2 #symbols('gain')
time_constant = 20000#symbols('time_constant')

#EQUATIONS

#NONLINEAR STATIC PART
u_nonlinear = u**2 # nonlinear input

#DYNAMIC PART
# first order system with inputs
rhe = (gain * u_nonlinear - y(t)) * 1/time_constant
ode = Eq(diff(y(t),t),rhe)

#solve equation
sol_step = dsolve(ode, ics = {y(0): y_init})
sol_step = sol_step.rhs

#lambdify (sympy)
system_step =lambdify((t,u, y_init),sol_step, 'sympy')

#####SIMULATE STEPWISE######
nr_steps = 10
dt=1
u_data =IndexedBase('u_data')
y_init_data =symbols('y_init_data')

#solution vector
sol =[]

for i in range(nr_steps):

    #first sim. step
    if i == 0:
        sol.append(system_step(dt,u_data[i],y_init_data))

    #uses the states of prev. solution as inits
    else:
        sol.append(system_step(dt,u_data[i],sol[i-1]))

#convert
system=lambdify((u_data,y_init_data),sol, 'numpy')

#EXAMPLE
t_obs = np.linspace(0,10,10)
u_obs = np.ones(10)* 40
x_obs_init =20

#RESULT
print(system(u_obs,x_obs_init))
</code>```

As you can see from the example, I solve the problem step by step. I always call the Sympy function object "system_step".
The performance is not particularly good with larger systems.

However, I would also like to use the simulation in a scipy optimizer, which leads to it being called several times, which extremely increases the solution time

My problem:

1.)
Can this step-by-step calculation also be implemented using sympy (e.g. indexed objects)? Can the repeated calculation in the loop be avoided?

2.) If so, how can this be done if the length of the input variables (u) should remain flexible and not be specified by a fixed index (m) using hardcode (see nr_steps).

Thank you very much!

答:
Thank you for the info. If I calculate the ODE system with constant input values, I do not need to calculate it step by step. Then the solution process is very quick. Therefore, my idea was to set up the system using vectors or indexed objects, which can prevent the step-by-step calculation.

My goal:

set up the system with variable input variables

solve the system symbolically, even if it takes a very long time

Lambdify and storage in a binary file

use the solved system for different operations

Body:
I currently want to implement a Hammerstein model in sympy. I have now created a small example for a simple system:

import numpy as np
from sympy import *

####HAMMERSTEIN MODEL####
#time
t = symbols("t")

#inputs
u = symbols('u')

#states
y = symbols('y',cls = Function, Function = True)

#init states
y_init =symbols('y_init')

#parameters
gain = 2 #symbols('gain')
time_constant = 20000#symbols('time_constant')

#EQUATIONS

#NONLINEAR STATIC PART
u_nonlinear = u**2 # nonlinear input

#DYNAMIC PART
# first order system with inputs
rhe = (gain * u_nonlinear - y(t)) * 1/time_constant
ode = Eq(diff(y(t),t),rhe)

#solve equation
sol_step = dsolve(ode, ics = {y(0): y_init})
sol_step = sol_step.rhs

#lambdify (sympy)
system_step =lambdify((t,u, y_init),sol_step, 'sympy')

#####SIMULATE STEPWISE######
nr_steps = 10
dt=1
u_data =IndexedBase('u_data')
y_init_data =symbols('y_init_data')

#solution vector
sol =[]

for i in range(nr_steps):

    #first sim. step
    if i == 0:
        sol.append(system_step(dt,u_data[i],y_init_data))

    #uses the states of prev. solution as inits
    else:
        sol.append(system_step(dt,u_data[i],sol[i-1]))

#convert
system=lambdify((u_data,y_init_data),sol, 'numpy')

#EXAMPLE
t_obs = np.linspace(0,10,10)
u_obs = np.ones(10)* 40
x_obs_init =20

#RESULT
print(system(u_obs,x_obs_init))

As you can see from the example, I solve the problem step by step. I always call the Sympy function object "system_step".
The performance is not particularly good with larger systems.

However, I would also like to use the simulation in a scipy optimizer, which leads to it being called several times, which extremely increases the solution time

My problem:

1.)
Can this step-by-step calculation also be implemented using sympy (e.g. indexed objects)? Can the repeated calculation in the loop be avoided?

2.) If so, how can this be done if the length of the input variables (u) should remain flexible and not be specified by a fixed index (m) using hardcode (see nr_steps).

Thank you very much!