问:
Create decimal values of character hex
With the following code I'm reading a text file and displaying one column on the screen.

```<code>externalData <- read.delim("testdata.txt", header = FALSE, sep = "@")

i = 1;
while(i < 11) {
  appel <- as.character(externalData[i,3,1])
  i = i + 1;
  print(appel)
}
</code>```

The output looks like this:

I'm trying to convert these values from hexadecimal to decimal.

I've tried the following:

```<code>strtoi(c(appel))
</code>```

but this doesn't seem to work, this only removes the quotation marks from the first one and the last one, and sets everything in-between to N/A (probably because there are letters in them).

答:
Here are 3 ways to convert hexadecimal(character) to decimal(numeric).</p>

```<code>x <- c("158308", "bb1787", "853f91")

# 1.
strtoi(x, base = 16L)

# 2.
as.integer(as.hexmode(x))

# 3.
as.integer(paste0("0x", x))
# more general edition:
# as.integer(ifelse(!grepl("^0x", x), paste0("0x", x), x))
</code>```

Title: Create decimal values of character hex

Body:
With the following code I'm reading a text file and displaying one column on the screen.

externalData <- read.delim("testdata.txt", header = FALSE, sep = "@")

i = 1;
while(i < 11) {
  appel <- as.character(externalData[i,3,1])
  i = i + 1;
  print(appel)
}

The output looks like this:

I'm trying to convert these values from hexadecimal to decimal.

I've tried the following:

strtoi(c(appel))

but this doesn't seem to work, this only removes the quotation marks from the first one and the last one, and sets everything in-between to N/A (probably because there are letters in them).

Body:
Here are 3 ways to convert hexadecimal(character) to decimal(numeric).

x <- c("158308", "bb1787", "853f91")

# 1.
strtoi(x, base = 16L)

# 2.
as.integer(as.hexmode(x))

# 3.
as.integer(paste0("0x", x))
# more general edition:
# as.integer(ifelse(!grepl("^0x", x), paste0("0x", x), x))


来源: stackexchange

问:
How do I mark URL's to appear as href's when viewed via the eclipse editor
// Refer: http://en.wikipedia.org/wiki/Decimal

I have a snippet like this in my java source code, viewed via the Eclipse editor. How do I make this appear as a href, so that users can just click on it, instead of doing a cut-n-paste.

Is is possible?

答: It`s appeared as URL, when you hover on it with Ctrl pressed. Currently it works in PDT under WIN.</p>

ContentLicense: CC BY-SA 3.0


问:
liquibase does not generate table DATABASECHANGELOG
I'm new to liquibase and I want to use it on an database in production.
It's a small application, but instead of creating schema by hand I would like to use something more professional like liquibase.

What I plan to do is to make a changelog between the current schema in production and the new schema ready for the new application. I've followed many tutorials but there is still something missing. The output changelog.xml always imports all the schema and doesn't make the difference with the existing. I saw that liquibase had to create the table DATABASECHANGELOG but I couldn't see them on my computer.

What I did :

dump of the current db in production and import on dev computer

from core project added liquibase.properties and launched the following command : mvn clean resources:resources liquibase:generateChangeLog

this generated a master.xml with all the schema, but didn't create the tables DATABASECHANGELOG in DB (the table DATABASECHANGELOGLOCK was created when commenting outputChangeLogFile, and the LOCKED value is 0)

created manually the DATABASECHANGELOG from http://www.liquibase.org/databases.html

rerun the command mvn liquibase:generateChangeLog. Still nothing

pom.xml :

```<code><dependencies>
    ...
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.17</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>

 <!-- edited build after 1st comment. Still got the problem -->
<build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase.version}</version>
            <configuration>
                <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                <propertyFile>src/main/resources/liquibase.properties</propertyFile>
            </configuration>
        </plugin>
    </plugins>
</build>

<!--- old section build, left for history purpose --->
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>${liquibase.version}</version>
                <configuration>
                    <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                    <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                    <propertyFile>src/main/resources/liquibase.properties</propertyFile>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
</code>```

liquibase.properties :

```<code>url=jdbc:mysql://localhost:3306/my_db
username=user
password=pass
driver=com.mysql.jdbc.Driver
outputChangeLogFile=src/main/resources/liquibase/master.xml
</code>```

NB : commenting outputChangeLogFile made liquibase create the table DATABASECHANGELOGLOCK, but only this one.

maven output :

```<code>[INFO] ------------------------------------------------------------------------
[INFO] Building -CORE 0.0.2
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- liquibase-maven-plugin:3.5.3:generateChangeLog (default-cli) @ EDI-CORE ---
[INFO] ------------------------------------------------------------------------
[INFO] Parsing Liquibase Properties File
[INFO]   File: src/main/resources/liquibase.properties
[INFO]   'classpath' in properties file is not being used by this task.
[INFO] ------------------------------------------------------------------------
[INFO] Executing on Database: jdbc:mysql://localhost:3306/my_db
[INFO] Generating Change Log from database root@localhost @ jdbc:mysql://localhost:3306/my_db (Default Schema: edi)
INFO 17/01/17 15:01: liquibase: src\main\resources\liquibase\master.xml exists, appending
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
[INFO] Output written to Change Log file, src/main/resources/liquibase/master.xml
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

答:
Since you are specify a outputChangeLogFile in your properties file Liquibase is trying to create it (via liquibase:generateChangeLog) for your based on your specified connection. Try to use changeLogFile in your liquibase.prperties instead:

```<code>url=jdbc:mysql://localhost:3306/my_db
username=user
password=pass
driver=com.mysql.jdbc.Driver
changeLogFile=src/main/resources/liquibase/master.xml
</code>```

Body:
I'm new to liquibase and I want to use it on an database in production.
It's a small application, but instead of creating schema by hand I would like to use something more professional like liquibase.

What I plan to do is to make a changelog between the current schema in production and the new schema ready for the new application. I've followed many tutorials but there is still something missing. The output changelog.xml always imports all the schema and doesn't make the difference with the existing. I saw that liquibase had to create the table DATABASECHANGELOG but I couldn't see them on my computer.

What I did :

dump of the current db in production and import on dev computer

from core project added liquibase.properties and launched the following command : mvn clean resources:resources liquibase:generateChangeLog

this generated a master.xml with all the schema, but didn't create the tables DATABASECHANGELOG in DB (the table DATABASECHANGELOGLOCK was created when commenting outputChangeLogFile, and the LOCKED value is 0)

created manually the DATABASECHANGELOG from http://www.liquibase.org/databases.html

rerun the command mvn liquibase:generateChangeLog. Still nothing

pom.xml :

<dependencies>
    ...
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.17</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase.version}</version>
            <configuration>
                <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                <propertyFile>src/main/resources/liquibase.properties</propertyFile>
            </configuration>
        </plugin>
    </plugins>
</build>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>${liquibase.version}</version>
                <configuration>
                    <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                    <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                    <propertyFile>src/main/resources/liquibase.properties</propertyFile>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

liquibase.properties :

url=jdbc:mysql://localhost:3306/my_db
username=user
password=pass
driver=com.mysql.jdbc.Driver
outputChangeLogFile=src/main/resources/liquibase/master.xml

NB : commenting outputChangeLogFile made liquibase create the table DATABASECHANGELOGLOCK, but only this one.

maven output :

[INFO] ------------------------------------------------------------------------
[INFO] Building -CORE 0.0.2
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- liquibase-maven-plugin:3.5.3:generateChangeLog (default-cli) @ EDI-CORE ---
[INFO] ------------------------------------------------------------------------
[INFO] Parsing Liquibase Properties File
[INFO]   File: src/main/resources/liquibase.properties
[INFO]   'classpath' in properties file is not being used by this task.
[INFO] ------------------------------------------------------------------------
[INFO] Executing on Database: jdbc:mysql://localhost:3306/my_db
[INFO] Generating Change Log from database root@localhost @ jdbc:mysql://localhost:3306/my_db (Default Schema: edi)
INFO 17/01/17 15:01: liquibase: src\main\resources\liquibase\master.xml exists, appending
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
[INFO] Output written to Change Log file, src/main/resources/liquibase/master.xml
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Body:
Since you are specify a outputChangeLogFile in your properties file Liquibase is trying to create it (via liquibase:generateChangeLog) for your based on your specified connection. Try to use changeLogFile in your liquibase.prperties instead:

url=jdbc:mysql://localhost:3306/my_db
username=user
password=pass
driver=com.mysql.jdbc.Driver
changeLogFile=src/main/resources/liquibase/master.xml

ContentLicense: CC BY-SA 4.0


问:
Error: 419|Page Expired (Laravel 6.0 -Mysql)
I have Added the @csrf token and in form and in the meta tag in header but still getting the same erro. When I register it works and redirects me to the home page. That's fine but it doesn't redirect me to home page when I login although the credentials are okay and fine.

Login.blade.php

```<code>@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col-md-6 offset-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label class="form-check-label" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
</code>```

WEB.PHP

```<code>Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/admin', function(){
    echo "Hello Admin";
})->middleware('auth','admin');

Route::get('/agent', function(){
    echo "Hello Agent";
})->middleware('auth','agent');

Route::get('/customer', function(){
    echo "Hello Customer";
})->middleware('auth','customer');
</code>```

LoginController.php

```<code><?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
//        $this->middleware('auth');
//        $this->middleware('admin');
    }

    protected function redirectTo( ) {
        if (Auth::check() && Auth::user()->role == 'customer') {
            return redirect('/customer');
        }
        elseif (Auth::check() && Auth::user()->role == 'agent') {
            return redirect('/agent');
        }
        else {
            return redirect('/admin');
        }
    }
}
</code>```

答:
```<code>## LoginController.php ##
</code>```

There was version difference the above code in the Question is for laravel framework 5.6 and i have updated laravel and the code for laravel framework 6.15.1 or 6 is below this is the only issue.

```<code> protected function redirectTo( ) {

//        dd(Auth::user()->role);

        if (Auth::check() && Auth::user()->role == 'customer') {
            $this->redirectTo = '/customer';
            return $this->redirectTo;
        }
        elseif (Auth::check() && Auth::user()->role == 'agent') {
            $this->redirectTo = '/agent';
            return $this->redirectTo;
        }
        else {
            $this->redirectTo = '/admin';
            return $this->redirectTo;
        }

    }
</code>```

Body:
I have Added the @csrf token and in form and in the meta tag in header but still getting the same erro. When I register it works and redirects me to the home page. That's fine but it doesn't redirect me to home page when I login although the credentials are okay and fine.

Login.blade.php

@extends('layouts.app')

@section('content')

{{ __('Login') }}

                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                            {{ __('E-Mail Address') }}

                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')

                                        {{ $message }}

                                @enderror

                            {{ __('Password') }}

                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')

                                        {{ $message }}

                                @enderror

                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                        {{ __('Remember Me') }}

                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))

                                        {{ __('Forgot Your Password?') }}

                                @endif

                    </form>

@endsection

WEB.PHP

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/admin', function(){
    echo "Hello Admin";
})->middleware('auth','admin');

Route::get('/agent', function(){
    echo "Hello Agent";
})->middleware('auth','agent');

Route::get('/customer', function(){
    echo "Hello Customer";
})->middleware('auth','customer');

LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
//        $this->middleware('auth');
//        $this->middleware('admin');
    }

    protected function redirectTo( ) {
        if (Auth::check() && Auth::user()->role == 'customer') {
            return redirect('/customer');
        }
        elseif (Auth::check() && Auth::user()->role == 'agent') {
            return redirect('/agent');
        }
        else {
            return redirect('/admin');
        }
    }
}

Body:
## LoginController.php ##

There was version difference the above code in the Question is for laravel framework 5.6 and i have updated laravel and the code for laravel framework 6.15.1 or 6 is below this is the only issue.

 protected function redirectTo( ) {

//        dd(Auth::user()->role);

        if (Auth::check() && Auth::user()->role == 'customer') {
            $this->redirectTo = '/customer';
            return $this->redirectTo;
        }
        elseif (Auth::check() && Auth::user()->role == 'agent') {
            $this->redirectTo = '/agent';
            return $this->redirectTo;
        }
        else {
            $this->redirectTo = '/admin';
            return $this->redirectTo;
        }

    }


问:
HammerJs: enable vertical scroll with horizontal swipe
I've got an angular 7 website, and I want to add horizontal swipe to one component, and vertical swipe to another (the components are in the same module). I'm using hammerjs for that.

By default, hammerjs disables vertical swipe, so I enabled swipping in all directions with the code below.

```<code>export class MyHammerConfig extends HammerGestureConfig
{
  overrides = <any>{
    swipe: {direction: Hammer.DIRECTION_ALL},
  };
}

//declare provider in AppModule
providers: [
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: MyHammerConfig
    }
]
</code>```

The problem is vertical scrolling does not work on the component with the horizontal swipe. From what I've read, the solution is to add touch-action: pan-y in the component with the horizontal swipe.

However, this works on chrome but safari does not recognise the touch-action property.

My idea was to declare multiple providers for HAMMER_GESTURE_CONFIG, at the component level:

on the component with horizontal swipe, use a provider which only allows horizontal swipe

on the other one, only enable vertical swipe

However, component-level providers do not seem to take my providers into account.

Here is some code I tried to use to only enable horizontal swipe

```<code>export class HorizontalHammerConfig extends HammerGestureConfig
{
  overrides = <any>{
    swipe: {Hammer.DIRECTION_HORIZONTAL},
    pinch: {enable: false},
    rotate: {enable: false}
  };
}

//Component declaration
@Component({
  ...

  providers:[
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: HorizontalHammerConfig
    }],
</code>```

Any idea?

Edit: Here is a stackblitz example demostrating the issue. The component level providers are ignored.

答:
I found the solution there.

Basically, the custom configuration has to override the buildHammer class, so different hammerjs options can be used depending on the context.

app.module.ts

```<code>export class MyHammerConfig extends HammerGestureConfig
{
  overrides = <any>{
    swipe: {direction: Hammer.DIRECTION_ALL},
  };

  buildHammer(element: HTMLElement)
  {
    let options = {};

    if (element.attributes['data-mc-options'])
    {
      try
      {
        options = JSON.parse(element.attributes['data-mc-options'].nodeValue);
      }
      catch (err)
      {
        console.error('An error occurred when attempting to parse Hammer.js options: ', err);
      }
    }

    const mc = new Hammer(element, options);

    // retain support for angular overrides object
    for (const eventName of Object.keys(this.overrides))
    {
      mc.get(eventName).set(this.overrides[eventName]);
    }

    return mc;
  }
}
</code>```

And then, in the component template, pass the extra option as a json string.

component.html

```<code><div (swipeleft)="onSwipeLeft()" data-mc-options='{ "touchAction": "pan-y" }'">
</div>
</code>```

This works with safari/iOS

Body:
I've got an angular 7 website, and I want to add horizontal swipe to one component, and vertical swipe to another (the components are in the same module). I'm using hammerjs for that.

By default, hammerjs disables vertical swipe, so I enabled swipping in all directions with the code below.

export class MyHammerConfig extends HammerGestureConfig
{
  overrides = <any>{
    swipe: {direction: Hammer.DIRECTION_ALL},
  };
}

//declare provider in AppModule
providers: [
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: MyHammerConfig
    }
]

The problem is vertical scrolling does not work on the component with the horizontal swipe. From what I've read, the solution is to add touch-action: pan-y in the component with the horizontal swipe.

However, this works on chrome but safari does not recognise the touch-action property.

My idea was to declare multiple providers for HAMMER_GESTURE_CONFIG, at the component level:

on the component with horizontal swipe, use a provider which only allows horizontal swipe

on the other one, only enable vertical swipe

However, component-level providers do not seem to take my providers into account.

Here is some code I tried to use to only enable horizontal swipe

export class HorizontalHammerConfig extends HammerGestureConfig
{
  overrides = <any>{
    swipe: {Hammer.DIRECTION_HORIZONTAL},
    pinch: {enable: false},
    rotate: {enable: false}
  };
}

//Component declaration
@Component({
  ...

  providers:[
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: HorizontalHammerConfig
    }],

Any idea?

Edit: Here is a stackblitz example demostrating the issue. The component level providers are ignored.

Body:
I found the solution there.

Basically, the custom configuration has to override the buildHammer class, so different hammerjs options can be used depending on the context.

app.module.ts

export class MyHammerConfig extends HammerGestureConfig
{
  overrides = <any>{
    swipe: {direction: Hammer.DIRECTION_ALL},
  };

  buildHammer(element: HTMLElement)
  {
    let options = {};

    if (element.attributes['data-mc-options'])
    {
      try
      {
        options = JSON.parse(element.attributes['data-mc-options'].nodeValue);
      }
      catch (err)
      {
        console.error('An error occurred when attempting to parse Hammer.js options: ', err);
      }
    }

    const mc = new Hammer(element, options);

    // retain support for angular overrides object
    for (const eventName of Object.keys(this.overrides))
    {
      mc.get(eventName).set(this.overrides[eventName]);
    }

    return mc;
  }
}

And then, in the component template, pass the extra option as a json string.

component.html

<div (swipeleft)="onSwipeLeft()" data-mc-options='{ "touchAction": "pan-y" }'">
</div>

This works with safari/iOS


问:
How to build index in a single groovy script?
When I have updated my janus graph schema, I have created a property key but forgot to build the index.If I run same piece of code with this buildIndex of that property then my data will get redundant data. So I am trying to build the index directly in the gremlin console.
What I have tried is

```<code>    :remote connect tinkerpop.server conf/remote.yaml
    // myScript = new File('/tmp/scripts/dbscripts/campaignTypeSchema/01_campaignTypeSchema.groovy').getText('UTF-8')
    // :> @myScript
    :> m = graph.openManagement()

    /** Getting Vertex Labels **/
    :> Campaign = m.getVertexLabel('Campaign')

    /** Vertex Properties creation **/
    :> campaignType = graph.openManagement().getPropertyKey('campaignType')

    /** Vertex supporting indexes **/
    :> graph.openManagement().buildIndex('campaignTypeByCampaign', Vertex.class).addKey(graph.openManagement().getPropertyKey('campaignType')).buildCompositeIndex()
    println "Finished updating schema"
    :remote close
    :x
</code>```

But endedup with an error

```<code>    Error in /tmp/scripts/dbscripts/campaignTypeSchema/run.groovy at [9: :> Campaign = m.getVertexLabel('Campaign')] - No such property: m for class: Script36
    org.apache.tinkerpop.gremlin.jsr223.console.RemoteException: No such property: m for class: Script36
    at org.apache.tinkerpop.gremlin.console.jsr223.DriverRemoteAcceptor.submit(DriverRemoteAcceptor.java:178)
    at org.apache.tinkerpop.gremlin.console.commands.SubmitCommand.execute(SubmitCommand.groovy:41)
    at org.codehaus.groovy.tools.shell.Shell.execute(Shell.groovy:104)
    at org.codehaus.groovy.tools.shell.Groovysh.super$2$execute(Groovysh.groovy)
    at sun.reflect.GeneratedMethodAccessor15.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:145)
    at org.codehaus.groovy.tools.shell.Groovysh.executeCommand(Groovysh.groovy:273)
    at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:164)
    at org.apache.tinkerpop.gremlin.console.GremlinGroovysh.super$3$execute(GremlinGroovysh.groovy)
    at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:145)
    at org.apache.tinkerpop.gremlin.console.GremlinGroovysh.execute(GremlinGroovysh.groovy:72)
    at org.apache.tinkerpop.gremlin.console.Console$_executeInShell_closure16.doCall(Console.groovy:371)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
    at groovy.lang.Closure.call(Closure.java:418)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2041)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2021)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2071)
    at org.codehaus.groovy.runtime.dgm$175.doMethodInvoke(Unknown Source)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.executeInShell(Console.groovy:348)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.<init>(Console.groovy:141)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.main(Console.groovy:453)
</code>```

Then I have tried running directly in gremlin console

```<code>    gremlin> :> graph.openManagement().buildIndex('campaignTypeByCampaign', Vertex.class).addKey(graph.openManagement().getPropertyKey('campaignType')).buildCompositeIndex()
</code>```

For this I got an error saying

```<code>    The vertex or type is not associated with this transaction [campaignType]
</code>```

答:
You need to create your remote connection as a session:

```<code>:remote connect tinkerpop.server conf/remote.yaml session
</code>```

as described here or else variable state won't be persisted between commands.

Body:
When I have updated my janus graph schema, I have created a property key but forgot to build the index.If I run same piece of code with this buildIndex of that property then my data will get redundant data. So I am trying to build the index directly in the gremlin console.
What I have tried is

    :remote connect tinkerpop.server conf/remote.yaml
    // myScript = new File('/tmp/scripts/dbscripts/campaignTypeSchema/01_campaignTypeSchema.groovy').getText('UTF-8')
    // :> @myScript
    :> m = graph.openManagement()

    /** Getting Vertex Labels **/
    :> Campaign = m.getVertexLabel('Campaign')

    /** Vertex Properties creation **/
    :> campaignType = graph.openManagement().getPropertyKey('campaignType')

    /** Vertex supporting indexes **/
    :> graph.openManagement().buildIndex('campaignTypeByCampaign', Vertex.class).addKey(graph.openManagement().getPropertyKey('campaignType')).buildCompositeIndex()
    println "Finished updating schema"
    :remote close
    :x

But endedup with an error

    Error in /tmp/scripts/dbscripts/campaignTypeSchema/run.groovy at [9: :> Campaign = m.getVertexLabel('Campaign')] - No such property: m for class: Script36
    org.apache.tinkerpop.gremlin.jsr223.console.RemoteException: No such property: m for class: Script36
    at org.apache.tinkerpop.gremlin.console.jsr223.DriverRemoteAcceptor.submit(DriverRemoteAcceptor.java:178)
    at org.apache.tinkerpop.gremlin.console.commands.SubmitCommand.execute(SubmitCommand.groovy:41)
    at org.codehaus.groovy.tools.shell.Shell.execute(Shell.groovy:104)
    at org.codehaus.groovy.tools.shell.Groovysh.super$2$execute(Groovysh.groovy)
    at sun.reflect.GeneratedMethodAccessor15.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:145)
    at org.codehaus.groovy.tools.shell.Groovysh.executeCommand(Groovysh.groovy:273)
    at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:164)
    at org.apache.tinkerpop.gremlin.console.GremlinGroovysh.super$3$execute(GremlinGroovysh.groovy)
    at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:145)
    at org.apache.tinkerpop.gremlin.console.GremlinGroovysh.execute(GremlinGroovysh.groovy:72)
    at org.apache.tinkerpop.gremlin.console.Console$_executeInShell_closure16.doCall(Console.groovy:371)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
    at groovy.lang.Closure.call(Closure.java:418)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2041)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2021)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.eachWithIndex(DefaultGroovyMethods.java:2071)
    at org.codehaus.groovy.runtime.dgm$175.doMethodInvoke(Unknown Source)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.executeInShell(Console.groovy:348)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.<init>(Console.groovy:141)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.console.Console.main(Console.groovy:453)

Then I have tried running directly in gremlin console

    gremlin> :> graph.openManagement().buildIndex('campaignTypeByCampaign', Vertex.class).addKey(graph.openManagement().getPropertyKey('campaignType')).buildCompositeIndex()

For this I got an error saying

    The vertex or type is not associated with this transaction [campaignType]

Body:
You need to create your remote connection as a session:

:remote connect tinkerpop.server conf/remote.yaml session

as described here or else variable state won't be persisted between commands.


问:
Can I run/use 3 feature files with a single step definition file in cucumber Java
Can I run/use  3 feature files  with a single step definition file in cucumber Java? Does cucumber java supports this?

I have the following feature files:

```<code>login.feature
registration.feature
search.feature
</code>```

I need to implement only 1 step-definition.java file
    for the 3  feature files.

答: You can create a step for one feature and if the step makes sense and the logic is the same you can use it on other feature files without creating another step.</p>

Body:
Can I run/use  3 feature files  with a single step definition file in cucumber Java? Does cucumber java supports this?

I have the following feature files:

login.feature
registration.feature
search.feature

I need to implement only 1 step-definition.java file
    for the 3  feature files.


问:
Unable to yum install anything on RHEL
I am on a new RHEL system.

I seem to be unable to be able to install anything package via yum install.

```<code>yum install nmap
</code>```

The current repos in

```<code>ls /etc/yum.repos.d/
google-chrome.repo  redhat.repo         rhel-source.repo
</code>```

What could be going wrong ?

OUTPUT OF YUM INSTALL:

```<code>$ sudo yum install nmap
[sudo] password for user:
Loaded plugins: product-id, refresh-packagekit, security, subscription-manager
Updating certificate-based repositories.
Setting up Install Process
No package nmap available.
Error: Nothing to do
</code>```

答:
Try installing using:

```<code>yum install nmap-frontend
</code>```

It worked for me on Red Hat Enterprise Linux Server release 7.7 (Maipo)

You can use the following line to test:

```<code>nmap 25 gmail-smtp-in.l.google.com
</code>```

Title: Unable to yum install anything on RHEL

Body:
I am on a new RHEL system.

I seem to be unable to be able to install anything package via yum install.

yum install nmap

The current repos in

ls /etc/yum.repos.d/
google-chrome.repo  redhat.repo         rhel-source.repo

What could be going wrong ?

OUTPUT OF YUM INSTALL:

$ sudo yum install nmap
[sudo] password for user:
Loaded plugins: product-id, refresh-packagekit, security, subscription-manager
Updating certificate-based repositories.
Setting up Install Process
No package nmap available.
Error: Nothing to do

Body:
Try installing using:

yum install nmap-frontend

It worked for me on Red Hat Enterprise Linux Server release 7.7 (Maipo)

You can use the following line to test:

nmap 25 gmail-smtp-in.l.google.com


问:
Accessing Windows Credential Manager from PowerShell
I'm using PowerShell 2.0 (necessary because of SP2010) On Windows Server 2008 R2. I need to retrieve credentials for a process from the Windows Credential Manager. I can't seem to make it work.

I was given this piece of code:

```<code>[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % { $_.RetrievePassword(); $_ }
</code>```

both lines of code throw errors

```<code>Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime : Unable to find type [Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]: make sure that the assembly containing this type is loaded.
</code>```

and

```<code>(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % {$_.RetrievePassword(); $_ }
</code>```

respectively. I've been trying to somehow import the PasswordVault class. So far Google has failed me, I haven't even been able to find out which assembly it resides in. What am I missing?

答:
SecretManagement and SecretStore from Microsoft appear to be the official solution. They were officially released on March 25, 2021. The secret can be a credential.</p>
```<code>Install-Module Microsoft.PowerShell.SecretManagement
Install-Module SecretManagement.JustinGrote.CredMan  # windows credential manager
Register-SecretVault SecretManagement.JustinGrote.CredMan
Set-Secret -Name TestSecret -Secret "TestSecret"
Get-Secret -Name TestSecret -AsPlainText
</code>```
```<code>TestSecret
</code>```

Body:
I'm using PowerShell 2.0 (necessary because of SP2010) On Windows Server 2008 R2. I need to retrieve credentials for a process from the Windows Credential Manager. I can't seem to make it work.

I was given this piece of code:

[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % { $_.RetrievePassword(); $_ }

both lines of code throw errors

Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime : Unable to find type [Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]: make sure that the assembly containing this type is loaded.

and

(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % {$_.RetrievePassword(); $_ }

respectively. I've been trying to somehow import the PasswordVault class. So far Google has failed me, I haven't even been able to find out which assembly it resides in. What am I missing?

Body:
SecretManagement and SecretStore from Microsoft appear to be the official solution. They were officially released on March 25, 2021. The secret can be a credential.

Install-Module Microsoft.PowerShell.SecretManagement
Install-Module SecretManagement.JustinGrote.CredMan  # windows credential manager
Register-SecretVault SecretManagement.JustinGrote.CredMan
Set-Secret -Name TestSecret -Secret "TestSecret"
Get-Secret -Name TestSecret -AsPlainText

TestSecret


问:
Accessing $_POST data sent by Jquery/AJAX
I am using this function:

```<code>function end_incident() {
    var dataString = 'name=Daniel&phone=01234123456';
    $.ajax({
        type: "POST",
        url: "http://www.example.co.uk/erc/end_incident.php",
        data: dataString,
        success: function(msg){
            alert('Success!'+dataString);
        }
    });
};
</code>```

to send information to end_incident.php, but I'm not able to access the $_POST variables. I've tried doing it like this:

```<code>$name = $_POST['name'];
$phone = $_POST['phone'];
</code>```

Am I doing something wrong?

Thanks for any help

答:
Try sending the data as an object:</p>

```<code>function end_incident() {
    $.ajax({
       type: "POST",
       url: "http://www.example.co.uk/erc/end_incident.php",
       data: { name: "Daniel", phone: "01234123456" },
       success: function(msg){
            alert('Success!');
       }
    });
};
</code>```

Body:
I am using this function:

function end_incident() {
    var dataString = 'name=Daniel&phone=01234123456';
    $.ajax({
        type: "POST",
        url: "http://www.example.co.uk/erc/end_incident.php",
        data: dataString,
        success: function(msg){
            alert('Success!'+dataString);
        }
    });
};

to send information to end_incident.php, but I'm not able to access the $_POST variables. I've tried doing it like this:

$name = $_POST['name'];
$phone = $_POST['phone'];

Am I doing something wrong?

Thanks for any help

Body:
Try sending the data as an object:

function end_incident() {
    $.ajax({
       type: "POST",
       url: "http://www.example.co.uk/erc/end_incident.php",
       data: { name: "Daniel", phone: "01234123456" },
       success: function(msg){
            alert('Success!');
       }
    });
};


问:
Can I select empty textareas with CSS?
Is there a way that I can select a textarea such that $('#id_of_textarea').val() in jQuery will be ''? I tried using :empty. I saw that CSS provides a way to select empty inputs because the text is in the value attribute ([value=""]). Is there an attribute for the text in a textarea?

I'm looking for a selector that will work with CSS, not just jQuery.

答:
this works in recent browsers except edge (at the moment):

```<code>textarea:placeholder-shown {
  /* this should be active only when area is empty and placeholder shown */
}
</code>```

so with jQuery for example you can pick all empty textareas:

```<code>$('textarea:placeholder-shown').val()
</code>```

https://developer.mozilla.org/en/docs/Web/CSS/:placeholder-shown

Title: Can I select empty textareas with CSS?

Body:
this works in recent browsers except edge (at the moment):

textarea:placeholder-shown {
  /* this should be active only when area is empty and placeholder shown */
}

so with jQuery for example you can pick all empty textareas:

$('textarea:placeholder-shown').val()

https://developer.mozilla.org/en/docs/Web/CSS/:placeholder-shown


问:
Optimize foreach loop in laravel
I need bulk insert in subscriber table and subscriber field table in which data comes from CSV file.

The subscriber table need the only email and subscriber fields table need subscriber id from subscriber table, field id from field table and other CSV fields.

So, I write this code for this job and here a lot of foreach loop, that's why it takes a lot of time for execute when I insert a large CSV file.

Now, Any possible to optimize this code?

Here is my code :

```<code>$emails = array();
foreach ($data as $item) {
    array_push($emails, $item['email']);
}

$subscribers = Subscriber::select('email')->whereIn('email', $emails)->where('mail_list_id', $this->id)->get();

//check exists mail in database
$exists_mail = array();
foreach ($subscribers as $item) {
    $exists_mail[$item->email] = true;
}

//get subscriber unique key
$subscriber_uid = array();

//get all field value
$total_field = array();

//bulk insert in subscribers table

$subscriberBatch = array();
foreach ($data as $item) {
    if (!isset($exists_mail[$item['email']])) {
        $column['uid'] = uniqid();
        $column['mail_list_id'] = $this->id;
        $column['email'] = $item['email'];
        $column['status'] = Subscriber::STATUS_SUBSCRIBED;
        $column['subscription_type'] = Subscriber::SUBSCRIPTION_TYPE_IMPORTED;

        array_push($subscriberBatch, $column);
        array_push($subscriber_uid, $column['uid']);

        $fieldKey['uid'] = $column['uid'];
        foreach ($fields as $field) {
            $fieldKey[Str::lower($field['tag'])] = $item[Str::lower($field['tag'])];
        }

        array_push($total_field, $fieldKey);
    }
}

Subscriber::insert($subscriberBatch);

//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')->whereIn('uid', $subscriber_uid)->get()->toArray();

foreach ($totalSubscriber as $index => $subscriber) {
    $total_field[$index]['subscriber_id'] =  $subscriber['id'];
}

$fieldBatch = array();
foreach ($total_field as $item) {
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $item['subscriber_id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
    }
}

SubscriberField::insert($fieldBatch);

</code>```

答:
```<code>//set all email in a array
$emails = array();
foreach ($data as $item) {
    array_push($emails, $item['email']);
}

$exists_mail = array();

$subscribers = Subscriber::whereIn('email', $emails)
->where('mail_list_id', $this->id)
->pluck('email')
->toArray();

//get subscriber unique key
$subscriber_uid = array();

//get all field value
$total_field = array();

//bulk insert in subscribers table
$subscriberBatch = array();
foreach ($data as $item) {
    if(!in_array($item['email'], $subscribers)){
        $column['uid'] = uniqid();
        $column['mail_list_id'] = $this->id;
        $column['email'] = $item['email'];
        $column['status'] = Subscriber::STATUS_SUBSCRIBED;
        $column['subscription_type'] = Subscriber::SUBSCRIPTION_TYPE_IMPORTED;

        array_push($subscriberBatch, $column);
        array_push($subscriber_uid, $column['uid']);

        $fieldKey['uid'] = $column['uid'];
        foreach ($fields as $field) {
            $fieldKey[Str::lower($field['tag'])] = $item[Str::lower($field['tag'])];
        }

        array_push($total_field, $fieldKey);
    }
}

Subscriber::insert($subscriberBatch);

//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')
->whereIn('uid', $subscriber_uid)
->get()
->toArray();

$fieldBatch = array();

foreach ($totalSubscriber as $index => $subscriber) {
    $total_field[$index]['subscriber_id'] =  $subscriber['id'];
}

foreach ($total_field as $item) {
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $item['subscriber_id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
    }
}

SubscriberField::insert($fieldBatch);
</code>```

I remove below code and use pluck

```<code>$subscribers = Subscriber::select('email')->whereIn('email', $emails)->where('mail_list_id', $this->id)->get();

//check exists mail in database
$exists_mail = array();
foreach ($subscribers as $item) {
    $exists_mail[$item->email] = true;
}
</code>```

We more optimize and we can remove below code

```<code>foreach ($total_field as $item) {
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $item['subscriber_id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
</code>```

}
}

Like:

```<code>//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')
->whereIn('uid', $subscriber_uid)
->get()
->toArray();

$fieldBatch = array();

foreach ($totalSubscriber as $index => $subscriber) {
    //$total_field[$index]['subscriber_id'] =  $subscriber['id'];
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $subscriber['id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
    }
}
</code>```

But I don't know what type of data in $fields array if you provide field array the I will try more optimize.

Title: Optimize foreach loop in laravel

Body:
I need bulk insert in subscriber table and subscriber field table in which data comes from CSV file.

The subscriber table need the only email and subscriber fields table need subscriber id from subscriber table, field id from field table and other CSV fields.

So, I write this code for this job and here a lot of foreach loop, that's why it takes a lot of time for execute when I insert a large CSV file.

Now, Any possible to optimize this code?

Here is my code :

$emails = array();
foreach ($data as $item) {
    array_push($emails, $item['email']);
}

$subscribers = Subscriber::select('email')->whereIn('email', $emails)->where('mail_list_id', $this->id)->get();

//check exists mail in database
$exists_mail = array();
foreach ($subscribers as $item) {
    $exists_mail[$item->email] = true;
}

//get subscriber unique key
$subscriber_uid = array();

//get all field value
$total_field = array();

//bulk insert in subscribers table

$subscriberBatch = array();
foreach ($data as $item) {
    if (!isset($exists_mail[$item['email']])) {
        $column['uid'] = uniqid();
        $column['mail_list_id'] = $this->id;
        $column['email'] = $item['email'];
        $column['status'] = Subscriber::STATUS_SUBSCRIBED;
        $column['subscription_type'] = Subscriber::SUBSCRIPTION_TYPE_IMPORTED;

        array_push($subscriberBatch, $column);
        array_push($subscriber_uid, $column['uid']);

        $fieldKey['uid'] = $column['uid'];
        foreach ($fields as $field) {
            $fieldKey[Str::lower($field['tag'])] = $item[Str::lower($field['tag'])];
        }

        array_push($total_field, $fieldKey);
    }
}

Subscriber::insert($subscriberBatch);

//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')->whereIn('uid', $subscriber_uid)->get()->toArray();

foreach ($totalSubscriber as $index => $subscriber) {
    $total_field[$index]['subscriber_id'] =  $subscriber['id'];
}

$fieldBatch = array();
foreach ($total_field as $item) {
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $item['subscriber_id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
    }
}

SubscriberField::insert($fieldBatch);

Body:
//set all email in a array
$emails = array();
foreach ($data as $item) {
    array_push($emails, $item['email']);
}

$exists_mail = array();

$subscribers = Subscriber::whereIn('email', $emails)
->where('mail_list_id', $this->id)
->pluck('email')
->toArray();

//get subscriber unique key
$subscriber_uid = array();

//get all field value
$total_field = array();

//bulk insert in subscribers table
$subscriberBatch = array();
foreach ($data as $item) {
    if(!in_array($item['email'], $subscribers)){
        $column['uid'] = uniqid();
        $column['mail_list_id'] = $this->id;
        $column['email'] = $item['email'];
        $column['status'] = Subscriber::STATUS_SUBSCRIBED;
        $column['subscription_type'] = Subscriber::SUBSCRIPTION_TYPE_IMPORTED;

        array_push($subscriberBatch, $column);
        array_push($subscriber_uid, $column['uid']);

        $fieldKey['uid'] = $column['uid'];
        foreach ($fields as $field) {
            $fieldKey[Str::lower($field['tag'])] = $item[Str::lower($field['tag'])];
        }

        array_push($total_field, $fieldKey);
    }
}

Subscriber::insert($subscriberBatch);

//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')
->whereIn('uid', $subscriber_uid)
->get()
->toArray();

$fieldBatch = array();

foreach ($totalSubscriber as $index => $subscriber) {
    $total_field[$index]['subscriber_id'] =  $subscriber['id'];
}

foreach ($total_field as $item) {
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $item['subscriber_id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
    }
}

SubscriberField::insert($fieldBatch);

I remove below code and use pluck

$subscribers = Subscriber::select('email')->whereIn('email', $emails)->where('mail_list_id', $this->id)->get();

//check exists mail in database
$exists_mail = array();
foreach ($subscribers as $item) {
    $exists_mail[$item->email] = true;
}

We more optimize and we can remove below code

foreach ($total_field as $item) {
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $item['subscriber_id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);

}
}

Like:

//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')
->whereIn('uid', $subscriber_uid)
->get()
->toArray();

$fieldBatch = array();

foreach ($totalSubscriber as $index => $subscriber) {
    //$total_field[$index]['subscriber_id'] =  $subscriber['id'];
    foreach ($fields as $field) {
        $fieldColumn['subscriber_id'] = $subscriber['id'];
        $fieldColumn['field_id']      = $field['id'];
        $fieldColumn['value']         = $item[Str::lower($field['tag'])];
        array_push($fieldBatch, $fieldColumn);
    }
}

But I don't know what type of data in $fields array if you provide field array the I will try more optimize.


问:
Unicode std::string class replacement
I'm looking for suggestions regarding unicode aware std::string library replacements. I have a bunch of code that uses std::string, its iterators etc, and would like to now support unicode strings (free or open source implementations preferred, regex capabilities would be great!).

I'm not sure at this point if I require a complete rewrite or if I can get away with dropping in a new string library that supports all of the std::string interfaces. The unicode world seems very complex and I'm just wanting to enable it in my applications not have to learn every single aspect of it.

btw how does the index operator work when it has to pass back a reference to either a 1, 2,3 or 4 structure which could in theory change to either a 1,2,3 or 4 byte structure.  if a larger or smaller sized value is passed, does the shifting back and forth of the internal data representation occur insitu?

答:
what unicode encoding do you need? If utf-8 is ok you can have a look at Glib::ustring

Glib::ustring has much the same
  interface as std::string, but contains
  Unicode characters encoded as UTF-8.

Title: Unicode std::string class replacement


问:
Logistic regression Machine Learning?
I have a dataset of 300 respondents (hours studied vs grade), I load the dataset in Excel run the data analysis add-in and run a linear regression. I get my results.

So the question is, Am I doing a Statistical Analysis or Am I doing Machine Learning? I know the question may seem simple but I think we should get some debate from this.

答: In the proper context, you're actually doing Statistical Analysis... (Which is part of Machine Learn</p>

Title: Logistic regression Machine Learning?


问:
Unable to deploy .war Tomcat
I am working on an API project, using Java and Tomcat. Friday everything was OK, but today I am not able to deploy the war on the server.
Here is the stack error in Tomcat:

```<code>17-Feb-2020 11:47:43.444 INFOS [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
17-Feb-2020 11:47:43.701 INFOS [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Feb-2020 11:47:43.715 INFOS [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
17-Feb-2020 11:47:43.717 INFOS [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Feb-2020 11:47:43.719 INFOS [main] org.apache.catalina.startup.Catalina.load Initialization processed in 784 ms
17-Feb-2020 11:47:45.114 INFOS [main] org.apache.catalina.core.StandardService.startInternal D├®marrage du service [Catalina]
17-Feb-2020 11:47:45.114 INFOS [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.38
17-Feb-2020 11:47:45.145 INFOS [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR D├®ploiement de l'archive [C:\Dev\Serveurs\anee\apache-tomcat-8.5.38\webapps\anee.war] de l'application web
17-Feb-2020 11:47:57.205 GRAVE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/anee]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/anee] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1Boolean->org.bouncycastle.asn1.DERBoolean->org.bouncycastle.asn1.ASN1Boolean]
        at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2116)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2054)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2000)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1970)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1923)
        at org.apache.catalina.startup.ContextConfig.processClasses(ContextConfig.java:1230)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1134)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:769)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:299)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:94)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 10 more
>
>
> Blockquote 17-Feb-2020 11:47:57.206 GRAVE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Erreur lors du d├®ploiement de l'archive [C:\Dev\Serveurs\anee\apache-tomcat-8.5.38\webapps\anee.war] de l'application web
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/anee]]
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:758)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

And here are the errors from the logs:

```<code>17-Feb-2020 11:43:37.813 GRAVE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) [org.springframework.web.context.ContextLoaderListener]
 org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'casBypassFilter' defined in class path resource [META-INF/spring/fwk-security-cas-filters.xml]: Could not resolve placeholder 'fwk.uri.protected' in string value "${fwk.uri.protected}"
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)
    at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:220)
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:84)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:669)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4817)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5283)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I do not explain myself why the changes, because I did not change the code.
The file where is placed the string ${fwk.uri.protected} is read-only, I am not able to change it.

In my pom.xml, for my properties, I have tomcat7 (the solution indicated for the similar problem here Unable to deploy to server running Tomcat).
I changed to tomcat8, and I had some other errors, about missing dependencies.

I am using JDK 1.8 and apache-tomcat-8.5.38

Could you please take a look, and tell me what you think about it ? This would help me a lot !
Thank you very much

答:
I found the problem, I had to use another GIT branch, because the version I used was an advanced one, and I needed some external libraries (which I didn't have yesterday).
All is OK now. </p>

Title: Unable to deploy .war Tomcat

Body:
I am working on an API project, using Java and Tomcat. Friday everything was OK, but today I am not able to deploy the war on the server.
Here is the stack error in Tomcat:

17-Feb-2020 11:47:43.444 INFOS [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
17-Feb-2020 11:47:43.701 INFOS [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Feb-2020 11:47:43.715 INFOS [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
17-Feb-2020 11:47:43.717 INFOS [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
17-Feb-2020 11:47:43.719 INFOS [main] org.apache.catalina.startup.Catalina.load Initialization processed in 784 ms
17-Feb-2020 11:47:45.114 INFOS [main] org.apache.catalina.core.StandardService.startInternal D├®marrage du service [Catalina]
17-Feb-2020 11:47:45.114 INFOS [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.38
17-Feb-2020 11:47:45.145 INFOS [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR D├®ploiement de l'archive [C:\Dev\Serveurs\anee\apache-tomcat-8.5.38\webapps\anee.war] de l'application web
17-Feb-2020 11:47:57.205 GRAVE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/anee]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/anee] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1Boolean->org.bouncycastle.asn1.DERBoolean->org.bouncycastle.asn1.ASN1Boolean]
        at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2116)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2054)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2000)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1970)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1923)
        at org.apache.catalina.startup.ContextConfig.processClasses(ContextConfig.java:1230)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1134)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:769)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:299)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:94)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 10 more
>
>
> Blockquote 17-Feb-2020 11:47:57.206 GRAVE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Erreur lors du d├®ploiement de l'archive [C:\Dev\Serveurs\anee\apache-tomcat-8.5.38\webapps\anee.war] de l'application web
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/anee]]
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:758)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

And here are the errors from the logs:

17-Feb-2020 11:43:37.813 GRAVE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) [org.springframework.web.context.ContextLoaderListener]
 org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'casBypassFilter' defined in class path resource [META-INF/spring/fwk-security-cas-filters.xml]: Could not resolve placeholder 'fwk.uri.protected' in string value "${fwk.uri.protected}"
    at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)
    at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:220)
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:84)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:669)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4817)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5283)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

I do not explain myself why the changes, because I did not change the code.
The file where is placed the string ${fwk.uri.protected} is read-only, I am not able to change it.

In my pom.xml, for my properties, I have tomcat7 (the solution indicated for the similar problem here Unable to deploy to server running Tomcat).
I changed to tomcat8, and I had some other errors, about missing dependencies.

I am using JDK 1.8 and apache-tomcat-8.5.38

Could you please take a look, and tell me what you think about it ? This would help me a lot !
Thank you very much


问:
Adding another suffix to a path that already has a suffix with pathlib
I was converting some old Python code to use pathlib instead of os.path for most path-related operations, but I ended up with the following problem: I needed to add another extension to a path that already had an extension (not replace it). With os.path, since we are merely manipulating strings, the solution was to add the extension with string operations:

```<code>newpath = path + '.res'
</code>```

It doesn't work with pathlib.Path because it doesn't allow concatenation of arbitrary characters. The closest I could find was the following:

```<code>newpath = path.with_suffix(path.suffix + '.res')
</code>```

It looks like a workaround because it still uses string addition in the end. And it has a new pitfall because I forgot at first to handle the case where there are already several extensions and you want to add a new one, leading to the following code to get back the old behaviour:

```<code>newpath = path.with_suffix(''.join(path.suffixes) + '.res')
</code>```

Now it doesn't feel terse nor clean since it uses more and more string operations to achieve the old behaviour instead of pure path operations. The fact that Path.suffixes exists means that the library's developers considered the case where a file can have multiple extensions, yet I couldn't find a way to simply add a new extension to a path. Is there a more idiomatic way that I have missed to achieve the same behaviour?

EDIT: actually path.with_suffix(path.suffix + '.res') is enough to handle the case where there are already several file extensions, even though it wasn't immeditely obvious to me.

答:
I find the following slightly more satisfying than the answers that have already been given:</p>

```<code>new_path = path.parent / (path.name + '.suffix')
</code>```

Body:
I was converting some old Python code to use pathlib instead of os.path for most path-related operations, but I ended up with the following problem: I needed to add another extension to a path that already had an extension (not replace it). With os.path, since we are merely manipulating strings, the solution was to add the extension with string operations:

newpath = path + '.res'

It doesn't work with pathlib.Path because it doesn't allow concatenation of arbitrary characters. The closest I could find was the following:

newpath = path.with_suffix(path.suffix + '.res')

It looks like a workaround because it still uses string addition in the end. And it has a new pitfall because I forgot at first to handle the case where there are already several extensions and you want to add a new one, leading to the following code to get back the old behaviour:

newpath = path.with_suffix(''.join(path.suffixes) + '.res')

Now it doesn't feel terse nor clean since it uses more and more string operations to achieve the old behaviour instead of pure path operations. The fact that Path.suffixes exists means that the library's developers considered the case where a file can have multiple extensions, yet I couldn't find a way to simply add a new extension to a path. Is there a more idiomatic way that I have missed to achieve the same behaviour?

EDIT: actually path.with_suffix(path.suffix + '.res') is enough to handle the case where there are already several file extensions, even though it wasn't immeditely obvious to me.

Body:
I find the following slightly more satisfying than the answers that have already been given:

new_path = path.parent / (path.name + '.suffix')


问:
Hybris backoffice extend widget

This is the syncronization popup (com.hybris.backoffice.widgets.syncpopup.SyncPopupController) used to synchronize catalogs . I want to modify this OOTB widget in order to add multiple selection instead of one (right now , you can only select one catalog at a time).

How can I achieve this ? I don't know how to extend backoffice widgets.

答:
The Listbox you're trying to modify has an attribute called multiple. By default at initialization this is false. The widget lists (because there are 2 lists, one for stage->online and one for online->stage) doesn't have this attribute set to true when the widget is created. The initialize() method from the SyncPopupController only fill these lists with items but nothing more.

Now that you know the root of the problem, you can read this tutorial which explains you how you can extend a widget mot-a-mot. One solution could be extending the original controller and make your custom configuration in the initialize() method.

This could look like this:

```<code>public class ExtendedSyncPopupController extends SyncPopupController
{
   public void initialize(Component component){
       super.initialize(component);
       super.getPullList().setMultiple(true);
       //etc.
   }
}
</code>```

And after this, you can override the widget definition ( Overriding the Widget Definition chapter from the tutorial provided above ) and pass your custom controller class in <controller class="ExtendedSyncPopupController">.

Title: Hybris backoffice extend widget

Body:
The Listbox you're trying to modify has an attribute called multiple. By default at initialization this is false. The widget lists (because there are 2 lists, one for stage->online and one for online->stage) doesn't have this attribute set to true when the widget is created. The initialize() method from the SyncPopupController only fill these lists with items but nothing more.

Now that you know the root of the problem, you can read this tutorial which explains you how you can extend a widget mot-a-mot. One solution could be extending the original controller and make your custom configuration in the initialize() method.

This could look like this:

public class ExtendedSyncPopupController extends SyncPopupController
{
   public void initialize(Component component){
       super.initialize(component);
       super.getPullList().setMultiple(true);
       //etc.
   }
}

And after this, you can override the widget definition ( Overriding the Widget Definition chapter from the tutorial provided above ) and pass your custom controller class in <controller class="ExtendedSyncPopupController">.


问:
How could I pass an array of objects through to my Express / SQL Server (react)
I have an array of objects that I would like to pass through to my back end (SQL Server).

Below is the array of objects this is the exact results from

```<code>console.info(results)
</code>```

Here is array of objects (this is named results)

```<code>[0] [
[0]   {
[0]     answer: 'bmbm,nn',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'problem specified'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing position?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'bnmgjvgh',
[0]     question: 'Is the mouse (or other pointing device) located sufficiently close to you?  ',
[0]     state: 'Declined with solution defined'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]
</code>```

This is how I was originally going to pass it though to my sql however I am stuck with the logic of how to do so.

```<code>app.post("/post-question-answers", async (req, res) => {
  console.log("!called");
  try {
    let results = req.body.results;

//This is the console.info posted earlier

    console.info(results);

    await sql.connect(config, function(err) {
      if (err) console.log(err);

      // create Request object
      var request = new sql.Request();
      request.input("Results", sql.VarChar, results);
      // query to the database and get the records
      request.execute("dbo.StoreAnswers", function(err, recordset) {
        if (err) console.log(err);
        // send records as a response
        res.json(recordset);
      });
    });
  } catch (e) {
    console.info(e);
  }
  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});
</code>```

All I need to know is how is this doable. Do I need to iterate through and rip out each separate variable? Do I need to use user defined tables within SQL Server? Can I pass a object straight into the database?

I have no clue what lead to follow and have been wasting a lot of time on this problem.

Please any advice is appreciated

答: You can bulk insert by using raw query</p>

Body:
I have an array of objects that I would like to pass through to my back end (SQL Server).

Below is the array of objects this is the exact results from

console.info(results)

Here is array of objects (this is named results)

[0] [
[0]   {
[0]     answer: 'bmbm,nn',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'problem specified'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing position?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'bnmgjvgh',
[0]     question: 'Is the mouse (or other pointing device) located sufficiently close to you?  ',
[0]     state: 'Declined with solution defined'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]

This is how I was originally going to pass it though to my sql however I am stuck with the logic of how to do so.

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");
  try {
    let results = req.body.results;

//This is the console.info posted earlier

    console.info(results);

    await sql.connect(config, function(err) {
      if (err) console.log(err);

      // create Request object
      var request = new sql.Request();
      request.input("Results", sql.VarChar, results);
      // query to the database and get the records
      request.execute("dbo.StoreAnswers", function(err, recordset) {
        if (err) console.log(err);
        // send records as a response
        res.json(recordset);
      });
    });
  } catch (e) {
    console.info(e);
  }
  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

All I need to know is how is this doable. Do I need to iterate through and rip out each separate variable? Do I need to use user defined tables within SQL Server? Can I pass a object straight into the database?

I have no clue what lead to follow and have been wasting a lot of time on this problem.

Please any advice is appreciated

Body: You can bulk insert by using raw query