问:
Intent filter activity and proper show of notifications
I'm writing Media files share application.

Now it is divided into 2 parts:

```<code><application>
        <activity android:name="FileUploader"
                  android:label="..."
                  >
            <intent-filter>
                <action android:name="android.intent.action.SEND"/>
                <data android:mimeType="*/*"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

    <service android:name=".FileUploaderService" />

    </application>
</code>```

FileUploader is an activity which should be launched from other activities (eg. Gallery or Camera).
FileUploaderService is a service, which actually uploads file to HTTP server. It executes several HTTP requests.

Now it is possible that user press Home button during uploading and returns to Home screen.
In this case I want to have a notification with current upload stage details which will return user to Activity when tapped.

I'm creatung it like this:

```<code>    int icon = R.drawable.icon;
    CharSequence tickerText = "Uploading File";
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);

    Context context = getApplicationContext();
    CharSequence contentTitle = "Uploading File";
    CharSequence contentText = "Upload in progress. Stage #" + i;

    Intent notificationIntent = new Intent(this, FileUploader.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(context, contentTitle, contentText,
            contentIntent);

    mNM.notify(R.layout.main, notification);
</code>```

The problem is that when I press home button during upload - FileUploader activity instance which was launched from Gallery becomes "stopped" and when I tap notification - 2nd FileUploader activity instance is launched.

So is it any way to "return" to the first activity when tapping notification instead of launch new one?

I've tried following ways but non of them work here:

call finish() in FileUploader.onStop() method - activity is closed when switching from portrait to landscape.

set android:launchMode="singleTask" for FileUploader activity in AndroidManifest.xml - after this my applcation starts to appear in Recent Applications list, which is not acceptable since it allows to launch FileUploader activity from there and as I mentioned above it only should be launched by sending android.intent.action.SEND intent from Gallery/Camera.

Use same intent as was used to launch 1st instance - 2nd instance still created and following warning is in logs:

04-12 17:01:17.041: WARN/ActivityManager(1289): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.intent.action.SEND typ=image/jpeg cmp=.FileUploader bnds=[0,628][480,723] (has extras) }

I've also tried to change line:

```<code>    Context context = getApplicationContext();
</code>```

with

```<code>    Context context = this; // FileUploadServiceContext
</code>```

But this doesn't help.

Hmmm. I thought, maybe I launch wrong activity. Probably I should launch "parent" activity for my FileUploader.
For example: if I launch FileUploader from Gallery, then tap Home, then launch Gallery from Home screen again - I return to my Activity. So I wonder, maybe I need to launch Gallery/Camera from notification. But 2 questions:

how to determine what exactly was the parent of my activity?

what to do if that parent was closed by the system?

答: You can't rely on being able to 'return' to any activity once it's navigated away from by the user. The OS can and may well destroy it so there'll be nothing to return from. I suggest you add extras to your Notification's Intent and recreate the Activity to show the appropriate data from these extras when it's launched.</p>

Body:
I'm writing Media files share application.

Now it is divided into 2 parts:

<application>
        <activity android:name="FileUploader"
                  android:label="..."
                  >
            <intent-filter>
                <action android:name="android.intent.action.SEND"/>
                <data android:mimeType="*/*"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

    <service android:name=".FileUploaderService" />

    </application>

FileUploader is an activity which should be launched from other activities (eg. Gallery or Camera).
FileUploaderService is a service, which actually uploads file to HTTP server. It executes several HTTP requests.

Now it is possible that user press Home button during uploading and returns to Home screen.
In this case I want to have a notification with current upload stage details which will return user to Activity when tapped.

I'm creatung it like this:

    int icon = R.drawable.icon;
    CharSequence tickerText = "Uploading File";
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);

    Context context = getApplicationContext();
    CharSequence contentTitle = "Uploading File";
    CharSequence contentText = "Upload in progress. Stage #" + i;

    Intent notificationIntent = new Intent(this, FileUploader.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(context, contentTitle, contentText,
            contentIntent);

    mNM.notify(R.layout.main, notification);

The problem is that when I press home button during upload - FileUploader activity instance which was launched from Gallery becomes "stopped" and when I tap notification - 2nd FileUploader activity instance is launched.

So is it any way to "return" to the first activity when tapping notification instead of launch new one?

I've tried following ways but non of them work here:

call finish() in FileUploader.onStop() method - activity is closed when switching from portrait to landscape.

set android:launchMode="singleTask" for FileUploader activity in AndroidManifest.xml - after this my applcation starts to appear in Recent Applications list, which is not acceptable since it allows to launch FileUploader activity from there and as I mentioned above it only should be launched by sending android.intent.action.SEND intent from Gallery/Camera.

Use same intent as was used to launch 1st instance - 2nd instance still created and following warning is in logs:

04-12 17:01:17.041: WARN/ActivityManager(1289): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.intent.action.SEND typ=image/jpeg cmp=.FileUploader bnds=[0,628][480,723] (has extras) }

I've also tried to change line:

    Context context = getApplicationContext();

with

    Context context = this; // FileUploadServiceContext

But this doesn't help.

Hmmm. I thought, maybe I launch wrong activity. Probably I should launch "parent" activity for my FileUploader.
For example: if I launch FileUploader from Gallery, then tap Home, then launch Gallery from Home screen again - I return to my Activity. So I wonder, maybe I need to launch Gallery/Camera from notification. But 2 questions:

how to determine what exactly was the parent of my activity?

what to do if that parent was closed by the system?


来源: stackexchange

问:
Pandas: Dealing with a column with multiple data types
I have a column in my dataframe df, which contains values of type float and str:

```<code>df['ESTACD'].unique()

Output:
array([11.0, 32.0, 31.0, 35.0, 37.0, 84.0, 83.0, 81.0, 97.0, 39.0,
   38.0, 40.0, 34.0, 7.0, 17.0, 16.0, 14.0, 82.0, 8.0, '11', '40',
   '31', '39', '68', '97', '32', '33', '37', '38', '83', '84', '93',
   '35', '81', '67', '07', '80', '71', 'A3', '14', '17', '22', '34',
   '36', '82', '08'], dtype=object)
</code>```

I wish to convert all values of this column to type string. Using astype(str) is not enough here since we end up with values like '11.0', '32.0', etc.

The only other way I could think of is using a for loop:

```<code>for i in range(len(df)):
    if (type(df['ESTACD'][i]) == float) or (df['ESTACD'][i].startswith('0')):
        df['ESTACD'][i] = str(int(df['ESTACD'][i]))
</code>```

However, this is very time consuming on large datasets. Is there a way to implement this without a loop?

答:
I think here should be very fast use pure python like:</p>

```<code>df['ESTACD'] = [str(int(x)) if isinstance(x, float) else x for x in df['ESTACD']]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column in my dataframe df, which contains values of type float and str:

df['ESTACD'].unique()

Output:
array([11.0, 32.0, 31.0, 35.0, 37.0, 84.0, 83.0, 81.0, 97.0, 39.0,
   38.0, 40.0, 34.0, 7.0, 17.0, 16.0, 14.0, 82.0, 8.0, '11', '40',
   '31', '39', '68', '97', '32', '33', '37', '38', '83', '84', '93',
   '35', '81', '67', '07', '80', '71', 'A3', '14', '17', '22', '34',
   '36', '82', '08'], dtype=object)

I wish to convert all values of this column to type string. Using astype(str) is not enough here since we end up with values like '11.0', '32.0', etc.

The only other way I could think of is using a for loop:

for i in range(len(df)):
    if (type(df['ESTACD'][i]) == float) or (df['ESTACD'][i].startswith('0')):
        df['ESTACD'][i] = str(int(df['ESTACD'][i]))

However, this is very time consuming on large datasets. Is there a way to implement this without a loop?

Body:
I think here should be very fast use pure python like:

df['ESTACD'] = [str(int(x)) if isinstance(x, float) else x for x in df['ESTACD']]


问:
javascript pass html input type id to function
Suppose I have a list of the following HTML elements with a Javascript event to copy the content of the HTML input type text into the clipboard:

```<code><input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>
</code>```

etc..

How do I copy the txt using javascript?

I am trying to tweak the code below but I can't figure out how to pass the HTML id to the javascript code. I know the getElementById() is not correct in that context and shouldn't be called. But I don't know how to carry the id value across into the Javascript function.

```<code><script>
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
</script>
</code>```

Any help would be greatly appreciated.

Thank you

答:
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById(myInput) // pass dynamic value here

console.log(copyText)
  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button></code>```

Body:
Suppose I have a list of the following HTML elements with a Javascript event to copy the content of the HTML input type text into the clipboard:

<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>

etc..

How do I copy the txt using javascript?

I am trying to tweak the code below but I can't figure out how to pass the HTML id to the javascript code. I know the getElementById() is not correct in that context and shouldn't be called. But I don't know how to carry the id value across into the Javascript function.

Any help would be greatly appreciated.

Thank you

Body:
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById(myInput) // pass dynamic value here

console.log(copyText)
  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}

<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>


问:
How do I run a shell script without using "sh" or "bash" commands?
I have a shell script which I want to run without using the "sh" or "bash" commands. For example:

Instead of: sh script.sh

I want to use: script.sh

How can I do this?

P.S. (i) I don't use shell script much and I tried reading about aliases, but I did not understand how to use them.

(ii) I also read about linking the script with another file in the PATH variables. I am using my  university server and I don't have permissions to create a file in those locations.

答:
Just:</p>

```<code>/path/to/file/my_script.sh
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just:

/path/to/file/my_script.sh


问:
Ruby on Rails [heroku] git push heroku master error
I am trying to upload my web app on heroku, but the following error occurs.

(I'm coding with cloud 9 IDE)

```<code>$ git push heroku master
.....
remote: -----> Installing node-v10.14.1-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-05-22T02:13:47.373334 #1766]  INFO -- : Writing
/tmp/build_fcc84922ee6a02bfc05a163c871d0548/public/assets/noimage-
3aa3997354b4e9c37f379deb61626f55ade493078d1b42dcefe4a3ccbed34106.jpg
remote:        rake aborted!
remote:        ExecJS::RuntimeError: SyntaxError: Unexpected character '`'
remote:        JS_Parse_Error.get ((execjs):3538:621)
remote:        (execjs):4060:48
remote:        (execjs):1:102
.....
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
</code>```

First of all, It says that "there Yarn executable was not detected in the system", but it is properly downloaded if I check it with yarn -v.

Also, ExecJS :: RuntimeError: SyntaxError: Unexpected character '`' error seems to be that es6 is not recognized, as a solution

config.assets.js_compressor =: uglifier

config.assets.js_compressor = Uglifier.new (harmony: true)

Changed to This seems to be able to read es6. But the above error still persists.

Also, if I run 'rake assets: precompile RAILS_ENV = production' on the console, it runs normally without error.

Thanks.

答:
config.assets.js_compressor =: uglifier

=: uglifier
space between : and uglifier?

should be = :uglifier

and try to use precompile command without string RAILS_ENV = production
because Heroku installs production mode by default. if I'm not mistaken

Body:
I am trying to upload my web app on heroku, but the following error occurs.

(I'm coding with cloud 9 IDE)

$ git push heroku master
.....
remote: -----> Installing node-v10.14.1-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-05-22T02:13:47.373334 #1766]  INFO -- : Writing
/tmp/build_fcc84922ee6a02bfc05a163c871d0548/public/assets/noimage-
3aa3997354b4e9c37f379deb61626f55ade493078d1b42dcefe4a3ccbed34106.jpg
remote:        rake aborted!
remote:        ExecJS::RuntimeError: SyntaxError: Unexpected character '`'
remote:        JS_Parse_Error.get ((execjs):3538:621)
remote:        (execjs):4060:48
remote:        (execjs):1:102
.....
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.

First of all, It says that "there Yarn executable was not detected in the system", but it is properly downloaded if I check it with yarn -v.

Also, ExecJS :: RuntimeError: SyntaxError: Unexpected character '`' error seems to be that es6 is not recognized, as a solution

config.assets.js_compressor =: uglifier

config.assets.js_compressor = Uglifier.new (harmony: true)

Changed to This seems to be able to read es6. But the above error still persists.

Also, if I run 'rake assets: precompile RAILS_ENV = production' on the console, it runs normally without error.

Thanks.


问:
mongoDB atlas scaling with AWS regions
I have 6 EC2 Instances on different region on AWS. I have only one MongoDB server on MongoDB Atlas (AWS). I am having latency issue while updating Data to the database. what is the best way to scale my MongoDB server with My 6 EC2 instances.</p>

答:
You can try one way you can apply the VPC peering from EC2 to MongoDB Atlas (AWS). As MongoDB Atlas as now VPC peering function.

If you are trying to connect the MongoDB using public-facing network, then it might be slow.

AWS launched instances in a different region may create a connection using inter-region cross VPC peering.

So if you are following tradition way to whitelisting  ACL's better try this it will reduce latency issue.please peer all the region's VPC (make sure there will not be any IP conflict) and try to connect using private connections.

EDIT : 1

There is no additional penalty with MongoDB in terms of using it out of region, but most database protocols are not optimized for high latency conditions. You might be much better off setting up a read replica in other regions.

You can read this: https://www.mongodb.com/blog/post/optimizing-fast-responsive-reads-cross-region-replication-mongodb-atlas

EDIT : 2

If you can't push your database to multiple regions (by using read replicas for example), then you should consider using CloudFront in front of your application(website) to allow for caching of requests in the different regions.

It won't technically improve the latency between application and database, but in terms of your user's perception of performance, it will be little speedy.

Title: mongoDB atlas scaling with AWS regions


问:
How to fix "element is not attached to the page document/element not interactable"?
I'm setting up a function that auto scrolls and auto likes on Instagram but when i try run it, it either comes up with an error that element not interactable or element is not attached to the page document

I tried the time.sleep and driver.implicitly_wait to check if it because the elements haven't loaded yet

```<code>      html = self.driver.find_element_by_tag_name('html')
      while True:
          button = self.driver.find_element_by_class_name('_9AhH0')
          time.sleep(0.5)
          html.send_keys(Keys.PAGE_DOWN)
          time.sleep(0.5)
          try:
              button.send_keys(Keys.ENTER)
              print("Like")
          except Exception as e:
              print(e)
</code>```

答:
Try adding a wait condition before interacting with the element:</p>

```<code>from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

button= WebDriverWait(driver, 20).until(
 expected_conditions.presence_of_element_located(By.CSS_SELECTOR, "._9AhH0")).send_keys(Keys.ENTER)
</code>```

Body:
I'm setting up a function that auto scrolls and auto likes on Instagram but when i try run it, it either comes up with an error that element not interactable or element is not attached to the page document

I tried the time.sleep and driver.implicitly_wait to check if it because the elements haven't loaded yet

      html = self.driver.find_element_by_tag_name('html')
      while True:
          button = self.driver.find_element_by_class_name('_9AhH0')
          time.sleep(0.5)
          html.send_keys(Keys.PAGE_DOWN)
          time.sleep(0.5)
          try:
              button.send_keys(Keys.ENTER)
              print("Like")
          except Exception as e:
              print(e)

Body:
Try adding a wait condition before interacting with the element:

from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

button= WebDriverWait(driver, 20).until(
 expected_conditions.presence_of_element_located(By.CSS_SELECTOR, "._9AhH0")).send_keys(Keys.ENTER)


问:
Looking for a PHP to Excel library

Possible Duplicate:

  Alternative for PHP_excel

I'm looking for a lightweight and fast PHP Excel writer. I need to export Excel files up to 50000 rows. I've tried PHPExcel, but it is far too slow and memory-intensive.

It's only data, so formatting is not necessary.

Another requirement is that fields are often bigger than 255 characters. A lot of solutions I found don't support this.

Any suggestions?

答:
You could try these projects:

http://code.google.com/p/php-excel/

http://phpexcel.codeplex.com/ (Excel 2007)

Title: Looking for a PHP to Excel library


问:
How to filter missing inner key by using jq
Got a json input like this:

```<code>[
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322460000,
      "value": "0.0"
    }
  },
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322160000,
      "value": "0.0"
    }
  },
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": "3423.25"
  }
]
</code>```

The third object doesnot have a timestamp on it. How could I return all the object only have a timestamp on it. Like the following:

```<code>[
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322460000,
      "value": "0.0"
    }
  },
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322160000,
      "value": "0.0"
    }
  }
]
</code>```

Many thanks in advance.

Cheers,
Vincent

答:
Working example:
[ .[] | select (.values | has("timestamp")?) ]

https://jqplay.org/s/n5jsRsPMhW

Or alternative:
[ .[] | select (.values.timestamp?) ]

https://jqplay.org/s/HRWV44YgUp

P.S. This one was incorrect because of after .[] you are working with each item separately, not with array. So 'map' function is unnecessary.

Body:
Got a json input like this:

[
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322460000,
      "value": "0.0"
    }
  },
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322160000,
      "value": "0.0"
    }
  },
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": "3423.25"
  }
]

The third object doesnot have a timestamp on it. How could I return all the object only have a timestamp on it. Like the following:

[
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322460000,
      "value": "0.0"
    }
  },
  {
    "dimensions": "helloworld",
    "metrics": "sum(is_error)",
    "values": {
      "timestamp": 1558322160000,
      "value": "0.0"
    }
  }
]

Many thanks in advance.

Cheers,
Vincent


问:
Gem install ffi Failed to build gem native extension
I'm having troubles to do bundle install in one project I get to work on in Rails 4.2.10. When I bundle I receive the next error:

An error occurred while installing ffi (1.9.25), and Bundler cannot continue.
Make sure that gem install ffi -v '1.9.25' succeeds before bundling.

```<code>In Gemfile:
  s3_direct_upload was resolved to 0.1.6, which depends on
    sass-rails was resolved to 5.0.7, which depends on
      sass was resolved to 3.6.0, which depends on
        sass-listen was resolved to 4.0.0, which depends on
          rb-inotify was resolved to 0.9.10, which depends on
            ffi
</code>```

When I run gem install ffi -v '1.9.25' also an error occurs:

```<code>Building native extensions. This could take a while...
ERROR:  Error installing ffi:
    ERROR: Failed to build gem native extension.

    current directory: /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c
/xxx/xxx/.rvm/rubies/ruby-2.5.3/bin/ruby -r ./siteconf20190110-6923-1jimorr.rb extconf.rb
checking for ffi.h... no
checking for ffi.h in /usr/local/include,/usr/include/ffi... yes
checking for ffi_call() in -lffi... yes
checking for ffi_closure_alloc()... no
checking for ffi_raw_call()... no
checking for shlwapi.h... no
checking for ruby/thread.h... yes
checking for rb_thread_blocking_region()... no
checking for rb_thread_call_with_gvl()... yes
checking for rb_thread_call_without_gvl()... yes
creating extconf.h
creating Makefile

current directory: /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c
make "DESTDIR=" clean

current directory: /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c
make "DESTDIR="
Configuring libffi
clang: error: unsupported option '-print-multi-os-directory'
clang: error: no input files
cd "/xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c/libffi-x86_64-darwin18" && /Volumes/Macintosh HD/Applications/Xcode.app/Contents/Developer/usr/bin/make
/bin/sh: /Volumes/Macintosh: No such file or directory
make: *** ["/xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c/libffi-x86_64-darwin18"/.libs/libffi_convenience.a] Error 127

make failed, exit code 2

Gem files will remain installed in /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25 for inspection.
Results logged to /xxx/xxx/.rvm/gems/ruby-2.5.3/extensions/x86_64-darwin-18/2.5.0/ffi-1.9.25/gem_make.out
</code>```

I've been trying many solutions online but cannot resolve this issue.
Seems the issue is with my system as I'm new to the team and the other developers were unable to help me as they do not have this kind of issue.

答:
I was able to successfully install ffi with the following command:

```<code>LDFLAGS="-L/usr/local/opt/libffi/lib" PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig" gem install ffi -v '1.9.25'
</code>```

Found on some japanese board

Body:
I'm having troubles to do bundle install in one project I get to work on in Rails 4.2.10. When I bundle I receive the next error:

An error occurred while installing ffi (1.9.25), and Bundler cannot continue.
Make sure that gem install ffi -v '1.9.25' succeeds before bundling.

In Gemfile:
  s3_direct_upload was resolved to 0.1.6, which depends on
    sass-rails was resolved to 5.0.7, which depends on
      sass was resolved to 3.6.0, which depends on
        sass-listen was resolved to 4.0.0, which depends on
          rb-inotify was resolved to 0.9.10, which depends on
            ffi

When I run gem install ffi -v '1.9.25' also an error occurs:

Building native extensions. This could take a while...
ERROR:  Error installing ffi:
    ERROR: Failed to build gem native extension.

    current directory: /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c
/xxx/xxx/.rvm/rubies/ruby-2.5.3/bin/ruby -r ./siteconf20190110-6923-1jimorr.rb extconf.rb
checking for ffi.h... no
checking for ffi.h in /usr/local/include,/usr/include/ffi... yes
checking for ffi_call() in -lffi... yes
checking for ffi_closure_alloc()... no
checking for ffi_raw_call()... no
checking for shlwapi.h... no
checking for ruby/thread.h... yes
checking for rb_thread_blocking_region()... no
checking for rb_thread_call_with_gvl()... yes
checking for rb_thread_call_without_gvl()... yes
creating extconf.h
creating Makefile

current directory: /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c
make "DESTDIR=" clean

current directory: /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c
make "DESTDIR="
Configuring libffi
clang: error: unsupported option '-print-multi-os-directory'
clang: error: no input files
cd "/xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c/libffi-x86_64-darwin18" && /Volumes/Macintosh HD/Applications/Xcode.app/Contents/Developer/usr/bin/make
/bin/sh: /Volumes/Macintosh: No such file or directory
make: *** ["/xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25/ext/ffi_c/libffi-x86_64-darwin18"/.libs/libffi_convenience.a] Error 127

make failed, exit code 2

Gem files will remain installed in /xxx/xxx/.rvm/gems/ruby-2.5.3/gems/ffi-1.9.25 for inspection.
Results logged to /xxx/xxx/.rvm/gems/ruby-2.5.3/extensions/x86_64-darwin-18/2.5.0/ffi-1.9.25/gem_make.out

I've been trying many solutions online but cannot resolve this issue.
Seems the issue is with my system as I'm new to the team and the other developers were unable to help me as they do not have this kind of issue.

Body:
I was able to successfully install ffi with the following command:

LDFLAGS="-L/usr/local/opt/libffi/lib" PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig" gem install ffi -v '1.9.25'

Found on some japanese board


问:
Join All dataframes which names starts with df
I've multiple dataframes (with exacly the same structure, same variables...) and they all starts with "df_".

What I would like to do is to join all these dataframes into one.

I can do it manually, but I have many data frames and their names can change.

```<code>
frames = [df_24_10000, df_48_10000, df_64_20000, df_82_30000]

result = pd.concat(frames)

</code>```

Is it possible to join all data frames that starts with "df_"?

答:
This is normally the sign of a design problem. If you find yourself trying to group a number of objects by their names, it means that should have been elements of the same container (list, dict, set, map or whatever) from the very beginning.

Said differently, if instead of df_24_10000, df_48_10000, df_64_20000, you had dfs['24_10000'], dfs['48_10000'], dfs['64_20000'], the join would simply be:

```<code>result = pd.concat(dfs.values)
</code>```

Body:
I've multiple dataframes (with exacly the same structure, same variables...) and they all starts with "df_".

What I would like to do is to join all these dataframes into one.

I can do it manually, but I have many data frames and their names can change.

frames = [df_24_10000, df_48_10000, df_64_20000, df_82_30000]

result = pd.concat(frames)

Is it possible to join all data frames that starts with "df_"?

Body:
This is normally the sign of a design problem. If you find yourself trying to group a number of objects by their names, it means that should have been elements of the same container (list, dict, set, map or whatever) from the very beginning.

Said differently, if instead of df_24_10000, df_48_10000, df_64_20000, you had dfs['24_10000'], dfs['48_10000'], dfs['64_20000'], the join would simply be:

result = pd.concat(dfs.values)


问:
PHP - How to sort multidimensional array by Key?
I have to sort multidimensional array by key and I need some recomendation how to do it.

I tried using ksort() and other php built-in functions, but none of them helped me.

This is my array, which I want to sort by key:

```<code>Array
(
[0] => Array
    (
        [20190529] => Array
            (
                [30] => Array
                    (
                        [17] => Array
                            (
                                [3846] => 0
                            )

                    )

            )

    )

[1] => Array
    (
        [20190516] => Array
            (
                [31] => Array
                    (
                        [17] => Array
                            (
                                [512] => 0
                            )

                    )

            )

    )
</code>```

)

In that case, keys are 20190529 and 20190516

答:
Working demo.

You can use array_multisort to achieve your requirement.

```<code>$keys = [];
foreach($arr as $k => $item){
    $keys[] = key($item);
}
array_multisort($keys, SORT_NATURAL, $arr);
</code>```

array_multisort — Sort multiple or multi-dimensional arrays

SORT_NATURAL - compare items as strings using "natural ordering" like natsort().

Body:
I have to sort multidimensional array by key and I need some recomendation how to do it.

I tried using ksort() and other php built-in functions, but none of them helped me.

This is my array, which I want to sort by key:

Array
(
[0] => Array
    (
        [20190529] => Array
            (
                [30] => Array
                    (
                        [17] => Array
                            (
                                [3846] => 0
                            )

                    )

            )

    )

[1] => Array
    (
        [20190516] => Array
            (
                [31] => Array
                    (
                        [17] => Array
                            (
                                [512] => 0
                            )

                    )

            )

    )

)

In that case, keys are 20190529 and 20190516

Body:
Working demo.

You can use array_multisort to achieve your requirement.

$keys = [];
foreach($arr as $k => $item){
    $keys[] = key($item);
}
array_multisort($keys, SORT_NATURAL, $arr);

array_multisort — Sort multiple or multi-dimensional arrays

SORT_NATURAL - compare items as strings using "natural ordering" like natsort().


问:
How to extend my endpoint with /download/?
My code looks like this:

```<code># models.py
class Recording(models.Model):
    title = . . .
    duration = . . .

# views.py
class RecordingViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = RecordingSerializer
    . . .

# urls.py
router = routers.DefaultRouter()
router.register(r'recordings', RecordingViewSet, base_name='recordings')
</code>```

How can I extend my endpoint to create a /recordings/X/ endpoint? (in my case X = download)

答:
You can change your current urls.py to create an endpoint with a ViewSet that deals with downloading.

You can create this endpoint by adding:

```<code>router.register(r'recordings/download', RecordingViewSet, base_name='recordings/download')
</code>```

When going to /recordings/download/ whatever functionality you have in RecordingViewSet will run.

You can also keep /recordings and assign a different ViewSet to that endpoint like this:

```<code>router.register(r'recordings', SomeViewSet, base_name='recordings')
</code>```

DRF-Docs about how routers in django-rest-framework work.

Body:
My code looks like this:

# models.py
class Recording(models.Model):
    title = . . .
    duration = . . .

# views.py
class RecordingViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = RecordingSerializer
    . . .

# urls.py
router = routers.DefaultRouter()
router.register(r'recordings', RecordingViewSet, base_name='recordings')

How can I extend my endpoint to create a /recordings/X/ endpoint? (in my case X = download)

Body:
You can change your current urls.py to create an endpoint with a ViewSet that deals with downloading.

You can create this endpoint by adding:

router.register(r'recordings/download', RecordingViewSet, base_name='recordings/download')

When going to /recordings/download/ whatever functionality you have in RecordingViewSet will run.

You can also keep /recordings and assign a different ViewSet to that endpoint like this:

router.register(r'recordings', SomeViewSet, base_name='recordings')

DRF-Docs about how routers in django-rest-framework work.


问:
FITS Export with custom Metadata
does anybody has experience in exporting data as a FITS file with custom Metadata (FITS header) information? So far I was only able to generate FITS files with the standard Mathematica FITS header template. The documentation gives no hint on whether custom Metadata export is supported and how it might be done.

The following suggestions from comp.soft-sys.math.mathematica do not work:

```<code>header=Import[<some FITS file>, "Metadata"];
Export<"test.fits",data ,"Metadata"->header]
</code>```

or

```<code>Export["test.fits",{"Data"->data,"Metadata"->header}]
</code>```

What is the proper way to export my own Metadata to a FITS file ?

Cheers,

Markus

Update: response from Wolfram Support:
"Mathematica does not yet support Export of metadata for FITS file.  The
example are referring to importing of this data.  We do plan to support
this in the future..."
"There are also plans to include binary tables into FITS import
functionality."

I will try to come up with some workaround.

答:
According to the documentation for v.7 and v.8, there is a couple of ways of accomplishing what you want, and you almost have the rule form correct:

```<code>Export["test.fits", {"Data" -> data, "Metadata" -> header}, "Rules"]
</code>```

The other ways are

```<code>Export["test.fits", header, "Metadata"]
Export["test.fits", {data, header}, {{"Data", "Metadata"}}]
</code>```

note the double brackets around the element labels in the second method.

Edit: After some testing, due to prodding from @belisarius, whenever I include the "Metadata" element, I get an error stating that it is not a valid export element. Also, you can't export a "RawData" element, either.  So, I'd submit a bug for two reasons: the metadata isn't user settable which is vitally important for any serious application.  At a minimum, the user should at least be able to augment the default Mathematica metadata. Second, the documentation is woefully inadequate in describing what is a "valid" export element vs. import element. Of course, I'd describe all of the documentation for v.6 and beyond as woefully inadequate, so this is par for the course.

Title: FITS Export with custom Metadata

Body:
does anybody has experience in exporting data as a FITS file with custom Metadata (FITS header) information? So far I was only able to generate FITS files with the standard Mathematica FITS header template. The documentation gives no hint on whether custom Metadata export is supported and how it might be done.

The following suggestions from comp.soft-sys.math.mathematica do not work:

header=Import[<some FITS file>, "Metadata"];
Export<"test.fits",data ,"Metadata"->header]

or

Export["test.fits",{"Data"->data,"Metadata"->header}]

What is the proper way to export my own Metadata to a FITS file ?

Cheers,

Markus

Update: response from Wolfram Support:
"Mathematica does not yet support Export of metadata for FITS file.  The
example are referring to importing of this data.  We do plan to support
this in the future..."
"There are also plans to include binary tables into FITS import
functionality."

I will try to come up with some workaround.

Body:
According to the documentation for v.7 and v.8, there is a couple of ways of accomplishing what you want, and you almost have the rule form correct:

Export["test.fits", {"Data" -> data, "Metadata" -> header}, "Rules"]

The other ways are

Export["test.fits", header, "Metadata"]
Export["test.fits", {data, header}, {{"Data", "Metadata"}}]

note the double brackets around the element labels in the second method.

Edit: After some testing, due to prodding from @belisarius, whenever I include the "Metadata" element, I get an error stating that it is not a valid export element. Also, you can't export a "RawData" element, either.  So, I'd submit a bug for two reasons: the metadata isn't user settable which is vitally important for any serious application.  At a minimum, the user should at least be able to augment the default Mathematica metadata. Second, the documentation is woefully inadequate in describing what is a "valid" export element vs. import element. Of course, I'd describe all of the documentation for v.6 and beyond as woefully inadequate, so this is par for the course.


问:
Apollo Server health check not getting called
This is a basic issue which I followed the documentation and it is not working as expected, please shed some light.

So, I am creating a grapqhl server with Apollo-Server and trying to get the health-check url working that is given here https://www.apollographql.com/docs/apollo-server/features/health-checks

Here is the code:

```<code>const { ApolloServer, makeExecutableSchema } = require('apollo-server')

const typeDefs = require('./schema/types/')
const resolvers = require('./schema/resolvers/')
const schema = makeExecutableSchema({ typeDefs, resolvers })
const server = new ApolloServer({
  schema,
  onHealthCheck: () => new Promise((resolve) => { console.log('hc called'); resolve() })
})
server
  .listen({ port: 5000 })
  .then(({ url }) => console.log(`  Server ready at ${url}`))
  .catch(() => console.log('error'))
</code>```

As I start the server I get this log:

```<code>  Server ready at http://localhost:5000/
</code>```

And also, I am able to see the Schema in graphql-playground as well, which means my typeDefs and resolvers are fine, but when I ping the url:

{server_address}:5000/.well-known/apollo/server-health

I am getting the output as:

```<code>{
   "status": "pass"
}
</code>```

Without any log saying: hc called which I added in the code for key named 'onHealthCheck' and for now I resolved it as well, as per the docs.

So where is the problem and what I missed, please shed some light.
Happy coding :)

PS: I am using apollo-server 2.5.0 version which I think very recently updated with onHealthCheck fix for onHealthCheck not getting called

答: The fix was just merged into master 6 days ago. You need to update to a later version, like 2.6.0-alpha.8.

Body:
This is a basic issue which I followed the documentation and it is not working as expected, please shed some light.

So, I am creating a grapqhl server with Apollo-Server and trying to get the health-check url working that is given here https://www.apollographql.com/docs/apollo-server/features/health-checks

Here is the code:

const { ApolloServer, makeExecutableSchema } = require('apollo-server')

const typeDefs = require('./schema/types/')
const resolvers = require('./schema/resolvers/')
const schema = makeExecutableSchema({ typeDefs, resolvers })
const server = new ApolloServer({
  schema,
  onHealthCheck: () => new Promise((resolve) => { console.log('hc called'); resolve() })
})
server
  .listen({ port: 5000 })
  .then(({ url }) => console.log(`  Server ready at ${url}`))
  .catch(() => console.log('error'))

As I start the server I get this log:

  Server ready at http://localhost:5000/

And also, I am able to see the Schema in graphql-playground as well, which means my typeDefs and resolvers are fine, but when I ping the url:

{server_address}:5000/.well-known/apollo/server-health

I am getting the output as:

{
   "status": "pass"
}

Without any log saying: hc called which I added in the code for key named 'onHealthCheck' and for now I resolved it as well, as per the docs.

So where is the problem and what I missed, please shed some light.
Happy coding :)

PS: I am using apollo-server 2.5.0 version which I think very recently updated with onHealthCheck fix for onHealthCheck not getting called


问:
Telegram bot sendMessage problem. Parse_mode='HTML' is not working
I want to send a message from Telegram Bot to user with parse_mode 'HTML' . I use node.js with telegram.bot.api. But I've got an error

I've tried to write a code without parse_mode='HTML'. And it is working. But if I only add parse_mode=''(html or markdown) node.js show me: "error: [polling_error] {}"

Wrong code:

```<code>   const chatId=msg.chat.id;
   if (msg.text=='test'){
       bot.sendMessage(chatId,'<b>TEST</b>', parse_mode='HTML');
       return;
      }
})
</code>```

Working code

```<code>    const chatId=msg.chat.id;
    if (msg.text=='test'){
        bot.sendMessage(chatId,'<b>TEST</b>');
        return;
       }
})
</code>```

I cant find any solution and info about parse_mode='HTML' and "error: [polling_error] {}".

答:
Try sending the parse mode as on object;

```<code>bot.sendMessage(chatId, '<b>TEST</b>', {parse_mode: 'HTML'});
</code>```

Git issue

More info (Git)

Body:
I want to send a message from Telegram Bot to user with parse_mode 'HTML' . I use node.js with telegram.bot.api. But I've got an error

I've tried to write a code without parse_mode='HTML'. And it is working. But if I only add parse_mode=''(html or markdown) node.js show me: "error: [polling_error] {}"

Wrong code:

   const chatId=msg.chat.id;
   if (msg.text=='test'){
       bot.sendMessage(chatId,'TEST', parse_mode='HTML');
       return;
      }
})

Working code

    const chatId=msg.chat.id;
    if (msg.text=='test'){
        bot.sendMessage(chatId,'TEST');
        return;
       }
})

I cant find any solution and info about parse_mode='HTML' and "error: [polling_error] {}".

Body:
Try sending the parse mode as on object;

bot.sendMessage(chatId, '<b>TEST</b>', {parse_mode: 'HTML'});

Git issue

More info (Git)


问:
Question about Self Joins. Seeing if two users interacted
I was given a SQL assignment that is the following table simulating a dating app: Table name = dating

```<code>user_id | viewing_profile_id | date | liked
   1              2             x       yes
   1              3             x       yes
   2              1             x       yes
   2              3             x       no
   3              1             x       no
   3              2             x       no
</code>```

essentially I want to see the % of profiles that match each other. a match is when both profiles like each other.

I think I know what I have to do. Perform a Self join onto the table itself and use a case when for when the profiles like each other.

```<code>select t.date, sum(t.match) / count(t.match) as p_match
from (
select s1.user_id, s1.viewing_profile_id,
date_trunc('day',s1.date) as date, case when s1.liked = 'yes'
and s2.liked = 'yes' then 1 else 0 end as match
from dating s1
left join dating s2 on s2.ser_id = s1.viewing_profile_id
group by 1,2) t
group by 1
</code>```

Since this is just a made up table, and I do not have any data execute this on, I was wondering if I can get some insight into whether or not this would work.

I am expecting the subquery to produce something like the following:

```<code>user_id | viewing_profile_id | date | match
   1              2             x       1
   1              3             x       0
   2              1             x       1
   2              3             x       0
   3              1             x       0
   3              2             x       0
</code>```

答:
If you just want a flag specifying whether the reverse matches, then:</p>

```<code>select d.*,
       (exists (select 1
                from dating d2
                where d2.user_id = d.viewing_profile_id and
                      d2.viewing_profile_id = d.user_id and
                      d2.liked = 'yes'
               ) and
        d.liked = 'yes'
       ) as match
from dating d;
</code>```

Body:
I was given a SQL assignment that is the following table simulating a dating app: Table name = dating

user_id | viewing_profile_id | date | liked
   1              2             x       yes
   1              3             x       yes
   2              1             x       yes
   2              3             x       no
   3              1             x       no
   3              2             x       no

essentially I want to see the % of profiles that match each other. a match is when both profiles like each other.

I think I know what I have to do. Perform a Self join onto the table itself and use a case when for when the profiles like each other.

select t.date, sum(t.match) / count(t.match) as p_match
from (
select s1.user_id, s1.viewing_profile_id,
date_trunc('day',s1.date) as date, case when s1.liked = 'yes'
and s2.liked = 'yes' then 1 else 0 end as match
from dating s1
left join dating s2 on s2.ser_id = s1.viewing_profile_id
group by 1,2) t
group by 1

Since this is just a made up table, and I do not have any data execute this on, I was wondering if I can get some insight into whether or not this would work.

I am expecting the subquery to produce something like the following:

user_id | viewing_profile_id | date | match
   1              2             x       1
   1              3             x       0
   2              1             x       1
   2              3             x       0
   3              1             x       0
   3              2             x       0

Body:
If you just want a flag specifying whether the reverse matches, then:

select d.*,
       (exists (select 1
                from dating d2
                where d2.user_id = d.viewing_profile_id and
                      d2.viewing_profile_id = d.user_id and
                      d2.liked = 'yes'
               ) and
        d.liked = 'yes'
       ) as match
from dating d;


答:
You want to group by replaced string, using te.alias_id will group by original value, And using alias_id will still group by original value as column names preceeds column alias.

So,

Use another column alias and use it in GROUP BY clause

or use the same replace expression in GROUP BY clause

or use column number syntax:

```<code>SELECT contract
     , REGEXP_SUBSTR(alias_id, '.+?(?=_rebate|$)') as alias_id
     , round(sum(sum),2) sum
FROM yt_report
GROUP BY contract, 2
</code>```

Title: MySQL group by field received with regex

Body:
From initinal table with a transaction id and transaction sum I need to receive total sums grouped by ids.

The twist is that ids may or may not have a '_rebate' suffix appended to them.

I basically need to ignore it and I can remove it with regex, but then GROUP BY stops working.

That is,
query

SELECT contract, REGEXP_SUBSTR(alias_id, '.+?(?=_rebate|$)') as alias_id, sum
FROM yt_reportLIMIT 10

returns

+-----------+----------------------------------+-------+
| contract  | alias_id                         | sum   |
+-----------+----------------------------------+-------+
| 187453/19 | 758ad57482d621f9b54d67f07b543f46 |  70.8 |
| 187453/19 | 3df373604d0b3f38aca283083468efd5 | 146.4 |
| 187453/19 | 3c6caf755f4e16c798c262ed06a735b3 |  70.8 |
| 187453/19 | 197358f0e522224f9a4e0b24ec265cfc | 139.2 |
| 187453/19 | 0815b324b5e81a199a984442f4d42bc8 |  93.6 |
| 187453/19 | 9e5203f585d622b0a95fc31c2e1a19be | 153.6 |
| 187453/19 | d1e1bbd7302233deac6e18107cac541f |  87.6 |
| 187453/19 | dd92fae2fc9c1fc7b208821f2f913724 | 127.2 |
| 187453/19 | b250e741e4e118fe8289e37f4bfd8523 | 148.8 |
| 187453/19 | 7bf53c61ca61162cb6f1406992acfdff |    96 |
+-----------+----------------------------------+-------+

but

SELECT te.contract, te.alias_id, ROUND(SUM(te.sum),2) as b_sum
FROM
(SELECT contract, REGEXP_SUBSTR(alias_id, '.+?(?=_rebate|$)') as alias_id, sum
FROM yt_report LIMIT 10) as te
GROUP BY te.alias_id, te.contract LIMIT 10

returns

+-----------+----------+---------+
| contract  | alias_id | b_sum   |
+-----------+----------+---------+
| 187453/19 |          | 1134.00 |
+-----------+----------+---------+

There are no NULL ids in the table. Looks like querying a regex processed field from subquery does not work.

How can this be solved?

Body:
You want to group by replaced string, using te.alias_id will group by original value, And using alias_id will still group by original value as column names preceeds column alias.

So,

Use another column alias and use it in GROUP BY clause

or use the same replace expression in GROUP BY clause

or use column number syntax:

SELECT contract
     , REGEXP_SUBSTR(alias_id, '.+?(?=_rebate|$)') as alias_id
     , round(sum(sum),2) sum
FROM yt_report
GROUP BY contract, 2


问:
How do I define new entity in Spacy nlp
I want to define a new entity in Spacy.

My code needs to achieve the following:

search text for a certain keyword (here: "Streitwert")

if keyword is in text find sentence where the word occurs

in that sentence look for the number

this number should be an entity with a label "keyword"

This is my code but it is not working:

```<code>def get_keyword_value(token):
    if "Streitwert" in token.doc.text:
        for sent in token.doc.sents:
            if "Streitwert" in sent.text:
                for token in sent:
                    if token.pos_ == "NUM":
                        return token.text

import spacy
from spacy.tokens import Token
nlp = spacy.load("de_core_news_sm")
Token.set_extension("Streitwert", getter=get_keyword_value, force=True)

text = "Die ist ein langer Text. Der Streitwert wird auf EUR 12.000 EUR festgesetzt"
doc = nlp(text)

[(token.text, token._.Streitwert) for token in doc]
</code>```

The code is not working properly and has two issues

every token has the token._.Streitwert = 12.000 (but it should only be the token 12.000

how do I define a new doc.ents with a label "Streitwert"

What I actually want is that the "12.000" is labelled as "Streitwert" when I do

[(ent.text, ent.label_) for ent in doc.ents]

答:
As for defining a new custom entity, you can easily add to the list of entities: ents. To find out how you can do this, I recommend look at this relatively short SpaCy example that is doing something very similar to what you want to do:
https://spacy.io/usage/rule-based-matching#on_match

In this example, they match a word and, based on the match, they add a custom entity. Here they use the ORTH property, but you can use {"POS": "NUM"} to suit your needs. Also, you might find it helpful to use the Rule-based Matcher Explorer to play around with your matterns in a nice friendly UI. In this example, there's no need to set a custom attribute.

If, however, you choose to go the custom attribute route, then you're right that you need to use Token.set_extension(...) to enable the token level custom property. I'd imagine you want to set the default to False and then overwrite that False with True if the token is "Streitwert". You can do that by adding a the default parameter.

```<code>Token.set_extension("Streitwert", default=None, force=True)
</code>```

Also, I notice that your get_key_word(...) method doesn't return anything most of the time. i.e. If any of the conditions are False, what value should be returned?

Title: How do I define new entity in Spacy nlp

Body:
I want to define a new entity in Spacy.

My code needs to achieve the following:

search text for a certain keyword (here: "Streitwert")

if keyword is in text find sentence where the word occurs

in that sentence look for the number

this number should be an entity with a label "keyword"

This is my code but it is not working:

def get_keyword_value(token):
    if "Streitwert" in token.doc.text:
        for sent in token.doc.sents:
            if "Streitwert" in sent.text:
                for token in sent:
                    if token.pos_ == "NUM":
                        return token.text

import spacy
from spacy.tokens import Token
nlp = spacy.load("de_core_news_sm")
Token.set_extension("Streitwert", getter=get_keyword_value, force=True)

text = "Die ist ein langer Text. Der Streitwert wird auf EUR 12.000 EUR festgesetzt"
doc = nlp(text)

[(token.text, token._.Streitwert) for token in doc]

The code is not working properly and has two issues

every token has the token._.Streitwert = 12.000 (but it should only be the token 12.000

how do I define a new doc.ents with a label "Streitwert"

What I actually want is that the "12.000" is labelled as "Streitwert" when I do

[(ent.text, ent.label_) for ent in doc.ents]

Body:
As for defining a new custom entity, you can easily add to the list of entities: ents. To find out how you can do this, I recommend look at this relatively short SpaCy example that is doing something very similar to what you want to do:
https://spacy.io/usage/rule-based-matching#on_match

In this example, they match a word and, based on the match, they add a custom entity. Here they use the ORTH property, but you can use {"POS": "NUM"} to suit your needs. Also, you might find it helpful to use the <a href="https://explosion.ai/demos/matcher?text=120%20kilograms%20of%20dagga%20seized%20from%20Cape%20Town%20shacks.&model=en_core_web_sm&pattern=%5B%7B%22id%22%3A0%2C%22attrs%22%3A%5B%7B%22name%22%3A%22POS%22%2C%22value%22%3A%22NUM%22%7D%5D%7D%2C%7B%22id%22%3A1%2C%22attrs%22%3A%5B%7B%22name%22%3A%22LOWER%22%2C%22value%22%3A%22kilograms%2C%20kg%22%7D%5D%7D%2C%7B%22id%22%3A2%2C%22attrs%22%3A%5B%7B%22name%22%3A%22LOWER%22%2C%22value%22%3A%22of%22%7D%5D%7D%2C%7B%22id%22%3A3%2C%22attrs%22%3A%5B%7B%22name%22%3A%22DEP%22%2C%22value%22%3A%22pobj%22%7D%5D%7D%5D" rel="nofollow noreferrer">Rule-based Matcher Explorer to play around with your matterns in a nice friendly UI. In this example, there's no need to set a custom attribute.

If, however, you choose to go the custom attribute route, then you're right that you need to use Token.set_extension(...) to enable the token level custom property. I'd imagine you want to set the default to False and then overwrite that False with True if the token is "Streitwert". You can do that by adding a the default parameter.

Token.set_extension("Streitwert", default=None, force=True)

Also, I notice that your get_key_word(...) method doesn't return anything most of the time. i.e. If any of the conditions are False, what value should be returned?


问:
how to replace all words from sentences from a pandas column with numbers from a dictionary and then sum them?
I have the following dataframe

```<code>import pandas as pd
df = pd.DataFrame({'col': ['bad good better three worst', 'awful best one']})
</code>```

and I have the following dictionary dc = dict({'bad':-1,'good':1,'better':2,'worst':-3,'awful':-5})

I would like to replace all the words from the col with the numbers that correspond with this word from the dc and then sum the numbers.

First I tried the replacement using

```<code>def replace_words(s, words):
    for k, v in words.items():
        s = s.replace('^'k+'$', v, regex=True)
    return s
</code>```

df['col'] = df['col'].apply(lambda x: [replace_words(i, dc) for i in x.split(' ')])

but this does not work.

Any ideas ?

答:
You can use series.str.findall() to find all matching words in the string and using get() replace the list of words by dict values:

```<code>df.col.str.findall('|'.join(dc.keys())).apply(lambda x: sum([dc.get(i,i) for i in x]))
</code>```

```<code>0   -1
1   -5
</code>```

Details:

```<code>df.col.str.findall('|'.join(dc.keys()))

0    [bad, good, better, worst]
1                       [awful]
Name: col, dtype: object
</code>```

```<code>df.col.str.findall('|'.join(dc.keys())).apply(lambda x: [dc.get(i,i) for i in x])
0    [-1, 1, 2, -3]
1              [-5]
Name: col, dtype: object
</code>```

Body:
I have the following dataframe

import pandas as pd
df = pd.DataFrame({'col': ['bad good better three worst', 'awful best one']})

and I have the following dictionary dc = dict({'bad':-1,'good':1,'better':2,'worst':-3,'awful':-5})

I would like to replace all the words from the col with the numbers that correspond with this word from the dc and then sum the numbers.

First I tried the replacement using

def replace_words(s, words):
    for k, v in words.items():
        s = s.replace('^'k+'$', v, regex=True)
    return s

df['col'] = df['col'].apply(lambda x: [replace_words(i, dc) for i in x.split(' ')])

but this does not work.

Any ideas ?

Body:
You can use series.str.findall() to find all matching words in the string and using get() replace the list of words by dict values:

df.col.str.findall('|'.join(dc.keys())).apply(lambda x: sum([dc.get(i,i) for i in x]))

0   -1
1   -5

Details:

df.col.str.findall('|'.join(dc.keys()))

0    [bad, good, better, worst]
1                       [awful]
Name: col, dtype: object

df.col.str.findall('|'.join(dc.keys())).apply(lambda x: [dc.get(i,i) for i in x])
0    [-1, 1, 2, -3]
1              [-5]
Name: col, dtype: object


问:
creating XML file with LINQ to XML
I need to write linq to xml query of such kind of below xml data

```<code><PRODUCT>
<ID>34169</ID>
<D1>good</D1>
<D2>well</D2>
<L1>lame</L1>
<L2>killer</L2>
<BR>IOMEGA</BR>
<KDV>18</KDV>
<IMG>34169.JPG</IMG>
<EAN>data1</EAN>
<ATP>50+</ATP>
<DM3>0,51</DM3>
<S>
  <L>Tip</L>
  <V>HARICI</V>
</S>
<S>
  <L>Renk</L>
  <V>METALIK GRI</V>
</S>
<S>
  <L>Kapasite (GB)</L>
  <V>500</V>
</S>
<S>
  <L>Dönüş Hızı (Rpm)</L>
  <V>5400,0</V>
</S>
<S>
  <L>Arabirim</L>
  <V>USB 2.0</V>
</S>
<S>
  <L>Form Faktörü (Inch)</L>
  <V>2,5</V>
</S>
<S>
  <L>Ön Bellek (Kb/mb)</L>
  <V>8,0</V>
</S>
<S>
  <L>Satış Garanti Süresi (ay)</L>
  <V>36</V>
</S>
</code>```

my problems are

get only the first image when there
is several images in the
database(img holds the path of an
image as a string in my database
table)

handle the <S> part

I am new to LINQ to XML please help, thanks.

答:
there is my answer </p>

```<code> XElement productCatalog =
                   new XElement("PRODUCTCATALOG",

                               from urun in db.TBLP1URUNs
                               select new XElement("PRODUCT",

                                           new XElement("ID", urun.ID),

                                           new XElement("D1", urun.MODEL),

                                           new XElement("D2", urun.URUNACIKLAMA),

                                           new XElement("L1", urun.TBLP1URUNKATEGORI.TREENAME),

                                           new XElement("IMG", db.TBLP1URUNRESIMs.Where(p => p.URUN_ID == urun.ID).First().FILE_NAME),

                                           new XElement("EAN", urun.STOKKODU),

                                           new XElement("ATP", GetUrunStokById(urun.ID)),//STOKMIKTARI

                                           new XElement("DM3", urun.DESI),

                                           from ozellikler in urun.TBLP1OZELLIK_URUNs
                                           select new XElement("S",

                                               new XElement("L", ozellikler.TBLP1OZELLIK.TBLP1OZELLIKTIPI.TIPI),

                                               new XElement("V", ozellikler.TBLP1OZELLIK.OZELLIK))

                                               )
                            );
</code>```

Title: creating XML file with LINQ to XML

Body:
I need to write linq to xml query of such kind of below xml data

<PRODUCT>
<ID>34169</ID>
<D1>good</D1>
<D2>well</D2>
<L1>lame</L1>
<L2>killer</L2>

IOMEGA

<KDV>18</KDV>
34169.JPG
<EAN>data1</EAN>
<ATP>50+</ATP>
<DM3>0,51</DM3>
<S>
  <L>Tip</L>
  <V>HARICI</V>
</S>
<S>
  <L>Renk</L>
  <V>METALIK GRI</V>
</S>
<S>
  <L>Kapasite (GB)</L>
  <V>500</V>
</S>
<S>
  <L>Dönüş Hızı (Rpm)</L>
  <V>5400,0</V>
</S>
<S>
  <L>Arabirim</L>
  <V>USB 2.0</V>
</S>
<S>
  <L>Form Faktörü (Inch)</L>
  <V>2,5</V>
</S>
<S>
  <L>Ön Bellek (Kb/mb)</L>
  <V>8,0</V>
</S>
<S>
  <L>Satış Garanti Süresi (ay)</L>
  <V>36</V>
</S>

my problems are

get only the first image when there
is several images in the
database(img holds the path of an
image as a string in my database
table)

handle the <S> part

I am new to LINQ to XML please help, thanks.

Body:
there is my answer

 XElement productCatalog =
                   new XElement("PRODUCTCATALOG",

                               from urun in db.TBLP1URUNs
                               select new XElement("PRODUCT",

                                           new XElement("ID", urun.ID),

                                           new XElement("D1", urun.MODEL),

                                           new XElement("D2", urun.URUNACIKLAMA),

                                           new XElement("L1", urun.TBLP1URUNKATEGORI.TREENAME),

                                           new XElement("IMG", db.TBLP1URUNRESIMs.Where(p => p.URUN_ID == urun.ID).First().FILE_NAME),

                                           new XElement("EAN", urun.STOKKODU),

                                           new XElement("ATP", GetUrunStokById(urun.ID)),//STOKMIKTARI

                                           new XElement("DM3", urun.DESI),

                                           from ozellikler in urun.TBLP1OZELLIK_URUNs
                                           select new XElement("S",

                                               new XElement("L", ozellikler.TBLP1OZELLIK.TBLP1OZELLIKTIPI.TIPI),

                                               new XElement("V", ozellikler.TBLP1OZELLIK.OZELLIK))

                                               )
                            );


答:
this should work

```<code>df.col.apply(lambda x: sum([dc.get(i) if dc.get(i) else 0 for i in x.split()]))
</code>```

Output

```<code>0   -1
1   -5
</code>```

Note :
if the word is not found in dc then using 0 value in place, do recommend if it is otherwise since it isn't mentioned

Title: how to replace all words from sentences from a pandas column with numbers from a dictionary and then sum them?

Body:
this should work

df.col.apply(lambda x: sum([dc.get(i) if dc.get(i) else 0 for i in x.split()]))

Output

0   -1
1   -5

Note :
if the word is not found in dc then using 0 value in place, do recommend if it is otherwise since it isn't mentioned


问:
How to inject services in to a custom class in beforeEach Karma/Jasmine test in Angular 7?
Hi I'm triying to test a custom class instantiation, i have several test in the same spec file, that's why use the beforeEach method, also i use inject method to get the services required by my class, but when i run the test the var appointmentCreationVehicle are undefined
this is my code:

```<code>describe('AppointmentCreationVehicle', () => {
  let appointmentCreationVehicle: AppointmentCreationVehicle;

  beforeAll(() => {
    TestBed.configureTestingModule({
      imports: [AppModule]
    })
    .compileComponents();
  });

  beforeEach(
    inject([AppointmentCreationVehicle], (vehicleRestService: VehicleRestService) => {
      appointmentCreationVehicle = new AppointmentCreationVehicle(vehicleRestService);
    })
  );
  it('should create an instance',() => {
      expect(appointmentCreationVehicle).toBeTruthy();
  });
</code>```

then my karma.conf.js look like this:

```<code>module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine', '@angular-devkit/build-angular'],
        plugins: [
            require('karma-jasmine'),
            require('karma-firefox-launcher'),
            require('karma-mocha-reporter'),
            require('@angular-devkit/build-angular/plugins/karma')
        ],
        client: {
            clearContext: false, // leave Jasmine Spec Runner output visible in browser
            jasmine: {
                random: false
            },
            captureConsole: true,
            mocha: {
                bail: true
            }
        },
        reporters: ['mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['HeadlessFirefox'],
        singleRun: true,
        customLaunchers: {
            HeadlessFirefox: {
                base: 'Firefox',
                flags: ['-headless']
            },
            ChromeDebugging: {
                base: 'Chrome',
                flags: ['--remote-debugging-port=9876']
            }
        }
    });
};

</code>```

It is possible than the injection of the services ends after the it execution? If i show, how can i avoid this behavior.

答:
You didn't import the providers into your testbed : </p>

```<code>beforeAll(() => {
  TestBed.configureTestingModule({
    providers: [...] // <---------- HERE
  })
  .compileComponents();
});
</code>```

<p>After that, make it simpler : use the testbed ! It contains a weekMap of the dependencies : </p>

```<code>const myServiceInstance = TestBed.get(MyService);
</code>```

Body:
Hi I'm triying to test a custom class instantiation, i have several test in the same spec file, that's why use the beforeEach method, also i use inject method to get the services required by my class, but when i run the test the var appointmentCreationVehicle are undefined
this is my code:

describe('AppointmentCreationVehicle', () => {
  let appointmentCreationVehicle: AppointmentCreationVehicle;

  beforeAll(() => {
    TestBed.configureTestingModule({
      imports: [AppModule]
    })
    .compileComponents();
  });

  beforeEach(
    inject([AppointmentCreationVehicle], (vehicleRestService: VehicleRestService) => {
      appointmentCreationVehicle = new AppointmentCreationVehicle(vehicleRestService);
    })
  );
  it('should create an instance',() => {
      expect(appointmentCreationVehicle).toBeTruthy();
  });

then my karma.conf.js look like this:

module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine', '@angular-devkit/build-angular'],
        plugins: [
            require('karma-jasmine'),
            require('karma-firefox-launcher'),
            require('karma-mocha-reporter'),
            require('@angular-devkit/build-angular/plugins/karma')
        ],
        client: {
            clearContext: false, // leave Jasmine Spec Runner output visible in browser
            jasmine: {
                random: false
            },
            captureConsole: true,
            mocha: {
                bail: true
            }
        },
        reporters: ['mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['HeadlessFirefox'],
        singleRun: true,
        customLaunchers: {
            HeadlessFirefox: {
                base: 'Firefox',
                flags: ['-headless']
            },
            ChromeDebugging: {
                base: 'Chrome',
                flags: ['--remote-debugging-port=9876']
            }
        }
    });
};

It is possible than the injection of the services ends after the it execution? If i show, how can i avoid this behavior.

Body:
You didn't import the providers into your testbed :

beforeAll(() => {
  TestBed.configureTestingModule({
    providers: [...] // <---------- HERE
  })
  .compileComponents();
});

After that, make it simpler : use the testbed ! It contains a weekMap of the dependencies :

const myServiceInstance = TestBed.get(MyService);


问:
What happens if arguments passed to sscanf are cast
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

```<code>struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}
</code>```

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

答:
OP code is UB as scan specifiers does not match arguments.

cleanest correct way to do this?

Cleaner

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

void horror1(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo) {
    sscanf(s1, "%" SCNu32, &(foo->bar));
    sscanf(s2, "%" SCNu8, &(foo->qux));
    sscanf(s2, "%" SCNu8, &(foo->xyz));
    sscanf(s1, "%" SCNu32, &(foo->etc));
}
</code>```

Cleanest

Add additional error handling if desired.

```<code>void horror2(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo) {
    foo->bar = (uint32_t) strtoul(s1, 0, 10);
    foo->qux = (uint8_t) strtoul(s1, 0, 10);
    foo->xyz = (uint8_t) strtoul(s1, 0, 10);
    foo->etc = (uint32_t) strtoul(s1, 0, 10);
}
</code>```

Body:
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

Body:
OP code is UB as scan specifiers does not match arguments.

cleanest correct way to do this?

Cleaner

#include <inttypes.h>

void horror1(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo) {
    sscanf(s1, "%" SCNu32, &(foo->bar));
    sscanf(s2, "%" SCNu8, &(foo->qux));
    sscanf(s2, "%" SCNu8, &(foo->xyz));
    sscanf(s1, "%" SCNu32, &(foo->etc));
}

Cleanest

Add additional error handling if desired.

void horror2(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo) {
    foo->bar = (uint32_t) strtoul(s1, 0, 10);
    foo->qux = (uint8_t) strtoul(s1, 0, 10);
    foo->xyz = (uint8_t) strtoul(s1, 0, 10);
    foo->etc = (uint32_t) strtoul(s1, 0, 10);
}


问:
Unexpected module path go-modules
I have a repo on Github which just holds some Go structs to be used as models throughout my services.

https://github.com/pocockn/models

I then want to import this into my services, I am using Go Modules in both repos. When I run 'go get' in my service I get the following error.

go: finding github.com/pocockn/models/api/football latestgo: finding
  github.com/pocockn/models/api latest go: finding
  github.com/pocockn/models latest go:
  github.com/pocockn/models@v0.0.0-20190511152220-d7675ec24338: parsing
  go.mod: unexpected module path "models"

My go.mod file in the models repo looks like this

```<code>module models

go 1.12

require github.com/jinzhu/gorm v1.9.8
</code>```

答:
Your module name in your go.mod should be github.com/pocockn/models, matching the repo path. It could also be a custom domain/path, assuming that domain either has the code hosted or the correct headers to redirect to your repo (using something like https://github.com/GoogleCloudPlatform/govanityurls).

(Looks like you may have already done this. Answering here if others find this question.)

Title: Unexpected module path go-modules

Body:
I have a repo on Github which just holds some Go structs to be used as models throughout my services.

https://github.com/pocockn/models

I then want to import this into my services, I am using Go Modules in both repos. When I run 'go get' in my service I get the following error.

go: finding github.com/pocockn/models/api/football latestgo: finding
  github.com/pocockn/models/api latest go: finding
  github.com/pocockn/models latest go:
  github.com/pocockn/models@v0.0.0-20190511152220-d7675ec24338: parsing
  go.mod: unexpected module path "models"

My go.mod file in the models repo looks like this

module models

go 1.12

require github.com/jinzhu/gorm v1.9.8


问:
"Cold" start of S3, DynamoDB, KMS or whatever
I use NodeJs AWS Lambdas. If I don't do calls to my S3, or DynamoDB, or KMS for some time (approx. 8h or more) the first call I make is usually painfully slow - up-to 5sec. There's nothing complex in the queries themselves - i.e. get a 0.2Kb S3 object, query a DynamoDB table by index.

So, it looks like AWS "hibernates" these resources when they aren't in active use and when I call them for the 1st time after a while they spend some time to return from "hibernated" state. This is my assumption, but I couldn't find any information about it in docs. So, the questions are the following two:

Is my assumption about "hibernation" correct?

If 1st point is correct, then is there any way to mitigate these "cold" calls to AWS services except keeping those services "warm" by calling them every X minutes?

Edit

Just to avoid confusions - this is not about Lambda's cold starts. I'm aware of them, they exist, they have their own share in functions' latency. Times I measure are the exact times of calls to S3/DynamoDB etc. - after the lambda is started.

答:
We have experienced the same issue for calls to SSM and DynamoDB. It's probably not these services that go into hibernation, but the parameters for calling them are cached on the lambda container, which means they need to be recreated when a new container is spawned.

Unfortunately, we have not found a solution other than pinging the lambda from time to time. In this case, you should execute a call to your services in the ping in order to see an improvement in the loading times. See also below benchmark.


问:
Cutting String by using regexp
I want to cut the string using regexp, but not to cut the regexp part...

```<code>String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
String[] substract=path.split("my_");
path=substract1[1].toString();// books/bought/2011/adventure/Black-Ship01/312 pages/...
String[] substract2=path.split("-Ship.."); //split using -Ship and two random simbols
path=substract[1].toString();

RESULT:   path= "books/bought/2011/adventure/Black"
Should be path= "books/bought/2011/adventure/Black-Ship01"
</code>```

so how to add -Ship01 ??

答:
I cannot think of a better way right now. But you could do something like that:

```<code>public class NewClass
{
    public static void main(String[] args)
    {
        String finalStr = "";
        String patternStr = "(-Ship..)";
        String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
        String[] substract2 = path.split(patternStr);
        System.out.println("substract2="+Arrays.toString(substract2));
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(path);
        matcher.find();
        System.out.println("g0="+matcher.group(0));
        finalStr = substract2[0]+matcher.group(0);
        System.out.println("finalStr="+finalStr);
      }
}
</code>```

Enjoy, Boro.

Title: Cutting String by using regexp

Body:
I want to cut the string using regexp, but not to cut the regexp part...

String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
String[] substract=path.split("my_");
path=substract1[1].toString();// books/bought/2011/adventure/Black-Ship01/312 pages/...
String[] substract2=path.split("-Ship.."); //split using -Ship and two random simbols
path=substract[1].toString();

RESULT:   path= "books/bought/2011/adventure/Black"
Should be path= "books/bought/2011/adventure/Black-Ship01"

so how to add -Ship01 ??

Body:
I cannot think of a better way right now. But you could do something like that:

public class NewClass
{
    public static void main(String[] args)
    {
        String finalStr = "";
        String patternStr = "(-Ship..)";
        String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
        String[] substract2 = path.split(patternStr);
        System.out.println("substract2="+Arrays.toString(substract2));
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(path);
        matcher.find();
        System.out.println("g0="+matcher.group(0));
        finalStr = substract2[0]+matcher.group(0);
        System.out.println("finalStr="+finalStr);
      }
}

Enjoy, Boro.


问:
How to convert a string to lower or upper case in Ruby
How do I take a string and convert it to lower or upper case in Ruby?</p>

答:
The .swapcase method transforms the uppercase letters in a string to lowercase and the lowercase letters to uppercase.

```<code>'TESTING'.swapcase #=> testing
'testing'.swapcase #=> TESTING
</code>```

Body:
The .swapcase method transforms the uppercase letters in a string to lowercase and the lowercase letters to uppercase.

'TESTING'.swapcase #=> testing
'testing'.swapcase #=> TESTING


问:
JSON Stringify ignores nested objects on Redis publish
I am using Redis in my backend to scale subscriptions. I am using this library to implement redis on top of my javascript code. And using mongoose for the models.

During a redis publish, I have to stringify the objects that I get from mongoose. I parse them on the subscribing end and it all works well until there's a nested object in the object that needs to be stringify-ed.

So if my object is this:

```<code>{ subtitle: '',
   description: '',
   checklists:
    [ { _id: 5cee450c0fa29d0b54275da0, items: [] },
      { _id: 5cee455c0c31785b0875e09d, items: [] },
      { _id: 5cee47dc6d32e72c6411ce2d, items: [] } ],
   attachments: [],
   labels: [],
   _id: 5ced1af26547233798f943f6,
   title: 'asfasf',
   box: 5cece1c3e6c3c13ff098658d,
   workflow: 5cece1cbe6c3c13ff0986591,
}
</code>```

I receive:

```<code>{ cardUpdated:
    {
      subtitle: '',
      description: '',
      checklists: [ [Object], [Object], [Object] ],
      attachments: [],
      labels: [],
      _id: '5ced1af26547233798f943f6',
      title: 'asfasf',
      box: '5cece1c3e6c3c13ff098658d',
      workflow: '5cece1cbe6c3c13ff0986591',
    }
}
</code>```

When I publish I use the following line:

```<code>pub.publish(types.CARD_UPDATED,
          JSON.stringify(
            { cardUpdated: await getUpdatedCardStats(checklist.card) },
          ));
</code>```

Note: I know that I am wrapping the argument for stringify in {} and without it the nested objects would not be ignored, but I need to do that because I need the key property name on the subscription end i.e. I am using this publish command with different key names at several places.

Is there a way to about this to get the nested objects stringify-ed?

EDIT: Turns out, I was getting the proper full object as a string on the subscribing end of Redis, but it was actually JSON.parse() that was the culprit. After parsing, it completely ignores the nested objects. Is there anyway to avoid this?

答:
Try:

const value = JSON.stringify({
    cardUpdated: await getUpdatedCardStats(checklist.card)
});
pub.publish(types.CARD_UPDATED, value);
```

Body:
I am using Redis in my backend to scale subscriptions. I am using this library to implement redis on top of my javascript code. And using mongoose for the models.

During a redis publish, I have to stringify the objects that I get from mongoose. I parse them on the subscribing end and it all works well until there's a nested object in the object that needs to be stringify-ed.

So if my object is this:

{ subtitle: '',
   description: '',
   checklists:
    [ { _id: 5cee450c0fa29d0b54275da0, items: [] },
      { _id: 5cee455c0c31785b0875e09d, items: [] },
      { _id: 5cee47dc6d32e72c6411ce2d, items: [] } ],
   attachments: [],
   labels: [],
   _id: 5ced1af26547233798f943f6,
   title: 'asfasf',
   box: 5cece1c3e6c3c13ff098658d,
   workflow: 5cece1cbe6c3c13ff0986591,
}

I receive:

{ cardUpdated:
    {
      subtitle: '',
      description: '',
      checklists: [ [Object], [Object], [Object] ],
      attachments: [],
      labels: [],
      _id: '5ced1af26547233798f943f6',
      title: 'asfasf',
      box: '5cece1c3e6c3c13ff098658d',
      workflow: '5cece1cbe6c3c13ff0986591',
    }
}

When I publish I use the following line:

pub.publish(types.CARD_UPDATED,
          JSON.stringify(
            { cardUpdated: await getUpdatedCardStats(checklist.card) },
          ));

Note: I know that I am wrapping the argument for stringify in {} and without it the nested objects would not be ignored, but I need to do that because I need the key property name on the subscription end i.e. I am using this publish command with different key names at several places.

Is there a way to about this to get the nested objects stringify-ed?

EDIT: Turns out, I was getting the proper full object as a string on the subscribing end of Redis, but it was actually JSON.parse() that was the culprit. After parsing, it completely ignores the nested objects. Is there anyway to avoid this?


问:
How can I convert this long-running background task to async/await?
I have code that is kicking off work on a long-running background task with a heartbeat. The application is being updated to use async/await and I am having problems updating this code to follow suite. Here is the code, roughly:

```<code>private void StartBackgroundTasks(CancellationTokenSource cancelTokenSrc)
{
    void TaskAction()
    {
        DoWork();
    }

    void HeartbeatAction()
    {
        var task = TaskFactory.CreateAndStartLongRunningTask(
            TaskAction, cancelTokenSrc.Token);

        while (true)
        {
            // checks Task.Status to figure out when to stop
            if (!TryPerformHeartbeat(task)) break;

            Task.Delay(TimeSpan.FromSeconds(20)).Wait();
        }
    }

    TaskFactory.CreateAndStartLongRunningTask(HeartbeatAction);
}
</code>```

And here is how the long-running tasks are being started:

```<code>internal static class TaskFactory
{
    internal static Task CreateAndStartLongRunningTask(
        Action action, CancellationToken? token = null)
    {
        return Task.Factory.StartNew(
            action,
            token ?? CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default);
    }
}
</code>```

From what I understand I need to:

pass a Func<Task> to CreateAndStartLongRunningTask

change StartNew to take async () => await taskFunc() instead of action

add async/awaits up through the method signatures as needed

What would be the correct way to get this code runs on a background thread and allows for the async/await pattern?

答:
Essentially in short unless you specifically need it you shouldn't use Task.Factory.StartNew or TaskCreationOptions.LongRunning. Just use Task.Run like so:

var task = Task.Run(async () =>
{
    while (true)
    {
        await TryPerformHeartbeat();
        await Task.Delay(TimeSpan.FromSeconds(20));

    }
}, token);
```

These two articles are helpful in explaining why:
http://blog.i3arnon.com/2015/07/02/task-run-long-running/ and https://sergeyteplyakov.github.io/Blog/async/2019/05/21/The-Dangers-of-Task.Factory.StartNew.html

Body:
I have code that is kicking off work on a long-running background task with a heartbeat. The application is being updated to use async/await and I am having problems updating this code to follow suite. Here is the code, roughly:

private void StartBackgroundTasks(CancellationTokenSource cancelTokenSrc)
{
    void TaskAction()
    {
        DoWork();
    }

    void HeartbeatAction()
    {
        var task = TaskFactory.CreateAndStartLongRunningTask(
            TaskAction, cancelTokenSrc.Token);

        while (true)
        {
            // checks Task.Status to figure out when to stop
            if (!TryPerformHeartbeat(task)) break;

            Task.Delay(TimeSpan.FromSeconds(20)).Wait();
        }
    }

    TaskFactory.CreateAndStartLongRunningTask(HeartbeatAction);
}

And here is how the long-running tasks are being started:

internal static class TaskFactory
{
    internal static Task CreateAndStartLongRunningTask(
        Action action, CancellationToken? token = null)
    {
        return Task.Factory.StartNew(
            action,
            token ?? CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default);
    }
}

From what I understand I need to:

pass a Func<Task> to CreateAndStartLongRunningTask

change StartNew to take async () => await taskFunc() instead of action

add async/awaits up through the method signatures as needed

What would be the correct way to get this code runs on a background thread and allows for the async/await pattern?

Body:
Essentially in short unless you specifically need it you shouldn't use Task.Factory.StartNew or TaskCreationOptions.LongRunning. Just use Task.Run like so:

var task = Task.Run(async () =>
{
    while (true)
    {
        await TryPerformHeartbeat();
        await Task.Delay(TimeSpan.FromSeconds(20));

    }
}, token);

These two articles are helpful in explaining why:
http://blog.i3arnon.com/2015/07/02/task-run-long-running/ and https://sergeyteplyakov.github.io/Blog/async/2019/05/21/The-Dangers-of-Task.Factory.StartNew.html


问:
Why is "partial RVO" not performed?
Please take a look at this silly function, which should only illustrate the problem and a simplification of the real code:

```<code>struct A;

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}
</code>```

I understand, that because it is not clear which object will be returned during the compilation, we cannot expect return value optimization (RVO) to be always performed.

However, one maybe could expect RVO to be performed in 50% of the cases (assuming uniform distribution for true/false due to lack of further information): just decide for which case RVO (first==true or first==false) should be performed and apply it for this parameter-value, accepting that in the other case the copy constructor must be called.

Yet this "partial RVO" is not the case for all compilers I can get my hands on (see live with gcc, clang and MSVC) - in both cases (i.e. first==true or first==false) the copy-constructor is used and not omitted.

Is there something, that renders the "partial RVO" in the above case invalid or is this an unlikely case of missed optimization by all compilers?

Complete program:

```<code>#include <iostream>

struct A{
    int val;
    A(int val_):val(val_){}
    A(const A&o):val(o.val){
        std::cout<<"copying: "<<val<<"\n";
    }
};

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}

int main(){
    std::cout<<"With true: ";
    create(true);
    std::cout<<"With false: ";
    create(false);
}
</code>```

答:
My take on this, apart from reading Jonathan Wakely's answer with interest, is that one can always define a move constructor for the object being returned.  This will then be favoured over the copy constructor if RVO cannot be applied for whatever reason and seems to me to be a good solution.

Things like std::vector define such a constructor, so you get that for free.

Title: Why is "partial RVO" not performed?

Body:
Please take a look at this silly function, which should only illustrate the problem and a simplification of the real code:

struct A;

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}

I understand, that because it is not clear which object will be returned during the compilation, we cannot expect return value optimization (RVO) to be always performed.

However, one maybe could expect RVO to be performed in 50% of the cases (assuming uniform distribution for true/false due to lack of further information): just decide for which case RVO (first==true or first==false) should be performed and apply it for this parameter-value, accepting that in the other case the copy constructor must be called.

Yet this "partial RVO" is not the case for all compilers I can get my hands on (see live with gcc, clang and MSVC) - in both cases (i.e. first==true or first==false) the copy-constructor is used and not omitted.

Is there something, that renders the "partial RVO" in the above case invalid or is this an unlikely case of missed optimization by all compilers?

Complete program:

#include <iostream>

struct A{
    int val;
    A(int val_):val(val_){}
    A(const A&o):val(o.val){
        std::cout<<"copying: "<<val<<"\n";
    }
};

A create(bool first){
        A f(21), s(42);
        if(first)
           return f;
        else
           return s;
}

int main(){
    std::cout<<"With true: ";
    create(true);
    std::cout<<"With false: ";
    create(false);
}


问:
JAXB bindings file: namespace-aware node selection
I tend to use external JAXB bindings files for my Schema-to-Java compilation. This works just fine, but I did notice one thing that I've started wondering about. It's not really JAXB-specific, more like an XPath question, but the context helps.

Suppose we have this schema:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:test="www.acme.com"
 targetNamespace="www.acme.com"
 elementFormDefault="qualified" attributeFormDefault="unqualified">

  <xs:element name="el1"/>

  <xs:complexType name="testType">
    <xs:sequence>
      <xs:element ref="test:el1"/>
    </xs:sequence>
  </xs:complexType>

</xs:schema>
</code>```

The element reference in the complex type requires the prefix "test", bound to our target namespace, to find the element definition. If we omitted the prefix, a schema processor would complain that it can't find the element it refers. So obviously the reference is a qualified name and a schema processor is aware of this.

Now take the following bindings file extract for XJC:

```<code><bindings node="//xs:complexType[@name='testType']">
  <bindings node=".//xs:element[@ref='test:el1']">
    <property name="element1"/>
  </bindings>
</bindings>
</code>```

The binding for the complex type is clear. We select it by name, and the xs prefix is bound in the bindings file's root (not shown here). It might as well be xsd.

What bugs me is the nested binding. In the context of our complex type node, we select an xs:element node for which attribute ref has value test:el1. But that value is simply regarded as text. The XML processor has no knowledge of the fact that it's supposed to be a qualified name and test: is actually a prefix declaration bound to a namespace.

Now I know I'm nitpicking, but the actual prefix string should have no importance, only the namespace URI itself. Someone could change the test prefix in the schema to acme and it would still be the same schema semantically. However, my bindings file would no longer work.

So, is there any way to construct the XPath expression without relying on knowledge of the prefix, only the namespace URI? It's obviously not a big problem, but I'm curious about this.

答:
Is there any way to construct the
  XPath expression without relying on
  knowledge of the prefix, only the
  namespace URI?

If you talk about an attribute value, this is XPath 1.0

```<code>.//xs:element[
   namespace::*[
      . = 'www.acme.com'
   ][
      susbtring-before(
         ../@ref,
         ':'
      )
    = name()
   ]
 and
   substring(
      concat(':', @ref),
      string-length(@ref) - 1
   )
 = 'el1'
]
</code>```

In XPath 2.0 is much more simple:

```<code>.//xs:element[resolve-QName(@ref,.) eq QName('www.acme.com','el1')]
</code>```

Body:
I tend to use external JAXB bindings files for my Schema-to-Java compilation. This works just fine, but I did notice one thing that I've started wondering about. It's not really JAXB-specific, more like an XPath question, but the context helps.

Suppose we have this schema:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:test="www.acme.com"
 targetNamespace="www.acme.com"
 elementFormDefault="qualified" attributeFormDefault="unqualified">

  <xs:element name="el1"/>

  <xs:complexType name="testType">
    <xs:sequence>
      <xs:element ref="test:el1"/>
    </xs:sequence>
  </xs:complexType>

</xs:schema>

The element reference in the complex type requires the prefix "test", bound to our target namespace, to find the element definition. If we omitted the prefix, a schema processor would complain that it can't find the element it refers. So obviously the reference is a qualified name and a schema processor is aware of this.

Now take the following bindings file extract for XJC:

<bindings node="//xs:complexType[@name='testType']">
  <bindings node=".//xs:element[@ref='test:el1']">
    <property name="element1"/>
  </bindings>
</bindings>

The binding for the complex type is clear. We select it by name, and the xs prefix is bound in the bindings file's root (not shown here). It might as well be xsd.

What bugs me is the nested binding. In the context of our complex type node, we select an xs:element node for which attribute ref has value test:el1. But that value is simply regarded as text. The XML processor has no knowledge of the fact that it's supposed to be a qualified name and test: is actually a prefix declaration bound to a namespace.

Now I know I'm nitpicking, but the actual prefix string should have no importance, only the namespace URI itself. Someone could change the test prefix in the schema to acme and it would still be the same schema semantically. However, my bindings file would no longer work.

So, is there any way to construct the XPath expression without relying on knowledge of the prefix, only the namespace URI? It's obviously not a big problem, but I'm curious about this.

Body:
Is there any way to construct the
  XPath expression without relying on
  knowledge of the prefix, only the
  namespace URI?

If you talk about an attribute value, this is XPath 1.0

.//xs:element[
   namespace::*[
      . = 'www.acme.com'
   ][
      susbtring-before(
         ../@ref,
         ':'
      )
    = name()
   ]
 and
   substring(
      concat(':', @ref),
      string-length(@ref) - 1
   )
 = 'el1'
]

In XPath 2.0 is much more simple:

.//xs:element[resolve-QName(@ref,.) eq QName('www.acme.com','el1')]