问:
JavaFX - TableView - setItems : The method setItems(ObservableList) in the type TableView is not showing me anything
iam new here so i dont know exactly what to do but i have this problem my tableview.setitems(oblist);
when i start my program the table view doesnt show me anything just strange lines inside the area

```<code>public class FXMLTableController implements Initializable {
private  Connection con;

@FXML
private TableView<LOC> tableview;
@FXML
private TableColumn<LOC, Integer> ttidLoc;
@FXML
private TableColumn<LOC,Integer> ttidProd;
@FXML
private TableColumn<LOC, Float> ttPrixJour;
@FXML
private TableColumn<LOC,Integer> ttMaxJour;
@FXML
private TableColumn<LOC,Integer> ttidClient;

ObservableList<LOC> oblist=FXCollections.observableArrayList();

@Override
public void initialize(URL location, ResourceBundle resources) {

    try {
         con = DataBase.getInstance().getConnection();
        ResultSet rs = con.createStatement().executeQuery("select * from locations");

        while(rs.next()) {
            oblist.add(new LOC(rs.getInt("idLoc"),rs.getInt("idProd"),rs.getFloat("PrixJour"),rs.getInt("MaxJour"),rs.getInt("idClient")));
        }

        ttidLoc.setCellValueFactory(new PropertyValueFactory<>("idLoc"));
        ttidProd.setCellValueFactory(new PropertyValueFactory<>("idProd"));
        ttPrixJour.setCellValueFactory(new PropertyValueFactory<>("PrixJour"));
        ttMaxJour.setCellValueFactory(new PropertyValueFactory<>("MaxJour"));
        ttidClient.setCellValueFactory(new PropertyValueFactory<>("idClient"));

       tableview.setItems(oblist);
    } catch (SQLException ex) {
        Logger.getLogger(FXMLTableController.class.getName()).log(Level.SEVERE, null, ex);
    }

}
</code>```

}

here is my entities code that i work with

```<code>public class LOC {
private int idLoc;
private int idProd;
private float PrixJour;
private int MaxJour;
private int idClient;

public LOC(int idLoc, int idProd, float PrixJour, int MaxJour, int idClient) {
    this.idLoc = idLoc;
    this.idProd = idProd;
    this.PrixJour = PrixJour;
    this.MaxJour = MaxJour;
    this.idClient=idClient;
}

public LOC( int idProd, float PrixJour, int MaxJour, int idClient) {

    this.idProd = idProd;
    this.PrixJour = PrixJour;
    this.MaxJour = MaxJour;
    this.idClient=idClient;
</code>```

btw im using scenebuilder and i trying to open the tableview in another scene when clicking a button on the first one

答:
U can also use your own implementation of a CellValueFactory this way u do not rely on the reflection logic of the PropertyValueFactory. As an example:</p>

```<code>ttidLoc.setCellValueFactory(param -> {
    LOC value = param.getValue();
    return new SimpleObjectProperty<>(value.idLoc);
});
</code>```

Body:
iam new here so i dont know exactly what to do but i have this problem my tableview.setitems(oblist);
when i start my program the table view doesnt show me anything just strange lines inside the area

public class FXMLTableController implements Initializable {
private  Connection con;

@FXML
private TableView<LOC> tableview;
@FXML
private TableColumn<LOC, Integer> ttidLoc;
@FXML
private TableColumn<LOC,Integer> ttidProd;
@FXML
private TableColumn<LOC, Float> ttPrixJour;
@FXML
private TableColumn<LOC,Integer> ttMaxJour;
@FXML
private TableColumn<LOC,Integer> ttidClient;

ObservableList<LOC> oblist=FXCollections.observableArrayList();

@Override
public void initialize(URL location, ResourceBundle resources) {

    try {
         con = DataBase.getInstance().getConnection();
        ResultSet rs = con.createStatement().executeQuery("select * from locations");

        while(rs.next()) {
            oblist.add(new LOC(rs.getInt("idLoc"),rs.getInt("idProd"),rs.getFloat("PrixJour"),rs.getInt("MaxJour"),rs.getInt("idClient")));
        }

        ttidLoc.setCellValueFactory(new PropertyValueFactory<>("idLoc"));
        ttidProd.setCellValueFactory(new PropertyValueFactory<>("idProd"));
        ttPrixJour.setCellValueFactory(new PropertyValueFactory<>("PrixJour"));
        ttMaxJour.setCellValueFactory(new PropertyValueFactory<>("MaxJour"));
        ttidClient.setCellValueFactory(new PropertyValueFactory<>("idClient"));

       tableview.setItems(oblist);
    } catch (SQLException ex) {
        Logger.getLogger(FXMLTableController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

here is my entities code that i work with

public class LOC {
private int idLoc;
private int idProd;
private float PrixJour;
private int MaxJour;
private int idClient;

public LOC(int idLoc, int idProd, float PrixJour, int MaxJour, int idClient) {
    this.idLoc = idLoc;
    this.idProd = idProd;
    this.PrixJour = PrixJour;
    this.MaxJour = MaxJour;
    this.idClient=idClient;
}

public LOC( int idProd, float PrixJour, int MaxJour, int idClient) {

    this.idProd = idProd;
    this.PrixJour = PrixJour;
    this.MaxJour = MaxJour;
    this.idClient=idClient;

btw im using scenebuilder and i trying to open the tableview in another scene when clicking a button on the first one

Body:
U can also use your own implementation of a CellValueFactory this way u do not rely on the reflection logic of the PropertyValueFactory. As an example:

ttidLoc.setCellValueFactory(param -> {
    LOC value = param.getValue();
    return new SimpleObjectProperty<>(value.idLoc);
});


来源: stackexchange

问:
user id and username not inserting with relationship
```<code>class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}
</code>```

This is Country Model

```<code>class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id','id');
    }
    public function history()
    {
        return $this->hasOne(UserHistory::class,'user_id','id');
    }
}
</code>```

This is User Model

```<code>class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $users = \App\User::with(['roles','profile'])->get();
        return view('dashboard.users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $roles = \App\Role::all();
        $countries = \App\Country::all();
        return view('dashboard.users.create',compact('countries','roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $user = [
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ];
        $user = \App\User::create($user);
               $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
        if ($request->hasFile('photo'))
         $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
     else
        $filename = "profiles/dummy.jpg";
    if ($user) {
        $profile = new \App\UserProfile([
            'user_id' => $user->id,
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);
        $user->profile()->save($profile);
        $user->roles()->attach($request->roles);
        return redirect()->route('users.index');
    }

}
</code>```

This is Controller

```<code>class UserProfile extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}
</code>```

This is UserProfile Model

```<code>@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf
    <div class="form-row align-item-center">
        <div class="col-md-12">
            <label for="inputUsername"> Name</label>
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">
        </div>
        <div class="col-md-12">
            <label for="inputName">Full Name</label>
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">
        </div>
        <div class="col-md-12">
            <label for="inputUserEmail">Email</label>
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">
        </div>
        <div class="col-md-12">
            <label for="inputPassword">Password</label>
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">
        </div>
        <div class="col-md-12">
            <label for="inputPhone">Phone</label>
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">
        </div>
        <div class="col-md-12">
            <label for="selectCountry">Select Country</label>
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 mt-3">
            <label for="inputCity">City</label>
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">
        </div>
        <div class="col-md-12">
            <label for="selectRoles">Select Roles</label>
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 my-3">
            <label for="inputFileName">Profile Image</label>
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">
        </div>
        <div class="col-md-12">
        <button type="submit" class="btn btn-primary mb-2">Add New User</button>
    </div>
</div>
</form>
@endsection
</code>```

This is create view

I have used this code with relationships when i create user and getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into user_profiles (user_id, city, country_id, photo, phone, updated_at, created_at) values (?, Karachi, 1, profiles/thumbnail_385.jpg, +923148790984, 2020-02-20 04:49:17, 2020-02-20 04:49:17))

答:
Your User model has:

```<code>protected $fillable = [
    'name', 'email', 'password',
];
</code>```

Then your controller does:

```<code>$user = [
    'username' => $request->username,
    'name' => $request->name,
    'email' => $request->email,
    'password' => bcrypt($request->password),
];
$user = \App\User::create($user);
</code>```

This will fail, as username is not mass-assignable.  As the docs describe, the create() method will only accept fields you have explicitly whitelisted in $fillable.

For this to work, you need to add username to the list of fillable fields:

```<code>protected $fillable = [
    'username', 'name', 'email', 'password',
];
</code>```

Side note: The test/error handling you have set up to make sure a user is created before trying to create a profile is not working.  The reason is that you first set $user as an array - the create() fails, but $user is still an array.  So your test:

```<code>if ($user) {
    // $user is an array so this still works
    // create user profile
}
</code>```

still evaluates as TRUE.  Maybe better would be to set up the user array with a different variable name, eg:

```<code>$array = [ ... user values ... ];
$user = \App\User::create($array);
</code>```

Or even simpler do it all in one command:

```<code>$user = \App\User::create([
    // ... user values ...
]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}

This is Country Model

class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id','id');
    }
    public function history()
    {
        return $this->hasOne(UserHistory::class,'user_id','id');
    }
}

This is User Model

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $users = \App\User::with(['roles','profile'])->get();
        return view('dashboard.users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $roles = \App\Role::all();
        $countries = \App\Country::all();
        return view('dashboard.users.create',compact('countries','roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $user = [
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ];
        $user = \App\User::create($user);
               $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
        if ($request->hasFile('photo'))
         $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
     else
        $filename = "profiles/dummy.jpg";
    if ($user) {
        $profile = new \App\UserProfile([
            'user_id' => $user->id,
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);
        $user->profile()->save($profile);
        $user->roles()->attach($request->roles);
        return redirect()->route('users.index');
    }

}

This is Controller

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

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}

This is UserProfile Model

@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf

             Name
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">

            Full Name
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">

            Email
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">

            Password
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">

            Phone
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">

            Select Country
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>

            City
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">

            Select Roles
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>

            Profile Image
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">

        <button type="submit" class="btn btn-primary mb-2">Add New User</button>

</form>
@endsection

This is create view

I have used this code with relationships when i create user and getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into user_profiles (user_id, city, country_id, photo, phone, updated_at, created_at) values (?, Karachi, 1, profiles/thumbnail_385.jpg, +923148790984, 2020-02-20 04:49:17, 2020-02-20 04:49:17))

Body:
Your User model has:

protected $fillable = [
    'name', 'email', 'password',
];

Then your controller does:

$user = [
    'username' => $request->username,
    'name' => $request->name,
    'email' => $request->email,
    'password' => bcrypt($request->password),
];
$user = \App\User::create($user);

This will fail, as username is not mass-assignable.  As the docs describe, the create() method will only accept fields you have explicitly whitelisted in $fillable.

For this to work, you need to add username to the list of fillable fields:

protected $fillable = [
    'username', 'name', 'email', 'password',
];

Side note: The test/error handling you have set up to make sure a user is created before trying to create a profile is not working.  The reason is that you first set $user as an array - the create() fails, but $user is still an array.  So your test:

if ($user) {
    // $user is an array so this still works
    // create user profile
}

still evaluates as TRUE.  Maybe better would be to set up the user array with a different variable name, eg:

$array = [ ... user values ... ];
$user = \App\User::create($array);

Or even simpler do it all in one command:

$user = \App\User::create([
    // ... user values ...
]);


问:
Ubuntu TestContainers unable to connect to Postgis:9.5
I have the following definition of TestContainers (version 1.12.2) module prepared to test liquibase schema in our app. When trying to execute I'm receiving Connection Refused error like it would not exist, however during run of the test I've checked containers and their up:

```<code>private static final String DB_URL = String.format("jdbc:postgresql://%s:%s/%s", "localhost", 5432, DB_NAME);

    @Rule
    public final GenericContainer<?> container =
            new GenericContainer<>("mdillon/postgis:9.5")
                .withExposedPorts(5432)
                .withEnv("POSTGRES_USER", USER)
                .withEnv("POSTGRES_PASSWORD", PASSWORD)
                .withEnv("POSTGRES_DB", DB_NAME);

    @Test
    public void transactionSchemaWasUpdated() throws Exception {
        try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD)) {
            // GIVEN
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            database.setDefaultSchemaName(SCHEMA);
            Liquibase liquibase = new Liquibase("install.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.setChangeLogParameter("schemaName", SCHEMA);
            // WHEN
            liquibase.update("main");
            // THEN
            assertEquals(getAppVersion(), getDbVersion(connection));
        }
    }
</code>```

Docker ls result during run of tests:

```<code>378e828e4149        mdillon/postgis:9.5                 "docker-entrypoint.s…"   7 seconds ago       Up 6 seconds        0.0.0.0:32784->5432/tcp   thirsty_stonebraker
6a270c963322        quay.io/testcontainers/ryuk:0.2.3   "/app"                   8 seconds ago       Up 7 seconds        0.0.0.0:32783->8080/tcp   testcontainers-ryuk-78a4fc8d-4fb9-41bf-995f-b31076b02465
</code>```

Error:

```<code>org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
</code>```

答:
When a port is exposed in testcontainers, it actually does not use the same port, but another one. According docs:

From the host's perspective Testcontainers actually exposes this on a
  random free port. This is by design, to avoid port collisions that may
  arise with locally running software or in between parallel test runs.

You need to ask the container for the mapped port:

```<code>Integer actualPostgresPort = container.getMappedPort(5432);
</code>```

If you analyze the output of docker ps, you will see that port 5432 is not being exposed, but 32784 instead.

Body:
I have the following definition of TestContainers (version 1.12.2) module prepared to test liquibase schema in our app. When trying to execute I'm receiving Connection Refused error like it would not exist, however during run of the test I've checked containers and their up:

private static final String DB_URL = String.format("jdbc:postgresql://%s:%s/%s", "localhost", 5432, DB_NAME);

    @Rule
    public final GenericContainer<?> container =
            new GenericContainer<>("mdillon/postgis:9.5")
                .withExposedPorts(5432)
                .withEnv("POSTGRES_USER", USER)
                .withEnv("POSTGRES_PASSWORD", PASSWORD)
                .withEnv("POSTGRES_DB", DB_NAME);

    @Test
    public void transactionSchemaWasUpdated() throws Exception {
        try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD)) {
            // GIVEN
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            database.setDefaultSchemaName(SCHEMA);
            Liquibase liquibase = new Liquibase("install.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.setChangeLogParameter("schemaName", SCHEMA);
            // WHEN
            liquibase.update("main");
            // THEN
            assertEquals(getAppVersion(), getDbVersion(connection));
        }
    }

Docker ls result during run of tests:

378e828e4149        mdillon/postgis:9.5                 "docker-entrypoint.s…"   7 seconds ago       Up 6 seconds        0.0.0.0:32784->5432/tcp   thirsty_stonebraker
6a270c963322        quay.io/testcontainers/ryuk:0.2.3   "/app"                   8 seconds ago       Up 7 seconds        0.0.0.0:32783->8080/tcp   testcontainers-ryuk-78a4fc8d-4fb9-41bf-995f-b31076b02465

Error:

org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

Body:
When a port is exposed in testcontainers, it actually does not use the same port, but another one. According docs:

From the host's perspective Testcontainers actually exposes this on a
  random free port. This is by design, to avoid port collisions that may
  arise with locally running software or in between parallel test runs.

You need to ask the container for the mapped port:

Integer actualPostgresPort = container.getMappedPort(5432);

If you analyze the output of docker ps, you will see that port 5432 is not being exposed, but 32784 instead.


问:
how to checkout only specific folder from git repo and build
Hey folks I need some help on the jenkinsfile. Below is my usecase

This is the strcuture of my GIT repo:

```<code>root
  |->app1
  |   |->jenkinsfile
  |   |->dockerfile
  |->app2
      |->jenkinsfile
      |->dockerfile
</code>```

I am having a monorepo, app1 and app2 in the root folder and I want when their is a change in app1 folder, only app1 should build and same for app2. I have defined the jenkinsfile in jenkins but when its build. its looking for dockerfile1 in root folder not inside app1.

jenkisfile:

```<code>pipeline {
    agent any

    environment {
        PIPENV_VENV_IN_PROJECT = true
        DEVPI_USER = '\'jenkins_user\''
        DEVPI_PASSWORD = '\'V$5_Z%Bf-:mJ\''
        WORKSPACE="${WORKSPACE}/app1"

    }
    stages {
        stage('Notify Bitbucket') {
            steps {
                bitbucketStatusNotify(buildState: 'INPROGRESS')
            }
        }

        stage('Build Environment') {
            steps {
                sh 'docker build -t app-builder .'
            }
        }

        stage('Test') {

            steps{
                sh 'docker run --rm app-builder pytest'
            }
        }
</code>```

答:
On a multi-branch pipeline, you could leverage the customWorkspace option of the jenkins agents

The change you are making to the WORKSPACE env variable affects the variable only, it does not change the workspace location.

```<code>pipeline {

    agent {
        node {
            label 'my-node'
            customWorkspace '${WORKSPACE}/app1'
        }
    }

    environment {
        PIPENV_VENV_IN_PROJECT = true
        DEVPI_USER = '\'jenkins_user\''
        DEVPI_PASSWORD = '\'V$5_Z%Bf-:mJ\''
    }
</code>```

Body:
Hey folks I need some help on the jenkinsfile. Below is my usecase

This is the strcuture of my GIT repo:

root
  |->app1
  |   |->jenkinsfile
  |   |->dockerfile
  |->app2
      |->jenkinsfile
      |->dockerfile

I am having a monorepo, app1 and app2 in the root folder and I want when their is a change in app1 folder, only app1 should build and same for app2. I have defined the jenkinsfile in jenkins but when its build. its looking for dockerfile1 in root folder not inside app1.

jenkisfile:

pipeline {
    agent any

    environment {
        PIPENV_VENV_IN_PROJECT = true
        DEVPI_USER = '\'jenkins_user\''
        DEVPI_PASSWORD = '\'V$5_Z%Bf-:mJ\''
        WORKSPACE="${WORKSPACE}/app1"

    }
    stages {
        stage('Notify Bitbucket') {
            steps {
                bitbucketStatusNotify(buildState: 'INPROGRESS')
            }
        }

        stage('Build Environment') {
            steps {
                sh 'docker build -t app-builder .'
            }
        }

        stage('Test') {

            steps{
                sh 'docker run --rm app-builder pytest'
            }
        }

Body:
On a multi-branch pipeline, you could leverage the customWorkspace option of the jenkins agents

The change you are making to the WORKSPACE env variable affects the variable only, it does not change the workspace location.

pipeline {

    agent {
        node {
            label 'my-node'
            customWorkspace '${WORKSPACE}/app1'
        }
    }

    environment {
        PIPENV_VENV_IN_PROJECT = true
        DEVPI_USER = '\'jenkins_user\''
        DEVPI_PASSWORD = '\'V$5_Z%Bf-:mJ\''
    }


问:
how to post object values in vuejs
New to vuejs, just trying to play around.
I have an object with values that I want to post in my template.

export default {
    name: 'frontPage',
    data : function() {
        return {

        }
    },
    methods : {
        player () {
            this.lvl = 1;
            this.df = this.lvl * 1.3;
            this.hp = this.lvl * 100 / 3;
            this.ap = this.hp/10;
            this.name = 'Guest';
        }
    },

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<h2 id="name">
    {{ player.name }}
</h2>
<h2 id="lvl">
    {{ player.lvl}}
</h2></code>```

答:
First you need to initialize player into your data so you will be able to access it everywhere into the component, then proceed by using the Computed Properties to give the dom the calculated player fields and update the player data too, for reference take a look at this :

https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties

For your code i did something like this:

new Vue({
  el: '#app',
  name: 'frontPage',
  data: function() {
    return {
      player: {
        lvl: 1,
        df: null,
        hp: null,
        ap: null,
        name: 'Guest'
      }
    }
  },
  computed: {
    // a computed getter
    showPlayer: function() {

      // `this` points to the vm instance
      this.player.df = this.player.lvl * 1.3
      this.player.hp = this.player.lvl * 100 / 3
      this.player.ap = this.player.hp / 10

      return this.player
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2 id="name">
    {{ showPlayer.name }}
  </h2>
  <h2 id="df">
    {{ showPlayer.df}}
  </h2>
  <h2 id="hp">
    {{ showPlayer.hp}}
  </h2>
  <h2 id="ap">
    {{ showPlayer.ap}}
  </h2>
</div></code>```

Title: how to post object values in vuejs

Body:
New to vuejs, just trying to play around.
I have an object with values that I want to post in my template.

export default {
    name: 'frontPage',
    data : function() {
        return {

        }
    },
    methods : {
        player () {
            this.lvl = 1;
            this.df = this.lvl * 1.3;
            this.hp = this.lvl * 100 / 3;
            this.ap = this.hp/10;
            this.name = 'Guest';
        }
    },

}

    {{ player.name }}

    {{ player.lvl}}

Body:
First you need to initialize player into your data so you will be able to access it everywhere into the component, then proceed by using the Computed Properties to give the dom the calculated player fields and update the player data too, for reference take a look at this :

https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties

For your code i did something like this:

new Vue({
  el: '#app',
  name: 'frontPage',
  data: function() {
    return {
      player: {
        lvl: 1,
        df: null,
        hp: null,
        ap: null,
        name: 'Guest'
      }
    }
  },
  computed: {
    // a computed getter
    showPlayer: function() {

      // `this` points to the vm instance
      this.player.df = this.player.lvl * 1.3
      this.player.hp = this.player.lvl * 100 / 3
      this.player.ap = this.player.hp / 10

      return this.player
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2 id="name">
    {{ showPlayer.name }}
  </h2>
  <h2 id="df">
    {{ showPlayer.df}}
  </h2>
  <h2 id="hp">
    {{ showPlayer.hp}}
  </h2>
  <h2 id="ap">
    {{ showPlayer.ap}}
  </h2>
</div>


问:
Unsure about how to use event function in Matlab
I am trying to plot a state-space diagram, as well as a time-history diagram, of a dynamical system. There's a catch, though. The state-space is divided into two halves by a plane located at x1 = 0. The state-space axes are x1, x2, x3. The x1 = 0 plane is parallel to the x2/x3 plane. The state-space above the x1 = 0 plane is described by the ODEs in eqx3, whereas the state-space below the x1 = 0 plane is described by the ODEs in eqx4.

So, there is a discontinuity on the plane x1 = 0. I have a vague understanding that an event function (function [value,isterminal,direction] = myEventsFcn(t,y)) should be used, but I do not know what values to give to "value", "isterminal", and "direction".

In my code below, I have an initial condition for eqx3, and another initial condition for eqx4. The initial condition for eqx3 is in the upper half of the state-space (x1 > 0). The orbit then hits the x1 = 0 plane and there is a discontinuity, and the eqx4 trajectory begins on this plane, but from a different point from where eqx3 ended.

Can this be done? How do I put it into a code? Do I stop the integration when the orbit reaches the plane x1 = 0?

eta = 0.05;
omega = 25;
tspan = [0,50];
initcond = [2, 3, 4]
[t,x] = ode45(@(t,x) eqx3(t,x,eta, omega), tspan, initcond);
initcond1 = [0, 1, 1]
[t,y] = ode45(@(t,y) eqx4(t,y,eta, omega), tspan, initcond1);

plot3(x(:,1), x(:,2), x(:,3),y(:,1), y(:,2), y(:,3))
xlabel('x1')
ylabel('x2')
zlabel('x3')

%subplot(222)
%plot(t, x(:,1), t,x(:,2),t,x(:,3),'--');
%xlabel('t')

function xdot = eqx3(t,x,eta,omega)
  xdot = zeros(3,1);
  xdot(1) = -(2*eta*omega + 1)*x(1) + x(2) - 1;
  xdot(2) = -(2*eta*omega + (omega^2))*x(1) + x(3) + 2;
  xdot(3) = -(omega^2)*x(1) + x(2) - 1;

end

function ydot = eqx4(t,y,eta,omega)
  ydot = zeros(3,1);
  ydot(1) = -(2*eta*omega + 1)*y(1) + y(2) + 1;
  ydot(2) = -(2*eta*omega + (omega^2))*y(1) + y(3) - 2;
  ydot(3) = -(omega^2)*y(1) + y(2) + 1;

end

function [value,isterminal,direction] = myEventsFcn(t,y)
   value = 0
   isterminal = 1
   direction = 1

end
```

答:
Without events, using a close-by smooth system

First, as the difference between the systems is the addition or subtraction of a constant vector it is easy to find an approximate smooth version of the system using some sigmoid function like tanh.

  eta = 0.05;
  omega = 25;
  t0=0; tf=4;
  initcond = [2, 3, 4];
  opt = odeset('AbsTol',1e-11,'RelTol',1e-13);
  opt = odeset(opt,'MaxStep',0.005); % in Matlab: opt = odeset('Refine',10);
  [t,x] = ode45(@(t,x) eqx34(t,x,eta, omega), [t0, tf], initcond, opt);

  clf;
  subplot(121);
  plot3(x(:,1), x(:,2), x(:,3));
  xlabel('x1');
  ylabel('x2');
  zlabel('x3');

  subplot(122);
  plot(t, 10.*x(:,1), t,x(:,2),':',t,x(:,3),'--');
  xlabel('t');

  function xdot = eqx34(t,x,eta,omega)
    S = tanh(1e6*x(1));
    xdot = zeros(3,1);
    xdot(1) = -(2*eta*omega + 1)*x(1) + x(2) - S;
    xdot(2) = -(2*eta*omega + (omega^2))*x(1) + x(3) + 2*S;
    xdot(3) = -(omega^2)*x(1) + x(2) - S;
  end
```

<p>resulting in the plots</p>

<p><img src="https://i.stack.imgur.com/EFlrD.png" alt="plots of the solution"></p>

<p>As is visible, after <code>t=1.2</code> the solution is essentially constant with <code>x(1)=0</code> and the other coordinates close to zero.</p>

<h2>With events</h2>

<p>If you want to use the event mechanism, make ODE and event function dependent on a sign parameter <code>S</code> denoting the phase and the direction of the zero crossing.</p>

<pre class="lang-matlab prettyprint-override"><code> eta = 0.05;
 omega = 25;
 t0=0; tf=4;
 initcond = [2, 3, 4];
 opt = odeset('AbsTol',1e-10,'RelTol',1e-12,'InitialStep',1e-6);
 opt = odeset(opt,'MaxStep',0.005); % in Matlab: opt = odeset('Refine',10);
 T = [t0]; TE = [];
 X = [initcond]; XE = [];
 S = 1; % sign of x(1)
 while t0<tf
    opt = odeset(opt,'Events', @(t,x)myEventsFcn(t,x,S));
    [t,x,te,xe,ie] = ode45(@(t,x) eqx34(t,x,eta, omega, S), [t0, tf], initcond, opt);
    T = [ T; t(2:end) ]; TE = [ TE; te ];
    X = [ X; x(2:end,:)]; XE = [ XE; xe ];
    t0 = t(end);
    initcond = x(end,:);
    S = -S % alternatively = 1-2*(initcond(1)<0);
 end
 disp(TE); disp(XE);

 subplot(121);
 hold on;
 plot3(X(:,1), X(:,2), X(:,3),'b-');
 plot3(XE(:,1), XE(:,2), XE(:,3),'or');
 hold off;
 xlabel('x1');
 ylabel('x2');
 zlabel('x3');

 subplot(122);
 plot(T, 10.*X(:,1), T,X(:,2),':',T,X(:,3),'--');
 xlabel('t');

 function xdot = eqx34(t,x,eta,omega,S)
  xdot = zeros(3,1);
  xdot(1) = -(2*eta*omega + 1)*x(1) + x(2) - S;
  xdot(2) = -(2*eta*omega + (omega^2))*x(1) + x(3) + 2*S;
  xdot(3) = -(omega^2)*x(1) + x(2) - S;
 end

 function [value,isterminal,direction] = myEventsFcn(t,x,S)
   value = x(1)+2e-4*S;
   isterminal = 1;
   direction = -S;
 end
</code>```

The solution enters a sliding mode for 1.36 < t < 1.43 where (theoretically) x(1)=0 and the vector field points to the other phase from both sides. The theoretical solution is to take a linear combination that sets the first component to zero, so that the resulting direction is tangential to the separating surface. In the first variant above the sigmoid achieves something like this automatically. Using events one could add additional event functions that test the vector field for these conditions, and when they cease to persist.

A quick solution is to thicken the boundary surface, that is, test for x(1)+epsilon*S==0 so that the solution has to cross the boundary surface before triggering the event. In sliding mode, it will be immediately pushed back, giving a ping-pong or zigzag motion. epsilon has to be small to not perturb the solution too much, however not too small to avoid the triggering of too many events. With epsilon=2e-4 octave gives the following solution in a close-up to the sliding interval

The octave solver, and in some way also Matlab, will not trigger a terminal event if it happens in the first integration step. For that reason the InitialStep option was set to a rather small value, it should be about 0.01*epsilon. The full solution looks now similar to the one obtained in the first variant

Body:
Without events, using a close-by smooth system

First, as the difference between the systems is the addition or subtraction of a constant vector it is easy to find an approximate smooth version of the system using some sigmoid function like tanh.

  eta = 0.05;
  omega = 25;
  t0=0; tf=4;
  initcond = [2, 3, 4];
  opt = odeset('AbsTol',1e-11,'RelTol',1e-13);
  opt = odeset(opt,'MaxStep',0.005); % in Matlab: opt = odeset('Refine',10);
  [t,x] = ode45(@(t,x) eqx34(t,x,eta, omega), [t0, tf], initcond, opt);

  clf;
  subplot(121);
  plot3(x(:,1), x(:,2), x(:,3));
  xlabel('x1');
  ylabel('x2');
  zlabel('x3');

  subplot(122);
  plot(t, 10.*x(:,1), t,x(:,2),':',t,x(:,3),'--');
  xlabel('t');

  function xdot = eqx34(t,x,eta,omega)
    S = tanh(1e6*x(1));
    xdot = zeros(3,1);
    xdot(1) = -(2*eta*omega + 1)*x(1) + x(2) - S;
    xdot(2) = -(2*eta*omega + (omega^2))*x(1) + x(3) + 2*S;
    xdot(3) = -(omega^2)*x(1) + x(2) - S;
  end

resulting in the plots

As is visible, after t=1.2 the solution is essentially constant with x(1)=0 and the other coordinates close to zero.

With events

If you want to use the event mechanism, make ODE and event function dependent on a sign parameter S denoting the phase and the direction of the zero crossing.

 eta = 0.05;
 omega = 25;
 t0=0; tf=4;
 initcond = [2, 3, 4];
 opt = odeset('AbsTol',1e-10,'RelTol',1e-12,'InitialStep',1e-6);
 opt = odeset(opt,'MaxStep',0.005); % in Matlab: opt = odeset('Refine',10);
 T = [t0]; TE = [];
 X = [initcond]; XE = [];
 S = 1; % sign of x(1)
 while t0<tf
    opt = odeset(opt,'Events', @(t,x)myEventsFcn(t,x,S));
    [t,x,te,xe,ie] = ode45(@(t,x) eqx34(t,x,eta, omega, S), [t0, tf], initcond, opt);
    T = [ T; t(2:end) ]; TE = [ TE; te ];
    X = [ X; x(2:end,:)]; XE = [ XE; xe ];
    t0 = t(end);
    initcond = x(end,:);
    S = -S % alternatively = 1-2*(initcond(1)<0);
 end
 disp(TE); disp(XE);

 subplot(121);
 hold on;
 plot3(X(:,1), X(:,2), X(:,3),'b-');
 plot3(XE(:,1), XE(:,2), XE(:,3),'or');
 hold off;
 xlabel('x1');
 ylabel('x2');
 zlabel('x3');

 subplot(122);
 plot(T, 10.*X(:,1), T,X(:,2),':',T,X(:,3),'--');
 xlabel('t');

 function xdot = eqx34(t,x,eta,omega,S)
  xdot = zeros(3,1);
  xdot(1) = -(2*eta*omega + 1)*x(1) + x(2) - S;
  xdot(2) = -(2*eta*omega + (omega^2))*x(1) + x(3) + 2*S;
  xdot(3) = -(omega^2)*x(1) + x(2) - S;
 end

 function [value,isterminal,direction] = myEventsFcn(t,x,S)
   value = x(1)+2e-4*S;
   isterminal = 1;
   direction = -S;
 end

The solution enters a sliding mode for 1.36 < t < 1.43 where (theoretically) x(1)=0 and the vector field points to the other phase from both sides. The theoretical solution is to take a linear combination that sets the first component to zero, so that the resulting direction is tangential to the separating surface. In the first variant above the sigmoid achieves something like this automatically. Using events one could add additional event functions that test the vector field for these conditions, and when they cease to persist.

A quick solution is to thicken the boundary surface, that is, test for x(1)+epsilon*S==0 so that the solution has to cross the boundary surface before triggering the event. In sliding mode, it will be immediately pushed back, giving a ping-pong or zigzag motion. epsilon has to be small to not perturb the solution too much, however not too small to avoid the triggering of too many events. With epsilon=2e-4 octave gives the following solution in a close-up to the sliding interval

The octave solver, and in some way also Matlab, will not trigger a terminal event if it happens in the first integration step. For that reason the InitialStep option was set to a rather small value, it should be about 0.01*epsilon. The full solution looks now similar to the one obtained in the first variant


问:
Mirror git to svn
I have a primary git repository for an opensource project

I want to mirror all commits to a svn repository (on code.google.com), is it possible ?

答:
I've faced this situation in my present job. Our primary Git repository has non-linear history so selected solution should handle this. Solution that seems to work so far is based around gitsvn proxy repository. I have a post-receive hook installed in primary Git repository that at it's core has something like this:

```<code>export GIT_DIR=$GITSVN_PROXY_DIR/.git
git pull -Xtheirs file://$GIT_PRIMARY_DIR master
git svn dcommit
</code>```

After dcommit log history is rewritten. On the next git pull from primary Git repository you'd normally get mrege conflicts. This is where -Xtheirs option kicks in. It's an merging strategy favoring remote version of changes. In this case it allows us to resolve conflicts automatically! :)

Only disadvantage: pretty SVN commit messages do not come for free. Some git hacking is required to make them contain all the info from primary Git commit messages.

ContentLicense: CC BY-SA 3.0

Title: Mirror git to svn

Body:
I've faced this situation in my present job. Our primary Git repository has non-linear history so selected solution should handle this. Solution that seems to work so far is based around gitsvn proxy repository. I have a post-receive hook installed in primary Git repository that at it's core has something like this:

export GIT_DIR=$GITSVN_PROXY_DIR/.git
git pull -Xtheirs file://$GIT_PRIMARY_DIR master
git svn dcommit

After dcommit log history is rewritten. On the next git pull from primary Git repository you'd normally get mrege conflicts. This is where -Xtheirs option kicks in. It's an merging strategy favoring remote version of changes. In this case it allows us to resolve conflicts automatically! :)

Only disadvantage: pretty SVN commit messages do not come for free. Some git hacking is required to make them contain all the info from primary Git commit messages.


问:
Remove Unexpected border of JTabbedPane
I am trying to add tabs in a JTabbedPane. It is displaying the below mentioned white borderline which I am not expecting here as Every color is already set to Black except the white color for the text colors. What I might be missing.
I am trying to change this class from jitsi project

Here is what I've tried so far.

OS: Ubuntu 19.10: Java Version: 1.8.0_242

Windows 10 Pro: Java Version: 1.8.0_241

I am using default look and feel for this Frame whereas, for my manually created design, it is Nimbus.

答:
The answer for the question heavily depends on the Look and Feel you're using for your application. I can't tell which one you're using by just looking at the screenshot because you modified it a lot and you've left out part of the code in your question that installs it. In case you aren't installing any specific one - you're running the default Look and Feel, which might also be different depending on the OS/JDK versions, if I'm not wrong.

So as @sleepToken already said in the comment - do not post random parts of your code or all of the code, instead post an SSCCE. While sometimes you might think it is unnecessary and/or unrelated - in many cases it is not, and it does help whoever will read and try to answer your question to run the code & debug the issue if necessary.

That being said - I can give a general answer to your question: All component are painted by their respective UI implementation (TabbedPaneUI in this particular case) and in some cases parts of the painting code might not be configurable, for instance some colors or other options might be hard-coded. You can simply look into the source code of the particular UI implementation that your application uses, find the painting code that you want to configure and see if it is actually configurable in the first place.

In case your application uses MetalLookAndFeel - the implementation is MetalTabbedPaneUI. From what I can tell by looking at it's code - it uses colors from TabbedPane.highlight, TabbedPane.borderHightlightColor and TabbedPane.darkShadow UI defaults for the border. Adding custom color for TabbedPane.highlight might fix the issue for you since you didn't mention that you modified that one in your question.

In case it doesn't - I once again recommend posting an SSCCE along with your OS type/version in case you're using a native Look and Feel. Native Look and Feel differs between different JDK versions for different OS version and often uses a highly customized UI implementation that might not be as configurable.

Title: Remove Unexpected border of JTabbedPane


问:
WPF, Frequently Picture refresh without flicker
I am trying to create a "live-view" from my webcam with WPF, which only gives me JPG snapshots over HTTP.
Every time I update the image source, it flickers.
Anyone has an idea how to fix this?

XAML:

```<code>     <Grid>
        <Image Name="img"/>
    </Grid>
</code>```

C#:

```<code>public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000.0);
            timer.Tick += timer_Tick;
            timer.Start();

        }

        void timer_Tick(object sender, EventArgs e)
        {

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480", UriKind.RelativeOrAbsolute);
            _image.EndInit();
            img.Source = _image;
        }
    }
</code>```

答:
Thanks @all for helping.
Got the solution from Update BitmapImage every second flickers

Converted to async HttpClient API instead of WebClient, it looks like:

```<code>private readonly HttpClient httpClient = new HttpClient();

private async void timer_Tick(object sender, EventArgs e)
{
    var uri = "http://0.0.0.0/api/camera/snapshot?width=640&height=480";

    using (var responseStream = await httpClient.GetStreamAsync(uri))
    using (var memoryStream = new MemoryStream())
    {
        await responseStream.CopyToAsync(memoryStream); // ensure full download

        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.StreamSource = memoryStream;
        image.EndInit();
        img.Source = image;
    }
}
</code>```

Body:
I am trying to create a "live-view" from my webcam with WPF, which only gives me JPG snapshots over HTTP.
Every time I update the image source, it flickers.
Anyone has an idea how to fix this?

XAML:

     <Grid>
        <Image Name="img"/>
    </Grid>

C#:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000.0);
            timer.Tick += timer_Tick;
            timer.Start();

        }

        void timer_Tick(object sender, EventArgs e)
        {

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480", UriKind.RelativeOrAbsolute);
            _image.EndInit();
            img.Source = _image;
        }
    }

Body:
Thanks @all for helping.
Got the solution from Update BitmapImage every second flickers

Converted to async HttpClient API instead of WebClient, it looks like:

private readonly HttpClient httpClient = new HttpClient();

private async void timer_Tick(object sender, EventArgs e)
{
    var uri = "http://0.0.0.0/api/camera/snapshot?width=640&height=480";

    using (var responseStream = await httpClient.GetStreamAsync(uri))
    using (var memoryStream = new MemoryStream())
    {
        await responseStream.CopyToAsync(memoryStream); // ensure full download

        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.StreamSource = memoryStream;
        image.EndInit();
        img.Source = image;
    }
}


问:
how to check if UIScrollView content doesn't need to use scroll
My problem is I need to change the label text color below my scroll view if the content of my scroll view is not all visible.

For example: I have a label colored red, if all the content of the scroll view can be seen on the screen(not using scroll at all), and the label colored blue if all the content inside of my scroll view is not visible. how to do it programmatically?

NOTE: I have a contentView -> scrollView (programmatically) -> stackView (programmatically).
(stackview inside scrollview and scrollview inside contentview. and a label below the content view)

Thanks.

答:
1: Get the height of the content view of scrollView

```<code>let totalHeight = scrollView.contentSize.height
</code>```

2: In viewDidLoad check:

```<code>if totalHeight > scrollView.frame.size.height {
    // can scroll more
} else {
   // full content visible
}
</code>```

3: once user starts scrolling, you can call:

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        //reached to bottom
    } else {
        // can scroll more
    }
}
</code>```

Body:
1: Get the height of the content view of scrollView

let totalHeight = scrollView.contentSize.height

2: In viewDidLoad check:

if totalHeight > scrollView.frame.size.height {
    // can scroll more
} else {
   // full content visible
}

3: once user starts scrolling, you can call:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        //reached to bottom
    } else {
        // can scroll more
    }
}


问:
How to import fuse.js into a react native project, getting an error
I'm getting the error Internal Error react-packager has encountered an internal error

When i try to import Fuse from 'fuse.js'; in one of my screens

I installed to my react-native project by yarn add fuse.js

答:
In Feb 2020, this worked for me, RN 0.5.9 & fuse.js^3.4.6</p>

```<code>import Fuse from 'fuse.js';
</code>```

Body:
In Feb 2020, this worked for me, RN 0.5.9 & fuse.js^3.4.6

import Fuse from 'fuse.js';


问:
Cannot upload file to Spring Boot REST using Axios and FormData
I try to upload file from page using axios and can't get it on my controller.
In fromt-end I use Vue.js with axios, and at the back end Spring MVC Controller. It seems that my controller can`t convert FormData() to MultipartFile in spring. I read a lot of questions but have no answer. here is my code:

```<code><!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- Vue.js development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <!--Axios dependency-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <!--Bootstrap-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

</head>
<body>
    <h4>Uploading files with Vue.js</h4>

    <div id="uploadSingle" class="container">

            <h5>Single file uploading</h5>
            <div class="large-12 medium-12 small-12 cell">

                <div class="form-row" >
                    <div class="col-md-4 mb-3">
                        <input type="file" ref="file" id="customFile"
                               v-on:change="handleFileUpload($event)"
                               class="custom-file-input"
                               enctype="multipart/form-data">
                        <label class="custom-file-label" for="customFile">{{chosenFile}}</label>
                    </div>
                </div>
                <button v-on:click="submitFile()" class="btn btn-primary">Submit</button>
            </div>
    </div>

    <div id="uploadMultiple" class="container">
        <h5>Multiple files uploading</h5>
    </div>

    <script >
        var app = new Vue({
            el: '#uploadSingle',
            data() {
                return {
                    message: 'Hello Vue!',
                    singleFile: '',
                    refFile: '',
                    chosenFile: 'Chose file'
                };
            },
            methods:{
                handleFileUpload(event){
                    this.singleFile = event.target.files[0];
                    this.chosenFile=this.singleFile.name;
                },
                submitFile(){
                    var formData = new FormData();
                    formData.append("file", this.singleFile);

                    axios.post( '/single-file',
                        formData,{
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }

                        }
                    ).then(function(){console.log('SUCCESS!')})
                        .catch((error) => console.log( error ) )

                },
            },
        })
    </script>
</body>
</html>
</code>```

and controller file:

```<code>package com.yurets_y.webdevelopment_uploading_file_with_vue.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@CrossOrigin("*")
@Controller
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath;

    @ResponseBody
    @PostMapping(value="/single-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadSingle(
            @RequestParam(name="file", required = false) MultipartFile file
    ) {
        System.out.println("uploaded");
        System.out.println(file);

        return ResponseEntity.ok().build();

    }

}
</code>```

I will be very grateful for the advice.

P.S.
when I use  @RequestParam(name="file", required=true) MultipartFile file I get error POST http://localhost:8080/single-file 400 (Bad Request), It looks like spring cannot get MultipartFile file from FormData. At back end I don't get any errors, only MultipartFile file = null

答:
After two days, that I spent to solve my promlem I fount a couple of working projects, compare all files and found, that my problem was in dependencies,
I used dependency:

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
</code>```

And when I change dependency:

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</code>```

Now it's working exactly how I need.

Body:
I try to upload file from page using axios and can't get it on my controller.
In fromt-end I use Vue.js with axios, and at the back end Spring MVC Controller. It seems that my controller can`t convert FormData() to MultipartFile in spring. I read a lot of questions but have no answer. here is my code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Uploading files with Vue.js

Single file uploading

                        <input type="file" ref="file" id="customFile"
                               v-on:change="handleFileUpload($event)"
                               class="custom-file-input"
                               enctype="multipart/form-data">
                        {{chosenFile}}

                <button v-on:click="submitFile()" class="btn btn-primary">Submit</button>

Multiple files uploading

and controller file:

package com.yurets_y.webdevelopment_uploading_file_with_vue.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@CrossOrigin("*")
@Controller
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath;

    @ResponseBody
    @PostMapping(value="/single-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadSingle(
            @RequestParam(name="file", required = false) MultipartFile file
    ) {
        System.out.println("uploaded");
        System.out.println(file);

        return ResponseEntity.ok().build();

    }

}

I will be very grateful for the advice.

P.S.
when I use  @RequestParam(name="file", required=true) MultipartFile file I get error POST http://localhost:8080/single-file 400 (Bad Request), It looks like spring cannot get MultipartFile file from FormData. At back end I don't get any errors, only MultipartFile file = null

Body:
After two days, that I spent to solve my promlem I fount a couple of working projects, compare all files and found, that my problem was in dependencies,
I used dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

And when I change dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Now it's working exactly how I need.


问:
TypeError: Cannot read property 'getParam' of undefined. for react native unit test using jest and enzyme?
I am trying to write unit test cases for react native for very first time..I am getting following error

AlbumDetailView.js

import { View, Image } from 'react-native';
import { Button, Provider, Text } from 'react-native-paper';
import React from 'react';
import styles from '../style/AlbumDetailView.component.style';

export default class DetailView extends React.Component {
    static navigationOptions = {
      title: 'Album Details',
    };

    render() {
      { /* Using the navigation prop we can get the value passed from the previous screen */ }
      const { navigation } = this.props;
      const albumTitle = navigation.getParam('albumTitle', 'Default data');
      const albumImg = navigation.getParam('albumImg', 'some default value');
      const goBackToHome = () => this.props.navigation.goBack(this.props.navigation.state.key);

      return (
          <React.Fragment>
            <Provider>
              <View style={styles.mainContainer}>
                <View style={styles.albumViewContainer}>
                    <Image source = {{ uri: albumImg }} style={styles.imageView} />
                    <Text style={styles.textStyle}>{albumTitle}</Text>
                    <Button mode="contained"
                        onPress={() => this.props.navigation.navigate('HomeScreen', { goBackToHome, })}
                        style={styles.buttonStyle} testID='HomeButton'>
                        HOME
                    </Button>
                </View>
              </View>
            </Provider>
          </React.Fragment>
      );
    }
}```
</div>
</div>
</p>

<p>and I am writing test cases for same as bellow </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import 'react-native';
import React, { Component } from 'react';
import { shallow } from 'enzyme';
import AlbumDetailsView from '../component/AlbumDetailsView';

describe('Album Details Screen', () => {

  it('should render Album Details component', () => {
      const wrapper = shallow(<AlbumDetailsView />);
  });

  it('should render initial layout', () => {
  // when
  const component = shallow(<AlbumDetailsView />);
  // then
  expect(component.getElements()).toMatchSnapshot();
  });

  it('should check if BackButton exists', () => {
    const wrapper = shallow(<AlbumDetailsView />);
    wrapper.findWhere(n => n.name() === 'Button' && n.prop('testID') === 'HomeButton')

  });

});</code>```

May I know how to handle this?

答:
You need to mock the navigation prop in your test. Of course getParam is undefined, since you haven't passed it in your test. It is passed automatically by react-navigation when running your app, but inside your tests, you have to manually mock it.

```<code>it('should render Album Details component', () => {
    const wrapper = shallow(
        <AlbumDetailsView navigation={{ getParam: jest.fn() }} />
    );
});
</code>```

Now getParam won't be undefined anymore. Of course, using the above code, won't return anything when calling getParam('albumTitle') since in your test getParam() is just a jest.fn(), which can translate to an empty function that does nothing.

If you want to make it return values, you will have to manually implement the mocked function as well, like

```<code>it('should render Album Details component', () => {
    const wrapper = shallow(
        <AlbumDetailsView navigation={{ getParam: (param) => {
            if (param === 'albumTitle') return 'albumTitle';
            ...
        } }} />
    );
});
</code>```

Body:
I am trying to write unit test cases for react native for very first time..I am getting following error

AlbumDetailView.js

import { View, Image } from 'react-native';
import { Button, Provider, Text } from 'react-native-paper';
import React from 'react';
import styles from '../style/AlbumDetailView.component.style';

export default class DetailView extends React.Component {
    static navigationOptions = {
      title: 'Album Details',
    };

    render() {
      { /* Using the navigation prop we can get the value passed from the previous screen */ }
      const { navigation } = this.props;
      const albumTitle = navigation.getParam('albumTitle', 'Default data');
      const albumImg = navigation.getParam('albumImg', 'some default value');
      const goBackToHome = () => this.props.navigation.goBack(this.props.navigation.state.key);

      return (
          <React.Fragment>
            <Provider>
              <View style={styles.mainContainer}>
                <View style={styles.albumViewContainer}>
                    <Image source = {{ uri: albumImg }} style={styles.imageView} />
                    <Text style={styles.textStyle}>{albumTitle}</Text>
                    <Button mode="contained"
                        onPress={() => this.props.navigation.navigate('HomeScreen', { goBackToHome, })}
                        style={styles.buttonStyle} testID='HomeButton'>
                        HOME
                    </Button>
                </View>
              </View>
            </Provider>
          </React.Fragment>
      );
    }
}

and I am writing test cases for same as bellow

import 'react-native';
import React, { Component } from 'react';
import { shallow } from 'enzyme';
import AlbumDetailsView from '../component/AlbumDetailsView';

describe('Album Details Screen', () => {

  it('should render Album Details component', () => {
      const wrapper = shallow(<AlbumDetailsView />);
  });

  it('should render initial layout', () => {
  // when
  const component = shallow(<AlbumDetailsView />);
  // then
  expect(component.getElements()).toMatchSnapshot();
  });

  it('should check if BackButton exists', () => {
    const wrapper = shallow(<AlbumDetailsView />);
    wrapper.findWhere(n => n.name() === 'Button' && n.prop('testID') === 'HomeButton')

  });

});

May I know how to handle this?

Body:
You need to mock the navigation prop in your test. Of course getParam is undefined, since you haven't passed it in your test. It is passed automatically by react-navigation when running your app, but inside your tests, you have to manually mock it.

it('should render Album Details component', () => {
    const wrapper = shallow(
        <AlbumDetailsView navigation={{ getParam: jest.fn() }} />
    );
});

Now getParam won't be undefined anymore. Of course, using the above code, won't return anything when calling getParam('albumTitle') since in your test getParam() is just a jest.fn(), which can translate to an empty function that does nothing.

If you want to make it return values, you will have to manually implement the mocked function as well, like

it('should render Album Details component', () => {
    const wrapper = shallow(
        <AlbumDetailsView navigation={{ getParam: (param) => {
            if (param === 'albumTitle') return 'albumTitle';
            ...
        } }} />
    );
});


问:
Flex 3: Creating and populating a new XML file on the server to be reloaded at a later date
I have an application that reads in an external XML file, parses out the pieces, displays them, and then allows the user to edit them.  I would like to have a save button that the user can press that would save any changes to a new XML document somewhere on the server (any file location that I specify).  I've been looking around online, and can't find any examples... all I can find is that this ability wasn't available until flash v.10.

Another option i was considering was to create an XML variable, create it's value, and then somehow forward the user to a coldfusion page where I could then create a file.

If anybody can help me out with either of these two methods, it'd be greatly appreciated.

答:
First, this ability has been around forever.  You're just 'saving' a string to the server.  Nothing complex with that.  You just need to make sure what the server has a service that can save said string to whatever format needed.

I'm not too sure what's the difficulty.  You do have some kind of server right?  Maybe show some code?


问:
JSON.parse generates error with backslash
Why does the following JSON fail to be parsed by JSON.parse?

```<code>{"page_title":"contact us","val":{"pattern":"/email/\s+us\s*(.*?)/\s/","type":"1"}}
</code>```

When I log result to the console then it gives above output. After using JSON.parse it gives this error :

Uncaught SyntaxError: Unexpected token s in JSON at position 1649 at JSON.parse ()
  see my code below:

```<code>var result ='<?php echo json_encode($output);?>';
console.log(result);
var data = JSON.parse(result);
</code>```

答:
Simple... don't single-quote wrap your json object nor call JSON.parse().

```<code>let result = <?php echo json_encode($output); ?>;
</code>```

Now result is a javascript object that is ready to use.

If you are json_encode() properly, your string will look like this:

Code: (Demo)

```<code>$array = [
    "page_title" => "contact us",
    "val" => [
        "pattern" => "/email/\s+us\s*(.*?)/\s/",
        "type" => "1"
    ]
];

echo json_encode($array);
</code>```

Output:

```<code>{"page_title":"contact us","val":{"pattern":"\/email\/\\s+us\\s*(.*?)\/\\s\/","type":"1"}}
</code>```

p.s. your regex pattern looks questionable with those unescaped slash after email and after the capture group despite the pattern having slashes as delimiters.

If this pattern is for js execution, you might have better success with:

```<code>email\/\s+us\s*(.*?)\/\s
</code>```

without delimters so that your pattern can be used by a regex function as a variable.

And if my above logic doesn't scream loud enough, here is a javascript demo that shows that json_encode() does not need addslashes():

The below data variable will be populated by:

```<code>data = <?php echo json_encode([
                      "page_title" => "contact us",
                      "val" => [
                      "pattern" => "email\/\s+us\s*(.*?)\/\s",
                      "type" => "1"
                  ]
                  ]); ?>;
</code>```

let data = {"page_title":"contact us","val":{"pattern":"email\\\/\\s+us\\s*(.*?)\\\/\\s","type":"1"}},
    str = "You can email/ us all-day-long if you wish/  or not.";

console.log(data.page_title);
console.log(data.val.pattern);
regex = new RegExp(data.val.pattern,"g");
console.log(str.match(regex));
console.log(data.val.type);```

Body:
Why does the following JSON fail to be parsed by JSON.parse?

{"page_title":"contact us","val":{"pattern":"/email/\s+us\s*(.*?)/\s/","type":"1"}}

When I log result to the console then it gives above output. After using JSON.parse it gives this error :

Uncaught SyntaxError: Unexpected token s in JSON at position 1649 at JSON.parse ()
  see my code below:

var result ='<?php echo json_encode($output);?>';
console.log(result);
var data = JSON.parse(result);

Body:
Simple... don't single-quote wrap your json object nor call JSON.parse().

let result = <?php echo json_encode($output); ?>;

Now result is a javascript object that is ready to use.

If you are json_encode() properly, your string will look like this:

Code: (Demo)

$array = [
    "page_title" => "contact us",
    "val" => [
        "pattern" => "/email/\s+us\s*(.*?)/\s/",
        "type" => "1"
    ]
];

echo json_encode($array);

Output:

{"page_title":"contact us","val":{"pattern":"\/email\/\\s+us\\s*(.*?)\/\\s\/","type":"1"}}

p.s. your regex pattern looks questionable with those unescaped slash after email and after the capture group despite the pattern having slashes as delimiters.

If this pattern is for js execution, you might have better success with:

email\/\s+us\s*(.*?)\/\s

without delimters so that your pattern can be used by a regex function as a variable.

And if my above logic doesn't scream loud enough, here is a javascript demo that shows that json_encode() does not need addslashes():

The below data variable will be populated by:

data = <?php echo json_encode([
                      "page_title" => "contact us",
                      "val" => [
                      "pattern" => "email\/\s+us\s*(.*?)\/\s",
                      "type" => "1"
                  ]
                  ]); ?>;

let data = {"page_title":"contact us","val":{"pattern":"email\\\/\\s+us\\s*(.*?)\\\/\\s","type":"1"}},
    str = "You can email/ us all-day-long if you wish/  or not.";

console.log(data.page_title);
console.log(data.val.pattern);
regex = new RegExp(data.val.pattern,"g");
console.log(str.match(regex));
console.log(data.val.type);


问:
Jenkins plugins for old versions
Fore some reasons I have to use Jenkins 2.32 and I need to install some plugins there. Machine with it has no internet, so I only can upload plugin file to install it from file.

So, the problem is there any easy way to obtain required plugin for required Jenkins version with all it's dependencies?

p.s.

I can't update Jenkins - it's out of my power.

p.p.s.

I find only way to download old versions of plugin, but by this way I can't check dependencies and required jenkins version before loading.

答:
I had such an environment before.

Warning: it's an annoying process.

Because there was no internet, we uploaded all plugins manually, i.e. looking at the plugin page (e.g. https://plugins.jenkins.io/git/) and then downloading from the archive (e.g. https://updates.jenkins.io/download/plugins/git) the .hpi file. As you have to use a relatively old version of Jenkins you may want to check the changelog of the plugin, if you have to use an older version.

In addition on each plugin page the dependencies are listed and you have to repeat the above steps for each dependency.

The only good thing is that usually Jenkins gives you hints, which dependencies are missing after you uploaded a plugin.

Title: Jenkins plugins for old versions


问:
Unexpected EOF - Terraform apply
I am new to Azure / Azure Devops and Terraform, I am getting the following error when im running terraform apply from an Azure DevOps Pipeline.

/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 9: unexpected EOF while looking for matching `"'
/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 10: syntax error: unexpected end of file

Here is the script I am trying to execute as part of a yaml pipeline. I can run the same code for UAT and Prod with no issues.

```<code>      - script: |
                terraform apply \
                  -auto-approve \
                  -var="client-id=$(client-id)" \
                  -var="client-secret=$(client-secret)" \
                  -var="subscription-id=$(subscription-id)" \
                  -var="tenant-id=$(tenant-id)" \
                  -var="application_name=transport" \
                  -var="environment_tag=dev" \
                  -var="location=northeurope" \
        workingDirectory: './deploy'
        displayName: 'Terraform apply'
</code>```

答:
I've generated a new client secret this morning and the script is running fine. I guess there was character within the last secret causing this to error.
I cannot explain why the Terraform init part for the script was able to execute correctly as this was also using the same secret.</p>

Title: Unexpected EOF - Terraform apply

Body:
I am new to Azure / Azure Devops and Terraform, I am getting the following error when im running terraform apply from an Azure DevOps Pipeline.

/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 9: unexpected EOF while looking for matching `"'
/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 10: syntax error: unexpected end of file

Here is the script I am trying to execute as part of a yaml pipeline. I can run the same code for UAT and Prod with no issues.

      - script: |
                terraform apply \
                  -auto-approve \
                  -var="client-id=$(client-id)" \
                  -var="client-secret=$(client-secret)" \
                  -var="subscription-id=$(subscription-id)" \
                  -var="tenant-id=$(tenant-id)" \
                  -var="application_name=transport" \
                  -var="environment_tag=dev" \
                  -var="location=northeurope" \
        workingDirectory: './deploy'
        displayName: 'Terraform apply'


问:
SQL syntax near WHERE?
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?</p>

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}
</code>```

答:
An INSERT can't have a WHERE clause. It makes no sense to have one, you're putting data in, not narrowing it down.

If you're trying to change preexisting data, that's an UPDATE, not an INSERT. Here's an example:

```<code>"UPDATE Submission
 SET Status='decline', StatusComment='" + TbComments.Text + "', StatusValue = 2
 WHERE SubmissionId = " + x
</code>```

Title: SQL syntax near WHERE?

Body:
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}

Body:
An INSERT can't have a WHERE clause. It makes no sense to have one, you're putting data in, not narrowing it down.

If you're trying to change preexisting data, that's an UPDATE, not an INSERT. Here's an example:

"UPDATE Submission
 SET Status='decline', StatusComment='" + TbComments.Text + "', StatusValue = 2
 WHERE SubmissionId = " + x


问:
How to get the full dates between two dates using javascript / react?
My requirement is to get the number of days between two dates.

For example, the start date is 02/20/2020 to 01/03/2020 I would like to display the results like

Feb 20 Thursday, Feb 21 Friday,....01 Mar Monday.

I went through this scenario in StackOverflow but I didn't get the expected solution for the same.

Could anyone please guide in achieving this scenario using javascript or react?

答:
you can use momentjs to get the result:

```<code>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//let moment = require("moment");

let date = [];

let startDate = "02/20/2020";
let endDate = "01/03/2020";
while ( moment(startDate, "MM/DD/YYYY").valueOf() <= moment(endDate, "DD/MM/YYYY").valueOf()) {
  date.push(moment(startDate, "MM/DD/YYYY").format("MMM DD dddd"));
  startDate = moment(startDate, "MM/DD/YYYY").add(1, "days").format("MM/DD/YYYY");
}
console.log(date);</code>```

```
</div>
</div>

</code>```

Body:
you can use momentjs to get the result:

//let moment = require("moment");

let date = [];

let startDate = "02/20/2020";
let endDate = "01/03/2020";
while ( moment(startDate, "MM/DD/YYYY").valueOf() <= moment(endDate, "DD/MM/YYYY").valueOf()) {
  date.push(moment(startDate, "MM/DD/YYYY").format("MMM DD dddd"));
  startDate = moment(startDate, "MM/DD/YYYY").add(1, "days").format("MM/DD/YYYY");
}
console.log(date);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


问:
Black background slide up
It is probably very simple but i'm stuck trying to make a homepage automatic background slider like here : https://www.jackdavison.co.uk

That's probably Jquery but I found a way to have something similar with html and Css, only it keeps repeating.

Any help ?

You can see my code here:

HTML

```<code><div class="wrapper">
  <div class="sliding-background"></div>
</div>
</code>```

CSS:

```<code>.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 2s linear infinite;
  animation-delay: 4000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);

  }
  100%{
    transform: translate3d(0px, -2000px, 0px);

  }

}
</code>```

See on Codepen here

Thank you !

答:
To stop the animation and keep the last state use:</p>

```<code>.sliding-background {
     animation: slide 2s linear;
     animation-fill-mode: forwards;
}
</code>```

Title: Black background slide up

Body:
It is probably very simple but i'm stuck trying to make a homepage automatic background slider like here : https://www.jackdavison.co.uk

That's probably Jquery but I found a way to have something similar with html and Css, only it keeps repeating.

Any help ?

You can see my code here:

HTML

CSS:

.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 2s linear infinite;
  animation-delay: 4000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);

  }
  100%{
    transform: translate3d(0px, -2000px, 0px);

  }

}

See on Codepen here

Thank you !

Body:
To stop the animation and keep the last state use:

.sliding-background {
     animation: slide 2s linear;
     animation-fill-mode: forwards;
}


问:
How to properly display the checked attributes in another div with different styles?
I am very new to jQuery. The first part of the code is to check the inputs and after checked it should display the checked items the below format. How can do this with the help of jquery.

Name

Initiator

          <input name="one" type="checkbox" id="one" />

```

<p>After checked it should displays in this format. </p>

<pre class="lang-html prettyprint-override"><code><div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1">
  <h6 class="heading--form mb-2 mt-3 mt-sm-0">
    User
  </h6>
  <ul class="approval approval_scrolltab mt-3">
    <li>
      <div class="approval--member">
        <img src="assets/images/user.jpg" class="user--image" />
        <div class="w-100">
          <h6 class="approval--name">Name</h6>
          <p>Initiator</p>
        </div>

          <span class="ic-close"></span>

      </div>
    </li>
  </ul>
</div>
</code>```

I tried like this.It was working fine for the names but got no idea how can display this user image attached with name and also there is a cancel icon too near the name.I am only being able to display name with this code.

```

<p><strong>UPDATE</strong>
With this close  button I want to remove this from checked list(which works great) as well as I want to uncheck this from checked in input.</p>

``` $('body').on('click', '.ic-close', function() {
    $(this).closest('li').remove()
    $(this).closest('li').prop('checked',false) #didn't worked
  });
```

答:
Simply check if you really need jQuery, in 2020 the pure Javascript have the majority of the jQuery fonctions : http://youmightnotneedjquery.com/

You can get the checked attribute via an event like this :

```<code>var checkbox = document.querySelector('[type="checkbox"]');

// Event Listener:
checkbox.addEventListener('change', function(event) {
    alert(event.target.checked);
    if(event.target.checked) {
        // Do want do you want when checked
    }
});

</code>```

I don't understand very well what you expected but I hope that it could help you.

Body:
I am very new to jQuery. The first part of the code is to check the inputs and after checked it should display the checked items the below format. How can do this with the help of jquery.

Name

Initiator

          <input name="one" type="checkbox" id="one" />

After checked it should displays in this format.

    User

Name

Initiator

I tried like this.It was working fine for the names but got no idea how can display this user image attached with name and also there is a cancel icon too near the name.I am only being able to display name with this code.

UPDATE
With this close  button I want to remove this from checked list(which works great) as well as I want to uncheck this from checked in input.

 $('body').on('click', '.ic-close', function() {
    $(this).closest('li').remove()
    $(this).closest('li').prop('checked',false) #didn't worked
  });

Body:
Simply check if you really need jQuery, in 2020 the pure Javascript have the majority of the jQuery fonctions : http://youmightnotneedjquery.com/

You can get the checked attribute via an event like this :

var checkbox = document.querySelector('[type="checkbox"]');

// Event Listener:
checkbox.addEventListener('change', function(event) {
    alert(event.target.checked);
    if(event.target.checked) {
        // Do want do you want when checked
    }
});

I don't understand very well what you expected but I hope that it could help you.


问:
IN operator in SQL Statement Does not work?
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

```<code>V = ABS((P & 0xFFFFFFFF) * 256 - F)
</code>```

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

```<code>DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)
</code>```

But in SQL Server, I will get the following error:

```<code>Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','
</code>```

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.

答: the select query after IN must return only one column , test it first

Body:
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

V = ABS((P & 0xFFFFFFFF) * 256 - F)

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)

But in SQL Server, I will get the following error:

Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.