问:
Char buffer with multiple null char
I am working on a socket program(using recvfrom) which returns me a buffer of char. However the received data contains multiple null chars and it does not let me post process it easily.

I would like to request if there is any way to escape the null chars if they are found in the middle of the buffer ?

Goal is to store the binary data into cassandra DB. I tried to ignore the null chars and store it directly into the DB. However it will only store the partial string. On research I learnt that I could use TextAsBlob() function to convert the received data into blob. Although this did not changed anything , only partial data is stored in the DB.(till the first null is seen).

So,  I need to know is there a way to escape them? I have the length of the received data available.

For printing the data I am  printing the data using %c byte by byte.

Structure of table:

```<code>cqlsh:network> desc packet;

CREATE TABLE network.packet (
    key text PRIMARY KEY,
    value blob
) WITH bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

cqlsh:network>

cqlsh:network> SELECT * from packet;

 key                                            | value
------------------------------------------------+--------------------
 1234                                           |     0x70e54c5bfd7f
 1235
</code>```

Error:

```<code>cqlsh:network> SELECT blobAsText(value) FROM network.packet WHERE key = '1234' ;
InvalidRequest: Error from server: code=2200 [Invalid query] message="In call to function system.blobastext, value 0x70e54c5bfd7f is not a valid binary representation for type text"
</code>```

Insert command:

```<code> char key[5] = 1234;
// value is received from socket.

INSERT INTO network.packet (key, value) VALUES (key, value);
</code>```

答:
You're saying that this data shouldn't be referred to as text, and then you're using TextToBlob() to store it. TextToBlob() would refer to your data as text (and would try to store it as binary data) but that's exactly what you wouldn't want. Because if it would have been referred to as text every 0 would mean string-termination.

You'd want to store this data received by recvfrom in some pointer to some data structure or maybe just a void *. Because otherwise, every byte which is null (0) will be referred to as end-of-string.

So, you should allocate some memory in the size you say you know, and then read all this data to this address not using any strings (char arrays) functions.

Title: Char buffer with multiple null char

Body:
I am working on a socket program(using recvfrom) which returns me a buffer of char. However the received data contains multiple null chars and it does not let me post process it easily.

I would like to request if there is any way to escape the null chars if they are found in the middle of the buffer ?

Goal is to store the binary data into cassandra DB. I tried to ignore the null chars and store it directly into the DB. However it will only store the partial string. On research I learnt that I could use TextAsBlob() function to convert the received data into blob. Although this did not changed anything , only partial data is stored in the DB.(till the first null is seen).

So,  I need to know is there a way to escape them? I have the length of the received data available.

For printing the data I am  printing the data using %c byte by byte.

Structure of table:

cqlsh:network> desc packet;

CREATE TABLE network.packet (
    key text PRIMARY KEY,
    value blob
) WITH bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

cqlsh:network>

cqlsh:network> SELECT * from packet;

 key                                            | value
------------------------------------------------+--------------------
 1234                                           |     0x70e54c5bfd7f
 1235

Error:

cqlsh:network> SELECT blobAsText(value) FROM network.packet WHERE key = '1234' ;
InvalidRequest: Error from server: code=2200 [Invalid query] message="In call to function system.blobastext, value 0x70e54c5bfd7f is not a valid binary representation for type text"

Insert command:

 char key[5] = 1234;
// value is received from socket.

INSERT INTO network.packet (key, value) VALUES (key, value);


来源: stackexchange

问:
Spring 3.1.x milestone repository
I am currently searching for a maven repository that contains the recent spring milestones of version 3.1.x.

There are a lot of links when searching google, but they all seem to be dead.

Does anyone know the link to the repository?

答:
This is the repo:

```<code><repository>
    <id>repository.springframework.milestone</id>
    <name>Spring Framework Maven Milestone Repository</name>
    <url>http://maven.springframework.org/milestone</url>
</repository>
</code>```

Source: http://forum.springsource.org/showthread.php?t=92277

Hint: you can't browse this repo, as it's in an Amazon Cloud. But it is there :-)

ContentLicense: CC BY-SA 3.0

Title: Spring 3.1.x milestone repository

Body:
This is the repo:

<repository>
    <id>repository.springframework.milestone</id>
    <name>Spring Framework Maven Milestone Repository</name>
    <url>http://maven.springframework.org/milestone</url>
</repository>

Source: http://forum.springsource.org/showthread.php?t=92277

Hint: you can't browse this repo, as it's in an Amazon Cloud. But it is there :-)


问:
Jhipster UAA External Client
I use jhipster UAA and Gatewy App in my server running in EC2.
(https://www.jhipster.tech/images/microservices_architecture_detail.002.png)

I have application running external cloud to put data in this server, It use REST endpoint to make request.

I need turn on security in this endpoint, then use access token or client secret.

I turned on the security, and copy my secret token by FrontEnd application. My first request work, but the second request don't work.

My OAuth2RestTemplate.

 @Bean
  public OAuth2RestTemplate redditRestTemplate(OAuth2ProtectedResourceDetails resourceDetails, OAuth2ClientContext clientContext) {
    clientContext.setAccessToken(new DefaultOAuth2AccessToken(applicationProperties.getAccessToken()));
    OAuth2RestTemplate template = new OAuth2RestTemplate(resourceDetails, clientContext);
    AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(
      Arrays.<AccessTokenProvider>asList(
        new ImplicitAccessTokenProvider(),
        new ResourceOwnerPasswordAccessTokenProvider(),
        new ClientCredentialsAccessTokenProvider())
    );
    template.setAccessTokenProvider(accessTokenProvider);
    return template;
  }
```

<p>My request.</p>

<pre class="lang-java prettyprint-override"><code>OAuth2RestTemplate b = a.getBean(OAuth2RestTemplate.class);
String c = b.getForEntity("https://cloud.com/api/app/v1/events", String.class).getBody();
</code>```

First request Ok.
I need save the new accessToken?

Is there any way to do this integration using "client secret" or anything?

答: After making the authentication request /auth/login you have to save the accessToken received in the response. Subsequent requests must contain this access token in the header Authorization: Bearer <accessToken>

ContentLicense: CC BY-SA 4.0

Title: Jhipster UAA External Client

Body:
I use jhipster UAA and Gatewy App in my server running in EC2.
(https://www.jhipster.tech/images/microservices_architecture_detail.002.png)

I have application running external cloud to put data in this server, It use REST endpoint to make request.

I need turn on security in this endpoint, then use access token or client secret.

I turned on the security, and copy my secret token by FrontEnd application. My first request work, but the second request don't work.

My OAuth2RestTemplate.

 @Bean
  public OAuth2RestTemplate redditRestTemplate(OAuth2ProtectedResourceDetails resourceDetails, OAuth2ClientContext clientContext) {
    clientContext.setAccessToken(new DefaultOAuth2AccessToken(applicationProperties.getAccessToken()));
    OAuth2RestTemplate template = new OAuth2RestTemplate(resourceDetails, clientContext);
    AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(
      Arrays.<AccessTokenProvider>asList(
        new ImplicitAccessTokenProvider(),
        new ResourceOwnerPasswordAccessTokenProvider(),
        new ClientCredentialsAccessTokenProvider())
    );
    template.setAccessTokenProvider(accessTokenProvider);
    return template;
  }

My request.

OAuth2RestTemplate b = a.getBean(OAuth2RestTemplate.class);
String c = b.getForEntity("https://cloud.com/api/app/v1/events", String.class).getBody();

First request Ok.
I need save the new accessToken?

Is there any way to do this integration using "client secret" or anything?


问:
Can I use the normal form of a value to avoid incomplete pattern matches in Agda?
In the following Agda program, I get a warning about a missing case in the definition of one, despite the fact that myList only fits the cons case.

open import Data.Nat

data List (A : Set) : Set where
  nil : List A
  cons : A → List A → List A

myList : List ℕ
myList = cons 1 (cons 2 (cons 3 nil))

one : ℕ
one with myList
... | (cons x xs) = x
```

<pre class="lang-none prettyprint-override"><code>Incomplete pattern matching for .test.with-16. Missing
cases:
  one | nil
</code>```

I know that this sounds a bit convoluted but is there a way to define one in terms of myList, without running into "incomplete pattern matching" errors?

This example is a simplification of my original problem, which is from a homework assignment and which uses slightly more complicated types. In that case, "myList" is a large value computed by a clever function from a small input. If I compute the normal form of "myList" using Emacs' Agda Mode (C-c C-n), I can grab the value of "one" from that and paste it into my program. However, this value takes dozens of lines when printed out so I was wandering if there is a way to directly define "one" in terms of "myList", without running into the incomplete pattern matching error.

答:
You can reflect a value at the type level and then pattern match on it. Looks like this:</p>

```<code>open import Data.Nat

data List (A : Set) : Set where
  nil : List A
  cons : A → List A → List A

myList : List ℕ
myList = cons 1 (cons 2 (cons 3 nil))

data Sing {α} {A : Set α} : A -> Set where
  sing : ∀ x -> Sing x

one : ℕ
one with sing myList
... | sing (cons x (cons _ (cons _ nil))) = x
</code>```

Body:
In the following Agda program, I get a warning about a missing case in the definition of one, despite the fact that myList only fits the cons case.

open import Data.Nat

data List (A : Set) : Set where
  nil : List A
  cons : A → List A → List A

myList : List ℕ
myList = cons 1 (cons 2 (cons 3 nil))

one : ℕ
one with myList
... | (cons x xs) = x

Incomplete pattern matching for .test.with-16. Missing
cases:
  one | nil

I know that this sounds a bit convoluted but is there a way to define one in terms of myList, without running into "incomplete pattern matching" errors?

This example is a simplification of my original problem, which is from a homework assignment and which uses slightly more complicated types. In that case, "myList" is a large value computed by a clever function from a small input. If I compute the normal form of "myList" using Emacs' Agda Mode (C-c C-n), I can grab the value of "one" from that and paste it into my program. However, this value takes dozens of lines when printed out so I was wandering if there is a way to directly define "one" in terms of "myList", without running into the incomplete pattern matching error.

Body:
You can reflect a value at the type level and then pattern match on it. Looks like this:

open import Data.Nat

data List (A : Set) : Set where
  nil : List A
  cons : A → List A → List A

myList : List ℕ
myList = cons 1 (cons 2 (cons 3 nil))

data Sing {α} {A : Set α} : A -> Set where
  sing : ∀ x -> Sing x

one : ℕ
one with sing myList
... | sing (cons x (cons _ (cons _ nil))) = x


问:
Java Mongo db 'and' operator
```<code>final Bson filter = and(in(ROUTEID_KEY, routeIds), or(ne(DELETED_KEY, TRUE), exists(DELETED_KEY, FALSE)));
final FindIterable<Document> doc = someCollection.find(filter);
</code>```

I am relatively new to mongodb. can some one please explain me this filter condition.I think it means all documents with given 'routeIds' as well as all documents having DELETED_KEY field value as false along with all documets where 'DELETED_KEY' field don't exist. But when i am running find() for below filter only, unexpectedly i am getting more values.

```<code> final Bson filter = and(in(ROUTEID_KEY, routeIds));
</code>```

Please explain what the 1st filter condition actually means.

答:
I'm not familiar with java driver and this exact api, but I'm relatively sure that it means "select all document which a) have ROUTEID_KEY value from this list and b) don't have their DELETED_KEY set to TRUE or don't have DELETED_KEY at all".

The second part (the or) reduces the returned dataset, it does not add to it.

Title: Java Mongo db 'and' operator

Body:
final Bson filter = and(in(ROUTEID_KEY, routeIds), or(ne(DELETED_KEY, TRUE), exists(DELETED_KEY, FALSE)));
final FindIterable<Document> doc = someCollection.find(filter);

I am relatively new to mongodb. can some one please explain me this filter condition.I think it means all documents with given 'routeIds' as well as all documents having DELETED_KEY field value as false along with all documets where 'DELETED_KEY' field don't exist. But when i am running find() for below filter only, unexpectedly i am getting more values.

 final Bson filter = and(in(ROUTEID_KEY, routeIds));

Please explain what the 1st filter condition actually means.


问:
Comparing a cell with a named range for conditional formatting
I'm importing hourly sensor data from 10 different sensors. In short, I want to be able to see when the hourly data exceeds the average usage for that day of the week and time of the day.

I've created sheets named each of the sensor names ("32022", for example) and each of those sheets is a 26 column matrix of the date, all the hours from 00:00 to 23:00, and a WEEKDAY() function to extract the day of the week from the date.

In a separate sheet ("Daily Usage"), I manually created 10 different matrices of the daily average usage by hour for each sensor, with column A being the day of the week (by name) and the following 24 columns being all the hours of the day. Each one of those matrices has been made into a Named Range called "averageusage_32022".

I am trying to iterate through all the data and identify which data is above average for that particular day/time, and change the background of that cell to red if it exceeds the average.

From what I've gathered, I cannot refer to a named ranged in conditional formatting, which is why I'm looking to solve this programmatically.

```<code>  var currentsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("32033");
  var usagerange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('averageusage_32033');

  //how many rows there are in the sheet
  var firstcolumn = currentsheet.getRange("A1:A").getValues();
  var bottomrow = firstcolumn.filter(String).length;

  //loop through every day, check day of week, iterate through each hour, compare cell to "averageusage" range

  for (var i = 2; i < bottomrow; i++){
    var day = currentsheet.getRange(i,26).getValue;
    for (var j = 2; j < 26; j++){
      if (currentsheet.getRange(i,j).getValue() > usagerange.getRange(day,j).getValue()){
        currentsheet.getRange(i,j).setBackground("red");
        }
     }
   }
</code>```

I'm receiving an error of Cannot find function getRange in object Range. I'm assuming that this is because I cannot refer to the named range as I would any normal sheet.

答:
Since getRangeByName(name) method returns Range instead of NamedRange, you need to remove both arguments and getRange() method from the one written into usagerange (please, note that day and j will be 0-based for values Array). Also, make sure to write values into a variable outside the loop to reduce service calls:

```<code>var usageVals = usagerange.getValues();
//...loop
if(currentsheet.getRange(i,j).getValue() > usageVals[day-1][j-1]) {
  //do something;
}
//...loop
</code>```

Body:
I'm importing hourly sensor data from 10 different sensors. In short, I want to be able to see when the hourly data exceeds the average usage for that day of the week and time of the day.

I've created sheets named each of the sensor names ("32022", for example) and each of those sheets is a 26 column matrix of the date, all the hours from 00:00 to 23:00, and a WEEKDAY() function to extract the day of the week from the date.

In a separate sheet ("Daily Usage"), I manually created 10 different matrices of the daily average usage by hour for each sensor, with column A being the day of the week (by name) and the following 24 columns being all the hours of the day. Each one of those matrices has been made into a Named Range called "averageusage_32022".

I am trying to iterate through all the data and identify which data is above average for that particular day/time, and change the background of that cell to red if it exceeds the average.

From what I've gathered, I cannot refer to a named ranged in conditional formatting, which is why I'm looking to solve this programmatically.

  var currentsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("32033");
  var usagerange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('averageusage_32033');

  //how many rows there are in the sheet
  var firstcolumn = currentsheet.getRange("A1:A").getValues();
  var bottomrow = firstcolumn.filter(String).length;

  //loop through every day, check day of week, iterate through each hour, compare cell to "averageusage" range

  for (var i = 2; i < bottomrow; i++){
    var day = currentsheet.getRange(i,26).getValue;
    for (var j = 2; j < 26; j++){
      if (currentsheet.getRange(i,j).getValue() > usagerange.getRange(day,j).getValue()){
        currentsheet.getRange(i,j).setBackground("red");
        }
     }
   }

I'm receiving an error of Cannot find function getRange in object Range. I'm assuming that this is because I cannot refer to the named range as I would any normal sheet.

Body:
Since getRangeByName(name) method returns Range instead of NamedRange, you need to remove both arguments and getRange() method from the one written into usagerange (please, note that day and j will be 0-based for values Array). Also, make sure to write values into a variable outside the loop to reduce service calls:

var usageVals = usagerange.getValues();
//...loop
if(currentsheet.getRange(i,j).getValue() > usageVals[day-1][j-1]) {
  //do something;
}
//...loop


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答: Do a little bit each day. Persistence is by far the biggest determining factor in getting side projects done.</p>

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: DasBoot


问:
How to find URLs that starts with "/" and contain "php"?
I have a 95MB XML file of content that is going from an old CMS (Drupal via Wordpress) to a new CMS (Squarespace).

The Squarespace import process keeps breaking & it appears to come down to links that attempt to execute PHP in the new server.

For example:

During the import process the new CMS recognises this as an internal link & tries to execute that URL to import the content, treats it as an attack or attempt at code injection & shuts down the process.

So I want a way of finding URLs that start with "/" & contain "php" so I can remove them.

I should be clear I only want to identify internal links & not external links to other sites.

Is this possible via Regex? I'd really like to avoid writing script to do this if I can just plug a Regex statement into Atom & Find/Replace.

答:
How about some simple regex by use of a negated class.

```<code>"\/[^\s"'><]+\.php
</code>```

[^\s"'><] matches any character besides white space, quotes, greater/lesser sign

add word boundary \b after php if desired

Here is the demo at regex101 comparing internal php links to external php links

Body:
How about some simple regex by use of a negated class.

"\/[^\s"'><]+\.php

[^\s"'><] matches any character besides white space, quotes, greater/lesser sign

add word boundary \b after php if desired

Here is the demo at regex101 comparing internal php links to external php links


问:
How to read reversed number from a binary file?
i would like to read a 32-bits number from binary file in C. The problem is that the order of bits is reversed. For an example 3 digits number 110 would stand for 3, not for 6. At the beginning we have the least significant bit (2^0), then 2^1 and so on. Is there any simple way to do this in C, or do i have to write all the logic by myself (read the first bit, multiply it by 2^0, add to the sum, repeat to the end)?</p>

答:
you have many possible ways:

Portable:

(not my algorithm)

```<code>uint32_t rev(uint32_t x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16));
}
</code>```

or

```<code>uint32_t bit_reverse_4bytes(uint32_t x)
{
    x = ((x & 0xF0F0F0F0) >> 4) | ((x & 0x0F0F0F0F) << 4);
    x = ((x & 0xCCCCCCCC) >> 2) | ((x & 0x33333333) << 2);
    return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1);
}
</code>```

Naive

```<code>uint32_t naiverevese(uint32_t x)
{
    uint32_t result = 0;
    for(int i = 0; i < 32; i++)
    {
        result |= x & 1;
        result <<=1;
        x >>= 1;
    }
    return result;
}
</code>```

or lookup table.

Not portable but the most efficient:

Many processors have a special instructions for it for example:

ARM - rbit and the intrinsic unsigned int __rbit(unsigned int val)

Body:
you have many possible ways:

Portable:

(not my algorithm)

uint32_t rev(uint32_t x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16));
}

or

uint32_t bit_reverse_4bytes(uint32_t x)
{
    x = ((x & 0xF0F0F0F0) >> 4) | ((x & 0x0F0F0F0F) << 4);
    x = ((x & 0xCCCCCCCC) >> 2) | ((x & 0x33333333) << 2);
    return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1);
}

Naive

uint32_t naiverevese(uint32_t x)
{
    uint32_t result = 0;
    for(int i = 0; i < 32; i++)
    {
        result |= x & 1;
        result <<=1;
        x >>= 1;
    }
    return result;
}

or lookup table.

Not portable but the most efficient:

Many processors have a special instructions for it for example:

ARM - rbit and the intrinsic unsigned int __rbit(unsigned int val)


问:
Replace capital letters in an entire string with lowercase letters and hyphens
I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be come sunny-&-cloudy

```<code>var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');
</code>```

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

答:
One possible approach for what you need is to use the replacement function of String.replace()

var name = 'Sunny&Cloudy';

let res = name.replace(/[A-Z&]/g, m => m === "&" ? "-and-" : m.toLowerCase());

console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Body:
I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be come sunny-&-cloudy

var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

Body:
One possible approach for what you need is to use the replacement function of String.replace()

var name = 'Sunny&Cloudy';

let res = name.replace(/[A-Z&]/g, m => m === "&" ? "-and-" : m.toLowerCase());

console.log(res);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
Cannot invoke 'addAnimations' with an argument list of type '(() -> (), delayFactor: Double)'
I'm using UIViewPropertyAnimator to control the progress of multiple animations. I have a 2d array of UIView subclasses. I want to display all elements at each index at once. For some reason the compiler won't let me add new animations with a delay by using addAnimations(_:delayFactor:) method. Can someone tell me what am I doing wrong here?

```<code>// I'm creating a new viewAnimator without any animations. No problems here
        self.viewAnimator = UIViewPropertyAnimator(duration: self.frameDelay * Double(self.spillBubbles.count),
                                                   curve: .easeIn,
                                                   animations: {})

        for (index, views) in self.spillBubbles.enumerated() {

            views.forEach({ self.simulationView.addSubview($0) })

            // That's where the compiler error occurs
            self.viewAnimator!.addAnimations({
                views.forEach({ self.simulationView.addSubview($0) })
            }, delayFactor: Double(index) / Double(self.spillBubbles.count))

        }
</code>```

When I try to call .addAnimations I get the following message:
Cannot invoke 'addAnimations' with an argument list of type '(() -> (), delayFactor: Double)'

What am I doing wrong here? The same closure called in the UIViewPropertyAnimator initializers works without any issues.

答:
The error message is pretty clear. Just look at the docs if it isn't clear enough:

https://developer.apple.com/documentation/uikit/uiviewpropertyanimator/1648370-addanimations

The delayFactor needs to be a CGFloat, not a Double.

Body:
I'm using UIViewPropertyAnimator to control the progress of multiple animations. I have a 2d array of UIView subclasses. I want to display all elements at each index at once. For some reason the compiler won't let me add new animations with a delay by using addAnimations(_:delayFactor:) method. Can someone tell me what am I doing wrong here?

// I'm creating a new viewAnimator without any animations. No problems here
        self.viewAnimator = UIViewPropertyAnimator(duration: self.frameDelay * Double(self.spillBubbles.count),
                                                   curve: .easeIn,
                                                   animations: {})

        for (index, views) in self.spillBubbles.enumerated() {

            views.forEach({ self.simulationView.addSubview($0) })

            // That's where the compiler error occurs
            self.viewAnimator!.addAnimations({
                views.forEach({ self.simulationView.addSubview($0) })
            }, delayFactor: Double(index) / Double(self.spillBubbles.count))

        }

When I try to call .addAnimations I get the following message:
Cannot invoke 'addAnimations' with an argument list of type '(() -> (), delayFactor: Double)'

What am I doing wrong here? The same closure called in the UIViewPropertyAnimator initializers works without any issues.


问:
How to print Extended ASCII characters correctly with json.dumps() - Python
I have this JSON file with some characters that belongs to Extended ASCII characters, for example », •, ñ, Ó, Ä

```<code>{
    "@index": "1",
    "row": [
    {
        "col": [
        {
            "text": {
            "@x": "1",
            "#text": "Text » 1 A\\CÓ"
            }
        }
        ]
    },
    {
        "col": [
        {
            "text": {
            "@x": "7",
            "#text": "Text • 2 Wñ"
            }
        }
        ]
    }
    ]
}
</code>```

I load it in d variable with json.load() as below

```<code>import json

with open('in.json') as f:
    d = json.load(f)
</code>```

and d looks like this:

```<code>d = {'@index': '1', 'row': [{'col': [{'text': {'@x': '1', '#text': 'Text » 1 A\\CÓ'}}]}, {'col': [{'text': {'@x': '7', '#text': 'Text • 2 Wñ'}}]}]}
</code>```

Then applying the following code, the json stored in d is converted to one level nested json (Until here, the extended ASCII characters are fine)

```<code>>>> z = {**d, 'row':[c['text'] for b in d['row'] for c in b['col']]}
>>> z
{'@index': '1', 'row': [{'@x': '1', '#text': 'Text » 1 A\\CÓ'}, {'@x': '7', '#text': 'Text • 2 Wñ'}]}
>>>
</code>```

The issue comes when I use json.dumps() because the extended ASCII characters are printed wrong as you can see below.

How to fix this? Thanks for any help.

```<code>>>> print(json.dumps(z, indent=4))
{
    "@index": "1",
    "row": [
        {
            "@x": "1",
            "#text": "Text \u00bb 1 A\\C\u00d3"
        },
        {
            "@x": "7",
            "#text": "Text \u2022 2 W\u00f1"
        }
    ]
}
>>>
</code>```

答:
You're looking for the ensure_ascii parameter.

```<code>import json

raw_data = '{"data": ["»", "•", "ñ", "Ó", "Ä"]}'
json_data = json.loads(raw_data)

print(json_data)
# {u'data': [u'\xbb', u'\u2022', u'\xf1', u'\xd3', u'\xc4']}

processed_data = json.dumps(json_data, indent=4, ensure_ascii=False, encoding='utf-8')

print(processed_data)
# {
#     "data": [
#         "»",
#         "•",
#         "ñ",
#         "Ó",
#         "Ä"
#     ]
# }
</code>```

For Python2 you'd do:

```<code>processed_data = json.dumps(json_data, indent=4, ensure_ascii=False).encode('utf-8')
</code>```

Body:
I have this JSON file with some characters that belongs to Extended ASCII characters, for example », •, ñ, Ó, Ä

{
    "@index": "1",
    "row": [
    {
        "col": [
        {
            "text": {
            "@x": "1",
            "#text": "Text » 1 A\\CÓ"
            }
        }
        ]
    },
    {
        "col": [
        {
            "text": {
            "@x": "7",
            "#text": "Text • 2 Wñ"
            }
        }
        ]
    }
    ]
}

I load it in d variable with json.load() as below

import json

with open('in.json') as f:
    d = json.load(f)

and d looks like this:

d = {'@index': '1', 'row': [{'col': [{'text': {'@x': '1', '#text': 'Text » 1 A\\CÓ'}}]}, {'col': [{'text': {'@x': '7', '#text': 'Text • 2 Wñ'}}]}]}

Then applying the following code, the json stored in d is converted to one level nested json (Until here, the extended ASCII characters are fine)

>>> z = {**d, 'row':[c['text'] for b in d['row'] for c in b['col']]}
>>> z
{'@index': '1', 'row': [{'@x': '1', '#text': 'Text » 1 A\\CÓ'}, {'@x': '7', '#text': 'Text • 2 Wñ'}]}
>>>

The issue comes when I use json.dumps() because the extended ASCII characters are printed wrong as you can see below.

How to fix this? Thanks for any help.

>>> print(json.dumps(z, indent=4))
{
    "@index": "1",
    "row": [
        {
            "@x": "1",
            "#text": "Text \u00bb 1 A\\C\u00d3"
        },
        {
            "@x": "7",
            "#text": "Text \u2022 2 W\u00f1"
        }
    ]
}
>>>

Body:
You're looking for the ensure_ascii parameter.

import json

raw_data = '{"data": ["»", "•", "ñ", "Ó", "Ä"]}'
json_data = json.loads(raw_data)

print(json_data)
# {u'data': [u'\xbb', u'\u2022', u'\xf1', u'\xd3', u'\xc4']}

processed_data = json.dumps(json_data, indent=4, ensure_ascii=False, encoding='utf-8')

print(processed_data)
# {
#     "data": [
#         "»",
#         "•",
#         "ñ",
#         "Ó",
#         "Ä"
#     ]
# }

For Python2 you'd do:

processed_data = json.dumps(json_data, indent=4, ensure_ascii=False).encode('utf-8')


问:
Dispatch Group wait stuck forever
I have a function making multiple HTTP requests with Alamofire. I want to wait for all of them to finish in order to return a value. However, it gets stuck at dispatch.wait()

class func getActionField(fieldid: String, completion: @escaping (_ res: [String: [Double]]) -> Void) {
        var resreturn: [String: [Double]] = ["temperature":[], "humidity":[], "ph":[], "light":[]]
        let dispatch = DispatchGroup()
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/temperatur/" + fieldid, method: .get).responseJSON{ response in
            resreturn["temperature"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/light/" + fieldid, method: .get).responseJSON{ response in
            resreturn["light"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/ph/" + fieldid, method: .get).responseJSON{ response in
            resreturn["ph"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/feuchtigkeit/" + fieldid, method: .get).responseJSON{ response in
            resreturn["humidity"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.wait()
        completion(resreturn)
    }
```

答:
Assuming that getActionField is being called on the main queue and the understanding that Alamofire calls its completion blocks on the main queue (bad design in my opinion), you are running into a deadlock since the call to wait is now blocking the main queue and none of the calls to leave can be made.

You must never use the same thread to call wait and leave.

The simplest solution is to replace the use of wait with notify.

```<code>group.notify(queue: DispatchQueue.main) {
    completion(resreturn)
}
</code>```

You should avoid the use of wait in general. Especially if you are already using a completion handler and there is no need for the method to wait.

Title: Dispatch Group wait stuck forever

Body:
Assuming that getActionField is being called on the main queue and the understanding that Alamofire calls its completion blocks on the main queue (bad design in my opinion), you are running into a deadlock since the call to wait is now blocking the main queue and none of the calls to leave can be made.

You must never use the same thread to call wait and leave.

The simplest solution is to replace the use of wait with notify.

group.notify(queue: DispatchQueue.main) {
    completion(resreturn)
}

You should avoid the use of wait in general. Especially if you are already using a completion handler and there is no need for the method to wait.


问:
How to publish environment specific appsettings in .Net core app?
I have 3 environment specific appsettings files in my .Net core application

in project.json I have setup publishOptions like this. ( based on suggestion here)

```<code>"publishOptions": {
    "include": [
      "wwwroot",
      "appsettings.development.json",
      "appsettings.staging.json",
      "appsettings.production.json",
      "web.config"
    ]
  },
</code>```

I have 3 corresponding startup classes that uses appropriate appsettings based on environment

```<code>var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
</code>```

However when I publish the application then all 3 appsettings files end up in all environments. How do I publish environment specific appsetting file?

答:
I recently had to find a solution for this as well and I accomplished it by adding some settings to the .csproj file and a minor change to Program.cs.

<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <DefineConstants>DEBUG;TRACE</DefineConstants>
        <EnvironmentName>Development</EnvironmentName>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <EnvironmentName>Production</EnvironmentName>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Stage|AnyCPU'">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <EnvironmentName>Staging</EnvironmentName>
    </PropertyGroup>
    <ItemGroup>
        <Content Remove="appsettings.json" />
        <Content Remove="appsettings.*.json" />
    </ItemGroup>
    <ItemGroup>
        <Content Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
        <Content Include="appsettings.*.json" Exclude="appsettings.$(EnvironmentName).json" DependentUpon="appsettings.json" CopyToOutputDirectory="Never" />
        <Content Include="appsettings.$(EnvironmentName).json" DependentUpon="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
    </ItemGroup>

    <Target Name="RenameAppsettings" AfterTargets="Publish">
        <Move SourceFiles="$(PublishDir)\appsettings.$(EnvironmentName).json" DestinationFiles="$(PublishDir)\appsettings.overrides.json" />
    </Target>
</Project>
```

<p>To explain it a little, I added an <code><EnvironmentName></code> element for each configuration so it can be used during the build process.  I'm using <code>appsettings.{EnvironmentName}.json</code> (i.e. <code>appsettings.Staging.json</code>) just as an "overrides" file so I just have it rename the necessary JSON file during the build process.  When you run <code>dotnet publish -c Stage</code>, for example, it will publish the <code>appsettings.Staging.json</code> file into the publish folder and rename it to <code>appsettings.overrides.json</code>.  In your <code>Program.cs</code>, you will just need to include the <code>appsettings.overrides.json</code> file as well:</p>

<pre class="lang-cs prettyprint-override"><code>    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.overrides.json", optional: true, reloadOnChange: true)
</code>```

I hope it helps!

Side note: I include appsettings.*.json and set it to CopyToOutputDirectory="Never" just so they still show up in Visual Studio when developing.  Otherwise, if you only want the current environment's appsettings file to show in VS, just remove that line from the csproj file.

Body:
I have 3 environment specific appsettings files in my .Net core application

in project.json I have setup publishOptions like this. ( based on suggestion here)

"publishOptions": {
    "include": [
      "wwwroot",
      "appsettings.development.json",
      "appsettings.staging.json",
      "appsettings.production.json",
      "web.config"
    ]
  },

I have 3 corresponding startup classes that uses appropriate appsettings based on environment

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);

However when I publish the application then all 3 appsettings files end up in all environments. How do I publish environment specific appsetting file?

Body:
I recently had to find a solution for this as well and I accomplished it by adding some settings to the .csproj file and a minor change to Program.cs.

<Project Sdk="Microsoft.NET.Sdk.Web">
    <!-- ... -->
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <DefineConstants>DEBUG;TRACE</DefineConstants>
        <EnvironmentName>Development</EnvironmentName>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <EnvironmentName>Production</EnvironmentName>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Stage|AnyCPU'">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <EnvironmentName>Staging</EnvironmentName>
    </PropertyGroup>
    <ItemGroup>
        <Content Remove="appsettings.json" />
        <Content Remove="appsettings.*.json" />
    </ItemGroup>
    <ItemGroup>
        <Content Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
        <Content Include="appsettings.*.json" Exclude="appsettings.$(EnvironmentName).json" DependentUpon="appsettings.json" CopyToOutputDirectory="Never" />
        <Content Include="appsettings.$(EnvironmentName).json" DependentUpon="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
    </ItemGroup>

    <Target Name="RenameAppsettings" AfterTargets="Publish">
        <Move SourceFiles="$(PublishDir)\appsettings.$(EnvironmentName).json" DestinationFiles="$(PublishDir)\appsettings.overrides.json" />
    </Target>
</Project>

To explain it a little, I added an <EnvironmentName> element for each configuration so it can be used during the build process.  I'm using appsettings.{EnvironmentName}.json (i.e. appsettings.Staging.json) just as an "overrides" file so I just have it rename the necessary JSON file during the build process.  When you run dotnet publish -c Stage, for example, it will publish the appsettings.Staging.json file into the publish folder and rename it to appsettings.overrides.json.  In your Program.cs, you will just need to include the appsettings.overrides.json file as well:

    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.overrides.json", optional: true, reloadOnChange: true)

I hope it helps!

Side note: I include appsettings.*.json and set it to CopyToOutputDirectory="Never" just so they still show up in Visual Studio when developing.  Otherwise, if you only want the current environment's appsettings file to show in VS, just remove that line from the csproj file.


问:
How to email specified cells in single row with Google Sheets
I'm trying to write a code within Google Sheets script in order to send an email containing the values from three cells (D2, H2, and L2).

I've got close with this code:

```<code>function sendCounts() {

//setup function
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh0 = ss.getSheetByName("PART COUNTS");

var message = "";
{

//set current row
var CurrentRow = 2;

//set HTML template for information
message +=
"<p><b>First Count: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Second Count: </b>" + CurrentRow[8] + "</p>" +
"<p><b>Third Count: </b>" + CurrentRow[12] + "</p><br><br>";

//set the row to look at
var setRow = CurrentRow;
}

//define who to send updates to
var SendTo = "me@emailaddress.com";

//set subject line
 var Subject = "DAILY PART COUNTS";

//send the actual email
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: Subject,
htmlBody: message,
});
}
</code>```

The email is sent in the correct format, but each of the three values appear as 'undefined' in the email body instead of the values of cells D2, H2, and L2.

Does anyone know what I am missing here?

答:
How about this modification?

Modification points:

The reason of the error of each of the three values appear as 'undefined' in the email body instead of the values of cells D2, H2, and L2 is CurrentRow. CurrentRow is a number. But in your script, you are using it as an array. This is the reason of the issue.

In order to avoid this issue, retrieve the values from the sheet of PART COUNTS.

When the value from the row 2 of the sheet is retrieved, CurrentRow can be used as an array. But in this case, the array index starts 0, and the indexes of "D", "H" and "L" are 3, 7 and 11.

Modified script:

Please modify as follows.

From:

```<code>var CurrentRow = 2;

//set HTML template for information
message +=
"<p><b>First Count: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Second Count: </b>" + CurrentRow[8] + "</p>" +
"<p><b>Third Count: </b>" + CurrentRow[12] + "</p><br><br>";
</code>```

To:

```<code>var CurrentRow = sh0.getRange("A2:L2").getValues()[0];

//set HTML template for information
message +=
"<p><b>First Count: </b>" + CurrentRow[3] + "</p>" +
"<p><b>Second Count: </b>" + CurrentRow[7] + "</p>" +
"<p><b>Third Count: </b>" + CurrentRow[11] + "</p><br><br>";
</code>```

References:

getRange()

getValues()

If I misunderstood your question and this was not the result you want, I apologize.

Body:
I'm trying to write a code within Google Sheets script in order to send an email containing the values from three cells (D2, H2, and L2).

I've got close with this code:

function sendCounts() {

//setup function
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh0 = ss.getSheetByName("PART COUNTS");

var message = "";
{

//set current row
var CurrentRow = 2;

//set HTML template for information
message +=
"
First Count: " + CurrentRow[4] + "
" +
"
Second Count: " + CurrentRow[8] + "
" +
"
Third Count: " + CurrentRow[12] + "

";

//set the row to look at
var setRow = CurrentRow;
}

//define who to send updates to
var SendTo = "me@emailaddress.com";

//set subject line
 var Subject = "DAILY PART COUNTS";

//send the actual email
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: Subject,
htmlBody: message,
});
}

The email is sent in the correct format, but each of the three values appear as 'undefined' in the email body instead of the values of cells D2, H2, and L2.

Does anyone know what I am missing here?

Body:
How about this modification?

Modification points:

The reason of the error of each of the three values appear as 'undefined' in the email body instead of the values of cells D2, H2, and L2 is CurrentRow. CurrentRow is a number. But in your script, you are using it as an array. This is the reason of the issue.

In order to avoid this issue, retrieve the values from the sheet of PART COUNTS.

When the value from the row 2 of the sheet is retrieved, CurrentRow can be used as an array. But in this case, the array index starts 0, and the indexes of "D", "H" and "L" are 3, 7 and 11.

Modified script:

Please modify as follows.

From:

var CurrentRow = 2;

//set HTML template for information
message +=
"<p><b>First Count: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Second Count: </b>" + CurrentRow[8] + "</p>" +
"<p><b>Third Count: </b>" + CurrentRow[12] + "</p><br><br>";

To:

var CurrentRow = sh0.getRange("A2:L2").getValues()[0];

//set HTML template for information
message +=
"<p><b>First Count: </b>" + CurrentRow[3] + "</p>" +
"<p><b>Second Count: </b>" + CurrentRow[7] + "</p>" +
"<p><b>Third Count: </b>" + CurrentRow[11] + "</p><br><br>";

References:

getRange()

getValues()

If I misunderstood your question and this was not the result you want, I apologize.


问:
The image you are attempting to upload doesn't fit into the allowed dimensions. problem
i am using codeigniter 3.1.10 and i am use upload library and i got some error

this is my form

```<code><form method="POST" enctype="multipart/form-data" action="<?php echo base_url() ?>addimg">
<input id="file-upload" type="file"  accept="image/*" name='book_image' onchange="preview_image(event)"/>
<button class="btn black">Add img</button>
</form>
</code>```

this is my addimage controller

```<code>$config['upload_path']          = './school_book_imgs/';
        $config['allowed_types']        = '*';
        $config['max_size']             = 1024;
        $config['max_width']            = 768;
        $config['max_height']           = 1024;

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if ($this->upload->do_upload('book_image')) {
            $form_data = $this->input->post();

            $data = $this->upload->data();
            $path = $data['raw_name'].$data['file_ext'];
            $form_data['book_image'] = "school_book_imgs/".$path;
            $form_data['user_id'] = $this->session->userdata('user_id');
            $this->load->model('savedata');
            if ($this->savedata->addschoolbook($form_data)){
                return redirect(base_url()."dashboard");
            }
            else{
                $this->load->view('404');
            }

        }else{
            $error = $this->upload->display_errors();
            // print_r($this->upload->data());
            $this->load->view('addschoolbook',compact('error'));
            $this->load->view('footer');
        }

    }
</code>```

i allowed all domail and i add manualy

```<code>$config['allowed_types']        = 'jpg|jpeg|png|gif';
</code>```

but i got same error every time

```<code>The image you are attempting to upload doesn't fit into the allowed dimensions.
</code>```

please tell me solution

答:
this error :
The image you are attempting to upload doesn't fit into the allowed dimensions

means that you are telling codeigniter to not accept or allow any picture dimensions bigger than 768x1024, max_width = 768 and max_height = 1024

just give higher dimensions example

```<code>$config['max_width']            = 6000; // 6000px you can set the value you want
$config['max_height']           = 6000; // 6000px
</code>```

Also your are setting accepted size to only 1mb and less, so any picture bigger than 1024kb= 1mb will not pass so change that too to a bigger size example:

```<code>$config['max_size']             = 10024; // 10mb you can set the value you want
</code>```

Body:
i am using codeigniter 3.1.10 and i am use upload library and i got some error

this is my form

<form method="POST" enctype="multipart/form-data" action="<?php echo base_url() ?>addimg">
<input id="file-upload" type="file"  accept="image/*" name='book_image' onchange="preview_image(event)"/>
<button class="btn black">Add img</button>
</form>

this is my addimage controller

$config['upload_path']          = './school_book_imgs/';
        $config['allowed_types']        = '*';
        $config['max_size']             = 1024;
        $config['max_width']            = 768;
        $config['max_height']           = 1024;

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if ($this->upload->do_upload('book_image')) {
            $form_data = $this->input->post();

            $data = $this->upload->data();
            $path = $data['raw_name'].$data['file_ext'];
            $form_data['book_image'] = "school_book_imgs/".$path;
            $form_data['user_id'] = $this->session->userdata('user_id');
            $this->load->model('savedata');
            if ($this->savedata->addschoolbook($form_data)){
                return redirect(base_url()."dashboard");
            }
            else{
                $this->load->view('404');
            }

        }else{
            $error = $this->upload->display_errors();
            // print_r($this->upload->data());
            $this->load->view('addschoolbook',compact('error'));
            $this->load->view('footer');
        }

    }

i allowed all domail and i add manualy

$config['allowed_types']        = 'jpg|jpeg|png|gif';

but i got same error every time

The image you are attempting to upload doesn't fit into the allowed dimensions.

please tell me solution

Body:
this error :
The image you are attempting to upload doesn't fit into the allowed dimensions

means that you are telling codeigniter to not accept or allow any picture dimensions bigger than 768x1024, max_width = 768 and max_height = 1024

just give higher dimensions example

$config['max_width']            = 6000; // 6000px you can set the value you want
$config['max_height']           = 6000; // 6000px

Also your are setting accepted size to only 1mb and less, so any picture bigger than 1024kb= 1mb will not pass so change that too to a bigger size example:

$config['max_size']             = 10024; // 10mb you can set the value you want


问:
Reference previous row in a data.frame
I have a very simple problem. I'm am trying to set the value of column X to 0 if column Y[n,] does not equal column Y[n-1,]. My issue is that I do not know how to reference a previous row value in R, and then use that value to set the value of another column.

As an example:

```<code>Y X
1 5
1 1
2 0
2 2
</code>```

X[3,2] is 0 because Y[3,1] does not equal Y[2,1].

I need to basically find all instance of this in a large data-set and set the corresponding X value to 0.

data$X <- 0 if data$Y[n] =! data$Y[n-1]

Is there a simple solution to this in R? It really feels as though there should be.

Thank you

答:
Given

```<code>Y <- c(1, 1, 2, 2)
X <- c(5, 1, 10, 2)
</code>```

an option would be diff

```<code>X * (c(0, diff(Y)) == 0)
# [1] 5 1 0 2
</code>```

The idea is to check if x[i] - x[i -1] equals zero which gives a logical vector that we multiply by X

Title: Reference previous row in a data.frame

Body:
I have a very simple problem. I'm am trying to set the value of column X to 0 if column Y[n,] does not equal column Y[n-1,]. My issue is that I do not know how to reference a previous row value in R, and then use that value to set the value of another column.

As an example:

Y X
1 5
1 1
2 0
2 2

X[3,2] is 0 because Y[3,1] does not equal Y[2,1].

I need to basically find all instance of this in a large data-set and set the corresponding X value to 0.

data$X <- 0 if data$Y[n] =! data$Y[n-1]

Is there a simple solution to this in R? It really feels as though there should be.

Thank you

Body:
Given

Y <- c(1, 1, 2, 2)
X <- c(5, 1, 10, 2)

an option would be diff

X * (c(0, diff(Y)) == 0)
# [1] 5 1 0 2

The idea is to check if x[i] - x[i -1] equals zero which gives a logical vector that we multiply by X


问:
Pytesseract OCR Bounding Box
I am trying to use pytesseract to ocr within a labeled image, the labels return an xml with the relevant bounding boxes. I would like to match the labels to see if they overlap with text OCR'ed from the whole image using their bounding box. Is there a way to get each full word's bounding box? I have tried this code below, but it returns the bounding box for each letter so I am wondering if anyone can recommend an alternative way to do this or if they know an alternative ocr package in python that can use my xml file to find the bounding boxes and ocr within them instead (or if they know how pytesseract could do this?). I don't need a code answer, just some advice.

```<code>> img = cv2.imread(filename) h, w, _ = img.shape boxes =
> pytesseract.image_to_boxes(img)  for b in boxes.splitlines():
>     b = b.split(' ')
>     img = cv2.rectangle(img, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 2)
</code>```

I expect for the code to return only the relevant occurring within the labels i have created, I can perform the code that does the overlap check but I just need each word complete bounding box...

答:
In case someone is still looking for an answer:
pytesseract's image_to_data returns a bounding box for the whole word. It returns bounding boxes for each word, the word, and other information. You can find out more about the function's output here: https://github.com/tesseract-ocr/tesseract/wiki/Command-Line-Usage#tsv-output-currently-available-in-305-dev-in-master-branch-on-github</p>

Title: Pytesseract OCR Bounding Box

Body:
I am trying to use pytesseract to ocr within a labeled image, the labels return an xml with the relevant bounding boxes. I would like to match the labels to see if they overlap with text OCR'ed from the whole image using their bounding box. Is there a way to get each full word's bounding box? I have tried this code below, but it returns the bounding box for each letter so I am wondering if anyone can recommend an alternative way to do this or if they know an alternative ocr package in python that can use my xml file to find the bounding boxes and ocr within them instead (or if they know how pytesseract could do this?). I don't need a code answer, just some advice.

> img = cv2.imread(filename) h, w, _ = img.shape boxes =
> pytesseract.image_to_boxes(img)  for b in boxes.splitlines():
>     b = b.split(' ')
>     img = cv2.rectangle(img, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 2)

I expect for the code to return only the relevant occurring within the labels i have created, I can perform the code that does the overlap check but I just need each word complete bounding box...


问:
How do I use Python to trigger the download of a file from a website?
I'm trying to set up a script to pull data from a website on a daily basis and I'm having trouble getting Python to actually read the table - I'm not a professional coder. I've tried two methods:

1) Scrape the table (headers, rows, etc) using Beautiful Soup, and

2) Use the website's export with excel button

Here is the precise website:
https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200

So far my code is:

#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`

#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)
```

<p>I think the easiest method would be to trigger the "export" function with the </p>

```xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a
```

All help is greatly appreciated!

答:
I would try to identify the API that does 'export to excel' and use that API. You can identify this from the browser's developer tools.  For example, here's what Google Chrome's Copy as Curl gives:

```<code>curl 'https://scgenvoy.sempra.com/Public/ViewExternalLowOFO.submitLowOfoSaveAs' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'Origin: https://scgenvoy.sempra.com' -H 'Upgrade-Insecure-Requests: 1' -H 'DNT: 1' -H 'Content-Type: application/x-www-form-urlencoded' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' -H 'Referer: https://scgenvoy.sempra.com/index.html' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.9' -H 'Cookie: FAROFFSession=537EB1587E4A063416D5F2206890A2B6.managed2' --data 'FileName=LowOFO05302019Cycle2&Class=com.sempra.krypton.common.saveas.constants.FancyExcelExportType&pageSize=letter&pageOrientation=portrait&HiddenGasFlowDateField=05%2F30%2F2019&HiddenCycleField=2&gasFlowDate=05%2F30%2F2019&cycle=2' --compressed
</code>```

The API url is
    https://scgenvoy.sempra.com/Public/ViewExternalLowOFO.submitLowOfoSaveAs

and the input parameters are:

```<code>FileName: LowOFO05302019Cycle2
Class: com.sempra.krypton.common.saveas.constants.FancyExcelExportType
pageSize: letter
pageOrientation: portrait
HiddenGasFlowDateField: 05/30/2019
HiddenCycleField: 2
gasFlowDate: 05/30/2019
cycle: 2
</code>```

and the request method is POST.

You can now use python requests library or beautifulsoup library to make this request, passing appropriate values for the parameter.

Providing you an idea, not solving the whole thing myself.

Body:
I'm trying to set up a script to pull data from a website on a daily basis and I'm having trouble getting Python to actually read the table - I'm not a professional coder. I've tried two methods:

1) Scrape the table (headers, rows, etc) using Beautiful Soup, and

2) Use the website's export with excel button

Here is the precise website:
https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200

So far my code is:

#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`

#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)

I think the easiest method would be to trigger the "export" function with the

xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a

All help is greatly appreciated!

Body:
I would try to identify the API that does 'export to excel' and use that API. You can identify this from the browser's developer tools.  For example, here's what Google Chrome's Copy as Curl gives:

curl 'https://scgenvoy.sempra.com/Public/ViewExternalLowOFO.submitLowOfoSaveAs' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'Origin: https://scgenvoy.sempra.com' -H 'Upgrade-Insecure-Requests: 1' -H 'DNT: 1' -H 'Content-Type: application/x-www-form-urlencoded' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' -H 'Referer: https://scgenvoy.sempra.com/index.html' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.9' -H 'Cookie: FAROFFSession=537EB1587E4A063416D5F2206890A2B6.managed2' --data 'FileName=LowOFO05302019Cycle2&Class=com.sempra.krypton.common.saveas.constants.FancyExcelExportType&pageSize=letter&pageOrientation=portrait&HiddenGasFlowDateField=05%2F30%2F2019&HiddenCycleField=2&gasFlowDate=05%2F30%2F2019&cycle=2' --compressed

The API url is
    https://scgenvoy.sempra.com/Public/ViewExternalLowOFO.submitLowOfoSaveAs

and the input parameters are:

FileName: LowOFO05302019Cycle2
Class: com.sempra.krypton.common.saveas.constants.FancyExcelExportType
pageSize: letter
pageOrientation: portrait
HiddenGasFlowDateField: 05/30/2019
HiddenCycleField: 2
gasFlowDate: 05/30/2019
cycle: 2

and the request method is POST.

You can now use python requests library or beautifulsoup library to make this request, passing appropriate values for the parameter.

Providing you an idea, not solving the whole thing myself.


问:
Appstore API Invalid Vendor number
I am trying to use the API on Appstore. I am using python to connnect and I get the  Invalid Vendor number error.

```<code>payload = {'filter[frequency]':'DAILY', 'filter[reportSubType]': 'SUMMARY', 'filter[reportDate]':'2019-03-01', 'filter[vendorNumber]': '12345678', 'filter[reportType]': 'SALES' }
</code>```

Here is the request call:

```<code>r = requests.get('https://api.appstoreconnect.apple.com/v1/salesReports', headers={'Authorization': 'Bearer {}'.format(token)}, params=payload)
</code>```

Here is the error that platform returns:

```<code>{
  "errors" : [ {
    "id" : "285874b4-16fb-4109-b810-ffa2973be714",
    "status" : "400",
    "code" : "PARAMETER_ERROR.INVALID",
    "title" : "A parameter has an invalid value",
    "detail" : "Invalid vendor number specified. Try again.",
    "source" : {
      "parameter" : "filter[vendorNumber]"
    }
  } ]
}
</code>```

The platform does not like the Vendor number. Any one else raninto this issue and were able to figure out a solution to this?
Thanks

答: Is 12345678 really your vendor number? It looks suspect. You can find your vendor number at the top of the page in Payments and Financial Reports.

Title: Appstore API Invalid Vendor number

Body:
I am trying to use the API on Appstore. I am using python to connnect and I get the  Invalid Vendor number error.

payload = {'filter[frequency]':'DAILY', 'filter[reportSubType]': 'SUMMARY', 'filter[reportDate]':'2019-03-01', 'filter[vendorNumber]': '12345678', 'filter[reportType]': 'SALES' }

Here is the request call:

r = requests.get('https://api.appstoreconnect.apple.com/v1/salesReports', headers={'Authorization': 'Bearer {}'.format(token)}, params=payload)

Here is the error that platform returns:

{
  "errors" : [ {
    "id" : "285874b4-16fb-4109-b810-ffa2973be714",
    "status" : "400",
    "code" : "PARAMETER_ERROR.INVALID",
    "title" : "A parameter has an invalid value",
    "detail" : "Invalid vendor number specified. Try again.",
    "source" : {
      "parameter" : "filter[vendorNumber]"
    }
  } ]
}

The platform does not like the Vendor number. Any one else raninto this issue and were able to figure out a solution to this?
Thanks


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答:
If you want to generate a large number of primes, or generate them quickly, pure python may not be the way to go - one option would be to use a python openssl wrapper, and use openssl's facility for generating RSA private keys (which are in fact a pair of primes), or some of openssl's other primality-related functions. Another way to acheive speed would be a C extension implementing one of the tests below...

If opessl isn't an option, your two choices (as many of the comments have mentioned) are the Miller-Rabin test and the AKS test. The main differences - AKS is deterministic, and is guaranteed to give no false results; whereas Miller-Rabin is probabalistic, it may occasionally give false positives - but the longer you run it, the lower that probability becomes (the odds are 1/4**k for k rounds of testing). You would think AKS would obviously be the way to go, except that it's much slower - O(log(n)**12) compared to Miller-Rabin's O(k*log(n)**3). (For comparison, the scan test you presented will take O(n**.5), so either of these will be much faster for large numbers).

If it would be useful, I can paste in a Miller-Rabin implementation I have, but it's rather long.

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break


问:
How to fix a table causing "502: Bad Gateway" error in PHP
I am creating a simple database that can do basic CRUD operations (create, read, update, delete) using php. I am able to complete the create, and able to see the results if I directly query the mySQL DB in the back end. But, I am having trouble getting the table to display on the webpage. It is instead displaying a "Bad Gateway" error if I attempt to display the database entries.

I tried removing the reference to the table, specifically

```<code>    <?php while ($row = mysqli_fetch_array($results)) { ?>
            <tr>
                <td><?php echo $row['name']; ?></td>...
</code>```

and the web page on front end works fine. Albeit can only see the data if I query the backend.

```<code>    <?php  include('php_code.php'); ?>
    ...
    ...
    ...

    <?php $results = mysqli_query($db, "SELECT * FROM info"); ?>

    <table>
        <thead>
        <tr>
            <th>Name</th>
            <th>Address</th>
            <th>City</th>
            <th colspan="2">Action</th>
        </tr>
        </thead>

        <?php while ($row = mysqli_fetch_array($results)) { ?>
            <tr>
                <td><?php echo $row['name']; ?></td>
                <td><?php echo $row['address']; ?></td>
                <td><?php echo $row['city']; ?></td>
                <td>
                    <a href="test.php?edit=<?php echo $row['id']; ?>"
    class="edit_btn" >Edit</a>
                </td>
                <td>
                    <a href="php_code.php?del=<?php echo $row['id']; ?>"
    class="del_btn">Delete</a>
                </td>
            </tr>
        <?php } ?>
    </table>

    <!--in php_code.php-->
     //to retrieve records
        $select_query = "SELECT * FROM info";
        $result = mysqli_query($db, $select_query);
</code>```

I should be able to see the table with data containing name, address and city. But I am getting a 502 error instead.

答:
you are closing the php statements so you cannot retrieve the result of your query. Don't split php parts  and just echo html like this</p>

```<code> <?php
    echo " <table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>City</th>
                <th colspan='2'>Action</th>
            </tr>
            </thead> ";
   while ($row = mysqli_fetch_array($results)) {

                echo "<tr>
                <td>$row['name']</td>
                <td>$row['address']</td>
                <td> $row['city']</td>
                <td>
                <a href='test.php?edit=$row['id']'
                class='edit_btn' >Edit</a>
                </td>
                <td>
                <a href='php_code.php?del=$row['id']'
    class='del_btn'>Delete</a>
                </td>
            </tr>";
       }
    echo "</table>";
    ?>
</code>```

Body:
I am creating a simple database that can do basic CRUD operations (create, read, update, delete) using php. I am able to complete the create, and able to see the results if I directly query the mySQL DB in the back end. But, I am having trouble getting the table to display on the webpage. It is instead displaying a "Bad Gateway" error if I attempt to display the database entries.

I tried removing the reference to the table, specifically

    <?php while ($row = mysqli_fetch_array($results)) { ?>

                <?php echo $row['name']; ?>	...

and the web page on front end works fine. Albeit can only see the data if I query the backend.

    <?php  include('php_code.php'); ?>
    ...
    ...
    ...

    <?php $results = mysqli_query($db, "SELECT * FROM info"); ?>

            Name
            Address
            City
            Action

        <?php while ($row = mysqli_fetch_array($results)) { ?>

                <?php echo $row['name']; ?>
                <?php echo $row['address']; ?>
                <?php echo $row['city']; ?>

                    <a href="test.php?edit=<?php echo $row['id']; ?>"
    class="edit_btn" >Edit

                    <a href="php_code.php?del=<?php echo $row['id']; ?>"
    class="del_btn">Delete

        <?php } ?>

     //to retrieve records
        $select_query = "SELECT * FROM info";
        $result = mysqli_query($db, $select_query);

I should be able to see the table with data containing name, address and city. But I am getting a 502 error instead.

Body:
you are closing the php statements so you cannot retrieve the result of your query. Don't split php parts  and just echo html like this

 <?php
    echo " <table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>City</th>
                <th colspan='2'>Action</th>
            </tr>
            </thead> ";
   while ($row = mysqli_fetch_array($results)) {

                echo "<tr>
                <td>$row['name']</td>
                <td>$row['address']</td>
                <td> $row['city']</td>
                <td>
                <a href='test.php?edit=$row['id']'
                class='edit_btn' >Edit</a>
                </td>
                <td>
                <a href='php_code.php?del=$row['id']'
    class='del_btn'>Delete</a>
                </td>
            </tr>";
       }
    echo "</table>";
    ?>


问:
Teradara SQL - Operation with max-min dates
suppose I have the following data frame in Reradata SQL.
How can I get the variation between the highest and lowest date, at user level? Regards</p>

```<code>Initial table
   user    date   price
    1       1-1       10
    1       2-1       20
    1       3-1       30
    2       1-1       12
    2       2-1       22
    2       3-1       32
    3       1-1       13
    3       2-1       23
    3       3-1       33

 Final table

user   var_price
1       30/10-1
2       32/12-1
3       33/13-1
</code>```

答:
Try this-

```<code>SELECT B.[user],
CAST(SUM(B.max_price) AS VARCHAR)+'/'+CAST(SUM(B.min_price) AS VARCHAR)+ '-1' var_price,
SUM(B.max_price)/SUM(B.min_price) -1 calculated_var_price
FROM
(
    SELECT *    FROM
    (
        SELECT [user],0 max_price,price min_price,ROW_NUMBER() OVER (PARTITION BY [user] ORDER BY DATE)  RN
        FROM your_table
    )A WHERE RN = 1

    UNION ALL

    SELECT * FROM
    (
        SELECT [user],price max_price,0 min_price, ROW_NUMBER() OVER (PARTITION BY [user] ORDER BY DATE DESC)  RN
        FROM your_table
    )A WHERE RN = 1
)B
GROUP BY B.[user]
</code>```

Output is-

```<code>user    var_price    calculated_var_price
1       30/10-1      2
2       32/12-1      1
3       33/13-1      1
</code>```

Body:
suppose I have the following data frame in Reradata SQL.
How can I get the variation between the highest and lowest date, at user level? Regards

Initial table
   user    date   price
    1       1-1       10
    1       2-1       20
    1       3-1       30
    2       1-1       12
    2       2-1       22
    2       3-1       32
    3       1-1       13
    3       2-1       23
    3       3-1       33

 Final table

user   var_price
1       30/10-1
2       32/12-1
3       33/13-1

Body:
Try this-

SELECT B.[user],
CAST(SUM(B.max_price) AS VARCHAR)+'/'+CAST(SUM(B.min_price) AS VARCHAR)+ '-1' var_price,
SUM(B.max_price)/SUM(B.min_price) -1 calculated_var_price
FROM
(
    SELECT *    FROM
    (
        SELECT [user],0 max_price,price min_price,ROW_NUMBER() OVER (PARTITION BY [user] ORDER BY DATE)  RN
        FROM your_table
    )A WHERE RN = 1

    UNION ALL

    SELECT * FROM
    (
        SELECT [user],price max_price,0 min_price, ROW_NUMBER() OVER (PARTITION BY [user] ORDER BY DATE DESC)  RN
        FROM your_table
    )A WHERE RN = 1
)B
GROUP BY B.[user]

Output is-

user    var_price    calculated_var_price
1       30/10-1      2
2       32/12-1      1
3       33/13-1      1


问:
using subprocess.run the program doesn't work, but copying the text from the run([xxx]) does work. any suggestions
I have written a short bit of code to run a program (cutadapt) on multiple files. however it gives the following error for each of the files it tries to run: "cutadapt: error: unrecognized arguments".
Run on MacOS, python 3.7.3,

If I print the statement in the same program, copy that as a single call in the terminal, then it does work. Does anyone see what I am doing wrong?

import glob

import subprocess

fastq_folder = "/path/2019.01_spades_output_pathodetect/FASTQ_trimming"

listoffiles = glob.glob(fastq_folder + "/*.gz")

for fastq in listoffiles:
    input_file = fastq
    output_file = fastq.replace("_001.fastq.gz", "_001CUT20.fastq.gz")
    output_file = fastq.replace("2019.01_spades_output_pathodetect/FASTQ_trimming/", "2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/")
    print("cutadapt", "--cut 20", "-o", output_file, input_file)
    subprocess.run(["cutadapt", "--cut 20", "-o", output_file, input_file])
```

<p><strong>so the output in the terminal is:</strong></p>

```cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Run "cutadapt --help" to see command-line options.
See https://cutadapt.readthedocs.io/ for full documentation.

cutadapt: error: unrecognized arguments: /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
```

<p><strong>Then, when I copy the printed statement, it works:</strong></p>

```cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz

This is cutadapt 2.3 with Python 3.7.3
Command line parameters: --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Processing reads on 1 core in single-end mode ...
[   8<-------] 00:00:06       490,635 reads  @     13.6 µs/read;   4.42 M reads/minute
Finished in 6.71 s (14 us/read; 4.39 M reads/minute).
```

答:
You need to separate all the arguments; "--cut 20" passes a single argument containing both the switch and its value (that it, it tells program it received a single switch named cut 20). You'd only pass it as a single argument if, at the command line, you literally passed "--cut 20" in quotes to prevent the whitespace from breaking it up into separate pieces of the program's argv (which you clearly don't in your example).

Split it up to "--cut", "20" and it should work.

Body:
I have written a short bit of code to run a program (cutadapt) on multiple files. however it gives the following error for each of the files it tries to run: "cutadapt: error: unrecognized arguments".
Run on MacOS, python 3.7.3,

If I print the statement in the same program, copy that as a single call in the terminal, then it does work. Does anyone see what I am doing wrong?

import glob

import subprocess

fastq_folder = "/path/2019.01_spades_output_pathodetect/FASTQ_trimming"

listoffiles = glob.glob(fastq_folder + "/*.gz")

for fastq in listoffiles:
    input_file = fastq
    output_file = fastq.replace("_001.fastq.gz", "_001CUT20.fastq.gz")
    output_file = fastq.replace("2019.01_spades_output_pathodetect/FASTQ_trimming/", "2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/")
    print("cutadapt", "--cut 20", "-o", output_file, input_file)
    subprocess.run(["cutadapt", "--cut 20", "-o", output_file, input_file])

so the output in the terminal is:

cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Run "cutadapt --help" to see command-line options.
See https://cutadapt.readthedocs.io/ for full documentation.

cutadapt: error: unrecognized arguments: /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz

Then, when I copy the printed statement, it works:

cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz

This is cutadapt 2.3 with Python 3.7.3
Command line parameters: --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Processing reads on 1 core in single-end mode ...
[   8<-------] 00:00:06       490,635 reads  @     13.6 µs/read;   4.42 M reads/minute
Finished in 6.71 s (14 us/read; 4.39 M reads/minute).


问:
ListBox with unknown type items - how to move items up/down
There are many samples on how to move ListBoxItem up or down - but only if ListBox.ItemsSource type is known.

Can anyone help share some more generic code, if ListBox.ItemsSource type is simply IEnumerable?

I need such code to move ListBoxItem up/down, regardless if ItemsSource was set in XAML, code-behind or ViewModel. In the latter case it will, most likely, be an ObservableCollection.

答:
Just cast the list into objects. Here is an example that takes the last item and moves it to the first item during a double click event:

```<code>private void LbFiles_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    var sourceList = lbFiles.ItemsSource
                            .OfType<object>()
                            .ToList();

    var moveLast = sourceList[sourceList.Count - 1];

    sourceList.RemoveAt(sourceList.Count - 1);

    var newList = new List<object>() { moveLast };

    newList.AddRange(sourceList);

    lbFiles.ItemsSource = newList;
}
</code>```

XAML

```<code><StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
        <x:Array x:Key="FileNames" Type="system:String">
            <system:String>C:\Temp\Alpha.txt</system:String>
            <system:String>C:\Temp\Beta.txt</system:String >
            <system:String>C:\Temp\Gamma.txt</system:String >
        </ x:Array >
    </ StackPanel.Resources >

    <ListBox Name = "lbFiles"
             ItemsSource = "{StaticResource FileNames}"
             MouseDoubleClick = "LbFiles_MouseDoubleClick"
             Margin = "10" />
</ StackPanel >
</code>```

Here it is in action

Body:
Just cast the list into objects. Here is an example that takes the last item and moves it to the first item during a double click event:

private void LbFiles_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    var sourceList = lbFiles.ItemsSource
                            .OfType<object>()
                            .ToList();

    var moveLast = sourceList[sourceList.Count - 1];

    sourceList.RemoveAt(sourceList.Count - 1);

    var newList = new List<object>() { moveLast };

    newList.AddRange(sourceList);

    lbFiles.ItemsSource = newList;
}

XAML

<StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
        <x:Array x:Key="FileNames" Type="system:String">
            <system:String>C:\Temp\Alpha.txt</system:String>
            <system:String>C:\Temp\Beta.txt</system:String >
            <system:String>C:\Temp\Gamma.txt</system:String >
        </ x:Array >
    </ StackPanel.Resources >

    <ListBox Name = "lbFiles"
             ItemsSource = "{StaticResource FileNames}"
             MouseDoubleClick = "LbFiles_MouseDoubleClick"
             Margin = "10" />
</ StackPanel >

Here it is in action


问:
Is it possible to convert a string into a node?
I'm trying to create a random name generator from a set list of names (from 1-10). I have assigned an id to each name (from "s01" to "s10") and am trying to write some JavaScript to randomly choose one from the list. This is what I have so far:

```<code>if (action === 'who') {
    console.log("who");
    let num = Math.floor((Math.random() * 10) + 1);
    console.log(num);
    if (num === 10) {
        numb = s10.textContent;
    } else {
        num = ("s0"+num);
        console.log(num);
        numb = num.textContent;
    }
console.log(numb);
</code>```

But I'm getting console.logs as "undefined," unless the number generated was 10, and then it is fine.

I am trying to convert what comes up as num into the id but I'm not sure how to do it.

答:
When you write

```<code>num = ("s0" + num);
</code>```

you're just creating a string, it doesn't try to use that as the name of a variable. So it doesn't access the node in the variable s06.

Use document.getElementById() to get the element with a specific ID, rather than trying to access it as a variable. You can use string concatenation to create the argument.

```<code>var id = num < 10 ? "s0" + num : "s" + num;
var element = document.getElementById(id);
var numb = element.textContent;
</code>```

Body:
I'm trying to create a random name generator from a set list of names (from 1-10). I have assigned an id to each name (from "s01" to "s10") and am trying to write some JavaScript to randomly choose one from the list. This is what I have so far:

if (action === 'who') {
    console.log("who");
    let num = Math.floor((Math.random() * 10) + 1);
    console.log(num);
    if (num === 10) {
        numb = s10.textContent;
    } else {
        num = ("s0"+num);
        console.log(num);
        numb = num.textContent;
    }
console.log(numb);

But I'm getting console.logs as "undefined," unless the number generated was 10, and then it is fine.

I am trying to convert what comes up as num into the id but I'm not sure how to do it.

Body:
When you write

num = ("s0" + num);

you're just creating a string, it doesn't try to use that as the name of a variable. So it doesn't access the node in the variable s06.

Use document.getElementById() to get the element with a specific ID, rather than trying to access it as a variable. You can use string concatenation to create the argument.

var id = num < 10 ? "s0" + num : "s" + num;
var element = document.getElementById(id);
var numb = element.textContent;


问:
Kubernetes jobs for different OS
With the support of Windows server 2019 in Kubernetes 1.14 it seems possible to have nodes of different OS. For example a Ubuntu 18.04 Node, RHEL 7 Node, Windows Server Node within one cluster.

In my use case I would like to have pre-configured queue system with a queue per OS type. The nodes would feed off their specific queues processing the job.

With the above in my mind is it possible to configure a Job to go to a specific queue and in turn a specific OS node?

答:
Kubernetes nodes come populated with a standard set of labels, this includes kubernetes.io/os

Pods can then be assigned to certain places via a nodeSelector, podAffinity and podAntiAffinity.

```<code>apiVersion: extensions/v1beta1
kind: Pod
metadata:
  name: anapp
spec:
  containers:
  - image: docker.io/me/anapp
    name: anapp
    ports:
     - containerPort: 8080
  nodeSelector:
    kubernetes.io/os: linux
</code>```

If you need finer grained control (for example choosing between Ubuntu/RHEL) you will need to add custom labels in your kubernetes node deployment to select from. This level of selection is rare as container runtimes try and hide most of the differences from you, but if you have a particular case then add extra label metadata to the nodes.

I would recommend using the ID and VERSION_ID fields from cat /etc/*release* as most Linux distros populate this information in some form.

```<code>kubectl label node thenode softey.com/release-id=debian
kubectl label node thenode softey.com/release-version-id=9
</code>```

Title: Kubernetes jobs for different OS

Body:
Kubernetes nodes come populated with a standard set of labels, this includes kubernetes.io/os

Pods can then be assigned to certain places via a nodeSelector, podAffinity and podAntiAffinity.

apiVersion: extensions/v1beta1
kind: Pod
metadata:
  name: anapp
spec:
  containers:
  - image: docker.io/me/anapp
    name: anapp
    ports:
     - containerPort: 8080
  nodeSelector:
    kubernetes.io/os: linux

If you need finer grained control (for example choosing between Ubuntu/RHEL) you will need to add custom labels in your kubernetes node deployment to select from. This level of selection is rare as container runtimes try and hide most of the differences from you, but if you have a particular case then add extra label metadata to the nodes.

I would recommend using the ID and VERSION_ID fields from cat /etc/*release* as most Linux distros populate this information in some form.

kubectl label node thenode softey.com/release-id=debian
kubectl label node thenode softey.com/release-version-id=9


问:
How to get satellite-street map in tileset in Mapbox
I want to use satellite-street map using tileset, but it is not available here. It is visible in style and dataset but not in tileset. I want to use mapID, not styleID.

How to get satellite-street map in tileset in Mapbox. It is available in styles and dataset but not in tileset. Any Help?

答: The raster tileset with the map ID satellite-streets would've been a composite of the satellite source (mapbox.satellite) and Mapbox Streets source (mapbox.streets). These tilesets were created as raster tiles using Mapbox Studio Classic and are no longer supported. Instead, it's recommended to create your own style with Mapbox Satellite and Streets sources and use the Static Tiles endpoint to generate raster tiles.


问:
Ajax POST not reaching server, returning 400 only in Firefox
I have a Flask server running in Apache that returns an HTML page with a button to submit an AJAX POST request to a relative URL. In Firefox, the AJAX call fails immediately with a 400, logging POST response ERROR code: 400. Logging the xhr object or the data parameter to the console results in <unavailable>, with its responseText attribute as undefined. The response is exactly the same, regardless of what URL is passed to AJAX. The absolute URL (http://thehostname.com/path/send-email) also gives the same result.

Apache's access.log shows no request coming in at the time of the AJAX requests. The request does not come up at all in Firefox's "Network" tab of the dev tools. The request works fine in Chrome with all other conditions the same, as well is with cURL.

The code is below. Please help!

HTML:

```<code><img width="20px" src="mail.png" alt="" onerror="this.style.display='none'" onclick="sendEmail('val1', 'val2', 'val3')">
</code>```

JS:

```<code>    function sendEmail(val1, val2, val3) {
        val1 = prompt('Prompt2 for ' + val2 + ':', val1);
        console.log('Val1: '+ val1);
        if(val1) {
            let xhr = $.ajax({
                method: 'POST',
                url: 'send-email',
                // Tried with and without stringify
                data: JSON.stringify({param1: val1, param2: val2, param3: val3}),
                contentType: "application/json; charset=utf-8",
                dataType: 'text',
                cache: false,
                traditional: true
            }).done(function(){
                alert("Sent!");
            }).fail(function(data){
                console.log("Info:");
                console.log(xhr.responseText);
                alert('Failed to send');
            });
        }
        console.log("Ret false");
        return false;
    };
</code>```

Python endpoint:

```<code>@app.route('/autorack_testing_report/send-email', methods=['POST'])
@app.route('/send-email', methods=['POST'])
def send_email():
    print("Send email") # Not getting printed
    info = request.form or request.json
    if not (info and info.get('param1') and info.get('param2')):
        abort(400, 'Must supply recipient and ticket')
    send_to_list = re.split(',|;', info['param1'])
    send_to = []
    for s in send_to_list:
        if s.strip():
            send_to.append(s.strip() + '@domain.com')
    send_to = ','.join(send_to)
    ticket = info['ticket']
    smtp = smtplib.SMTP('mysmtphost', 25)
    msg = MIMEMultipart('alternative')
    msg['Subject'] = 'subject'
    msg['From'] = msg['To'] = send_to
    msg.attach(MIMEText('somecontent', 'plain'))
    smtp.sendmail(send_to, send_to, msg.as_string())
    smtp.quit()
    resp = make_response('Success', 200)
    resp.headers['Content-Type'] = 'text/plain'
    return resp
</code>```

Firefox console output:

```<code>Val1: myinput
Ret false
POST response ERROR code: 400
POST response ERROR code: 400
Info:
undefined
</code>```

No Python output, since Apache isn't receiving the request.

答: The 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). where does 'send-email' point to?</p>

Body:
I have a Flask server running in Apache that returns an HTML page with a button to submit an AJAX POST request to a relative URL. In Firefox, the AJAX call fails immediately with a 400, logging POST response ERROR code: 400. Logging the xhr object or the data parameter to the console results in <unavailable>, with its responseText attribute as undefined. The response is exactly the same, regardless of what URL is passed to AJAX. The absolute URL (http://thehostname.com/path/send-email) also gives the same result.

Apache's access.log shows no request coming in at the time of the AJAX requests. The request does not come up at all in Firefox's "Network" tab of the dev tools. The request works fine in Chrome with all other conditions the same, as well is with cURL.

The code is below. Please help!

HTML:

JS:

    function sendEmail(val1, val2, val3) {
        val1 = prompt('Prompt2 for ' + val2 + ':', val1);
        console.log('Val1: '+ val1);
        if(val1) {
            let xhr = $.ajax({
                method: 'POST',
                url: 'send-email',
                // Tried with and without stringify
                data: JSON.stringify({param1: val1, param2: val2, param3: val3}),
                contentType: "application/json; charset=utf-8",
                dataType: 'text',
                cache: false,
                traditional: true
            }).done(function(){
                alert("Sent!");
            }).fail(function(data){
                console.log("Info:");
                console.log(xhr.responseText);
                alert('Failed to send');
            });
        }
        console.log("Ret false");
        return false;
    };

Python endpoint:

@app.route('/autorack_testing_report/send-email', methods=['POST'])
@app.route('/send-email', methods=['POST'])
def send_email():
    print("Send email") # Not getting printed
    info = request.form or request.json
    if not (info and info.get('param1') and info.get('param2')):
        abort(400, 'Must supply recipient and ticket')
    send_to_list = re.split(',|;', info['param1'])
    send_to = []
    for s in send_to_list:
        if s.strip():
            send_to.append(s.strip() + '@domain.com')
    send_to = ','.join(send_to)
    ticket = info['ticket']
    smtp = smtplib.SMTP('mysmtphost', 25)
    msg = MIMEMultipart('alternative')
    msg['Subject'] = 'subject'
    msg['From'] = msg['To'] = send_to
    msg.attach(MIMEText('somecontent', 'plain'))
    smtp.sendmail(send_to, send_to, msg.as_string())
    smtp.quit()
    resp = make_response('Success', 200)
    resp.headers['Content-Type'] = 'text/plain'
    return resp

Firefox console output:

Val1: myinput
Ret false
POST response ERROR code: 400
POST response ERROR code: 400
Info:
undefined

No Python output, since Apache isn't receiving the request.