问:
Failed to create JVM after trying to set more memory for Android Studio
I am trying to set my memory on 4GB using the command -Xmx4g from Help->Edit VME Options but when I try to open the Android Studio I get the error mentioned in the title.

If you already have a 64-bit JDK installed, define a JAVA_HOME variable in Computer >System Properties > System Settings > Environment Variables.
  Failed to create JVM. JVM Path ...\jre.

I've already tried some other answers from the same questions, but nothing worked for me

Tried:

Go to C:\Program Files\Android\Android Studio\bin\studio.exe.vmoptions

Open it with notepad. some times it will not be editable so give
  administrative permission and change the following attributes:

-Xmx512m to -Xmx256m

-XX:MaxPermSize=250m to -XX:MaxPermSize=128m

Or change:

-Xmx750m to -Xmx512m

-XX:MaxPermSize=350m to -XX:MaxPermSize=250m

But in my C:\Program Files\Android\Android Studio\bin\studio.exe.vmoptions or C:\Program Files\Android\Android Studio\bin\studio64.exe.vmoptions

I don't have the -XX:MaxPermSize, only the -Xmx's which I already tried to change but nothing worked.

答: I finally made it work by tracking down the config file created when trying to change the memory. C:\Users\(pc-name)\.AndroidStudio\config\studio.exe.vmoptions. Ive deleted that file and it started working.


来源: stackexchange

问:
Change many values with specific
I have data like this:

```<code>data.frame(text1 = c("Amazon", "Google", "other"))
</code>```

Add I would like to replace whatever is in the list with a specific value

```<code>mylist <- c("Amazon", "Google")
</code>```

replace what is in the mylist with stock value

Expected output:

```<code>data.frame(text1 = c("stock", "stock", "other"))
</code>```

答:
Also you can use ifelse() and get a data frame directly</p>

```<code>a <- data.frame(text1=ifelse(ls$text1 %in% mylist,"stock",as.character(ls$text1)))
a
  text1
1 stock
2 stock
3 other
</code>```

ContentLicense: CC BY-SA 4.0

Title: Change many values with specific

Body:
I have data like this:

data.frame(text1 = c("Amazon", "Google", "other"))

Add I would like to replace whatever is in the list with a specific value

mylist <- c("Amazon", "Google")

replace what is in the mylist with stock value

Expected output:

data.frame(text1 = c("stock", "stock", "other"))

Body:
Also you can use ifelse() and get a data frame directly

a <- data.frame(text1=ifelse(ls$text1 %in% mylist,"stock",as.character(ls$text1)))
a
  text1
1 stock
2 stock
3 other


问:
Select columns together with the sum()
I have a problem in getting the columns and I also want to get the sum of total_amount.

```<code>CREATE TABLE purchase (
    id int,
    sheet_number varchar(255),
    total_amount decimal(23,6),
    transaction_status int
);

INSERT INTO purchase (id, sheet_number, total_amount, transaction_status)
VALUES (
    '1', 'PO10010000001', '120.18', 1,
    '2', 'PO10010000002', '87.23', 1,
    '3', 'PO10010000003', '53.56', 3,
    '4', 'PO10010000004', '150.28', 4,
    '5', 'PO10010000005', '160.53' 3,
);
</code>```

I want to get the columns and also the sum of this total_amount with respect (group by) of transaction_status.

I've created a SQL query like this but it doesn't work with the expected one.

Here is the SQL query that I've made:

```<code>SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status, id, sheet_number
</code>```

I think the problem because I listed the other columns/attributes in the GROUP BY clause.

But I needed it because it will prompt an error message that the column is not valid since it is not contained in the group by clause.

The expected SQL query is like this (but I can't since there will be a prompt error):

```<code>SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status
</code>```

The expected result will be:

```<code>[id],[sheet_number],[total],[transaction_status]

[1],[PO10010000001],[207.41],[1],
[2],[PO10010000002],[207.41],[1],
[3],[PO10010000003],[214.09],[3],
[4],[PO10010000004],[150.28],[4],
[5],[PO10010000005],[214.09],[3]
</code>```

I just want to get all the same columns but I can get also the sum of total_amount.

答:
You can use window function :</p>

```<code>SELECT p.id, p.sheet_number, p.transaction_status,
       SUM(p.total_amount) OVER (PARTITION BY p.transaction_status) AS total
FROM purchase p
ORDER BY p.id;
</code>```

Title: Select columns together with the sum()

Body:
I have a problem in getting the columns and I also want to get the sum of total_amount.

CREATE TABLE purchase (
    id int,
    sheet_number varchar(255),
    total_amount decimal(23,6),
    transaction_status int
);

INSERT INTO purchase (id, sheet_number, total_amount, transaction_status)
VALUES (
    '1', 'PO10010000001', '120.18', 1,
    '2', 'PO10010000002', '87.23', 1,
    '3', 'PO10010000003', '53.56', 3,
    '4', 'PO10010000004', '150.28', 4,
    '5', 'PO10010000005', '160.53' 3,
);

I want to get the columns and also the sum of this total_amount with respect (group by) of transaction_status.

I've created a SQL query like this but it doesn't work with the expected one.

Here is the SQL query that I've made:

SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status, id, sheet_number

I think the problem because I listed the other columns/attributes in the GROUP BY clause.

But I needed it because it will prompt an error message that the column is not valid since it is not contained in the group by clause.

The expected SQL query is like this (but I can't since there will be a prompt error):

SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status

The expected result will be:

[id],[sheet_number],[total],[transaction_status]

[1],[PO10010000001],[207.41],[1],
[2],[PO10010000002],[207.41],[1],
[3],[PO10010000003],[214.09],[3],
[4],[PO10010000004],[150.28],[4],
[5],[PO10010000005],[214.09],[3]

I just want to get all the same columns but I can get also the sum of total_amount.

Body:
You can use window function :

SELECT p.id, p.sheet_number, p.transaction_status,
       SUM(p.total_amount) OVER (PARTITION BY p.transaction_status) AS total
FROM purchase p
ORDER BY p.id;


问:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")

In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?

Tried:

Rollback tables: heroku run php artisan migrate:rollback

migrate fresh: heroku run php artisan migrate:fresh

migrate reset: heroku run php artisan migrate:reset

The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.

stories table:

        <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateStoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('story');
                $table->date('published_on');
                $table->integer('count_views')->default(0);
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedBigInteger("category_id");
                $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stories');
        }
    }

```

<p>categories table: </p>

<pre class="lang-php prettyprint-override"><code>    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateCategoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category');
                $table->string('title')->nullable();
                $table->string('img')->nullable();
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('categories');
        }
    }
</code>```

Story model:

        <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Reviews;
    use App\User;
    use App\Category;
    use App\ReadingList;

    class Story extends Model
    {

        protected $guarded = [];

        public function readingList()
        {
            return $this->belongsTo(ReadingList::class);
        }

        public function category()
        {
            return $this->belongsTo(Category::class);
        }

        public function reviews() {
            return $this->hasMany(Reviews::class);
        }

        public function user() {
            return $this->belongsTo(User::class);
        }

    }
```

<p>Category model: </p>

<pre class="lang-php prettyprint-override"><code>    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    use App\Story;

    class Category extends Model
    {
        protected $guarded = [];

        public function story()
        {
            return $this->hasMany(Story::class);
        }

    }

</code>```

Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.

答:
You can create a single migration file in these scenarios.

```<code>use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category');
            $table->string('title')->nullable();
            $table->string('img')->nullable();
            $table->timestamps();
        });

        Schema::create('stories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('story');
            $table->date('published_on');
            $table->integer('count_views')->default(0);
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger("category_id");
            $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
        Schema::dropIfExists('stories');
    }
}
</code>```

Body:
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")

In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?

Tried:

Rollback tables: heroku run php artisan migrate:rollback

migrate fresh: heroku run php artisan migrate:fresh

migrate reset: heroku run php artisan migrate:reset

The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.

stories table:

        <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateStoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('stories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('story');
                $table->date('published_on');
                $table->integer('count_views')->default(0);
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
                $table->unsignedBigInteger("category_id");
                $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('stories');
        }
    }

categories table:

    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateCategoriesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('category');
                $table->string('title')->nullable();
                $table->string('img')->nullable();
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('categories');
        }
    }

Story model:

        <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Reviews;
    use App\User;
    use App\Category;
    use App\ReadingList;

    class Story extends Model
    {

        protected $guarded = [];

        public function readingList()
        {
            return $this->belongsTo(ReadingList::class);
        }

        public function category()
        {
            return $this->belongsTo(Category::class);
        }

        public function reviews() {
            return $this->hasMany(Reviews::class);
        }

        public function user() {
            return $this->belongsTo(User::class);
        }

    }

Category model:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    use App\Story;

    class Category extends Model
    {
        protected $guarded = [];

        public function story()
        {
            return $this->hasMany(Story::class);
        }

    }

Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.

Body:
You can create a single migration file in these scenarios.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category');
            $table->string('title')->nullable();
            $table->string('img')->nullable();
            $table->timestamps();
        });

        Schema::create('stories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('story');
            $table->date('published_on');
            $table->integer('count_views')->default(0);
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger("category_id");
            $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
        Schema::dropIfExists('stories');
    }
}


问:
ISO 369 (german) != 639 (english)
I found two translations of one article at:

https://www.w3.org/International/questions/qa-lang-2or3.en.html

began with either a ISO 639-1 two-letter language code or ISO 639-2 three-letter code

vs

https://www.w3.org/International/questions/qa-lang-2or3.de.html

begannen entweder mit einem zweibuchstabigen Code nach ISO 369-1 oder einem dreibuchstabigen Code nach ISO 369-2

Have there ever been a ISO 369-x what have been changed to ISO 639-x?

I have a table SYSTEM_LANGUAGE having a field ISO_369_CODE.

```<code>SYSTEM_LANGUAGE
+----+--------------+
| id | iso_369_code |
+----+--------------+
|  1 | en           |
+----+--------------+
</code>```

Is the field named correctly?

答:
No the field is named incorrectly International standard 369 it is about something else:

ISO 369:2009 Machine tools - Symbols for indications appearing on machine tools

Title: ISO 369 (german) != 639 (english)

Body:
I found two translations of one article at:

https://www.w3.org/International/questions/qa-lang-2or3.en.html

began with either a ISO 639-1 two-letter language code or ISO 639-2 three-letter code

vs

https://www.w3.org/International/questions/qa-lang-2or3.de.html

begannen entweder mit einem zweibuchstabigen Code nach ISO 369-1 oder einem dreibuchstabigen Code nach ISO 369-2

Have there ever been a ISO 369-x what have been changed to ISO 639-x?

I have a table SYSTEM_LANGUAGE having a field ISO_369_CODE.

SYSTEM_LANGUAGE
+----+--------------+
| id | iso_369_code |
+----+--------------+
|  1 | en           |
+----+--------------+

Is the field named correctly?


问:
Xamarin UI Tests IOS Device Error: Xamarin.UITest.XDB.Exceptions.DeviceAgentException : Failed to install DeviceAgent
Configuration:

Visual Studio 8.5 Build 2739
Mono 6.8.0.104
Xcode Version 11.3.1 (11C504)

Visual Studio 8.4.5 Build 19
Mono 6.6.0.155
Xcode Version 11.3.1 (11C504)

Code:

```<code>ConfigureApp.iOS
            .InstalledApp("com.xamarin.MyNewApp55")
            .StartApp();
</code>```

Exception:

Xamarin.UITest.XDB.Exceptions.DeviceAgentException : Failed to install
  DeviceAgent

ExitCode: 5

```<code>  -c,--codesign-identity  <codesign-identifier> [OPTIONAL]    Identity
</code>```

used to codesign app bundle [device only]. Deprecated - should use
  profile path. DEFAULT=        -d,--device-id   iOS
  Simulator GUID, physical device ID, or an alias
        -f,--force   [OPTIONAL]    Reinstall the app if
  the device contains an older version than the bundle
  specified DEFAULT=0       -i,--resources-path  [OPTIONAL]
    Path to resources (executables) to inject into app directory. A list
  of colon separated files may be specified.
        -p,--profile-path    [OPTIONAL]   Path to provisioning
  profile   install  Application
  com.apple.test.DeviceAgent-Runner is not installed on
  00008030-0003048114F0802E Error installing application: Failed to
  install application with path
  /var/folders/39/0rfg9kc92gx9bbslgw3td95h0000gq/T/xdb/DeviceAgent.iOS.Dependencies/b747d1445588083eee4d1d93a53f3e5b/ipa/DeviceAgent-Runner.app

How can I solve this issue?

答:
About method InstalledApp(string bundleId) , it has follow definition :

Configures the installed app to use. Will force a run on physical device.

You should run it in a physical device .

Therefore , if need to run in simulator device ,should use AppBundle (string path) :

Configures the app bundle to use. Will force a run on simulator.

The AppBundle method can be used to specify where on the file system the app bundle may be found. There are two ways to do so, with an absolute path, or a relative path. This snippet shows using an absolute path to the app bundle:

```<code>IApp app = ConfigureApp
    .iOS
    .AppBundle("/path/to/iosapp.app")
    .StartApp();
</code>```

To use a relative path, the path must be relative to the Xamarin.UITest assembly. This snippet is and example of how to use a relative path to locate the app bundle:

```<code>IApp app = ConfigureApp
    .iOS
    .AppBundle("../../../iOSAppProject/bin/iPhoneSimulator/Debug/iosapp.app")
    .StartApp();
</code>```

The relative path example tells AppBundle to go up three directories from the Xamarin.UITest assembly, and then navigate down the project tree of the iOS application project to find the app bundle.

Here is the official document about Initialize IApp for iOS Applications.

Body:
Configuration:

Visual Studio 8.5 Build 2739
Mono 6.8.0.104
Xcode Version 11.3.1 (11C504)

Visual Studio 8.4.5 Build 19
Mono 6.6.0.155
Xcode Version 11.3.1 (11C504)

Code:

ConfigureApp.iOS
            .InstalledApp("com.xamarin.MyNewApp55")
            .StartApp();

Exception:

Xamarin.UITest.XDB.Exceptions.DeviceAgentException : Failed to install
  DeviceAgent

ExitCode: 5

  -c,--codesign-identity  <codesign-identifier> [OPTIONAL]    Identity

used to codesign app bundle [device only]. Deprecated - should use
  profile path. DEFAULT=        -d,--device-id   iOS
  Simulator GUID, physical device ID, or an alias
        -f,--force   [OPTIONAL]    Reinstall the app if
  the device contains an older version than the bundle
  specified DEFAULT=0       -i,--resources-path  [OPTIONAL]
    Path to resources (executables) to inject into app directory. A list
  of colon separated files may be specified.
        -p,--profile-path    [OPTIONAL]   Path to provisioning
  profile   install  Application
  com.apple.test.DeviceAgent-Runner is not installed on
  00008030-0003048114F0802E Error installing application: Failed to
  install application with path
  /var/folders/39/0rfg9kc92gx9bbslgw3td95h0000gq/T/xdb/DeviceAgent.iOS.Dependencies/b747d1445588083eee4d1d93a53f3e5b/ipa/DeviceAgent-Runner.app

How can I solve this issue?

Body:
About method InstalledApp(string bundleId) , it has follow definition :

Configures the installed app to use. Will force a run on physical device.

You should run it in a physical device .

Therefore , if need to run in simulator device ,should use AppBundle (string path) :

Configures the app bundle to use. Will force a run on simulator.

The AppBundle method can be used to specify where on the file system the app bundle may be found. There are two ways to do so, with an absolute path, or a relative path. This snippet shows using an absolute path to the app bundle:

IApp app = ConfigureApp
    .iOS
    .AppBundle("/path/to/iosapp.app")
    .StartApp();

To use a relative path, the path must be relative to the Xamarin.UITest assembly. This snippet is and example of how to use a relative path to locate the app bundle:

IApp app = ConfigureApp
    .iOS
    .AppBundle("../../../iOSAppProject/bin/iPhoneSimulator/Debug/iosapp.app")
    .StartApp();

The relative path example tells AppBundle to go up three directories from the Xamarin.UITest assembly, and then navigate down the project tree of the iOS application project to find the app bundle.

Here is the official document about Initialize IApp for iOS Applications.


问:
Read text file from google drive
I have simple text file in my google drive and it is publicly shared. When I read it

```<code>   InputStream is = new URL(url).openStream();
</code>```

The following is read. I assume my file is google doc format. Is there anyway I can read it as a text or convert it to text?

```<code>   <!DOCTYPE html><html><head><meta name="google" content="notranslate"><meta http-equiv="X-UA-
   Compatible" content="IE=edge;"><meta name="viewport" content="width=device-width, initial-
   scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"/><style>@font-face{font-
   family:'Roboto';font-style:italic;font-...……..
</code>```

答:
I would recommend you to use the Drive API, using the Files: export endpoint and setting the mimeType as text/plain, you will be able to get the file as the format you want.

You can check the Java Quickstart to get an idea about how to use the API on Java.

Title: Read text file from google drive

Body:
I have simple text file in my google drive and it is publicly shared. When I read it

   InputStream is = new URL(url).openStream();

The following is read. I assume my file is google doc format. Is there anyway I can read it as a text or convert it to text?

   <!DOCTYPE html><meta name="google" content="notranslate"><meta http-equiv="X-UA-
   Compatible" content="IE=edge;"><meta name="viewport" content="width=device-width, initial-
   scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"/>


问:
Calling Typescript function from Highcharts load event
I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :

```<code>events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },

  public openDialog(option,type){
       //Do Something
  }
</code>```

EDIT

I have got one link where there are binding this with function.

Is there anything that I am missing ?

答:
I am not sure this will work or not, but from my understanding, your this is not pointing to myOptions object and series key is present in myOptions object,

To make this work you should declare series outside of myOptions object

```<code>seriesData = [{
  name: 'John',
  data: [5, 3, 4, 7, 2]
}, {
  name: 'Jane',
  data: [2, 2, 3, 2, 1]
}, {
  name: 'Joe',
  data: [3, 4, 4, 2, 5]
}];

 myOptions = {
    chart: {
        type: 'bar',
        events: {
           load: () => {
              for (var j in this.seriesData) {
                  var series = this.seriesData[j];
                  for (var i in series.data) {
                   .
                   .
                  }
              }
            }
        }
    },

    series: this.seriesData
 }
</code>```

Body:
I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :

events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },

  public openDialog(option,type){
       //Do Something
  }

EDIT

I have got one link where there are binding this with function.

Is there anything that I am missing ?

Body:
I am not sure this will work or not, but from my understanding, your this is not pointing to myOptions object and series key is present in myOptions object,

To make this work you should declare series outside of myOptions object

seriesData = [{
  name: 'John',
  data: [5, 3, 4, 7, 2]
}, {
  name: 'Jane',
  data: [2, 2, 3, 2, 1]
}, {
  name: 'Joe',
  data: [3, 4, 4, 2, 5]
}];

 myOptions = {
    chart: {
        type: 'bar',
        events: {
           load: () => {
              for (var j in this.seriesData) {
                  var series = this.seriesData[j];
                  for (var i in series.data) {
                   .
                   .
                  }
              }
            }
        }
    },

    series: this.seriesData
 }


问:
Mockito Inject mock into Spy object
I'm writing a test case for a Class which has a 2 level of dependency injection. I use @Spy annotation for the 1 level dependency injection object, and I would like to Mock the 2nd level of injection. However, I kept getting null pointer exception on the 2nd level. Is there any way that I inject the mock into the @Spy object?</p>

```<code>public class CarTestCase{
    @Mock
    private Configuration configuration;

    @Spy
    private Engine engine;

    @InjectMocks
    private Car car;

    @Test
    public void test(){

       Mockito.when(configuration.getProperties("")).return("Something");
       car.drive();
    }

}

public class Car{
    @Inject
    private Engine engine;

    public void drive(){
        engine.start();
    }
}

public class Engine{
    @Inject
    private Configuration configuration;

    public void start(){
        configuration.getProperties();   // null pointer exception
    }

}
</code>```

答:
The (simplest) solution that worked for me.

```<code>@InjectMocks
private MySpy spy = Mockito.spy(new MySpy());
</code>```

No need for MockitoAnnotations.initMocks(this) in this case, as long as test class is annotated with @RunWith(MockitoJUnitRunner.class).

ContentLicense: CC BY-SA 3.0

Title: Mockito Inject mock into Spy object

Body:
I'm writing a test case for a Class which has a 2 level of dependency injection. I use @Spy annotation for the 1 level dependency injection object, and I would like to Mock the 2nd level of injection. However, I kept getting null pointer exception on the 2nd level. Is there any way that I inject the mock into the @Spy object?

public class CarTestCase{
    @Mock
    private Configuration configuration;

    @Spy
    private Engine engine;

    @InjectMocks
    private Car car;

    @Test
    public void test(){

       Mockito.when(configuration.getProperties("")).return("Something");
       car.drive();
    }

}

public class Car{
    @Inject
    private Engine engine;

    public void drive(){
        engine.start();
    }
}

public class Engine{
    @Inject
    private Configuration configuration;

    public void start(){
        configuration.getProperties();   // null pointer exception
    }

}

Body:
The (simplest) solution that worked for me.

@InjectMocks
private MySpy spy = Mockito.spy(new MySpy());

No need for MockitoAnnotations.initMocks(this) in this case, as long as test class is annotated with @RunWith(MockitoJUnitRunner.class).


问:
Change mac os x default php version
In my mac (version 10.13.6 High Sierra) php -v output is PHP 7.1.32 .
I need to update this 7.1 version to 7.3.

i tried to remove this version using brew unlink php7.1 but it's not worked.

How can i upgrade php version.

答:
I am not sure about the 10.13.6 High Sierra version, but this worked for me.

php -v (To see what version php has. But you have already done that)

brew unlink php55 (In my case I use php 5.5)

brew install php73 (For the php 7.3 version.)

php -v (To check of the version is the one I need.)

Hope this helps.

Title: Change mac os x default php version


问:
Reading binary data file in python for analysis
I use Fortran to write data to a binary file in the following format

```<code>open(unit=99,form='unformatted',status='unknown')
do i=1,N
write(99) (i),(A(i)),(B(i))
enddo
close(99)
</code>```

Here, A and B are double precision arrays.
How can this binary data file be read in python?

PS: So far, I tried the following steps to read data.

```<code>with open('fort.99', 'rb') as binfile:
    data=binfile.read()
</code>```

Though the file reading is succesful, I am unable to use the numpy functions on this data, which is my preferred choice for most of the analyses.

Body:
I use Fortran to write data to a binary file in the following format

open(unit=99,form='unformatted',status='unknown')
do i=1,N
write(99) (i),(A(i)),(B(i))
enddo
close(99)

Here, A and B are double precision arrays.
How can this binary data file be read in python?

PS: So far, I tried the following steps to read data.

with open('fort.99', 'rb') as binfile:
    data=binfile.read()

Though the file reading is succesful, I am unable to use the numpy functions on this data, which is my preferred choice for most of the analyses.

Body:
Updated Answer

I played around with this some more in Numpy and you can read the file much more cleanly like this - the information below still applies and explains how it works:

import numpy as np

# Read file and reshape as "records" of 28 bytes each
n = np.fromfile('fort.99',dtype=np.uint8).reshape(-1,28)
I = n[:,4:8].copy().view(np.int32)     # pick bytes 4-8, make contiguous and view as integer
A = n[:,8:16].copy().view(np.float64)  # pick bytes 8-16, make contiguous and view as float64
B = n[:,16:24].copy().view(np.float64) # pick bytes 16-24, make contiguous and view as float64

Original Answer

I changed your program to have some recognisable data:

      program thing
      REAL*8, DIMENSION(128) :: A,B
      INTEGER N
      N=128

      open(unit=99,form='unformatted',status='unknown')
      do i=1,N
      A(i)=100.0 * i
      B(i)=-1000.0 * i
      write(99) (2*i),(A(i)),(B(i))
      enddo
      close(99)
      end program

Then I looked at the file size and it was 3,584 bytes, so I divided that by 128 to get the bytes per fortran WRITE as 28.

So, inspected the data with xxd as follows:

xxd -c 28 fort.99

00000000: 1400 0000 0200 0000 0000 0000 0000 5940 0000 0000 0040 8fc0 1400 0000  ..............Y@.....@......
0000001c: 1400 0000 0400 0000 0000 0000 0000 6940 0000 0000 0040 9fc0 1400 0000  ..............i@.....@......
00000038: 1400 0000 0600 0000 0000 0000 00c0 7240 0000 0000 0070 a7c0 1400 0000  ..............r@.....p......
00000054: 1400 0000 0800 0000 0000 0000 0000 7940 0000 0000 0040 afc0 1400 0000  ..............y@.....@......
00000070: 1400 0000 0a00 0000 0000 0000 0040 7f40 0000 0000 0088 b3c0 1400 0000  .............@.@............
0000008c: 1400 0000 0c00 0000 0000 0000 00c0 8240 0000 0000 0070 b7c0 1400 0000  ...............@.....p......
000000a8: 1400 0000 0e00 0000 0000 0000 00e0 8540 0000 0000 0058 bbc0 1400 0000  ...............@.....X......
000000c4: 1400 0000 1000 0000 0000 0000 0000 8940 0000 0000 0040 bfc0 1400 0000  ...............@.....@......
000000e0: 1400 0000 1200 0000 0000 0000 0020 8c40 0000 0000 0094 c1c0 1400 0000  ............. .@............
000000fc: 1400 0000 1400 0000 0000 0000 0040 8f40 0000 0000 0088 c3c0 1400 0000  .............@.@............

So there are 28 bytes per fortran WRITE and there are 4 bytes of indexing at the start and end of each record.

Then I decoded them like this:

#!/usr/bin/env python3

import struct

# Important to open the file in binary mode, 'b'
with open('fort.99','rb') as f:
     # You should really read until error in case there are more or fewer than 128 records one day - but you know there are 128

    for i in range(128):
        # Read one record, i.e. output of one fortran WRITE
        record = f.read(28)
        # Unpack 2 INTEGERs, 2 DOUBLEs and an INTEGER
        _, I, A, B, _ = struct.unpack('2i2di',record)
        print(I,A,B)

Output

2 100.0 -1000.0
4 200.0 -2000.0
6 300.0 -3000.0
8 400.0 -4000.0
10 500.0 -5000.0
12 600.0 -6000.0
14 700.0 -7000.0
16 800.0 -8000.0
18 900.0 -9000.0
20 1000.0 -10000.0
22 1100.0 -11000.0
24 1200.0 -12000.0
26 1300.0 -13000.0
28 1400.0 -14000.0
30 1500.0 -15000.0
32 1600.0 -16000.0
34 1700.0 -17000.0
36 1800.0 -18000.0
38 1900.0 -19000.0
40 2000.0 -20000.0
42 2100.0 -21000.0
44 2200.0 -22000.0
46 2300.0 -23000.0
48 2400.0 -24000.0
50 2500.0 -25000.0
52 2600.0 -26000.0
54 2700.0 -27000.0
56 2800.0 -28000.0
58 2900.0 -29000.0
60 3000.0 -30000.0
62 3100.0 -31000.0
64 3200.0 -32000.0
66 3300.0 -33000.0
68 3400.0 -34000.0
70 3500.0 -35000.0
72 3600.0 -36000.0
74 3700.0 -37000.0
76 3800.0 -38000.0
78 3900.0 -39000.0
80 4000.0 -40000.0
82 4100.0 -41000.0
84 4200.0 -42000.0
86 4300.0 -43000.0
88 4400.0 -44000.0
90 4500.0 -45000.0
92 4600.0 -46000.0
94 4700.0 -47000.0
96 4800.0 -48000.0
98 4900.0 -49000.0
100 5000.0 -50000.0
102 5100.0 -51000.0
104 5200.0 -52000.0
106 5300.0 -53000.0
108 5400.0 -54000.0
110 5500.0 -55000.0
112 5600.0 -56000.0
114 5700.0 -57000.0
116 5800.0 -58000.0
118 5900.0 -59000.0
120 6000.0 -60000.0
122 6100.0 -61000.0
124 6200.0 -62000.0
126 6300.0 -63000.0
128 6400.0 -64000.0
130 6500.0 -65000.0
132 6600.0 -66000.0
134 6700.0 -67000.0
136 6800.0 -68000.0
138 6900.0 -69000.0
140 7000.0 -70000.0
142 7100.0 -71000.0
144 7200.0 -72000.0
146 7300.0 -73000.0
148 7400.0 -74000.0
150 7500.0 -75000.0
152 7600.0 -76000.0
154 7700.0 -77000.0
156 7800.0 -78000.0
158 7900.0 -79000.0
160 8000.0 -80000.0
162 8100.0 -81000.0
164 8200.0 -82000.0
166 8300.0 -83000.0
168 8400.0 -84000.0
170 8500.0 -85000.0
172 8600.0 -86000.0
174 8700.0 -87000.0
176 8800.0 -88000.0
178 8900.0 -89000.0
180 9000.0 -90000.0
182 9100.0 -91000.0
184 9200.0 -92000.0
186 9300.0 -93000.0
188 9400.0 -94000.0
190 9500.0 -95000.0
192 9600.0 -96000.0
194 9700.0 -97000.0
196 9800.0 -98000.0
198 9900.0 -99000.0
200 10000.0 -100000.0
202 10100.0 -101000.0
204 10200.0 -102000.0
206 10300.0 -103000.0
208 10400.0 -104000.0
210 10500.0 -105000.0
212 10600.0 -106000.0
214 10700.0 -107000.0
216 10800.0 -108000.0
218 10900.0 -109000.0
220 11000.0 -110000.0
222 11100.0 -111000.0
224 11200.0 -112000.0
226 11300.0 -113000.0
228 11400.0 -114000.0
230 11500.0 -115000.0
232 11600.0 -116000.0
234 11700.0 -117000.0
236 11800.0 -118000.0
238 11900.0 -119000.0
240 12000.0 -120000.0
242 12100.0 -121000.0
244 12200.0 -122000.0
246 12300.0 -123000.0
248 12400.0 -124000.0
250 12500.0 -125000.0
252 12600.0 -126000.0
254 12700.0 -127000.0
256 12800.0 -128000.0

As you can see there are record markers 1400 0000 on each record, meaning the records are 20 bytes long (1 fortran INTEGER@4, 2 fortran DOUBLE@8) with 4 bytes of record marker at each end - which I read into a variable called _ and discarded in Python. If you don't want that, you need to use DIRECT /STREAM output in fortran - but I don't know if you can control that at the other end of your processing chain. See here for a description.

Keywords: fortran, Python, binary, unformatted, xxd, dump, records, view as integer, view as float, view as float64, view as double


问:
Python staticmethod decorator with inheritance
My case:

```<code>class BaseClass:

    @staticmethod
    def dummy_decorator(fnc):
        def wrapper():
            print('Im so dummy')
        return wrapper

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    def anymethod(self):
        print('hello world')
</code>```

When I look at dir(), I see my staticmethod

```<code>>>> c = InheritedClass()
>>> dir(c)
['__doc__', '__init__', '__module__', 'anymethod', 'dummy_decorator']
</code>```

Also, I can use my dummy operator as simple staticmethod inside new class.
But when I try to use it as decorator -- I get error

```<code>class InheritedClass(BaseClass):
    def __init__(self):
        pass

    @dummy_decorator
    def anymethod(self):
        print('hello world')

>>> NameError: name 'dummy_decorator' is not defined
</code>```

Why it works so?
I know, that if I change @dummy_decorator to @BaseClass.dummy_decorator -- everything will work, but why I can't use decorator without ref to parent class?

答:
To understand this properly, you need to understand how class definitions work. In a nutshell, everything inside a class block is executed just like regular Python code. Every name that has been created inside that class block (e.g. def or variable assignments) are then wrapped up at the end of the class block and become attributes of the new class object. It goes something like:

```<code># START CAPTURE
def __init__(self):
    pass

foo = 'bar'
# END CAPTURE

InheritedClass = # OBJECT WITH ATTRIBUTES "CAPTURED" ABOVE AND ADDITIONAL MAGIC
</code>```

So, any code within the class block is just regular Python code. It hasn't "inherited" anything yet. That's the "additional magic" applied to the resulting class object at the end of the class block. And since there's no global "dummy_decorator" name defined, you can't call it by that name. It exists as "BaseClass.dummy_decoator", same as it would outside any class block.

Body:
My case:

class BaseClass:

    @staticmethod
    def dummy_decorator(fnc):
        def wrapper():
            print('Im so dummy')
        return wrapper

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    def anymethod(self):
        print('hello world')

When I look at dir(), I see my staticmethod

>>> c = InheritedClass()
>>> dir(c)
['__doc__', '__init__', '__module__', 'anymethod', 'dummy_decorator']

Also, I can use my dummy operator as simple staticmethod inside new class.
But when I try to use it as decorator -- I get error

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    @dummy_decorator
    def anymethod(self):
        print('hello world')

>>> NameError: name 'dummy_decorator' is not defined

Why it works so?
I know, that if I change @dummy_decorator to @BaseClass.dummy_decorator -- everything will work, but why I can't use decorator without ref to parent class?

Body:
To understand this properly, you need to understand how class definitions work. In a nutshell, everything inside a class block is executed just like regular Python code. Every name that has been created inside that class block (e.g. def or variable assignments) are then wrapped up at the end of the class block and become attributes of the new class object. It goes something like:

# START CAPTURE
def __init__(self):
    pass

foo = 'bar'
# END CAPTURE

InheritedClass = # OBJECT WITH ATTRIBUTES "CAPTURED" ABOVE AND ADDITIONAL MAGIC

So, any code within the class block is just regular Python code. It hasn't "inherited" anything yet. That's the "additional magic" applied to the resulting class object at the end of the class block. And since there's no global "dummy_decorator" name defined, you can't call it by that name. It exists as "BaseClass.dummy_decoator", same as it would outside any class block.


问:
Storing data points in a vector in a loop in R
I have a loop as written below:

```<code>Net_Sentiment_n = c()

for (i in 1:length(corpfinal)) {
  sentence = sentimentr::get_sentences(as.character(corpfinal[[i]][1]))
  sentence_sentiment_n[i] = sentimentr::sentiment(sentence[i],
           lexicon::hash_sentiment_loughran_mcdonald, n.before = Inf, n.after = Inf)
   Net_Sentiment_n[i] = mean(sentence_sentiment_n$sentiment)
}
</code>```

Here, the resultant Net_Sentiment_n is a vector

corpfinal is a corpus with length 797 (797 text files), also corpfinal[[i]][1] gives the text for each file (i.e. [1] for 1st text file and [2] for second and so on)

The sentence function extracts individual sentences from each file in the corpus and stores it as a list,for example, to get first sentence of the first text files it would sentence[[1]][1], for second sentence[[1]][2] and so on

The sentence_sentiment_n is a function extract sentiment from these sentences for each individual text file.

And the mean(sentence_sentiment_n) gives the average (overall) sentiment for each text file (Averages across sentences).

I want to store the overall sentiment for each text file in the vector Net_sentiment_n, however currently I am only getting the sentiment of the last file when I run the loop.

As an example for corpus, please consider below:

text_1 = tm::PlainTextDocument("this is just an example.However it does serve a good purpose.","if this works, the overall text should also work.")

corp_test = tm::Corpus(tm::VectorSource(text_1))

Can someone please suggest on how to proceed.

答:
Net_Sentiment_n = c()

for (i in 1:length(corpfinal)){

sentence = sentimentr::get_sentences(as.character(corpfinal[[i]][1]))

sentence_sentiment_n = sentimentr::sentiment(sentence,lexicon::hash_sentiment_loughran_mcdonald, n.before = 0, n.after = 1)

Net_Sentiment_n = mean(sentence_sentiment_n$sentiment)

}

needed a minor adjustment, works perfect now.

Body:
I have a loop as written below:

Net_Sentiment_n = c()

for (i in 1:length(corpfinal)) {
  sentence = sentimentr::get_sentences(as.character(corpfinal[[i]][1]))
  sentence_sentiment_n[i] = sentimentr::sentiment(sentence[i],
           lexicon::hash_sentiment_loughran_mcdonald, n.before = Inf, n.after = Inf)
   Net_Sentiment_n[i] = mean(sentence_sentiment_n$sentiment)
}

Here, the resultant Net_Sentiment_n is a vector

corpfinal is a corpus with length 797 (797 text files), also corpfinal[[i]][1] gives the text for each file (i.e. [1] for 1st text file and [2] for second and so on)

The sentence function extracts individual sentences from each file in the corpus and stores it as a list,for example, to get first sentence of the first text files it would sentence[[1]][1], for second sentence[[1]][2] and so on

The sentence_sentiment_n is a function extract sentiment from these sentences for each individual text file.

And the mean(sentence_sentiment_n) gives the average (overall) sentiment for each text file (Averages across sentences).

I want to store the overall sentiment for each text file in the vector Net_sentiment_n, however currently I am only getting the sentiment of the last file when I run the loop.

As an example for corpus, please consider below:

text_1 = tm::PlainTextDocument("this is just an example.However it does serve a good purpose.","if this works, the overall text should also work.")

corp_test = tm::Corpus(tm::VectorSource(text_1))

Can someone please suggest on how to proceed.


问:
Create data array with loop in vue
I have this data array holding repetitive item in the component:

```<code>data () {
datasets: [ {
        text: "",
        value:[ {
          x: "",
          y: "",
          type: 'bar'
        }]
        },
          {
        text: "",
        value: [{
          x: "",
          y: "",
          type: 'bar'
        }]
        },
        {
        text: "",
        value: [{
          x: "",
          y: "",
          type: 'bar'
        }]
        }
]
}
</code>```

As you can see those are the same items. Is it possible to set this data like

```<code>datasets:[ {
        text: "",
        value:[ {
          x: "",
          y: "",
          type: 'bar'
        }]
        } * 3 ]
</code>```

Instead of hardcoding it several times?

答:
It is:

```<code>datasets: Array(3).fill().map(() => ({
  text: "",
  value:[ {
    x: "",
    y: "",
    type: 'bar'
  }]
}))
</code>```

In case elements are guaranteed to be read-only and can benefit from holding a reference to the same object, it can be:

```<code>datasets: Array(3).fill({
  text: "",
  value:[ {
    x: "",
    y: "",
    type: 'bar'
  }]
})
</code>```

Title: Create data array with loop in vue

Body:
I have this data array holding repetitive item in the component:

data () {
datasets: [ {
        text: "",
        value:[ {
          x: "",
          y: "",
          type: 'bar'
        }]
        },
          {
        text: "",
        value: [{
          x: "",
          y: "",
          type: 'bar'
        }]
        },
        {
        text: "",
        value: [{
          x: "",
          y: "",
          type: 'bar'
        }]
        }
]
}

As you can see those are the same items. Is it possible to set this data like

datasets:[ {
        text: "",
        value:[ {
          x: "",
          y: "",
          type: 'bar'
        }]
        } * 3 ]

Instead of hardcoding it several times?

Body:
It is:

datasets: Array(3).fill().map(() => ({
  text: "",
  value:[ {
    x: "",
    y: "",
    type: 'bar'
  }]
}))

In case elements are guaranteed to be read-only and can benefit from holding a reference to the same object, it can be:

datasets: Array(3).fill({
  text: "",
  value:[ {
    x: "",
    y: "",
    type: 'bar'
  }]
})


问:
Fill blank values with data from following columns
Having a dataframe like this:

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))
</code>```

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))
</code>```

答:
here is a data.table approach...

explanation in comments below

```<code>#sample data
df <- data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"), stringsAsFactors = FALSE)

library( data.table )
#create data.table
setDT( df )
#paste together columns by id
ans <- df[, .(string = paste0( .SD, collapse =";")), by = .(id) ][]
#    id            string
# 1:  1    sth;more;final
# 2:  2      ;another;and
# 3:  3 another;add;where
# 4:  4             ;;all

#remove leading;'s
ans[, string := gsub("^;+", "", string) ]
#    id            string
# 1:  1    sth;more;final
# 2:  2       another;and
# 3:  3 another;add;where
# 4:  4               all

#split string back to columns, remove the temporary string-column
ans[, paste0( "text", 1:length( tstrsplit(ans$string, ";") ) ) :=
      tstrsplit( string, ";") ][, string := NULL ]
#    id   text1 text2 text3
# 1:  1     sth  more final
# 2:  2 another   and  <NA>
# 3:  3 another   add where
# 4:  4     all  <NA>  <NA>
</code>```

Body:
Having a dataframe like this:

data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))

Body:
here is a data.table approach...

explanation in comments below

#sample data
df <- data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"), stringsAsFactors = FALSE)

library( data.table )
#create data.table
setDT( df )
#paste together columns by id
ans <- df[, .(string = paste0( .SD, collapse =";")), by = .(id) ][]
#    id            string
# 1:  1    sth;more;final
# 2:  2      ;another;and
# 3:  3 another;add;where
# 4:  4             ;;all

#remove leading;'s
ans[, string := gsub("^;+", "", string) ]
#    id            string
# 1:  1    sth;more;final
# 2:  2       another;and
# 3:  3 another;add;where
# 4:  4               all

#split string back to columns, remove the temporary string-column
ans[, paste0( "text", 1:length( tstrsplit(ans$string, ";") ) ) :=
      tstrsplit( string, ";") ][, string := NULL ]
#    id   text1 text2 text3
# 1:  1     sth  more final
# 2:  2 another   and  <NA>
# 3:  3 another   add where
# 4:  4     all  <NA>  <NA>


问:
Running Ruby on Rails in browser
Hi I really want to learn Ruby on Rails and I have heard it is a great community so hopefully someone can help with this. Couldn't find any direct answering this already but if there is one I'm sure someone will close this and point me in the right direction.

Is it possible to create Ruby on Rails applications from just a browser? I have bought a book and want the easiest possible way to do the exercises and experiment with building some applications, try Gems etc. I know the greatest chance of success is if I can do this when I have a spare 30 minutes ideally on my iPad.

As I am also looking at learning node.js I have signed upto Duostack and Joyent but both still need SSH setup, Github install etc. I'm looking for something that is just in a browser Window, I can write code and see it execute without having to setup any infrastructure. Found this on HackerNews today (reticular activation system?): http://bellard.org/jslinux/ . Looks promising will need to play with it to see if I can get Ruby on Rails working there but HN comments say no Internet connection so maybe not.

I do have a small netbook which I am going to run Ubuntu on which I guess is the other option but carrying this around will reduce my chances of success.

答:
There is no way to directly create application from browser but if you want to really start rails then you can quickly start using scaffold.installed rail gem on your system and start with the following command

```<code>rails application_name
</code>```

go to the application and run below command

```<code>ruby script/generate scaffold users
</code>```

then run rake db:create and rake db:migrate

run your server using ruby script/server

it will start on port 3000 by default.

you can check it on browser using http://localhost:3000/

Note all above code is written in rails 2.x version

Title: Running Ruby on Rails in browser

Body:
There is no way to directly create application from browser but if you want to really start rails then you can quickly start using scaffold.installed rail gem on your system and start with the following command

rails application_name

go to the application and run below command

ruby script/generate scaffold users

then run rake db:create and rake db:migrate

run your server using ruby script/server

it will start on port 3000 by default.

you can check it on browser using http://localhost:3000/

Note all above code is written in rails 2.x version


问:
Is it normal to have two different dependent assembly but have the same public key token?
System.IO.FileSystem.Primitives -> b03f5f7f11d50a3a

System.Runtime.CompilerServices.Unsafe -> b03f5f7f11d50a3a

```<code><dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>
</code>```

I have this error:

An assembly with the same identity 'System.IO.FileSystem.Primitives,
  Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' has
  already been imported. Try removing one of the duplicate references.

答:
I manage to solve this error by removing the references of System.IO.FileSystem.Primitives in the project References section, but kept the nuget package installed

Use this link
https://github.com/dotnet/sdk/issues/1539#issuecomment-427397310

Body:
System.IO.FileSystem.Primitives -> b03f5f7f11d50a3a

System.Runtime.CompilerServices.Unsafe -> b03f5f7f11d50a3a

<dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>

I have this error:

An assembly with the same identity 'System.IO.FileSystem.Primitives,
  Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' has
  already been imported. Try removing one of the duplicate references.


问:
Save position of Snake and Detect Collison with it self. Whats wrong?

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Graphics;

namespace Snake
    {
    public partial class GameWindow : Form
    {
    private int glcontrolFieldWidth = 20, glcontrolFieldHeight = 20; //Playing Field
    public int speedincr = 0; //Speed, Increase by 5% Check out GenerateFood()
    public int GamePoints = -10; //Score
    private int shaderProgram, color_attribute; //Shader Program
    private int view, model, projection;//Shader Program
    private Matrix4 ViewMatrix, ModelMatrix, ProjectionMatrix; // Matrix4
    private List<Point> snake = new List<Point>() { new Point(1, 1) }; //Where the Snake Start off
    private Point snakeDirection = new Point(1, 0);//Snake Direction
    private Point mouse = new Point(); //Food
    private Random random = new Random(); //Random Genereator
    public bool bGameOver;
    private static readonly Timer timer = new Timer();

    public GameWindow()
    {
        //Form1.Designer
        InitializeComponent();

        // Centers the form on the current screen
        CenterToScreen();

        // Create a timer
        //var timer = new Timer();
        timer.Tick += new EventHandler(GameLoop);
        timer.Interval = 150; // This is the snake inital speed
        timer.Start();

        // Generate an initial random position for the food
        GenerateFood();
    }

    public void GameOver(bool bGameOver)
    {
        //Snake Collision with its own body
        //for (int i = 0; i < snake.Count; i++)
        //{
        //    //if Snake equal itself then snake hasn't touch any other parts of its body
        //    if (snake[0].X == snake[i].X || snake[0].Y == snake[i].Y)
        //    {
        //        this.bGameOver = false;
        //        //Console.WriteLine("Snake " + snake2[i].X + "," + snake2[i].Y);
        //        //Console.WriteLine("Snake2 " + snake[i].X + "," + snake[i].Y);
        //    }
        //    else
        //    {
        //        this.bGameOver = true;
        //        //Console.WriteLine(snake[i].X+","+snake[i].Y);
        //    }
        //}

        ////---Display GameOver Message If Where Dead-- - //

        //if (bGameOver == true)
        //{
        //    Console.WriteLine("Game Over! Push Enter to Continue");
        //    if (bGameOver == false)
        //    {
        //        //Game Start Over

        //    }
        //}
        return;
    } //GameOver Reset Game

    public void GameLoop(object sender, System.EventArgs e)
    {
        // Update coordinates of game entities and check collisions
        Update();
        // UpdateWall check collisions with snake to bounce off wall
        UpdateWall();
        GameOver(bGameOver);
        glControl.Invalidate();
    } //Basic of the Game Loop

    private void UpdateWall()
    {
        // Snake collison with Walls
        if (snake[0].X < 1)
        {
            //snake[0].X = (glcontrolFieldWidth - 2) / 10; //Warp to right
            //snakeDirection.X = (snake[0].X + glcontrolFieldWidth-2)/10;
            //snakeDirection.X = (glcontrolFieldWidth-2)/10;
            snakeDirection.X = (int)(glcontrolFieldWidth-0.5) / 10;
            snakeDirection.Y = (int)(glcontrolFieldWidth-0.5) / 10;
            Console.WriteLine("Snake hit left wall");
        }
        else if (snake[0].X > glcontrolFieldWidth - 2)
        {
            //snakeDirection.X = 0; //Warp to left
            snakeDirection.X = (int)(glcontrolFieldWidth - 0.5) / -10;
            snakeDirection.Y = (int)(glcontrolFieldWidth - 0.5) / -10;
            Console.WriteLine("Snake hit right wall");
        }

        if (snake[0].Y < 1)
        {
            //snake.getFirst().y = windowHeight / 10; //Warp to bottom
            //snakeDirection.Y = (snake[0].Y + glcontrolFieldWidth - 2)/10;
            snakeDirection.X = (int)(glcontrolFieldHeight - 0.5)/10;
            snakeDirection.Y = (int)(glcontrolFieldHeight - 0.5)/10;
            Console.WriteLine("Snake hit Top wall");
        }
        else if (snake[0].Y > glcontrolFieldHeight - 2)
        {
            //snake.getFirst().y = 0; //Warp to top
            snakeDirection.X = (int)(glcontrolFieldHeight - 0.5) / -10;
            snakeDirection.Y = (int)(glcontrolFieldHeight - 0.5) / -10;
            Console.WriteLine("Snake hit Bottom wall");
        }

    } //Wall Collision

    private new void Update()
    {
        // Calculate a new position of the head of the snake
        Point newHeadPosition = new Point(snake[0].X + snakeDirection.X, snake[0].Y + snakeDirection.Y);
        // Insert new position in the beginning of the snake list
        snake.Insert(0, newHeadPosition);
        snake.RemoveAt(snake.Count - 1);

        // Check snake collision with the food
        if (snake[0].X != mouse.X || snake[0].Y != mouse.Y)
        {
            return;
        }
        else
        {
            //Snake Grow
            snake.Add(new Point(mouse.X, mouse.Y));
        }
        Console.WriteLine();

        //foreach (Point aPart in snake)
        //{
        //    Console.WriteLine(aPart);
        //}

        // Generate a new food(mouse) position
        GenerateFood();

    }//...more code.
```

The rest of the code in GitHub @mrcoffeecode Snake Game C#. I manage to create the wall,food and snake. Also the detection with food and walls. Now am stuck in trying to figure out Game Over basically the snake detect it self getting bitten. The code is ready to run without any errors you just need opentk, opengl, openglcontrol.dll.

答:
It is sufficient to evaluate if the head of the snake hits its body. Test if snake[0] hits any element from 1 to snake.Count-1.
You have to verify if the x component and (&&) the y component is equal:

//Snake Collision with its own body
for (int i = 1; i < snake.Count; i++)
{
    //if Snake equal itself then snake hasn't touch any other parts of its body
    if (snake[0].X == snake[i].X && snake[0].Y == snake[i].Y)
    {
        this.bGameOver = true;
        break;
    }
}
```

<p>Note, in your code every time when the snake grows, a collision of the head with the body will be detected, because you insert a new element at the had position.<br>
You can get rid about set, if you just avoid to remove the tail element of the snake instead:</p>

<pre class="lang-cs prettyprint-override"><code>private new void Update()
{
    // Calculate a new position of the head of the snake
    Point newHeadPosition = new Point(snake[0].X + snakeDirection.X, snake[0].Y + snakeDirection.Y);
    // Insert new position in the beginning of the snake list
    snake.Insert(0, newHeadPosition);
    # snake.RemoveAt(snake.Count - 1); <--------- DELETE

    // Check snake collision with the food
    if (snake[0].X != mouse.X || snake[0].Y != mouse.Y)
    {
        # remove tail if snake does not grow
        snake.RemoveAt(snake.Count - 1); # <---------- ADD
        return;
    }
    else
    {
        //Snake Grow
        // snake.Add(new Point(mouse.X, mouse.Y)); <------ DELETE
    }
    Console.WriteLine();

    // Generate a new food(mouse) position
    GenerateFood();

} //Events
</code>```

Body:
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Graphics;

namespace Snake
    {
    public partial class GameWindow : Form
    {
    private int glcontrolFieldWidth = 20, glcontrolFieldHeight = 20; //Playing Field
    public int speedincr = 0; //Speed, Increase by 5% Check out GenerateFood()
    public int GamePoints = -10; //Score
    private int shaderProgram, color_attribute; //Shader Program
    private int view, model, projection;//Shader Program
    private Matrix4 ViewMatrix, ModelMatrix, ProjectionMatrix; // Matrix4
    private List<Point> snake = new List<Point>() { new Point(1, 1) }; //Where the Snake Start off
    private Point snakeDirection = new Point(1, 0);//Snake Direction
    private Point mouse = new Point(); //Food
    private Random random = new Random(); //Random Genereator
    public bool bGameOver;
    private static readonly Timer timer = new Timer();

    public GameWindow()
    {
        //Form1.Designer
        InitializeComponent();

        // Centers the form on the current screen
        CenterToScreen();

        // Create a timer
        //var timer = new Timer();
        timer.Tick += new EventHandler(GameLoop);
        timer.Interval = 150; // This is the snake inital speed
        timer.Start();

        // Generate an initial random position for the food
        GenerateFood();
    }

    public void GameOver(bool bGameOver)
    {
        //Snake Collision with its own body
        //for (int i = 0; i < snake.Count; i++)
        //{
        //    //if Snake equal itself then snake hasn't touch any other parts of its body
        //    if (snake[0].X == snake[i].X || snake[0].Y == snake[i].Y)
        //    {
        //        this.bGameOver = false;
        //        //Console.WriteLine("Snake " + snake2[i].X + "," + snake2[i].Y);
        //        //Console.WriteLine("Snake2 " + snake[i].X + "," + snake[i].Y);
        //    }
        //    else
        //    {
        //        this.bGameOver = true;
        //        //Console.WriteLine(snake[i].X+","+snake[i].Y);
        //    }
        //}

        ////---Display GameOver Message If Where Dead-- - //

        //if (bGameOver == true)
        //{
        //    Console.WriteLine("Game Over! Push Enter to Continue");
        //    if (bGameOver == false)
        //    {
        //        //Game Start Over

        //    }
        //}
        return;
    } //GameOver Reset Game

    public void GameLoop(object sender, System.EventArgs e)
    {
        // Update coordinates of game entities and check collisions
        Update();
        // UpdateWall check collisions with snake to bounce off wall
        UpdateWall();
        GameOver(bGameOver);
        glControl.Invalidate();
    } //Basic of the Game Loop

    private void UpdateWall()
    {
        // Snake collison with Walls
        if (snake[0].X < 1)
        {
            //snake[0].X = (glcontrolFieldWidth - 2) / 10; //Warp to right
            //snakeDirection.X = (snake[0].X + glcontrolFieldWidth-2)/10;
            //snakeDirection.X = (glcontrolFieldWidth-2)/10;
            snakeDirection.X = (int)(glcontrolFieldWidth-0.5) / 10;
            snakeDirection.Y = (int)(glcontrolFieldWidth-0.5) / 10;
            Console.WriteLine("Snake hit left wall");
        }
        else if (snake[0].X > glcontrolFieldWidth - 2)
        {
            //snakeDirection.X = 0; //Warp to left
            snakeDirection.X = (int)(glcontrolFieldWidth - 0.5) / -10;
            snakeDirection.Y = (int)(glcontrolFieldWidth - 0.5) / -10;
            Console.WriteLine("Snake hit right wall");
        }

        if (snake[0].Y < 1)
        {
            //snake.getFirst().y = windowHeight / 10; //Warp to bottom
            //snakeDirection.Y = (snake[0].Y + glcontrolFieldWidth - 2)/10;
            snakeDirection.X = (int)(glcontrolFieldHeight - 0.5)/10;
            snakeDirection.Y = (int)(glcontrolFieldHeight - 0.5)/10;
            Console.WriteLine("Snake hit Top wall");
        }
        else if (snake[0].Y > glcontrolFieldHeight - 2)
        {
            //snake.getFirst().y = 0; //Warp to top
            snakeDirection.X = (int)(glcontrolFieldHeight - 0.5) / -10;
            snakeDirection.Y = (int)(glcontrolFieldHeight - 0.5) / -10;
            Console.WriteLine("Snake hit Bottom wall");
        }

    } //Wall Collision

    private new void Update()
    {
        // Calculate a new position of the head of the snake
        Point newHeadPosition = new Point(snake[0].X + snakeDirection.X, snake[0].Y + snakeDirection.Y);
        // Insert new position in the beginning of the snake list
        snake.Insert(0, newHeadPosition);
        snake.RemoveAt(snake.Count - 1);

        // Check snake collision with the food
        if (snake[0].X != mouse.X || snake[0].Y != mouse.Y)
        {
            return;
        }
        else
        {
            //Snake Grow
            snake.Add(new Point(mouse.X, mouse.Y));
        }
        Console.WriteLine();

        //foreach (Point aPart in snake)
        //{
        //    Console.WriteLine(aPart);
        //}

        // Generate a new food(mouse) position
        GenerateFood();

    }//...more code.

The rest of the code in GitHub @mrcoffeecode Snake Game C#. I manage to create the wall,food and snake. Also the detection with food and walls. Now am stuck in trying to figure out Game Over basically the snake detect it self getting bitten. The code is ready to run without any errors you just need opentk, opengl, openglcontrol.dll.

Body:
It is sufficient to evaluate if the head of the snake hits its body. Test if snake[0] hits any element from 1 to snake.Count-1.
You have to verify if the x component and (&&) the y component is equal:

//Snake Collision with its own body
for (int i = 1; i < snake.Count; i++)
{
    //if Snake equal itself then snake hasn't touch any other parts of its body
    if (snake[0].X == snake[i].X && snake[0].Y == snake[i].Y)
    {
        this.bGameOver = true;
        break;
    }
}

Note, in your code every time when the snake grows, a collision of the head with the body will be detected, because you insert a new element at the had position.

You can get rid about set, if you just avoid to remove the tail element of the snake instead:

private new void Update()
{
    // Calculate a new position of the head of the snake
    Point newHeadPosition = new Point(snake[0].X + snakeDirection.X, snake[0].Y + snakeDirection.Y);
    // Insert new position in the beginning of the snake list
    snake.Insert(0, newHeadPosition);
    # snake.RemoveAt(snake.Count - 1); <--------- DELETE

    // Check snake collision with the food
    if (snake[0].X != mouse.X || snake[0].Y != mouse.Y)
    {
        # remove tail if snake does not grow
        snake.RemoveAt(snake.Count - 1); # <---------- ADD
        return;
    }
    else
    {
        //Snake Grow
        // snake.Add(new Point(mouse.X, mouse.Y)); <------ DELETE
    }
    Console.WriteLine();

    // Generate a new food(mouse) position
    GenerateFood();

} //Events


问:
Failed to create JVM after trying to set more memory for Android Studio
I am trying to set my memory on 4GB using the command -Xmx4g from Help->Edit VME Options but when I try to open the Android Studio I get the error mentioned in the title.

If you already have a 64-bit JDK installed, define a JAVA_HOME variable in Computer >System Properties > System Settings > Environment Variables.
  Failed to create JVM. JVM Path ...\jre.

I've already tried some other answers from the same questions, but nothing worked for me

Tried:

Go to C:\Program Files\Android\Android Studio\bin\studio.exe.vmoptions

Open it with notepad. some times it will not be editable so give
  administrative permission and change the following attributes:

-Xmx512m to -Xmx256m

-XX:MaxPermSize=250m to -XX:MaxPermSize=128m

Or change:

-Xmx750m to -Xmx512m

-XX:MaxPermSize=350m to -XX:MaxPermSize=250m

But in my C:\Program Files\Android\Android Studio\bin\studio.exe.vmoptions or C:\Program Files\Android\Android Studio\bin\studio64.exe.vmoptions

I don't have the -XX:MaxPermSize, only the -Xmx's which I already tried to change but nothing worked.

答:
Workarounds for this situation:

Run with -XX:-UseCompressedOops (keeping in mind that you would lose the performance benefit that comes with enabling CompressedOops).
  This will instruct the JVM to run without the Compressed Oops feature
  and it would not try to fit the Java Heap in the first 4GB of heap.

Keep the CompressedOops and set the base of the Java Heap with the JVM option -XX:HeapBaseMinAddress=n to specify the address where the
  Java Heap should start from. If you are running out of native memory,
  set it to a higher address so that there is enough room available for
  the native mallocs, and if Java Heap is getting exhausted then set it
  to a lower value. And if you need java heap to be allocated beyond 4GB
  or 32GB then HeapBaseMinAddress should be set to a value so that
  HeapBaseMinAddress + heap size > 4GB or 32GB. The default value of
  HeapBaseMinAddress on most of the platforms is 2GB.

Let's run a simple test program on solaris-sparc 10 and solaris-x64 11
  and see where the Java Heap is placed on these platforms when using
  CompressedOops.

For the work procedure refer the below link

https://blogs.oracle.com/poonam/running-on-a-64bit-platform-and-still-running-out-of-memory


问:
Is a STL vector pf pointers to vectors my best option?
I currently have a ton of vectors all set to have 1200 items, which is overkill, but could be used. So I don't have to recode a lot of stuff, what is the best way to create and iterate through a list of these vectors and resize them all as needed? (they all are equal in size)

One of my options is to create a pointer (after the fact) to each vector, and then create a vector of these pointers which can be iterated to resize.  Another option is to create the vectors in the first place as pointers instead of objects. This seems like it would be a lot of work, and I currently have a lot of code where I use the vector objects.

Are there other options?

Fred E.

答:
In C++, std::vector is just a wrapper around a raw data pointer. The vector itself stores data in the heap. So you can store vectors in a vector as objects, or you can store pointers to them.

The easiest way is to store vectors in a vector as objects, but you must carefully monitor how you pass this outer vector into functions. You should always pass it by reference or pass a pointer to it, so as not to trigger copying all nested vectors. On the other hand, such a vector will automatically and correctly remove nested vectors when its destructor fires.

The vector of pointers to vectors has its advantages and disadvantages. On the one hand, when a function is called inaccurately with this vector as a parameter, only pointers will be copied. On the other hand, accessing vectors through a pointer affects performance. In addition, when storing pointers to vectors, you must take care to delete them yourself.

If your vectors are created and deleted elsewhere and you only need to iterate through them and modify them in your code, then obviously the vector of pointers to vectors is your best choice.


问:
GIT merge conflict: after create new branch and deleting some files
I have a problem with a GIT merge. In fact, I have a master branch with this architecture:

```<code>.git
doc
   \__ some files

src
   \__ tools 1
              \__ some files

   \__ tools 2
              \__ some files
</code>```

In my project, I developed tools and I will add other tools in the "src" directory. For that, for each time I want to create a new tool, I will create a new branch named "tools3" from master branch and then remove all directories that I do not need, here "tools 1", "tools 2" and "doc". The reason is that I do not need documentation and other tools to develop.

So now, after those deleting I code my "tools 3" and I commit and push it into the new branch "tools3". It's time to merge my two branches with a git merge tools3 -m "Merge tools3 branch with master branch" (in master branch).

I have two problems, first some conflicts among with documentation files:

CONFLICT MESSAGE:
CONFLICT (modify/delete): doc/api_project.json deleted in tools3 and modified in HEAD. Version HEAD of doc/api_project.json left in tree.

In the second time, the merging removes my "src" files (the ones I deleted earlier in "tools3" branch).

So, how can I fix this merge conflict and then how can I retrieve my removing files in master branch? I think I do not have the best practice to do this type of things with GIT so I am open to any suggestions about GIT practices.

答:
You mustn't delete the files from the repo you don't need. This is the reason you get the conflict(s).

While you've been working in your tools 3 dir, other contributors may have worked in them. E.g. fixing bugs, adding new features, etc. They've completed their work and pushed it to master.

When its time for you to do push your work, history has diverged. Since you started your branch, on one hand you've deleted some files, and on the other these files have been changed by other people. Git can't make the decision on what the correct route to take is, so it creates a conflict.

You only really want to delete a file from a git repo if it is no longer useful for the entire project and no longer need it source controlled. To me it looks like you are only deleting them because you want to keep your directory structure "clean" or some other reason we can only speculate on.

Body:
I have a problem with a GIT merge. In fact, I have a master branch with this architecture:

.git
doc
   \__ some files

src
   \__ tools 1
              \__ some files

   \__ tools 2
              \__ some files

In my project, I developed tools and I will add other tools in the "src" directory. For that, for each time I want to create a new tool, I will create a new branch named "tools3" from master branch and then remove all directories that I do not need, here "tools 1", "tools 2" and "doc". The reason is that I do not need documentation and other tools to develop.

So now, after those deleting I code my "tools 3" and I commit and push it into the new branch "tools3". It's time to merge my two branches with a git merge tools3 -m "Merge tools3 branch with master branch" (in master branch).

I have two problems, first some conflicts among with documentation files:

CONFLICT MESSAGE:
CONFLICT (modify/delete): doc/api_project.json deleted in tools3 and modified in HEAD. Version HEAD of doc/api_project.json left in tree.

In the second time, the merging removes my "src" files (the ones I deleted earlier in "tools3" branch).

So, how can I fix this merge conflict and then how can I retrieve my removing files in master branch? I think I do not have the best practice to do this type of things with GIT so I am open to any suggestions about GIT practices.


问:
How do I implement graceful termination in Java?
Say for instance I have my application running in a Linux terminal and I press "CTRL+C" on my keyboard to kill the process it will terminate the Java program.

Is there any way to catch this "request" in my Java application so I can shut it down gracefully and release all resources/write logs. I have several different threads running if it makes a difference to the response.

I know you have have an addShutDownHook, but as written in the Java documentation, it isn't called under certain circumstances, like the kill signal from "CTRL+C" in linux...are there any other ways?

```<code>Runtime.getRuntime().addShutdownHook(new Thread()
{
    public void run ()
    {
        // TODO: implement graceful shutdown here.
    }
});
</code>```

答:
I think the disclaimer is only there for  kill -9, so that you don't rely on the shutdown hook being invoked to maintain say the consistency of your data.

So if the process is allowed to act on the signal by the OS, the shutdown hook is invoked, which is pretty obvious if you know how an OS works, but maybe not to all Java developers.

It is actually explained in great detail in the javadoc.

Also worth bearing in mind is that there can be multiple shutdown hooks registered in a VM, so yours might not be THE shutdown hook, just one of several.

Body:
Say for instance I have my application running in a Linux terminal and I press "CTRL+C" on my keyboard to kill the process it will terminate the Java program.

Is there any way to catch this "request" in my Java application so I can shut it down gracefully and release all resources/write logs. I have several different threads running if it makes a difference to the response.

I know you have have an addShutDownHook, but as written in the Java documentation, it isn't called under certain circumstances, like the kill signal from "CTRL+C" in linux...are there any other ways?

Runtime.getRuntime().addShutdownHook(new Thread()
{
    public void run ()
    {
        // TODO: implement graceful shutdown here.
    }
});


问:
Extract only numbers and only string from pandas dataframe
I am trying to extract only numbers and only strings in two different dataframes. I am using regular expression to extract numbers and string.

```<code>import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)
</code>```

I have also tried using '([\d+][\d+\.\d+])' and '([\d+\.\d+])'

Here I am getting output but not what I am expecting. Though I am expecting float numbers I am not getting 1.5 or 2.5.

I am getting something like below image:

```<code>df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)
</code>```

In this case when the number is at the end or in the beginning then I am getting the string but if the number placed in the middle or any other place then the result which I expect I am not getting.
Current output is like below image:

I think my regular expression is not correct. Which will be the right regular expression to solve these problems? Or is there any other way to extract only numbers and only strings in pandas dataframe?

答:
You could use (\d+\.\d+|\d+) to extract your numbers, and replace the results with "" to get your string.

```<code>print (df_num.assign(colors_num=df_num["Colors"].str.extract(r"(\d+\.\d+|\d+)"))
             .assign(colors_col=df_num["Colors"].str.replace(r"(\d+\.\d+|\d+)","")))

       Colors     Animals colors_num colors_col
0     lila1.5      hu11nd        1.5       lila
1     rosa2.5     12welpe        2.5       rosa
2     gelb3.5     13katze        3.5       gelb
3       grün4  s14chlange          4       grün
4        rot5     vo15gel          5        rot
5    schwarz6   16papagei          6    schwarz
6       grau7       ku17h          7       grau
7       weiß8     18ziege          8       weiß
8      braun9     19pferd          9      braun
9  hellblau10      esel20         10   hellblau
</code>```

Body:
I am trying to extract only numbers and only strings in two different dataframes. I am using regular expression to extract numbers and string.

import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)

I have also tried using '([\d+][\d+\.\d+])' and '([\d+\.\d+])'

Here I am getting output but not what I am expecting. Though I am expecting float numbers I am not getting 1.5 or 2.5.

I am getting something like below image:

df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)

In this case when the number is at the end or in the beginning then I am getting the string but if the number placed in the middle or any other place then the result which I expect I am not getting.
Current output is like below image:

I think my regular expression is not correct. Which will be the right regular expression to solve these problems? Or is there any other way to extract only numbers and only strings in pandas dataframe?

Body:
You could use (\d+\.\d+|\d+) to extract your numbers, and replace the results with "" to get your string.

print (df_num.assign(colors_num=df_num["Colors"].str.extract(r"(\d+\.\d+|\d+)"))
             .assign(colors_col=df_num["Colors"].str.replace(r"(\d+\.\d+|\d+)","")))

       Colors     Animals colors_num colors_col
0     lila1.5      hu11nd        1.5       lila
1     rosa2.5     12welpe        2.5       rosa
2     gelb3.5     13katze        3.5       gelb
3       grün4  s14chlange          4       grün
4        rot5     vo15gel          5        rot
5    schwarz6   16papagei          6    schwarz
6       grau7       ku17h          7       grau
7       weiß8     18ziege          8       weiß
8      braun9     19pferd          9      braun
9  hellblau10      esel20         10   hellblau


问:
How convert DateTime to string
I get from server response in DateTime like this :

2019-04-24T16:25:02.557Z

and I would like only in String:

2019-04-23

How can I do this?

my code:

```<code>let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)
    destinationVC.createdJob = k
} else {
    print("There was an error decoding the string")
}
</code>```

答:
To convert the 2019-04-24T16:25:02.557Z to a Date object, you'd use:

```<code>let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions.insert(.withFractionalSeconds)
guard let date = iso8601DateFormatter.date(from: "2019-04-24T16:25:02.557Z") else { return }
</code>```

And then to output only a date string in the UI, with no time, you'd use something like:

```<code>let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .medium
let result = outputFormatter.string(from: date)
</code>```

Title: How convert DateTime to string

Body:
I get from server response in DateTime like this :

2019-04-24T16:25:02.557Z

and I would like only in String:

2019-04-23

How can I do this?

my code:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)
    destinationVC.createdJob = k
} else {
    print("There was an error decoding the string")
}

Body:
To convert the 2019-04-24T16:25:02.557Z to a Date object, you'd use:

let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions.insert(.withFractionalSeconds)
guard let date = iso8601DateFormatter.date(from: "2019-04-24T16:25:02.557Z") else { return }

And then to output only a date string in the UI, with no time, you'd use something like:

let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .medium
let result = outputFormatter.string(from: date)


答:
A vectorized base R approach :

```<code>#Get indices where text1 is empty
inds <- which(df$text1 == '')
#get values to replace from the corresponding rows
vals <- cbind(inds, max.col(df[inds, 3:ncol(df)] != "") + 2)
#Replace the values
df$text1[inds] <- df[vals]
#Change the replaced value with blank.
df[vals] <- ''

df
#  id   text1 text2 text3
#1  1     sth  more final
#2  2 another         and
#3  3 another   add where
#4  4     all
</code>```

data

```<code>df <- data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""),
       text2 = c("more","another","add",""),
       text3 = c("final","and","where","all"), stringsAsFactors = FALSE)
</code>```

Title: Fill blank values with data from following columns

Body:
A vectorized base R approach :

#Get indices where text1 is empty
inds <- which(df$text1 == '')
#get values to replace from the corresponding rows
vals <- cbind(inds, max.col(df[inds, 3:ncol(df)] != "") + 2)
#Replace the values
df$text1[inds] <- df[vals]
#Change the replaced value with blank.
df[vals] <- ''

df
#  id   text1 text2 text3
#1  1     sth  more final
#2  2 another         and
#3  3 another   add where
#4  4     all

data

df <- data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""),
       text2 = c("more","another","add",""),
       text3 = c("final","and","where","all"), stringsAsFactors = FALSE)


问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答:
Inside <appSettings> you can create application keys,

```<code><add key="KeyName" value="Keyvalue"/>
</code>```

Later on you can access these values using:

```<code>ConfigurationManager.AppSettings["Keyname"]
</code>```

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

Body:
Inside <appSettings> you can create application keys,

<add key="KeyName" value="Keyvalue"/>

Later on you can access these values using:

ConfigurationManager.AppSettings["Keyname"]

OwnerDisplayName: Sergio