问:
In PHP Remove several characters from the beginning of a String?
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

```<code>JOHN
MIKE
BEN
*BJAMES
PETE
</code>```

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

```<code>if ( preg_match( "/^\*(B)/",$contents[$a] ) )
</code>```

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

答:
This approach writes the lines as the file is read, which is more memory efficient:

```<code>$sourceFile      = new SplFileObject('source.txt');
$destinationFile = new SplFileObject('destination.txt', 'w+');
foreach (new RegexIterator($sourceFile, '/^\*B.*/') as $filteredLine) {
    $destinationFile->fwrite(
        substr_replace($filteredLine, '', 0, 2)
    );
}
</code>```

demo

Body:
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

JOHN
MIKE
BEN
*BJAMES
PETE

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

if ( preg_match( "/^\*(B)/",$contents[$a] ) )

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

Body:
This approach writes the lines as the file is read, which is more memory efficient:

$sourceFile      = new SplFileObject('source.txt');
$destinationFile = new SplFileObject('destination.txt', 'w+');
foreach (new RegexIterator($sourceFile, '/^\*B.*/') as $filteredLine) {
    $destinationFile->fwrite(
        substr_replace($filteredLine, '', 0, 2)
    );
}

demo


来源: stackexchange

问:
Codeigniter and AngularJS bug: pagination does not work when the application is not in the root directory
I am working on a blog application with Codeigniter 3.1.8 and AngularJS v1.7.8.

The Dashboard of the application is "pure" Codeigniter, with Models, Controllers, and views, while the fronted is made up of JSONs managed and displayed by AngularJS. (I operated this clear separation between back-end and front-end in order to enable "themeing".)

The posts are paginated. On the back-end, in the Posts controller, the posts list looks like this:

```<code>private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
  //load and configure pagination
    $this->load->library('pagination');
    $config['base_url'] = "http://".$_SERVER['HTTP_HOST'] . $path;
    $config['query_string_segment'] = $query_string_segment;
    $config['enable_query_strings'] =TRUE;
    $config['reuse_query_string'] =TRUE;
    $config['total_rows'] = $totalRows;
    $config['per_page'] = 12;
    if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
        $_GET[$config['query_string_segment']] = 1;
    }
    $this->pagination->initialize($config);

    $limit = $config['per_page'];
    $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

    return ['limit' => $limit, 'offset' => $offset];
}

public function index() {

  //call initialization method
    $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

    $data = $this->Static_model->get_static_data();
    $data['pagination'] = $this->pagination->create_links();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();

  //use limit and offset returned by _initPaginator method
    $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

    // All posts
    $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
}
</code>```

On the front-end, in AngularJS, I have:

```<code> // All posts
.controller('PostsController', ['$scope', '$http', function($scope, $http){

    //Get current page (?page=2, ?page=3 etc)
    const currPage = window.location.search;

    // Get all the posts on the current page
    $http.get('api/' + currPage).then(function(response) {

        //Categories
        $scope.categories = response.data.categories;

        // Posts
        $scope.posts = response.data.posts;

        // posts pagination
        $scope.pagination = response.data.pagination;

    });
}])
</code>```

The problem is that the pagination does not work (the links are pointing to the wrong likne) when the application is not in the root directory (it is at www.examplesite.com/blog, not at www.examplesite.com).

I suppose it has something to do Codeigniter's base_url() but I have not been able to spot the bug and fix it.

How can I fix this issue?

答:
The problem is here:

```<code>$config['base_url'] = "http://".$_SERVER['HTTP_HOST'] . $path;
</code>```

Because $_SERVER['HTTP_HOST'] is always the root without other directory.

You need to use something like:

```<code>$config['base_url'] = str_replace("/api/", "/", base_url()) . $path;
</code>```

But I recomand you to implement the pagination in your front end (Angular) and in CI you need only something like:

```<code>public function index($offset, $limit) {
    $data = [];
    $data['count'] = $this->Posts_model->get_num_rows();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();
    $data['posts'] = $this->Posts_model->get_posts($limit, $offset);

    $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a blog application with Codeigniter 3.1.8 and AngularJS v1.7.8.

The Dashboard of the application is "pure" Codeigniter, with Models, Controllers, and views, while the fronted is made up of JSONs managed and displayed by AngularJS. (I operated this clear separation between back-end and front-end in order to enable "themeing".)

The posts are paginated. On the back-end, in the Posts controller, the posts list looks like this:

private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
  //load and configure pagination
    $this->load->library('pagination');
    $config['base_url'] = "http://".$_SERVER['HTTP_HOST'] . $path;
    $config['query_string_segment'] = $query_string_segment;
    $config['enable_query_strings'] =TRUE;
    $config['reuse_query_string'] =TRUE;
    $config['total_rows'] = $totalRows;
    $config['per_page'] = 12;
    if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
        $_GET[$config['query_string_segment']] = 1;
    }
    $this->pagination->initialize($config);

    $limit = $config['per_page'];
    $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

    return ['limit' => $limit, 'offset' => $offset];
}

public function index() {

  //call initialization method
    $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

    $data = $this->Static_model->get_static_data();
    $data['pagination'] = $this->pagination->create_links();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();

  //use limit and offset returned by _initPaginator method
    $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

    // All posts
    $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
}

On the front-end, in AngularJS, I have:

 // All posts
.controller('PostsController', ['$scope', '$http', function($scope, $http){

    //Get current page (?page=2, ?page=3 etc)
    const currPage = window.location.search;

    // Get all the posts on the current page
    $http.get('api/' + currPage).then(function(response) {

        //Categories
        $scope.categories = response.data.categories;

        // Posts
        $scope.posts = response.data.posts;

        // posts pagination
        $scope.pagination = response.data.pagination;

    });
}])

The problem is that the pagination does not work (the links are pointing to the wrong likne) when the application is not in the root directory (it is at www.examplesite.com/blog, not at www.examplesite.com).

I suppose it has something to do Codeigniter's base_url() but I have not been able to spot the bug and fix it.

How can I fix this issue?

Body:
The problem is here:

$config['base_url'] = "http://".$_SERVER['HTTP_HOST'] . $path;

Because $_SERVER['HTTP_HOST'] is always the root without other directory.

You need to use something like:

$config['base_url'] = str_replace("/api/", "/", base_url()) . $path;

But I recomand you to implement the pagination in your front end (Angular) and in CI you need only something like:

public function index($offset, $limit) {
    $data = [];
    $data['count'] = $this->Posts_model->get_num_rows();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();
    $data['posts'] = $this->Posts_model->get_posts($limit, $offset);

    $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
}


问:
HTTP 500 error while accessing the application
I am trying to migrate an application which is running on 2008 Windows to 2012 servers.
The application requires Tomcat , Oracle 12c, java, jakarta connector and using IIS .

I am not a developer and therefore unable to find the issue here as its giving null pointer exception .

Can someone guide me on where i am going wrong of if its the code issue. It's a legacy application built many years ago ,so i have less details on code and how it was setup.

答:
If you are lucky, the reason will be in the config or something like.
You can to get .class file of NationalitySingleton from /tomcat/webapps/..

developer will decompile this file (just drag and drop file to ide) and will try to say reason


问:
Use Vue phone number component outside of Vue app
I have a static website that I would like to add a Vue component to. I cannot get it to recognize the component that I'm trying to add. It's called vue-phone-number-input https://github.com/LouisMazel/vue-phone-number-input It says VuePhoneNumberInput is not defined. Here's what I have:

```<code><script src="../../assets/global/js/vue/polyfill.min.js"></script>
<script src="../../assets/global/js/vue/vue.min.js"></script>
<script src="../../assets/global/js/vue/vue-phone-number-input.umd.min.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="../../assets/global/css/vue-phone-number-input.css">

<div id="phone-search">
   <VuePhoneNumberInput class="search-input" v-model="phoneNumber" :only-countries="['US']" @update="onUpdate" />
</div>

new Vue({
      el: '#phone-search',
      components: {
          VuePhoneNumberInput: VuePhoneNumberInput
      },
      data: {
         phoneNumber: null
      }
})
</code>```

I have tried VuePhoneNumberInput: 'vue-phone-number-input' and the error goes away but the component still does not render. I have tried adding Vue.component('vue-phone-number-input', window.VuePhoneNumberInput.default); as is in the docs but I get the error Cannot read property 'default' of undefined. I have also tried the other Vue script they have in the doc, unpkg.com/vue which doesn't work either. Vue itself is working properly within the #phone-search element, it is just the component that's not working.

答:
It seems like the library UMD bundle is broken so avoid using it and import the library using ES6 imports.

here is a working example: Live Demo

Body:
I have a static website that I would like to add a Vue component to. I cannot get it to recognize the component that I'm trying to add. It's called vue-phone-number-input https://github.com/LouisMazel/vue-phone-number-input It says VuePhoneNumberInput is not defined. Here's what I have:

<link rel="stylesheet" type="text/css" href="../../assets/global/css/vue-phone-number-input.css">

   <VuePhoneNumberInput class="search-input" v-model="phoneNumber" :only-countries="['US']" @update="onUpdate" />

new Vue({
      el: '#phone-search',
      components: {
          VuePhoneNumberInput: VuePhoneNumberInput
      },
      data: {
         phoneNumber: null
      }
})

I have tried VuePhoneNumberInput: 'vue-phone-number-input' and the error goes away but the component still does not render. I have tried adding Vue.component('vue-phone-number-input', window.VuePhoneNumberInput.default); as is in the docs but I get the error Cannot read property 'default' of undefined. I have also tried the other Vue script they have in the doc, unpkg.com/vue which doesn't work either. Vue itself is working properly within the #phone-search element, it is just the component that's not working.


问:
Get the element with the highest occurrence in an array
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

```<code>['pear', 'apple', 'orange', 'apple']
</code>```

the 'apple' element is the most frequent one.

答:
For the sake of really easy to read, maintainable code I share this:

```<code>function getMaxOcurrences(arr = []) {
  let item = arr[0];
  let ocurrencesMap = {};

  for (let i in arr) {
    const current = arr[i];

    if (ocurrencesMap[current]) ocurrencesMap[current]++;
    else ocurrencesMap[current] = 1;

    if (ocurrencesMap[item] < ocurrencesMap[current]) item = current;
  }

  return {
    item: item,
    ocurrences: ocurrencesMap[item]
  };
}
</code>```

Hope it helps someone ;)!

ContentLicense: CC BY-SA 3.0

Body:
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

['pear', 'apple', 'orange', 'apple']

the 'apple' element is the most frequent one.

Body:
For the sake of really easy to read, maintainable code I share this:

function getMaxOcurrences(arr = []) {
  let item = arr[0];
  let ocurrencesMap = {};

  for (let i in arr) {
    const current = arr[i];

    if (ocurrencesMap[current]) ocurrencesMap[current]++;
    else ocurrencesMap[current] = 1;

    if (ocurrencesMap[item] < ocurrencesMap[current]) item = current;
  }

  return {
    item: item,
    ocurrences: ocurrencesMap[item]
  };
}

Hope it helps someone ;)!


问:
TinyMCE past image from MS Word
I need to copy word text with image to my server through copy - paste function. For that purpose, I choose TinyMCE editor.

The editor works fine, when inserting from word just text. It also works fine, when inserting from word just picture (the picture shows in TinyMCE textarea).

However, when I copy paste word text together with image, only the text shows in textarea.

Is there any way around how to solve this issue?

Next problem is, is there a plugin for TinyMCE that would get the link to the image from TinyMCE textarea, when pasting, and save the image on server?

答: You should have a look at the tinymce paste plugin - this should be able to handle it.</p>

Title: TinyMCE past image from MS Word


问:
Firebase taking long time to write document and freezing app
I'm trying to to write an array to a document on Firebase as the code below describes. However when that array contains 100 items (only names as strings, so no issue with quantity of data) it freezes the app for another minute and in the console I get the message

Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
   This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

The internet connection is fine though. The issue also happens on a smaller array of only 20 items but isn't so pronounced.

What am I doing wrong that is causing the app to take such a long time to write to Firebase?

```<code>func saveDocOnline() {

    let db = Firestore.firestore()

    db.collection("Collection 1").document("Document 1").setData([
        "Array" : loadItems()
    ]) { (error) in
        if let e = error {
            print("Error saving: \(e)")
        } else {
            print("Successfully Saved Online")
        }
    }
}

func loadItems() -> [String] {
    var itemTitle: [String] = []

    itemTitle = ["Generic", "Generic Bars", "Generic Restaurants" ... "Halloween", "Jazz", "Xmas", "Acid Jazz"]

    return itemTitle

}
</code>```

答:
Very weird. Not 100% sure what could be causing this. I tried loading similar sized data without issue, but I would try a few things.

There might be an issue by calling a function inside as an argument for setData(). Try initializing the contents of loadData with a let data:[String:[String]] = loadData() before the setData line. Then use data as the argument instead of loadData(). That will do two things, it will help with type inference if Firebase is having trouble for some reason, and limits the scope of the function if firebase doesn't like that.

(Edit: ignore this suggestion, just reread your post and I can see you tried this)Also experiment with smaller sized arrays and see if you can successfully write 50 items. If that works, go for 75, or if it doesn't try 25. Etc. There might be a limit to the number of items in an array you can put up in this scenario, but that would be a pretty weird limitation of firebase.

try not using the keyword array, I don't think this will affect it, but just to be safe.

All these solutions, if they work, would suggest some weirdness inside the firebase framework, but at least you can eliminate possibilities.

Body:
I'm trying to to write an array to a document on Firebase as the code below describes. However when that array contains 100 items (only names as strings, so no issue with quantity of data) it freezes the app for another minute and in the console I get the message

Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
   This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

The internet connection is fine though. The issue also happens on a smaller array of only 20 items but isn't so pronounced.

What am I doing wrong that is causing the app to take such a long time to write to Firebase?

func saveDocOnline() {

    let db = Firestore.firestore()

    db.collection("Collection 1").document("Document 1").setData([
        "Array" : loadItems()
    ]) { (error) in
        if let e = error {
            print("Error saving: \(e)")
        } else {
            print("Successfully Saved Online")
        }
    }
}

func loadItems() -> [String] {
    var itemTitle: [String] = []

    itemTitle = ["Generic", "Generic Bars", "Generic Restaurants" ... "Halloween", "Jazz", "Xmas", "Acid Jazz"]

    return itemTitle

}


问:
Amazon Kinesis: Caught exception while sync'ing Kinesis shards and leases
I am trying to make Snowplow work on AWS. When I am trying to run stream-enrich service on instance, I am getting this exception:

```<code>[main] INFO com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker - Syncing Kinesis shard info
[main] ERROR com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardSyncTask - Caught exception while sync'ing Kinesis shards and leases
[cw-metrics-publisher] WARN com.amazonaws.services.kinesis.metrics.impl.CWPublisherRunnable - Could not publish 4 datums to CloudWatch
</code>```

I don't think error is due to Cloud Watch:

Caught exception while sync'ing Kinesis shards and leases

答:
As mentioned in the comments above, this error will crop when you're lacking permissions to AWS resources required by Kinesis Client Library (KCL). This can be the DynamoDB, CloudWatch, or Kinesis. For the Stream Enrich component of Snowplow, you'll need the following permissions:

Read permission to input kinesis stream (collector good)

Write permission to output kinesis streams (enrich good & enrich bad)

List permission to kinesis streams

Read/write/create permission to DynamoDB state table (table name is the “appName” value in your stream enrich application.conf)

PutMetricData to Cloudwatch

A templated version of an IAM policy that meets these needs is as follows:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "kinesis:DescribeStream",
        "kinesis:GetShardIterator",
        "kinesis:GetRecords",
        "kinesis:ListShards"
      ],
      "Resource": [
        "${collector_stream_out_good}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
          "kinesis:ListStreams"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "kinesis:DescribeStream",
        "kinesis:PutRecord",
        "kinesis:PutRecords"
      ],
      "Resource": [
        "${enricher_stream_out_good}",
        "${enricher_stream_out_bad}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:CreateTable",
        "dynamodb:DescribeTable",
        "dynamodb:Scan",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:UpdateItem",
        "dynamodb:DeleteItem"
      ],
      "Resource": [
        "${enricher_state_table}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "cloudwatch:PutMetricData"
      ],
      "Resource": "*"
    }
  ]
}
</code>```

I've written up a blog post that covers required IAM permissions for Stream Enrich and other Snowplow components since documentation on the exact required permissions was sparse/non-existent in the Snowplow documentation.

Hope that helps!

Body:
I am trying to make Snowplow work on AWS. When I am trying to run stream-enrich service on instance, I am getting this exception:

[main] INFO com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker - Syncing Kinesis shard info
[main] ERROR com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardSyncTask - Caught exception while sync'ing Kinesis shards and leases
[cw-metrics-publisher] WARN com.amazonaws.services.kinesis.metrics.impl.CWPublisherRunnable - Could not publish 4 datums to CloudWatch

I don't think error is due to Cloud Watch:

Caught exception while sync'ing Kinesis shards and leases

Body:
As mentioned in the comments above, this error will crop when you're lacking permissions to AWS resources required by Kinesis Client Library (KCL). This can be the DynamoDB, CloudWatch, or Kinesis. For the Stream Enrich component of Snowplow, you'll need the following permissions:

Read permission to input kinesis stream (collector good)

Write permission to output kinesis streams (enrich good & enrich bad)

List permission to kinesis streams

Read/write/create permission to DynamoDB state table (table name is the “appName” value in your stream enrich application.conf)

PutMetricData to Cloudwatch

A templated version of an IAM policy that meets these needs is as follows:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "kinesis:DescribeStream",
        "kinesis:GetShardIterator",
        "kinesis:GetRecords",
        "kinesis:ListShards"
      ],
      "Resource": [
        "${collector_stream_out_good}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
          "kinesis:ListStreams"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "kinesis:DescribeStream",
        "kinesis:PutRecord",
        "kinesis:PutRecords"
      ],
      "Resource": [
        "${enricher_stream_out_good}",
        "${enricher_stream_out_bad}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:CreateTable",
        "dynamodb:DescribeTable",
        "dynamodb:Scan",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:UpdateItem",
        "dynamodb:DeleteItem"
      ],
      "Resource": [
        "${enricher_state_table}"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "cloudwatch:PutMetricData"
      ],
      "Resource": "*"
    }
  ]
}

I've written up a blog post that covers required IAM permissions for Stream Enrich and other Snowplow components since documentation on the exact required permissions was sparse/non-existent in the Snowplow documentation.

Hope that helps!


问:
Don't emit until some other observable has emitted, then emit all previous values
I'm looking for a way to buffer values of an observable until some other observable has emitted, but then emit all the previous values. Something like skipUntil, if skipUntil also emitted skipped values as soon as the second observable emitted.</p>

```<code>--a--b----c-----d---e--- (source)
-----------1------------- (other1)
------------abc-d---e----(desired output)
</code>```

答:
Here's the custom operator I came up with. Not sure if it can be done in a prettier way.</p>

```<code>export function bufferUntil(stopBufferSignal: Observable<any>) {
    return <T>(source: Observable<T>): Observable<T> => {
        return source.pipe(buffer(stopBufferSignal),
            take(1),
            flatMap(ar => {
                const sourceWithNSkipped$: Observable<T> = source.pipe(skip(ar.length));
                const bufferedItems$: Observable<T> = from(ar);
                return bufferedItems$.pipe(concat(sourceWithNSkipped$))
            }));
    }
}
</code>```

Body:
I'm looking for a way to buffer values of an observable until some other observable has emitted, but then emit all the previous values. Something like skipUntil, if skipUntil also emitted skipped values as soon as the second observable emitted.

--a--b----c-----d---e--- (source)
-----------1------------- (other1)
------------abc-d---e----(desired output)

Body:
Here's the custom operator I came up with. Not sure if it can be done in a prettier way.

export function bufferUntil(stopBufferSignal: Observable<any>) {
    return <T>(source: Observable<T>): Observable<T> => {
        return source.pipe(buffer(stopBufferSignal),
            take(1),
            flatMap(ar => {
                const sourceWithNSkipped$: Observable<T> = source.pipe(skip(ar.length));
                const bufferedItems$: Observable<T> = from(ar);
                return bufferedItems$.pipe(concat(sourceWithNSkipped$))
            }));
    }
}


问:
arrange number with 5 digits from the biggest to lowest in c only with 'if'
I have a question.
I working in c and I need to take a number from the user with 5 digits and sort it from the biggest number to the lowest  only with 'if'
I tried to do with 5 variables but the code getting huge.
there some easy way to do it only with 'ifs'???

for example, I get the number: 87953
the output should be : 98753.

(in the pic it only one situation).
enter image description here

答:
example:</p>

```<code>#include <string.h>
#include <stdio.h>

int main()
{
    char values[10] = {0};
    scanf("%9s", values); // read input
    int nrOfCharacters = strlen(values);

    for(int i = 0; i < nrOfCharacters; i++) {

        for( int y = i + 1; y < nrOfCharacters; y++) {

            if((values[i] - '0') > (values[y] - '0')) {
                char tmp = values[y];
                values[y] = values[i];
                values[i] = tmp;
            }

        }
    }

    printf("output: %s", values);

    return 0;
}
</code>```

Body:
example:

#include <string.h>
#include <stdio.h>

int main()
{
    char values[10] = {0};
    scanf("%9s", values); // read input
    int nrOfCharacters = strlen(values);

    for(int i = 0; i < nrOfCharacters; i++) {

        for( int y = i + 1; y < nrOfCharacters; y++) {

            if((values[i] - '0') > (values[y] - '0')) {
                char tmp = values[y];
                values[y] = values[i];
                values[i] = tmp;
            }

        }
    }

    printf("output: %s", values);

    return 0;
}


问:
ActiveX component can’t create object : PCOMM.autECLConnList
I am trying to automate the sending keystrokes to a mainframe application which is being connected using PCOMM iSeries emulator. I am not sure on what I am doing wrong here, as the same code works on a different machine.
Below are the configurations,

Working Machine  : Windows 10 64 bit, Office 32-Bit

Error Machine : Windows 7 64 bit, Office 64-Bit

Below is the code

```<code>On Error Resume Next

Set autECLWinObj = CreateObject("PCOMM.autECLConnList")

Set IA = CreateObject("PCOMM.autECLOIA")
Set PS = CreateObject("PCOMM.autECLPS")

PS.SetConnectionByName (Client)
IA.SetConnectionByName (Client)
autECLWinObj.SetConnectionByName (Client)
</code>```

Please help, i am new to this and stuck .

P.S : Kindly don't duplicate the question as there are none specific to PCOMM.

答: You must upgrade you IBM Personal Communications to the new Version 14 (64 bits) since may 2019</p>

Body:
I am trying to automate the sending keystrokes to a mainframe application which is being connected using PCOMM iSeries emulator. I am not sure on what I am doing wrong here, as the same code works on a different machine.
Below are the configurations,

Working Machine  : Windows 10 64 bit, Office 32-Bit

Error Machine : Windows 7 64 bit, Office 64-Bit

Below is the code

On Error Resume Next

Set autECLWinObj = CreateObject("PCOMM.autECLConnList")

Set IA = CreateObject("PCOMM.autECLOIA")
Set PS = CreateObject("PCOMM.autECLPS")

PS.SetConnectionByName (Client)
IA.SetConnectionByName (Client)
autECLWinObj.SetConnectionByName (Client)

Please help, i am new to this and stuck .

P.S : Kindly don't duplicate the question as there are none specific to PCOMM.


答:
Suppose you have a swap function

```<code>void swap(char *a, char *b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}
</code>```

First, a bubble sort as a pair of loops could be

```<code>char s[] = "87953";

for(int i = 0; i < 5; i++) {
    for(int j = i + 1; j < 5; j++) {
        if(s[i] > s[j]) {
            swap(s + i, s + j);
        }
    }
}

printf("%s\n", s);
</code>```

Unrolling the loops, we only need 10 if statements:

```<code>char s[] = "87953";

if(s[0] > s[1])
    swap(s + 0, s + 1);
if(s[0] > s[2])
    swap(s + 0, s + 2);
if(s[0] > s[3])
    swap(s + 0, s + 3);
if(s[0] > s[4])
    swap(s + 0, s + 4);

if(s[1] > s[2])
    swap(s + 1, s + 2);
if(s[1] > s[3])
    swap(s + 1, s + 3);
if(s[1] > s[4])
    swap(s + 1, s + 4);

if(s[2] > s[3])
    swap(s + 2, s + 3);
if(s[2] > s[4])
    swap(s + 2, s + 4);

if(s[3] > s[4])
    swap(s + 3, s + 4);

printf("%s\n", s);
</code>```

You could even move the comparisons into the swap function for more compact code, if you are allowed to use a function. If not, you'll have to expand it in-line anyway.

Title: arrange number with 5 digits from the biggest to lowest in c only with 'if'

Body:
I have a question.
I working in c and I need to take a number from the user with 5 digits and sort it from the biggest number to the lowest  only with 'if'
I tried to do with 5 variables but the code getting huge.
there some easy way to do it only with 'ifs'???

for example, I get the number: 87953
the output should be : 98753.

(in the pic it only one situation).
enter image description here

Body:
Suppose you have a swap function

void swap(char *a, char *b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}

First, a bubble sort as a pair of loops could be

char s[] = "87953";

for(int i = 0; i < 5; i++) {
    for(int j = i + 1; j < 5; j++) {
        if(s[i] > s[j]) {
            swap(s + i, s + j);
        }
    }
}

printf("%s\n", s);

Unrolling the loops, we only need 10 if statements:

char s[] = "87953";

if(s[0] > s[1])
    swap(s + 0, s + 1);
if(s[0] > s[2])
    swap(s + 0, s + 2);
if(s[0] > s[3])
    swap(s + 0, s + 3);
if(s[0] > s[4])
    swap(s + 0, s + 4);

if(s[1] > s[2])
    swap(s + 1, s + 2);
if(s[1] > s[3])
    swap(s + 1, s + 3);
if(s[1] > s[4])
    swap(s + 1, s + 4);

if(s[2] > s[3])
    swap(s + 2, s + 3);
if(s[2] > s[4])
    swap(s + 2, s + 4);

if(s[3] > s[4])
    swap(s + 3, s + 4);

printf("%s\n", s);

You could even move the comparisons into the swap function for more compact code, if you are allowed to use a function. If not, you'll have to expand it in-line anyway.


问:
I get different result from Graphql playground and front-end
I am using graphql and Vue.js and apollo

Here is my DateBank

const sensorsdb = [
{
    name: "sensor 1",
    id: "s-1",
    timestamp: 1582021371,
    value: 100
},
{
    name: "sensor 1",
    id: "s-1",
    timestamp: 1579451703,
    value: 150
},
{
    name: "sensor 2-1",
    id: "s-2-1",
    timestamp: 1582021371,
    value: 200
},
{
    name: "sensor 2-2",
    id: "s-2-2",
    timestamp: 1579451703,
    value: 350
},
{
    name: "sensor 2-2",
    id: "s-2-2",
    timestamp: 1582021371,
    value: 300
},
{
    name: "sensor 3",
    id: "s-3",
    timestamp: 1582021371,
    value: 400
},];
```
<p>I want to get all objects according to object id. sensorId is an array. because I want to get multiple objects with multiple ids.</p>
<p>The following is my API function to get object.</p>
<pre class="lang-js prettyprint-override"><code>async getDataById({ sensorId }) {
    let sensorsData = [];
    for (let i = 0; i < sensorId.length; i++) {
        let sensorData = this.sensorDataStore.sensors.filter(sensor => sensor.id === sensorId[i]);
        sensorsData = sensorsData.concat(sensorData);
    }
    return sensorsData;
}
</code>```

In Front-end, gql file is following:

query sensorData($id: [String]){
sensorData(id: $id){
    name
    id
    value
    timestamp
}}
```
<p>and with my apollo query code in vue.js, in this case selectedSensorId is ["s-2-1", "s-2-2"]</p>
<pre class="lang-html prettyprint-override"><code><ApolloQuery :query="require('../graphql/sensorDataById.gql')" :variables="{ id: selectedSensorId }">
  <template v-slot="{ result: { loading, error, data } }">
    <b-loading :is-full-page=true :active.sync=loading :can-cancel="false"/>
    <div v-if="error">
      <no-data-error />
    </div>
    <div v-if="data">
      {{ data }}
      <bar-chart-view :sensorInfo="data.sensorData"/>
    </div>
  </template>
</ApolloQuery>
</code>```

But I got the following different result:
Graphql playground which has correct result
The front-end result with duplicated sensor-s-2

答:
Apollo Client normalizes results according to the id and __typename fields as described in the docs. If an array returns multiple items with the same id, by default they will share the same cache key, which means what's returned by the client will be the same object.

You should provide a custom dataIdFromObject function to your InMemoryCache constructor that accommodates your specific use case. Something like:

const dataIdFromObject = object => {
  switch (object.__typename) {
    case 'SensorDataPoint': return `SensorDataPoint:${object.id}:{value}`;
    default: return defaultDataIdFromObject(object);
  }
}
```
<p>Note that if you use the same type elsewhere, you may experience issues with the cache updated correctly after mutations because we are now keying off both the <code>value</code> and <code>id</code>. You might want to consider a different approach to your schema where the ids are actually unique :</p>
<pre class="lang-json prettyprint-override"><code>type SensorDataPoint {
  id: ID!
  sensorId: ID!
  sensorName: String!
  value: Int!
  timestamp: Int!
}
</code>```

or even better

type SensorDataPoint {
  id: ID!
  value: Int!
  timestamp: Int!
  sensor: Sensor!
}

type Sensor {
  id: ID!
  name: String!
}
```

Body:
I am using graphql and Vue.js and apollo

Here is my DateBank

const sensorsdb = [
{
    name: "sensor 1",
    id: "s-1",
    timestamp: 1582021371,
    value: 100
},
{
    name: "sensor 1",
    id: "s-1",
    timestamp: 1579451703,
    value: 150
},
{
    name: "sensor 2-1",
    id: "s-2-1",
    timestamp: 1582021371,
    value: 200
},
{
    name: "sensor 2-2",
    id: "s-2-2",
    timestamp: 1579451703,
    value: 350
},
{
    name: "sensor 2-2",
    id: "s-2-2",
    timestamp: 1582021371,
    value: 300
},
{
    name: "sensor 3",
    id: "s-3",
    timestamp: 1582021371,
    value: 400
},];

I want to get all objects according to object id. sensorId is an array. because I want to get multiple objects with multiple ids.

The following is my API function to get object.

async getDataById({ sensorId }) {
    let sensorsData = [];
    for (let i = 0; i < sensorId.length; i++) {
        let sensorData = this.sensorDataStore.sensors.filter(sensor => sensor.id === sensorId[i]);
        sensorsData = sensorsData.concat(sensorData);
    }
    return sensorsData;
}

In Front-end, gql file is following:

query sensorData($id: [String]){
sensorData(id: $id){
    name
    id
    value
    timestamp
}}

and with my apollo query code in vue.js, in this case selectedSensorId is ["s-2-1", "s-2-2"]

<ApolloQuery :query="require('../graphql/sensorDataById.gql')" :variables="{ id: selectedSensorId }">
  <template v-slot="{ result: { loading, error, data } }">

      <no-data-error />

      {{ data }}
      <bar-chart-view :sensorInfo="data.sensorData"/>

  </template>
</ApolloQuery>

But I got the following different result:
Graphql playground which has correct result
The front-end result with duplicated sensor-s-2

Body:
Apollo Client normalizes results according to the id and __typename fields as described in the docs. If an array returns multiple items with the same id, by default they will share the same cache key, which means what's returned by the client will be the same object.

You should provide a custom dataIdFromObject function to your InMemoryCache constructor that accommodates your specific use case. Something like:

const dataIdFromObject = object => {
  switch (object.__typename) {
    case 'SensorDataPoint': return `SensorDataPoint:${object.id}:{value}`;
    default: return defaultDataIdFromObject(object);
  }
}

Note that if you use the same type elsewhere, you may experience issues with the cache updated correctly after mutations because we are now keying off both the value and id. You might want to consider a different approach to your schema where the ids are actually unique :

type SensorDataPoint {
  id: ID!
  sensorId: ID!
  sensorName: String!
  value: Int!
  timestamp: Int!
}

or even better

type SensorDataPoint {
  id: ID!
  value: Int!
  timestamp: Int!
  sensor: Sensor!
}

type Sensor {
  id: ID!
  name: String!
}


问:
Download Html + Blob image as text
I need to save an html code as a text file (preferably MS word) with a signature represented as a blob (drawn with HTML5 Canvas).

I tried this solution but unfortunately, the downloaded file appears with the html tags and does not render the blob as an image.

JSfiddle

JS Code:

```<code> window.export.onclick = function() {

   if (!window.Blob) {
      alert('Your legacy browser does not support this action.');
      return;
   }

   var html, link, blob, url, css;

   // EU A4 use: size: 841.95pt 595.35pt;
   // US Letter use: size:11.0in 8.5in;

   css = (
     '<style>' +
     '@page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' +
     'div.WordSection1 {page: WordSection1;}' +
     'table{border-collapse:collapse;}td{border:1px gray solid;width:5em;padding:2px;}'+
     '</style>'
   );

   html = window.docx.innerHTML;
   blob = new Blob(['\ufeff', html], {
     type: 'application/msword'
   });
   url = URL.createObjectURL(blob);
   link = document.createElement('A');
   link.href = url;
   // Set default file name.
   // Word will append file extension - do not add an extension here.
   link.download = 'Document';
   document.body.appendChild(link);
   if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
        else link.click();  // other browsers
   document.body.removeChild(link);
 };
</code>```

答:
Here's the solution based on a JavaScript library called html-docx-js:

var documentElement = document.getElementById("docx");

function exportDocxFile() {
    if (!window.Blob) {
        alert('Your legacy browser does not support this action.');
        return;
    }

    var processedDocumentElement = convertImagesToBase64(documentElement);

    var html = processedDocumentElement.innerHTML;
    var blob = htmlDocx.asBlob(html);

    var url = URL.createObjectURL(blob);
    var link = document.createElement('A');

    link.href = url;
    // Set default file name.
    // Word will append file extension - do not add an extension here.
    link.download = 'Document';

    document.body.appendChild(link);

    if (navigator.msSaveOrOpenBlob) {
        navigator.msSaveOrOpenBlob(blob, 'Document.docx'); // IE10-11
    } else {
        link.click();  // other browsers
    }

    document.body.removeChild(link);
}

function convertImagesToBase64(targetDocumentElement) {
    var clonedDocumentElement = targetDocumentElement.cloneNode(true);

    var regularImages = targetDocumentElement.querySelectorAll("img");
    var clonedImages = clonedDocumentElement.querySelectorAll("img");
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    for (var i = 0; i < regularImages.length; i++) {
        var regularImgElement = regularImages[i];
        var clonedImgElement = clonedImages[i];

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        canvas.width = regularImgElement.width;
        canvas.height = regularImgElement.height;

        ctx.scale(regularImgElement.width / regularImgElement.naturalWidth, regularImgElement.height / regularImgElement.naturalHeight);
        ctx.drawImage(regularImgElement, 0, 0);

        // by default toDataURL() produces png image, but you can also export to jpeg
        // checkout function's documentation for more details
        var dataURL = canvas.toDataURL();

        clonedImgElement.setAttribute('src', dataURL);
    }

    canvas.remove();

    return clonedDocumentElement;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/html-docx-js@0.3.1/dist/html-docx.js"></script>

<button id="export" onclick="exportDocxFile()">Export</button> Click to open table in Microsoft Word
<div id="docx">
    <h1>
        This is a test
    </h1>
    <p>
        Some paragraph text lorem ipsum
    </p>
    <p style='margin-top:0cm;margin-right:0cm;margin-bottom:.0001pt;margin-left:0cm;font-size:16px;font-family:"Times New Roman",serif;'>
        <span style="font-size:15px;">Date: <u>
                 02/01/2020       </u>
                      Date: <u>

                       </u>
        </span>
    </p>
    <img width="100" src="data:image/svg+xml;base64,[encoded data, 12096 characters]" />
</div></code>```

Title: Download Html + Blob image as text

Body:
I need to save an html code as a text file (preferably MS word) with a signature represented as a blob (drawn with HTML5 Canvas).

I tried this solution but unfortunately, the downloaded file appears with the html tags and does not render the blob as an image.

JSfiddle

JS Code:

 window.export.onclick = function() {

   if (!window.Blob) {
      alert('Your legacy browser does not support this action.');
      return;
   }

   var html, link, blob, url, css;

   // EU A4 use: size: 841.95pt 595.35pt;
   // US Letter use: size:11.0in 8.5in;

   css = (
     ''
   );

   html = window.docx.innerHTML;
   blob = new Blob(['\ufeff', html], {
     type: 'application/msword'
   });
   url = URL.createObjectURL(blob);
   link = document.createElement('A');
   link.href = url;
   // Set default file name.
   // Word will append file extension - do not add an extension here.
   link.download = 'Document';
   document.body.appendChild(link);
   if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
        else link.click();  // other browsers
   document.body.removeChild(link);
 };

Body:
Here's the solution based on a JavaScript library called html-docx-js:

var documentElement = document.getElementById("docx");

function exportDocxFile() {
    if (!window.Blob) {
        alert('Your legacy browser does not support this action.');
        return;
    }

    var processedDocumentElement = convertImagesToBase64(documentElement);

    var html = processedDocumentElement.innerHTML;
    var blob = htmlDocx.asBlob(html);

    var url = URL.createObjectURL(blob);
    var link = document.createElement('A');

    link.href = url;
    // Set default file name.
    // Word will append file extension - do not add an extension here.
    link.download = 'Document';

    document.body.appendChild(link);

    if (navigator.msSaveOrOpenBlob) {
        navigator.msSaveOrOpenBlob(blob, 'Document.docx'); // IE10-11
    } else {
        link.click();  // other browsers
    }

    document.body.removeChild(link);
}

function convertImagesToBase64(targetDocumentElement) {
    var clonedDocumentElement = targetDocumentElement.cloneNode(true);

    var regularImages = targetDocumentElement.querySelectorAll("img");
    var clonedImages = clonedDocumentElement.querySelectorAll("img");
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    for (var i = 0; i < regularImages.length; i++) {
        var regularImgElement = regularImages[i];
        var clonedImgElement = clonedImages[i];

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        canvas.width = regularImgElement.width;
        canvas.height = regularImgElement.height;

        ctx.scale(regularImgElement.width / regularImgElement.naturalWidth, regularImgElement.height / regularImgElement.naturalHeight);
        ctx.drawImage(regularImgElement, 0, 0);

        // by default toDataURL() produces png image, but you can also export to jpeg
        // checkout function's documentation for more details
        var dataURL = canvas.toDataURL();

        clonedImgElement.setAttribute('src', dataURL);
    }

    canvas.remove();

    return clonedDocumentElement;
}

<script src="https://cdn.jsdelivr.net/npm/html-docx-js@0.3.1/dist/html-docx.js"></script>

<button id="export" onclick="exportDocxFile()">Export</button> Click to open table in Microsoft Word
<div id="docx">
    <h1>
        This is a test
    </h1>
    <p>
        Some paragraph text lorem ipsum
    </p>
    <p style='margin-top:0cm;margin-right:0cm;margin-bottom:.0001pt;margin-left:0cm;font-size:16px;font-family:"Times New Roman",serif;'>
        <span style="font-size:15px;">Date: <u>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                &nbsp;02/01/2020&nbsp; &nbsp; &nbsp; &nbsp;</u>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;
            &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Date: <u>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                &nbsp; &nbsp; &nbsp; &nbsp;</u>
        </span>
    </p>
    <img width="100" src="data:image/svg+xml;base64,[encoded data, 12096 characters]" />
</div>


问:
How to add a new row to Excel file using unmanaged C++?
How can I add a new row (with contents) to an existing Excel .xls file using unmanaged C++ running on Windows?

I don't mind using OLE, COM, or any external free library, whatever is the easiest way.

答:
There is a COM interface which is well documented.

I'd suggest you start with the Workbooks.Open method to open an existing excel file.

If you only need basic features (no formatting, formula's, ...), you can also use BasicExcel: A c++ library which doesn't have any dependencies (it reads and writes the excel file as a compound file) and is much easier to use than the COM interface (at least from c++).


问:
Matplotlib table formatting column width
I wish to format one column of a table but when iterating through the rows it appears the width of the column width changes after each iteration.

Source Code

```<code>def p_create_table(self, events, dates, rows, columns, portfolio):
    """
    :param events: Dict - {Date:Event} where Event is a String identifying
    what event happened
    :param dates: List - Dates of events
    :param rows: Int - number of Dates (rows) to create for the table
    :param columns: List - Column headers
    :param portfolio: Dataframe - Portfolio with calculated totals and returns
    :return:
    """
    cell_text = self.p_create_cell_text(events, dates, portfolio)
    cell_text.pop(0)
    row_labels = self.p_create_row_labels(rows)
    row_labels.pop(len(row_labels) - 1)
    colors = self.p_set_table_colors(row_labels)

    table = plt.table(cellText=cell_text, cellColours=colors[0],
              rowColours=colors[1], rowLabels=row_labels,
              colColours=colors[2], colLabels=columns,
              bbox=[0.0, -1.3, 1.0, 1.0], cellLoc='center')

    table.auto_set_font_size(False)
    table.set_fontsize(9)
    table.scale(2, 2)

    cell_dict = table.get_celld()
    for i in range(13):
        cell_dict[(i,1)].set_width(0.3)
</code>```

Below is an image of the table BEFORE the resizing. The snapshot was taken after line table.set_fontsize(9) was executed. I would like to re-size the second column Event.

Before formatting

Unfortunately, after ever iteration of:

```<code>for i in range(13):
    cell_dict[(i,1)].set_width(0.3)
</code>```

it looks like the cell width increases, resulting in something like this:

After formatting

Any suggestions on why this could be happening, or an alternative solution to adjusting the width would be much appreciated!

答:
In addition to @jma answer, I found the table method .auto_set_column_width(col=<list of col indices>) to be very helpful, especially in conjunction with .auto_set_font_size(False). Example use below:

from matplotlib import pyplot as plt
import pandas as pd
# Create some example data
data = [{"Movie": "Happy Gilmore", "Lead Actor": "Adam Sandler" , "Year": "1996",
              "Plot": "An ice hockey star takes up golfing.",
              "Quotes": "\"Just give it a little tappy. Tap tap taparoo.\""}]
dff = pd.DataFrame(data)
fig, ax = plt.subplots(3,1, figsize=(10,4))

tab0 = ax[0].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[0].set_title("Default")
tab1 = ax[1].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[1].set_title("Font AutoSize off")
tab2 = ax[2].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[2].set_title("Column Width Auto Set, Font AutoSize off")
[a.axis("off") for a in ax]
[t.auto_set_font_size(False) for t in [tab1, tab2]]
[t.set_fontsize(8) for t in [tab1, tab2]]

tab2.auto_set_column_width(col=list(range(len(dff.columns)))) # Provide integer list of columns to adjust
plt.show()
```

Body:
I wish to format one column of a table but when iterating through the rows it appears the width of the column width changes after each iteration.

Source Code

def p_create_table(self, events, dates, rows, columns, portfolio):
    """
    :param events: Dict - {Date:Event} where Event is a String identifying
    what event happened
    :param dates: List - Dates of events
    :param rows: Int - number of Dates (rows) to create for the table
    :param columns: List - Column headers
    :param portfolio: Dataframe - Portfolio with calculated totals and returns
    :return:
    """
    cell_text = self.p_create_cell_text(events, dates, portfolio)
    cell_text.pop(0)
    row_labels = self.p_create_row_labels(rows)
    row_labels.pop(len(row_labels) - 1)
    colors = self.p_set_table_colors(row_labels)

    table = plt.table(cellText=cell_text, cellColours=colors[0],
              rowColours=colors[1], rowLabels=row_labels,
              colColours=colors[2], colLabels=columns,
              bbox=[0.0, -1.3, 1.0, 1.0], cellLoc='center')

    table.auto_set_font_size(False)
    table.set_fontsize(9)
    table.scale(2, 2)

    cell_dict = table.get_celld()
    for i in range(13):
        cell_dict[(i,1)].set_width(0.3)

Below is an image of the table BEFORE the resizing. The snapshot was taken after line table.set_fontsize(9) was executed. I would like to re-size the second column Event.

Before formatting

Unfortunately, after ever iteration of:

for i in range(13):
    cell_dict[(i,1)].set_width(0.3)

it looks like the cell width increases, resulting in something like this:

After formatting

Any suggestions on why this could be happening, or an alternative solution to adjusting the width would be much appreciated!


问:
Is there a way to import a module in Rust knowing its directory but not its filename?
I'm writing a game-playing AI in Rust. The strategy module includes a folder with standardized modules that handle specific situations. I want to be able to create a new module anytime I think of a new situation that I would like handled.

I can accomplish this in Node. For example, in an MVC setup, you might have

├── src
    ├── controllers
        ├── index.js
        └── ...
    ├── models
        ├── index.js
        └── ...
    └── views
        ├── index.js
        └── ...
```

<p>with a controllers/index.js file containing</p>

<pre class="lang-js prettyprint-override"><code>////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////

// Models
const models = require('../models');

// Modules
const fs   = require('fs');
const path = require('path');

////////////////////////////////////////////////////////////////////////////////
// Module
////////////////////////////////////////////////////////////////////////////////

const controllers = {};

const basename = path.basename(__filename);
fs.readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) &&
           (file !== basename) &&
           (file.slice(-3) === '.js');
  })
  .forEach(file => {
    controllers[file.slice(0,-3)] = require(`./${file}`)(models) ;
  });
</code>```

Can I accomplish something similar in Rust?

答:
No, there is no way to import a module at runtime; Rust is a statically-compiled language.

The closest thing you could do would be to write a build script that enumerates your filesystem and generates the appropriate mod and/or use statements.

require(`./${file}`)(models)
```

Rust also doesn't have "default exports" of imports, so this pattern cannot exist. You'd have to call a specifically-named function from the module.

See also:

How can I statically register structures at compile time?

Body:
I'm writing a game-playing AI in Rust. The strategy module includes a folder with standardized modules that handle specific situations. I want to be able to create a new module anytime I think of a new situation that I would like handled.

I can accomplish this in Node. For example, in an MVC setup, you might have

├── src
    ├── controllers
        ├── index.js
        └── ...
    ├── models
        ├── index.js
        └── ...
    └── views
        ├── index.js
        └── ...

with a controllers/index.js file containing

////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////

// Models
const models = require('../models');

// Modules
const fs   = require('fs');
const path = require('path');

////////////////////////////////////////////////////////////////////////////////
// Module
////////////////////////////////////////////////////////////////////////////////

const controllers = {};

const basename = path.basename(__filename);
fs.readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) &&
           (file !== basename) &&
           (file.slice(-3) === '.js');
  })
  .forEach(file => {
    controllers[file.slice(0,-3)] = require(`./${file}`)(models) ;
  });

Can I accomplish something similar in Rust?

Body:
No, there is no way to import a module at runtime; Rust is a statically-compiled language.

The closest thing you could do would be to write a build script that enumerates your filesystem and generates the appropriate mod and/or use statements.

require(`./${file}`)(models)

Rust also doesn't have "default exports" of imports, so this pattern cannot exist. You'd have to call a specifically-named function from the module.

See also:

How can I statically register structures at compile time?


问:
What is the colon (:) expression in verilog structure assignment pattern?
For example,

```<code>typedef struct packed {
  logic foo_1;
  logic foo_2;
} my_type

my_type foo_out;

assign foo_out = ‘{
  foo_1 : sig_1,
  foo_2 : sig_2
};
</code>```

It looks like that, just same as

```<code>assign foo_out = {sig_1, sig_2};
</code>```

I can’t find any structure assignment pattern using colon (:) in LRM.
Anybody please leave comment where this kind of expression is describled.

答:
The last statement you wrote is not an assignment pattern; it is a concatenation. If sig_1 and sig_2 are not single bit variables you have a problem. The ' in front of the {}'s is critical.

Section 10.9.2 Structure assignment patterns of the IEEE 1800-2017 LRM explains that

```<code>assign foo_out = '{sig_1, sig_2};
</code>```

is a positional structure element assignment pattern where the first argument gets assigned to the first element, the second argument gets assigned to the second element, and so on. Each argument gets truncated or padded too match each element.

The other form with the : gets matched by name instead of position.

```<code>assign foo_out = '{foo_2:sig_2, foo_1:sig_1};
</code>```

Body:
For example,

typedef struct packed {
  logic foo_1;
  logic foo_2;
} my_type

my_type foo_out;

assign foo_out = ‘{
  foo_1 : sig_1,
  foo_2 : sig_2
};

It looks like that, just same as

assign foo_out = {sig_1, sig_2};

I can’t find any structure assignment pattern using colon (:) in LRM.
Anybody please leave comment where this kind of expression is describled.

Body:
The last statement you wrote is not an assignment pattern; it is a concatenation. If sig_1 and sig_2 are not single bit variables you have a problem. The ' in front of the {}'s is critical.

Section 10.9.2 Structure assignment patterns of the IEEE 1800-2017 LRM explains that

assign foo_out = '{sig_1, sig_2};

is a positional structure element assignment pattern where the first argument gets assigned to the first element, the second argument gets assigned to the second element, and so on. Each argument gets truncated or padded too match each element.

The other form with the : gets matched by name instead of position.

assign foo_out = '{foo_2:sig_2, foo_1:sig_1};


问:
How to write SQL Query (Get all Categories and get 10 Products on each Category)
I am very new to Database and I want to know raw sql query.
I have 2 tables Category and Product
Product table has foreign_key(category_id).

How can I get all categories with 10 products for each category? So I will display each category name and 10 products on first page.

```<code>SELECT *
FROM categories
INNER JOIN
(SELECT * FROM products ORDER BY price LIMIT 10) as p
ON
 categories.id = p.category_id
</code>```

And also want to query reviews table that product has. How can I join 2 tables(Category with Product(1), Review(2)

答:
A simple way is a lateral join:</p>

```<code>SELECT *
FROM categories c LEFT JOIN LATERAL
     (SELECT p.*
      FROM products p
      WHERE c.id = p.category_id
      ORDER_BY p.price
      LIMIT 10
     ) p
     ON 1 = 1
</code>```

Body:
I am very new to Database and I want to know raw sql query.
I have 2 tables Category and Product
Product table has foreign_key(category_id).

How can I get all categories with 10 products for each category? So I will display each category name and 10 products on first page.

SELECT *
FROM categories
INNER JOIN
(SELECT * FROM products ORDER BY price LIMIT 10) as p
ON
 categories.id = p.category_id

And also want to query reviews table that product has. How can I join 2 tables(Category with Product(1), Review(2)

Body:
A simple way is a lateral join:

SELECT *
FROM categories c LEFT JOIN LATERAL
     (SELECT p.*
      FROM products p
      WHERE c.id = p.category_id
      ORDER_BY p.price
      LIMIT 10
     ) p
     ON 1 = 1


问:
How to plot a chart in the frontend using data from the backend with node.js?
My current situation is this:

I have a SQL database that I get my data from on the server side, and I want to show that data in a chart for the user, using Plotly. But I'm not sure how to approach this: should I pass the data to the frontend and make a chart there, or make the chart on the server side and try to change the content of the HTML?

Also, in the front end, I would like to use a external script, meaning I can't include plotly as a module, but maybe there is a way to do it?
And if I try to do it on the server side, how should I approach this passing the chart to the front end?

I'm fairly new to web development thing, trying to grasp the right concept of how data should be passed arround.

答:
First you need to create an api, this api will serve x and y coordinates in array format.
Please refer following link https://plot.ly/javascript/getting-started/#hello-world-example (in this web-page click on js tab and see the "x" and "y" coordinates.)

Next make ajax call to above api and subscribe the response.


问:
How do you apply a Combine operator only after the first message has been received?
In Combine, using only the built-in operators, is there a way to skip an operator on the first value but then apply that operator for all subsequent values?

Consider the following:

```<code>publisher
  .debounce(...)
  .sink(...)
</code>```

In this arrangement, debounce will wait for the specified timeout to elapse before passing on the value to sink. However, there are many times when you only want debounce to kick-in after the first element. For example, if the user is trying to filter a list of contacts, it's very possible that they only enter one letter into a text field. If that's the case, the application should probably start filtering immediately, without having to wait for the debounce to timeout.

I'm aware of the Drop publishers, but I can't seem to find a combination of them that will perform more of a "skip" operation such that the sink receives every value, but the debounce is ignored on the first value.

Something like the following:

```<code>publisher
  .if_first_element_passthrough_to_sink(...), else_debounce(...)
  .sink(...)
</code>```

Is something like this possible with the built-in operators?

Clarification

Some clarification since my original posting wasn't as clear as it should have been... The answer provided by Asperi below is very close, but ideally the first element in a sequence is always delivered, then debounce would kick in.

Imagine the user is typing the following:

A B C ... (pauses typing for a few seconds) ... D ... (pauses) ... E F G

What I would like is:

A, D and E are delivered immediately.

B C is coalesced into just C using debounce

F G is coalesced into just G using debounce

答:
In your particular case of debounce, you might prefer the behavior of throttle. It sends the first element immediately, and then sends no more than one element per interval.

Anyway, can you do it with Combine built-ins? Yes, with some difficulty. Should you? Maybe…

Here's a marble diagram of your goal:

Each time a value goes into the kennyc-debouncer, it starts a timer (represented by a shaded region). If a value arrives while the timer is running, the kennyc-debouncer saves the value and restarts the timer. When the timer expires, if any values arrived while the timer was running, the kennyc-debouncer emits the latest value immediately.

The scan operator allows us to keep state that we mutate each time an input arrives. We need to send two kinds of inputs into scan: the outputs from the upstream publisher, and timer firings. So let's define a type for those inputs:

```<code>fileprivate enum DebounceEvent<Value> {
    case value(Value)
    case timerFired
}
</code>```

What kind of state do we need inside our scan transform? We definitely need the scheduler, the interval, and the scheduler options, so that we can set timers.

We also need a PassthroughSubject we can use to turn timer firings into inputs to the scan operator.

We can't actually cancel and restart a timer, so instead, when the timer fires, we'll see whether it should have been restarted. If so, we'll start another timer. So we need to know whether the timer is running, and what output to send when the timer fires, and the restart time for the timer if restarting is necessary.

Since scan's output is the entire state value, we also need the state to include the output value to send downstream, if any.

Here's the state type:

```<code>fileprivate struct DebounceState<Value, S: Scheduler> {
    let scheduler: S
    let interval: S.SchedulerTimeType.Stride
    let options: S.SchedulerOptions?

    let subject = PassthroughSubject<Void, Never>()

    enum TimerState {
        case notRunning
        case running(PendingOutput?)

        struct PendingOutput {
            var value: Value
            var earliestDeliveryTime: S.SchedulerTimeType
        }
    }

    var output: Value? = nil
    var timerState: TimerState = .notRunning
}
</code>```

Now let's look at how to actually use scan with some other operators to implement the kennyc version of debounce:

```<code>extension Publisher {
    func kennycDebounce<S: Scheduler>(
        for dueTime: S.SchedulerTimeType.Stride,
        scheduler: S,
        options: S.SchedulerOptions? = nil
    ) -> AnyPublisher<Output, Failure>
    {
        let initialState = DebounceState<Output, S>(
            scheduler: scheduler,
            interval: dueTime,
            options: options)
        let timerEvents = initialState.subject
            .map { _ in DebounceEvent<Output>.timerFired }
            .setFailureType(to: Failure.self)
        return self
            .map { DebounceEvent.value($0) }
            .merge(with: timerEvents)
            .scan(initialState) { $0.updated(with: $1) }
            .compactMap { $0.output }
            .eraseToAnyPublisher()
    }
}
</code>```

We start by constructing the initial state for the scan operator.

Then, we create a publisher that turns the Void outputs of the state's PassthroughSubject into .timerFired events.

Finally, we construct our full pipeline, which has four stages:

Turn the upstream outputs (from self) into .value events.

Merge the value events with the timer events.

Use scan to update the debouncing state with the value and timer events. The actual work is done in an updated(with:) method we'll add to DebounceState below.

Map the full state down to just the value we want to pass downstream, and discard nulls (which happen when upstream events get suppressed by debouncing).

All that's left is to write the updated(with:) method. It looks at each incoming event's type (value or timerFired) and the state of the timer to decide what the new state should be and, if necessary, set a new timer.

```<code>extension DebounceState {
    func updated(with event: DebounceEvent<Value>) -> DebounceState<Value, S> {
        var answer = self
        switch (event, timerState) {
        case (.value(let value), .notRunning):
            answer.output = value
            answer.timerState = .running(nil)
            scheduler.schedule(after: scheduler.now.advanced(by: interval), tolerance: .zero, options: options) { [subject] in subject.send() }
        case (.value(let value), .running(_)):
            answer.output = nil
            answer.timerState = .running(.init(value: value, earliestDeliveryTime: scheduler.now.advanced(by: interval)))
        case (.timerFired, .running(nil)):
            answer.output = nil
            answer.timerState = .notRunning
        case (.timerFired, .running(.some(let pendingOutput))):
            let now = scheduler.now
            if pendingOutput.earliestDeliveryTime <= now {
                answer.output = pendingOutput.value
                answer.timerState = .notRunning
            } else {
                answer.output = nil
                scheduler.schedule(after: pendingOutput.earliestDeliveryTime, tolerance: .zero, options: options) { [subject] in subject.send() }
            }
        case (.timerFired, .notRunning):
            // Impossible!
            answer.output = nil
        }
        return answer
    }
}
</code>```

Does it work? Let's test it:

```<code>import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let subject = PassthroughSubject<String, Never>()
let q = DispatchQueue.main
let start = DispatchTime.now()
let cfStart = CFAbsoluteTimeGetCurrent()
q.asyncAfter(deadline: start + .milliseconds(100)) { subject.send("A") }
// A should be delivered at start + 100ms.
q.asyncAfter(deadline: start + .milliseconds(200)) { subject.send("B") }
q.asyncAfter(deadline: start + .milliseconds(300)) { subject.send("C") }
// C should be delivered at start + 800ms.
q.asyncAfter(deadline: start + .milliseconds(1100)) { subject.send("D") }
// D should be delivered at start + 1100ms.
q.asyncAfter(deadline: start + .milliseconds(1800)) { subject.send("E") }
// E should be delivered at start + 1800ms.
q.asyncAfter(deadline: start + .milliseconds(1900)) { subject.send("F") }
q.asyncAfter(deadline: start + .milliseconds(2000)) { subject.send("G") }
// G should be delivered at start + 2500ms.

let ticket = subject
    .kennycDebounce(for: .milliseconds(500), scheduler: q)
    .sink {
        print("\($0) \(((CFAbsoluteTimeGetCurrent() - cfStart) * 1000).rounded())") }
</code>```

Output:

```<code>A 107.0
C 847.0
D 1167.0
E 1915.0
G 2714.0
</code>```

I'm not sure why the later events are so delayed. It could just be playground side effects.

Body:
In Combine, using only the built-in operators, is there a way to skip an operator on the first value but then apply that operator for all subsequent values?

Consider the following:

publisher
  .debounce(...)
  .sink(...)

In this arrangement, debounce will wait for the specified timeout to elapse before passing on the value to sink. However, there are many times when you only want debounce to kick-in after the first element. For example, if the user is trying to filter a list of contacts, it's very possible that they only enter one letter into a text field. If that's the case, the application should probably start filtering immediately, without having to wait for the debounce to timeout.

I'm aware of the Drop publishers, but I can't seem to find a combination of them that will perform more of a "skip" operation such that the sink receives every value, but the debounce is ignored on the first value.

Something like the following:

publisher
  .if_first_element_passthrough_to_sink(...), else_debounce(...)
  .sink(...)

Is something like this possible with the built-in operators?

Clarification

Some clarification since my original posting wasn't as clear as it should have been... The answer provided by Asperi below is very close, but ideally the first element in a sequence is always delivered, then debounce would kick in.

Imagine the user is typing the following:

A B C ... (pauses typing for a few seconds) ... D ... (pauses) ... E F G

What I would like is:

A, D and E are delivered immediately.

B C is coalesced into just C using debounce

F G is coalesced into just G using debounce

Body:
In your particular case of debounce, you might prefer the behavior of throttle. It sends the first element immediately, and then sends no more than one element per interval.

Anyway, can you do it with Combine built-ins? Yes, with some difficulty. Should you? Maybe…

Here's a marble diagram of your goal:

Each time a value goes into the kennyc-debouncer, it starts a timer (represented by a shaded region). If a value arrives while the timer is running, the kennyc-debouncer saves the value and restarts the timer. When the timer expires, if any values arrived while the timer was running, the kennyc-debouncer emits the latest value immediately.

The scan operator allows us to keep state that we mutate each time an input arrives. We need to send two kinds of inputs into scan: the outputs from the upstream publisher, and timer firings. So let's define a type for those inputs:

fileprivate enum DebounceEvent<Value> {
    case value(Value)
    case timerFired
}

What kind of state do we need inside our scan transform? We definitely need the scheduler, the interval, and the scheduler options, so that we can set timers.

We also need a PassthroughSubject we can use to turn timer firings into inputs to the scan operator.

We can't actually cancel and restart a timer, so instead, when the timer fires, we'll see whether it should have been restarted. If so, we'll start another timer. So we need to know whether the timer is running, and what output to send when the timer fires, and the restart time for the timer if restarting is necessary.

Since scan's output is the entire state value, we also need the state to include the output value to send downstream, if any.

Here's the state type:

fileprivate struct DebounceState<Value, S: Scheduler> {
    let scheduler: S
    let interval: S.SchedulerTimeType.Stride
    let options: S.SchedulerOptions?

    let subject = PassthroughSubject<Void, Never>()

    enum TimerState {
        case notRunning
        case running(PendingOutput?)

        struct PendingOutput {
            var value: Value
            var earliestDeliveryTime: S.SchedulerTimeType
        }
    }

    var output: Value? = nil
    var timerState: TimerState = .notRunning
}

Now let's look at how to actually use scan with some other operators to implement the kennyc version of debounce:

extension Publisher {
    func kennycDebounce<S: Scheduler>(
        for dueTime: S.SchedulerTimeType.Stride,
        scheduler: S,
        options: S.SchedulerOptions? = nil
    ) -> AnyPublisher<Output, Failure>
    {
        let initialState = DebounceState<Output, S>(
            scheduler: scheduler,
            interval: dueTime,
            options: options)
        let timerEvents = initialState.subject
            .map { _ in DebounceEvent<Output>.timerFired }
            .setFailureType(to: Failure.self)
        return self
            .map { DebounceEvent.value($0) }
            .merge(with: timerEvents)
            .scan(initialState) { $0.updated(with: $1) }
            .compactMap { $0.output }
            .eraseToAnyPublisher()
    }
}

We start by constructing the initial state for the scan operator.

Then, we create a publisher that turns the Void outputs of the state's PassthroughSubject into .timerFired events.

Finally, we construct our full pipeline, which has four stages:

Turn the upstream outputs (from self) into .value events.

Merge the value events with the timer events.

Use scan to update the debouncing state with the value and timer events. The actual work is done in an updated(with:) method we'll add to DebounceState below.

Map the full state down to just the value we want to pass downstream, and discard nulls (which happen when upstream events get suppressed by debouncing).

All that's left is to write the updated(with:) method. It looks at each incoming event's type (value or timerFired) and the state of the timer to decide what the new state should be and, if necessary, set a new timer.

extension DebounceState {
    func updated(with event: DebounceEvent<Value>) -> DebounceState<Value, S> {
        var answer = self
        switch (event, timerState) {
        case (.value(let value), .notRunning):
            answer.output = value
            answer.timerState = .running(nil)
            scheduler.schedule(after: scheduler.now.advanced(by: interval), tolerance: .zero, options: options) { [subject] in subject.send() }
        case (.value(let value), .running(_)):
            answer.output = nil
            answer.timerState = .running(.init(value: value, earliestDeliveryTime: scheduler.now.advanced(by: interval)))
        case (.timerFired, .running(nil)):
            answer.output = nil
            answer.timerState = .notRunning
        case (.timerFired, .running(.some(let pendingOutput))):
            let now = scheduler.now
            if pendingOutput.earliestDeliveryTime <= now {
                answer.output = pendingOutput.value
                answer.timerState = .notRunning
            } else {
                answer.output = nil
                scheduler.schedule(after: pendingOutput.earliestDeliveryTime, tolerance: .zero, options: options) { [subject] in subject.send() }
            }
        case (.timerFired, .notRunning):
            // Impossible!
            answer.output = nil
        }
        return answer
    }
}

Does it work? Let's test it:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let subject = PassthroughSubject<String, Never>()
let q = DispatchQueue.main
let start = DispatchTime.now()
let cfStart = CFAbsoluteTimeGetCurrent()
q.asyncAfter(deadline: start + .milliseconds(100)) { subject.send("A") }
// A should be delivered at start + 100ms.
q.asyncAfter(deadline: start + .milliseconds(200)) { subject.send("B") }
q.asyncAfter(deadline: start + .milliseconds(300)) { subject.send("C") }
// C should be delivered at start + 800ms.
q.asyncAfter(deadline: start + .milliseconds(1100)) { subject.send("D") }
// D should be delivered at start + 1100ms.
q.asyncAfter(deadline: start + .milliseconds(1800)) { subject.send("E") }
// E should be delivered at start + 1800ms.
q.asyncAfter(deadline: start + .milliseconds(1900)) { subject.send("F") }
q.asyncAfter(deadline: start + .milliseconds(2000)) { subject.send("G") }
// G should be delivered at start + 2500ms.

let ticket = subject
    .kennycDebounce(for: .milliseconds(500), scheduler: q)
    .sink {
        print("\($0) \(((CFAbsoluteTimeGetCurrent() - cfStart) * 1000).rounded())") }

Output:

A 107.0
C 847.0
D 1167.0
E 1915.0
G 2714.0

I'm not sure why the later events are so delayed. It could just be playground side effects.


问:
for loop repeats itself in python
I have created a web bot that iterates over a website e.g example.com/?id=int where int is some integer. the function gets the result in raw html using requests library then hands it to parseAndWrite to extract a div and save its value in a sqlite db:

```<code>def archive(initial_index, final_index):
    while True:
        try:
            for i in range(initial_index, final_index):
                res = requests.get('https://www.example.com/?id='+str(i))
                parseAndWrite(res.text)
                print(i, ' archived')

        except requests.exceptions.ConnectionError:
            print("[-] Connection lost. ")
            continue
        except:
            exit(1)
        break

archive(1, 10000)
</code>```

My problem is that, after some time, the loop doesn't continue to 10000 but repeats itself from a random value, resulting in many duplicate records in the database. What is causing this inconsistency ?

答:
I think your two loops are nested in the wrong order. The outer while loop is supposed to retry any URLs that cause connection errors, but you've put it outside the for loop the iterates over the URL numbers. That means you always start from the initial index whenever an error happens.

Try swapping the loops, and you'll only repeat one URL until it works:

```<code>def archive(initial_index, final_index):
    for i in range(initial_index, final_index):
        while True:
            try:
                res = requests.get('https://www.example.com/?id='+str(i))
                parseAndWrite(res.text)
                print(i, ' archived')

            except requests.exceptions.ConnectionError:
                print("[-] Connection lost. ")
                continue
            except:
                exit(1)
            break

archive(1, 10000)
</code>```

Title: for loop repeats itself in python

Body:
I have created a web bot that iterates over a website e.g example.com/?id=int where int is some integer. the function gets the result in raw html using requests library then hands it to parseAndWrite to extract a div and save its value in a sqlite db:

def archive(initial_index, final_index):
    while True:
        try:
            for i in range(initial_index, final_index):
                res = requests.get('https://www.example.com/?id='+str(i))
                parseAndWrite(res.text)
                print(i, ' archived')

        except requests.exceptions.ConnectionError:
            print("[-] Connection lost. ")
            continue
        except:
            exit(1)
        break

archive(1, 10000)

My problem is that, after some time, the loop doesn't continue to 10000 but repeats itself from a random value, resulting in many duplicate records in the database. What is causing this inconsistency ?

Body:
I think your two loops are nested in the wrong order. The outer while loop is supposed to retry any URLs that cause connection errors, but you've put it outside the for loop the iterates over the URL numbers. That means you always start from the initial index whenever an error happens.

Try swapping the loops, and you'll only repeat one URL until it works:

def archive(initial_index, final_index):
    for i in range(initial_index, final_index):
        while True:
            try:
                res = requests.get('https://www.example.com/?id='+str(i))
                parseAndWrite(res.text)
                print(i, ' archived')

            except requests.exceptions.ConnectionError:
                print("[-] Connection lost. ")
                continue
            except:
                exit(1)
            break

archive(1, 10000)


问:
What does the "?:^" regular expression mean?
I am looking at this sub-expression (this is in JavaScript):

```<code>(?:^|.....)
</code>```

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

答:
?: Generally indicates making the group a non capture.  You can do some research here.

I'm almost positive any regex engine should but when I switch between engines I run into some quirks.

Edit: This should be the case, non captures seems to work fine.

OwnerDisplayName: levik

ContentLicense: CC BY-SA 2.5

Body:
I am looking at this sub-expression (this is in JavaScript):

(?:^|.....)

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

LastEditorDisplayName: levik

OwnerDisplayName: Quintin Robinson


问:
Facing a difficulty in a bubble sort algorithm in C
First of all I am beginner in C, so I am sorry if my question seems stupid.
I was learning how to use the bubble sort algorithm in C, and I came through this code :

```<code>#include <stdio.h>

int main() {
    int ctr, inner, outer, didSwap, temp;
    int nums[10] = {
        78,
        16,
        21,
        7,
        13,
        9,
        22,
        52,
        67,
        19
    };

    //Listing the array before sorting

    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    //Sorting the arrays

    for (outer = 0; outer < 9; outer++) {
        didSwap = 0;
        for (inner = outer; inner < 10; inner++) {
            if (nums[inner] < nums[outer]) {
                temp = nums[inner];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }
        if (didSwap == 0) {
            break;
        }
    }

    //Listing the array after sorting

    printf("\n\nThis is the sorted array\n");
    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    return 0;
}
</code>```

The code works fine, but what I want to understand is how in the second for loop it is written inner = outer, and in the next if statement it is comparing the elements of the array were one of them has the same number as inner and the other has the same number as outer.
And since we said that inner = outer, that means that we are comparing the same element.
The way I think about it is, if outer = 0, and since inner = outer, then inner will be 0 too, so the next if statement will be if (nums[0] < nums[0]) and that doesn't make any sense.

I know that I am probably wrong about it because the code works fine, but what did I think wrong?

Thanks in advance.

答:
The essence of your Bubble Sort is that on each scan the "bubble" is the largest value seen so far, so at the end of the scan, the largest value has "bubbled" to the top.  Then you repeat from the beginning, but each time around (clearly) you have one less value you need to consider.  Also, if at the end of a scan, nothing moved, then everything is in order and you can stop.

So the Bubble Sort might look like this:

```<code>    for (int n = 10 ; n > 0 ; n--)
      {
        bool no_swaps ;

        no_swaps = true ;
        for (int i = 1 ; i < n ; ++i)
          {
            if (nums[i-1] > nums[i])
              {
                int temp ;
                temp = nums[i-1];
                nums[i-1] = nums[i];
                nums[i]   = temp;
                no_swaps = false ;
              } ;
          } ;

        if (no_swaps)
          break ;
      } ;
</code>```

Or:

```<code>    for (int n = 10 ; n > 0 ; n--)
      {
        bool no_swaps ;
        int bubb ;

        no_swaps = true ;
        bubb = nums[0] ;
        for (int i = 1 ; i < n ; ++i)
          {
            int this ;

            this = nums[i] ;
            if (bubb <= this)
              bubb = this ;
            else
              {
                nums[i-1] = this ;
                nums[i]   = bubb ;
                no_swaps = false;
              } ;
          } ;

        if (no_swaps)
          break ;
      } ;
</code>```

which, perhaps, makes it clearer that the eponymous "bubble" (bubb) is the largest value found in the current scan (or the rightmost largest, if have seen 2 or more with that value).

If you remove the didSwap from your sort, it will work fine.  Like Bubble Sort, each pass of your sort moves one item to its final destination.  Your sort always does (n-1)*(n-2)/2 comparisons, which is the same as the worst case for Bubble Sort.  But the Bubble Sort best case is (n-1) -- if the values are already in order !

So a real Bubble Sort has an edge over your sort.  Nevertheless, Bubble Sort is also generally O(n^2) and, therefore, about as useful as a chocolate teapot except when n is small.

Body:
First of all I am beginner in C, so I am sorry if my question seems stupid.
I was learning how to use the bubble sort algorithm in C, and I came through this code :

#include <stdio.h>

int main() {
    int ctr, inner, outer, didSwap, temp;
    int nums[10] = {
        78,
        16,
        21,
        7,
        13,
        9,
        22,
        52,
        67,
        19
    };

    //Listing the array before sorting

    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    //Sorting the arrays

    for (outer = 0; outer < 9; outer++) {
        didSwap = 0;
        for (inner = outer; inner < 10; inner++) {
            if (nums[inner] < nums[outer]) {
                temp = nums[inner];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }
        if (didSwap == 0) {
            break;
        }
    }

    //Listing the array after sorting

    printf("\n\nThis is the sorted array\n");
    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    return 0;
}

The code works fine, but what I want to understand is how in the second for loop it is written inner = outer, and in the next if statement it is comparing the elements of the array were one of them has the same number as inner and the other has the same number as outer.
And since we said that inner = outer, that means that we are comparing the same element.
The way I think about it is, if outer = 0, and since inner = outer, then inner will be 0 too, so the next if statement will be if (nums[0] < nums[0]) and that doesn't make any sense.

I know that I am probably wrong about it because the code works fine, but what did I think wrong?

Thanks in advance.

Body:
The essence of your Bubble Sort is that on each scan the "bubble" is the largest value seen so far, so at the end of the scan, the largest value has "bubbled" to the top.  Then you repeat from the beginning, but each time around (clearly) you have one less value you need to consider.  Also, if at the end of a scan, nothing moved, then everything is in order and you can stop.

So the Bubble Sort might look like this:

    for (int n = 10 ; n > 0 ; n--)
      {
        bool no_swaps ;

        no_swaps = true ;
        for (int i = 1 ; i < n ; ++i)
          {
            if (nums[i-1] > nums[i])
              {
                int temp ;
                temp = nums[i-1];
                nums[i-1] = nums[i];
                nums[i]   = temp;
                no_swaps = false ;
              } ;
          } ;

        if (no_swaps)
          break ;
      } ;

Or:

    for (int n = 10 ; n > 0 ; n--)
      {
        bool no_swaps ;
        int bubb ;

        no_swaps = true ;
        bubb = nums[0] ;
        for (int i = 1 ; i < n ; ++i)
          {
            int this ;

            this = nums[i] ;
            if (bubb <= this)
              bubb = this ;
            else
              {
                nums[i-1] = this ;
                nums[i]   = bubb ;
                no_swaps = false;
              } ;
          } ;

        if (no_swaps)
          break ;
      } ;

which, perhaps, makes it clearer that the eponymous "bubble" (bubb) is the largest value found in the current scan (or the rightmost largest, if have seen 2 or more with that value).

If you remove the didSwap from your sort, it will work fine.  Like Bubble Sort, each pass of your sort moves one item to its final destination.  Your sort always does (n-1)*(n-2)/2 comparisons, which is the same as the worst case for Bubble Sort.  But the Bubble Sort best case is (n-1) -- if the values are already in order !

So a real Bubble Sort has an edge over your sort.  Nevertheless, Bubble Sort is also generally O(n^2) and, therefore, about as useful as a chocolate teapot except when n is small.


问:
DocuSign connect event when a user has viewed the document
I have been digging in the DocuSign Connect documentation and can't seem to find anything. I am wondering if there is a way to send out a Connect event when a recipient has viewed the DocuSign document. Thank you in advanced!</p>

答:
Yes, the Recipient: Delivered status will fire the first time a particular signer views an envelope. Note that you can only track the first time a recipient views the envelope - further events won't fire if the user views the envelope multiple times.

More information is available in the Connect guide: https://docs.docusign.com/supportdocs/ndse-admin-guide/Content/custom-connect-configuration.htm


问:
trouble aligning html headers and td cells
I'm trying to make a small table which can scroll when there are many tr tags under the headers. I have managed to get it to work correctly with just one column but I am struggling to get it to work with more than one column as the columns do not align. It is important that the size of the table stay what it is since I am adding new rows using jQuery and auto scrolling.

I just want the columns of the thead and tbody to align...

Here is what I have so far:

.grid_background_comm {
  background-color: rgb(173, 173, 173);
  padding: 0px;
  margin-left: 10px;
  margin-right: 10px;
  width: 950px;
  height: 90px;
}

.grid_background_comm thead {
  display: block;
  text-align: left;
  width: 950px;
}

.grid_background_comm th {
  padding-left: 4px;
  width: 950px;
}

.grid_comm {
  display: block;
  overflow-y: auto;
  overflow-x: hidden;
  text-align: left;
  width: 950px;
  height: 85px;
}

.grid_comm tr {
  background-color: rgb(231, 231, 231);
  display: block;
  width: 935px;
  margin-left: 3px;
  margin-right: 10px;
  padding-left: 4px;
  padding-right: 4px;
}

.grid_header {
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(44, 44, 44);
  padding: 0px;
  margin: 0px;
  width: 960px;
  height: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table_comm" class="grid_background_comm">
  <thead>
    <th id="1" class='grid_header'>Line</th>
    <th id="2" class='grid_header'>I/O</th>
  </thead>
  <tbody id="gv_comm_data" class="grid_comm">
    <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
  </tbody>
</table></code>```

答:
The display:block is attached to thead and tr which is affecting their default behaviour. You could remove them
https://codepen.io/rohinikumar4073/pen/zYGKqZL

.grid_background_comm {
  background-color: rgb(173, 173, 173);
  padding: 0px;
  margin-left: 10px;
  margin-right: 10px;
  width: 950px;
  height: 90px;
}

.grid_background_comm thead {
  text-align: left;
  width: 950px;
}

.grid_background_comm th {
  padding-left: 4px;
  width: 950px;
}

.grid_comm {
  overflow-y: auto;
  overflow-x: hidden;
  text-align: left;
  width: 950px;
  height: 85px;
}

.grid_comm tr {
  background-color: rgb(231, 231, 231);
  width: 935px;
  margin-left: 3px;
  margin-right: 10px;
  padding-left: 4px;
  padding-right: 4px;
}

.grid_header {
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(44, 44, 44);
  padding: 0px;
  margin: 0px;
  width: 960px;
  height: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table_comm" class="grid_background_comm">
  <thead>
    <tr>
    <th id="1" class='grid_header'>Line</th>
    <th id="2" class='grid_header'>I/O</th>
    </tr>
  </thead>
  <tbody id="gv_comm_data" class="grid_comm">
    <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
    <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
     <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
     <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
  </tbody>
</table></code>```

Body:
I'm trying to make a small table which can scroll when there are many tr tags under the headers. I have managed to get it to work correctly with just one column but I am struggling to get it to work with more than one column as the columns do not align. It is important that the size of the table stay what it is since I am adding new rows using jQuery and auto scrolling.

I just want the columns of the thead and tbody to align...

Here is what I have so far:

.grid_background_comm {
  background-color: rgb(173, 173, 173);
  padding: 0px;
  margin-left: 10px;
  margin-right: 10px;
  width: 950px;
  height: 90px;
}

.grid_background_comm thead {
  display: block;
  text-align: left;
  width: 950px;
}

.grid_background_comm th {
  padding-left: 4px;
  width: 950px;
}

.grid_comm {
  display: block;
  overflow-y: auto;
  overflow-x: hidden;
  text-align: left;
  width: 950px;
  height: 85px;
}

.grid_comm tr {
  background-color: rgb(231, 231, 231);
  display: block;
  width: 935px;
  margin-left: 3px;
  margin-right: 10px;
  padding-left: 4px;
  padding-right: 4px;
}

.grid_header {
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(44, 44, 44);
  padding: 0px;
  margin: 0px;
  width: 960px;
  height: 20px;
}

    Line
    I/O

      01
      02

Body:
The display:block is attached to thead and tr which is affecting their default behaviour. You could remove them
https://codepen.io/rohinikumar4073/pen/zYGKqZL

.grid_background_comm {
  background-color: rgb(173, 173, 173);
  padding: 0px;
  margin-left: 10px;
  margin-right: 10px;
  width: 950px;
  height: 90px;
}

.grid_background_comm thead {
  text-align: left;
  width: 950px;
}

.grid_background_comm th {
  padding-left: 4px;
  width: 950px;
}

.grid_comm {
  overflow-y: auto;
  overflow-x: hidden;
  text-align: left;
  width: 950px;
  height: 85px;
}

.grid_comm tr {
  background-color: rgb(231, 231, 231);
  width: 935px;
  margin-left: 3px;
  margin-right: 10px;
  padding-left: 4px;
  padding-right: 4px;
}

.grid_header {
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(44, 44, 44);
  padding: 0px;
  margin: 0px;
  width: 960px;
  height: 20px;
}

<table id="table_comm" class="grid_background_comm">
  <thead>
    <tr>
    <th id="1" class='grid_header'>Line</th>
    <th id="2" class='grid_header'>I/O</th>
    </tr>
  </thead>
  <tbody id="gv_comm_data" class="grid_comm">
    <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
    <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
     <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
     <tr>
      <td headers="1">01</td>
      <td headers="2">02</td>
    </tr>
  </tbody>
</table>


问:
Raw Data Printing without dialog from PHP / JAVASCRIPT
I am currently adding features to a PHP web application for a client. They require to be able to print some raw data to a ticket / thermal printer direct from the php which will be run on an internet browser from a self service kiosk.

The data needs to printed on the local kiosk's in built ticket printer.

From my preliminary research I understand that I must perform this task using javascript for any client side actions and wondered if anybody knew of any method or example function that will allow the printing of a string to a designated printer / com port which would bypass the printer dialog box?

Thanks in advance for any help

Alex

答:
Not possible, at least not without some extra steps.

Without knowing more about the kiosk environment, you have three main options:

1).  Install a Web service on the local kiosk.  This Web service would manage printing and ultimately be the most extensible solution.

2).  Create a plug-in for the print service.  This would be uglier, and really tie you to a single browser solution forever.

3).  Wrap the browser in custom code to allow external calls.  Again, somewhat ugly, but since you're running a kiosk, you're likely to have some sort of custom/extensible wrapper anyway.