问:
Laravel 5.8 check record in the database if exists not working
I got a schedules table and i want it to have any duplicates. If the user puts same datas in the form that has already in the database it will not go to dd('exists') does anyone know what seems to be the problem?

Here is my update

```<code>$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->count();

if($validate == 1){
          dd('exist');
} else{
            $schedule->update($request->all());
}
</code>```

tried
dd($request->all());
I got

```<code>array:11 [
  "id" => 9
  "term" => "2"
  "semester" => "2"
  "start_time" => "10:30 PM"
  "end_time" => "12:30 AM"
  "scid" => 10
  "teacher_id" => 5
  "room_id" => 6
  "subject_code_id" => 9
  "day" => "SAT"
  "school_year" => "2020"
]
</code>```

答:
use first() method instead of count()

```<code>$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->first();

if($validate){
          dd('exist');
} else{
            $schedule->update($request->all());
}
</code>```

Body:
I got a schedules table and i want it to have any duplicates. If the user puts same datas in the form that has already in the database it will not go to dd('exists') does anyone know what seems to be the problem?

Here is my update

$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->count();

if($validate == 1){
          dd('exist');
} else{
            $schedule->update($request->all());
}

tried
dd($request->all());
I got

array:11 [
  "id" => 9
  "term" => "2"
  "semester" => "2"
  "start_time" => "10:30 PM"
  "end_time" => "12:30 AM"
  "scid" => 10
  "teacher_id" => 5
  "room_id" => 6
  "subject_code_id" => 9
  "day" => "SAT"
  "school_year" => "2020"
]

Body:
use first() method instead of count()

$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->first();

if($validate){
          dd('exist');
} else{
            $schedule->update($request->all());
}


来源: stackexchange

问:
Fluentd with elasticsearch unreachable_exception
I am setting up elasticsearch and fluentd in a docker i am getting host_unreachable_exceptions. Below is my full exception log:

```<code>2020-02-13 08:45:05 +0000 [error]: #0 unexpected error error_class=NameError error="uninitialized constant Faraday::Error::ConnectionFailed"
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-7.4.0/lib/elasticsearch/transport/transport/http/faraday.rb:51:in `host_unreachable_exceptions'
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/fluent-plugin-elasticsearch-4.0.3/lib/fluent/plugin/elasticsearch_index_template.rb:36:in `rescue in retry_operate'
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/fluent-plugin-elasticsearch-4.0.3/lib/fluent/plugin/elasticsearch_index_template.rb:34:in `retry_operate'
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/fluent-plugin-elasticsearch-4.0.3/lib/fluent/plugin/out_elasticsearch.rb:282:in `configure'

</code>```

My docker-compose file is:

```<code>version: '3'
services:

    elasticsearch:
      image: docker.elastic.co/elasticsearch/elasticsearch:7.4.0
      container_name: Eagle_Core_local_elasticsearch
      environment:
        - xpack.security.enabled=false
        - discovery.type=single-node
      ulimits:
        memlock:
          soft: -1
          hard: -1
        nofile:
          soft: 65536
          hard: 65536
      cap_add:
        - IPC_LOCK
      volumes:
        - ./../../../data/elasticsearch-data:/usr/share/elasticsearch/data
      networks:
        - eaglenet
      ports:
        - 9200:9200
        - 9300:9300

    fluentd:
      container_name: Eagle_Core_FluentLogger
      build:
        context: ./docker-conf/fluentd
      environment:
        - FLUENT_UID=1000
      networks:
        - eaglenet
      ports:
        - "24231:24231"
      volumes:
        - ./../../../log/fluentd:/fluentd/log
        - ./docker-conf/fluentd/fluent.conf:/fluentd/etc/fluent.conf
      logging:
        driver: "json-file"
        options:
          max-size: "200k"
          max-file: "3"
      env_file:
        - ./local.config.env

</code>```

and here is my fluent.conf:

```<code><match flight.error.log>
  @type elasticsearch
  host elasticsearch
  port 9200
  utc_index false
  target_index_key @target_index
  logstash_prefix ${tag}
  logstash_dateformat %Y%m%d
  type_name error_log
  <buffer>
    flush_interval 2s
    chunk_limit_size 64m
    flush_thread_count 4
    @type file
    path /fluentd/log/flight
  </buffer>
</match>
</code>```

Note: I can ping elasticsearch:9200 from fluentd container

答: I have same problem too.  please look this  https://github.com/uken/fluent-plugin-elasticsearch/issues/699,   lucasteles22 said need modify the script elasticsearch-transport-7.4.0/lib/elasticsearch/transport/transport/http/fa raday.rb:51. I tried it and it worked.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am setting up elasticsearch and fluentd in a docker i am getting host_unreachable_exceptions. Below is my full exception log:

2020-02-13 08:45:05 +0000 [error]: #0 unexpected error error_class=NameError error="uninitialized constant Faraday::Error::ConnectionFailed"
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-7.4.0/lib/elasticsearch/transport/transport/http/faraday.rb:51:in `host_unreachable_exceptions'
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/fluent-plugin-elasticsearch-4.0.3/lib/fluent/plugin/elasticsearch_index_template.rb:36:in `rescue in retry_operate'
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/fluent-plugin-elasticsearch-4.0.3/lib/fluent/plugin/elasticsearch_index_template.rb:34:in `retry_operate'
  2020-02-13 08:45:05 +0000 [error]: #0 /usr/lib/ruby/gems/2.5.0/gems/fluent-plugin-elasticsearch-4.0.3/lib/fluent/plugin/out_elasticsearch.rb:282:in `configure'

My docker-compose file is:

version: '3'
services:

    elasticsearch:
      image: docker.elastic.co/elasticsearch/elasticsearch:7.4.0
      container_name: Eagle_Core_local_elasticsearch
      environment:
        - xpack.security.enabled=false
        - discovery.type=single-node
      ulimits:
        memlock:
          soft: -1
          hard: -1
        nofile:
          soft: 65536
          hard: 65536
      cap_add:
        - IPC_LOCK
      volumes:
        - ./../../../data/elasticsearch-data:/usr/share/elasticsearch/data
      networks:
        - eaglenet
      ports:
        - 9200:9200
        - 9300:9300

    fluentd:
      container_name: Eagle_Core_FluentLogger
      build:
        context: ./docker-conf/fluentd
      environment:
        - FLUENT_UID=1000
      networks:
        - eaglenet
      ports:
        - "24231:24231"
      volumes:
        - ./../../../log/fluentd:/fluentd/log
        - ./docker-conf/fluentd/fluent.conf:/fluentd/etc/fluent.conf
      logging:
        driver: "json-file"
        options:
          max-size: "200k"
          max-file: "3"
      env_file:
        - ./local.config.env

and here is my fluent.conf:

<match flight.error.log>
  @type elasticsearch
  host elasticsearch
  port 9200
  utc_index false
  target_index_key @target_index
  logstash_prefix ${tag}
  logstash_dateformat %Y%m%d
  type_name error_log
  <buffer>
    flush_interval 2s
    chunk_limit_size 64m
    flush_thread_count 4
    @type file
    path /fluentd/log/flight
  </buffer>
</match>

Note: I can ping elasticsearch:9200 from fluentd container


问:
Is it possible to have children routes and route-views in vuepress?
I'm trying to have a children route-view inside my main page, and can't find a way to accomplish this in vuepress.

This is how I would normally accomplish this in Vue, in router.js

```<code>    routes: [
        {
            path: '/',
            name: 'home',
            component: Home,
            children: [
                {
                    path: '/work/:worktitle',
                    name: 'workpage',
                    // component: () => import(/* webpackChunkName: "about" */ './views/WorkView.vue'),

                    component: WorkView,
                    props: true
                }
            ]
        }
    ]
</code>```

But I don't know where can I put such code in vuepress. (no router.js)

I am trying to accomplish this because I'm trying to have a collection of links in my homepage, and when clicked, I'd like to have the pages of those links rendered as a modal without going to a new page. But I'd like to retain the ability to link directly to these modals.

答:
use .vuepress/enhanceApp.js with router.addRoutes

// async function is also supported, too
export default ({
  Vue, // the version of Vue being used in the VuePress app
  options, // the options for the root Vue instance
  router, // the router instance for the app
  siteData, // site metadata
  isServer // is this enhancement applied in server-rendering or client
}) => {
  // ...apply enhancements to the app
  router.addRoutes([
    // ...
  ])
}
```

Body:
I'm trying to have a children route-view inside my main page, and can't find a way to accomplish this in vuepress.

This is how I would normally accomplish this in Vue, in router.js

    routes: [
        {
            path: '/',
            name: 'home',
            component: Home,
            children: [
                {
                    path: '/work/:worktitle',
                    name: 'workpage',
                    // component: () => import(/* webpackChunkName: "about" */ './views/WorkView.vue'),

                    component: WorkView,
                    props: true
                }
            ]
        }
    ]

But I don't know where can I put such code in vuepress. (no router.js)

I am trying to accomplish this because I'm trying to have a collection of links in my homepage, and when clicked, I'd like to have the pages of those links rendered as a modal without going to a new page. But I'd like to retain the ability to link directly to these modals.


问:
Spotify API Authorization gives me different refresh token each time
I follow the steps in the Spotify Web Api Tutorial using the authorization-code from the Spotify Accounts Authentication Examples. Everything is okey, I register an application with Spotify, authenticate a user and get authorization to access user data and when the page show me the user data the refresh token is different each time I authenticate myself. I think refresh token shuld not change.

The only modification I did in the example code was replace the client id, client secret and the redirect uri with the correct values from my application.

Any advices?

答: For the Authorisation Code Flow you just need to do that initial authentication you're already doing. It will always return a new refresh token however that token can be used over an over with 4. Requesting a refreshed access token; Spotify returns a new access token to your app from Authorisation Guide that will return you a new access token for subsequent calls and you won't need to do the Authentication Step you're doing multiple times just keep doing that one.


问:
Calling a validation from within another custom validation
I want to have two different custom validators, but would like one of the validators to reference the other:

```<code>class URLFormatValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # ... validates the format of a URL is correct
  end
end

class URLReachableValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # ... validates the URL is reachable
  end
end
</code>```

How can I reference the URLFormatValidator within the URLReachableValidator?

答:
```<code>class URLReachableValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    format_validator = URLFormatValidator.new
    format_validator.validate_each(record, attribute, value)
  end
end
</code>```

But I would just use inheritance or a mix-in to share functionality instead.

```<code>class URLValidator < ActiveModel::EachValidator
  # shared funtionality ...
end

class URLFormatValidator < URLValidator
  def validate_each(record, attribute, value)
    # ...
  end
end

class URLReachableValidator < URLValidator
  def validate_each(record, attribute, value)
    # ...
  end
end
</code>```

Body:
I want to have two different custom validators, but would like one of the validators to reference the other:

class URLFormatValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # ... validates the format of a URL is correct
  end
end

class URLReachableValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # ... validates the URL is reachable
  end
end

How can I reference the URLFormatValidator within the URLReachableValidator?

Body:
class URLReachableValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    format_validator = URLFormatValidator.new
    format_validator.validate_each(record, attribute, value)
  end
end

But I would just use inheritance or a mix-in to share functionality instead.

class URLValidator < ActiveModel::EachValidator
  # shared funtionality ...
end

class URLFormatValidator < URLValidator
  def validate_each(record, attribute, value)
    # ...
  end
end

class URLReachableValidator < URLValidator
  def validate_each(record, attribute, value)
    # ...
  end
end


问:
Select nested field in a query with Parse platform
I have extended Parse.Object and my subclass has a nested field like this:

```<code>{
    timesheet: {
        activities: [],
        entries: [],
        clients: []
    }
}
</code>```

timesheet can be quite big, so I want to select only a specific field of it:

```<code>new Parse.Query('MyObject')
    .select('timesheet.activities')
    .find();
</code>```

However, what is returned are all fields of the nested object timesheet, not only activities. How can I achieve that?

答:
You refactor your code like this :

```<code>MyObject['timesheet'].activities

</code>```

in this way you can access your object nested property

Body:
I have extended Parse.Object and my subclass has a nested field like this:

{
    timesheet: {
        activities: [],
        entries: [],
        clients: []
    }
}

timesheet can be quite big, so I want to select only a specific field of it:

new Parse.Query('MyObject')
    .select('timesheet.activities')
    .find();

However, what is returned are all fields of the nested object timesheet, not only activities. How can I achieve that?

Body:
You refactor your code like this :

MyObject['timesheet'].activities

in this way you can access your object nested property


问:
Warning: A non-numeric value encountered
Recently updated to PHP 7.1 and start getting following error

Warning: A non-numeric value encountered in on line 29

Here is what line 29 looks like

```<code>$sub_total += ($item['quantity'] * $product['price']);
</code>```

On localhost all works fine..

Any ideas how to tackle this or what it is ?

答:
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
 https://www.php.net/manual/en/language.operators.arithmetic.php

wrong use of + operator:

```<code>            "<label for='content'>Content:</label>"+
            "<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
            "</div>";
</code>```

use . for concatenation

```<code>$output = "<div class='from-group'>".
            "<label for='content'>Content:</label>".
            "<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
            "</div>";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Recently updated to PHP 7.1 and start getting following error

Warning: A non-numeric value encountered in on line 29

Here is what line 29 looks like

$sub_total += ($item['quantity'] * $product['price']);

On localhost all works fine..

Any ideas how to tackle this or what it is ?

Body:
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
 https://www.php.net/manual/en/language.operators.arithmetic.php

wrong use of + operator:

            "<label for='content'>Content:</label>"+
            "<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
            "</div>";

use . for concatenation

$output = "<div class='from-group'>".
            "<label for='content'>Content:</label>".
            "<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
            "</div>";


问:
Change Button text in html and angular 2
I want to change the button text once it is selected, logically it is working fine, initially YES button is highlighting once i click on it sightly change then if i hover disable symbol will show
first image : before click
second image : after click
So what i want is , when i click on yes it should change it to NO and if i hover disable symbol has to show
here is my HTML code

```<code> <div>
                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                        YES
                    </button>

</div>
</code>```

答:
the shortest way would be to conditionally render text inside of a button with innerText

```<code><button [innerText]="condition ? 'YES' : 'NO'"></button>
</code>```

Body:
I want to change the button text once it is selected, logically it is working fine, initially YES button is highlighting once i click on it sightly change then if i hover disable symbol will show
first image : before click
second image : after click
So what i want is , when i click on yes it should change it to NO and if i hover disable symbol has to show
here is my HTML code

                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                        YES
                    </button>

Body:
the shortest way would be to conditionally render text inside of a button with innerText

<button [innerText]="condition ? 'YES' : 'NO'"></button>


问:
Is DI the only solution to Singleton and/or static objects?
I have been told that Singletons are hard to test.

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

I have been told that Static methods/objects are no good either.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

So basically the only solution appears to be dependency injection.

But ... I really can't get used to DI, take this example:

In my framework I have a class that manages SQL. This class (and many other of my framework) uses a singleton Logger to logs message (and many other helpers).

With DI my code would turn to:

```<code>global $logger; //> consider i have been instanciated it at the start of my fw

$query = new PreparedQuery($logger);
$query->prepare() etc.
</code>```

Now that doesn't seem too bad. But consider a page that needs many queries I believe it's pretty redundant to have to write everytime $logger in the constructor, especially if you consider if PreparedQuery needed many other dependencies in the constructor.

The only solution to avoid singleton that I have found is to use a method (or just a simple function) in the main application that stores every references to this helper objects (Service Locator/Container) but this doens't solve the problem of hiding the dependencies

So in your experience other than DI what is a good pattern to use?

Solution:

For everyone interesetd the creator of PHPunit explains how to solve the Singleton problem (and how to solve static methods testing problem with PHP 5.3)

(singleton) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

(static) http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Pretty interesting read if you ask me.

答:
Please, don't use global.

You need to pass $logger in constructors or pass Service Container instead (also known as Objects manager, Service Locator, Resources Manager).

Variant from Symfony framework http://symfony.com/doc/current/book/service_container.html

You can create your own Objects Manager, and his methods should not be static.

Body:
I have been told that Singletons are hard to test.

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

I have been told that Static methods/objects are no good either.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

So basically the only solution appears to be dependency injection.

But ... I really can't get used to DI, take this example:

In my framework I have a class that manages SQL. This class (and many other of my framework) uses a singleton Logger to logs message (and many other helpers).

With DI my code would turn to:

global $logger; //> consider i have been instanciated it at the start of my fw

$query = new PreparedQuery($logger);
$query->prepare() etc.

Now that doesn't seem too bad. But consider a page that needs many queries I believe it's pretty redundant to have to write everytime $logger in the constructor, especially if you consider if PreparedQuery needed many other dependencies in the constructor.

The only solution to avoid singleton that I have found is to use a method (or just a simple function) in the main application that stores every references to this helper objects (Service Locator/Container) but this doens't solve the problem of hiding the dependencies

So in your experience other than DI what is a good pattern to use?

Solution:

For everyone interesetd the creator of PHPunit explains how to solve the Singleton problem (and how to solve static methods testing problem with PHP 5.3)

(singleton) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

(static) http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Pretty interesting read if you ask me.


问:
In opencv-python cap.read() returns false after 1 second
I'm trying to label a video with opencv version 4.2.0.32, python 3.7.4 and win10. I installed opencv with pip. After I select a video from QFileDialog at first cap.read return with frame but after 15-16 frames cap.read return false and output video is only first 1 second of the main video. Help pls.</p>

```<code>while cap.isOpened():
    ret,frame = cap.read()
    ""some codes here""
    out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cap.release()
cv2.destroyAllWindows()
</code>```

答: I actually solve the problem. It was code independent. It looks like opencv dlls were missing from the python path. I pasted the dlls and problem solved. </p>

Body:
I'm trying to label a video with opencv version 4.2.0.32, python 3.7.4 and win10. I installed opencv with pip. After I select a video from QFileDialog at first cap.read return with frame but after 15-16 frames cap.read return false and output video is only first 1 second of the main video. Help pls.

while cap.isOpened():
    ret,frame = cap.read()
    ""some codes here""
    out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cap.release()
cv2.destroyAllWindows()


问:
Why do I get "System.Data.DataRowView" instead of real values in my WinForms Listbox?
Whenever I run my code and try to view a highscore all I get back in my listbox is System.Data.DataRowView.

Can anyone see why?

Code:

```<code>MySqlConnection myConn = new MySqlConnection(connStr);

string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
                "FROM highscore ORDER BY Score DESC";

MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.DataSource = dTable;
</code>```

答: Sometimes what might cause it is mis-spelt displaymember variable name.</p>

Body:
Whenever I run my code and try to view a highscore all I get back in my listbox is System.Data.DataRowView.

Can anyone see why?

Code:

MySqlConnection myConn = new MySqlConnection(connStr);

string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
                "FROM highscore ORDER BY Score DESC";

MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.DataSource = dTable;


问:
Numpy array is modified globally by the function without return
When I use the function that doesn't return anything, the input parameters remain globally unchanged.

For example:

```<code>def func(var):
    var += 1

a = 0

for i in range(3):
    func(a)
    print(a)
</code>```

logically results in

```<code>0
0
0
</code>```

By it doesn't seem to work the same when the input is numpy array:

```<code>import numpy as np

def func(var):
    var += 1

a = np.zeros(3)

for i in range(3):
    func(a)
    print(a)
</code>```

Output:

```<code>[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]
</code>```

Thus, all modifications were applied to array globally, not inside the function. Why is it happening? And, more generally, are there any special rules on how to handle np arrays as functions input?

答:
+= for int (and float, str, ...) creates a new value. Such types are known as immutable, because each individual object cannot be changed.

```<code>>>> i = 1
>>> id(i)
4550541072
>>> i += 1
>>> id(i)  # different id
4550541104
</code>```

This means incrementing such a value inside a function creates a new value inside the function. Any references outside of the function are unaffected.

+= for np.array (and list, Counter, ...) modifies the content. Such types are known as mutable, because each individual object can be changed.

```<code>>>> l = [0, 1, 2, 3]
>>> id(l)
4585425088
>>> l += [4]
>>> id(l)
4585425088
</code>```

This means incrementing such a value inside a function changes the value of the object visible inside and outside of the function. Any references inside and outside of the function point to the exact same object, and show its changed value.

Body:
When I use the function that doesn't return anything, the input parameters remain globally unchanged.

For example:

def func(var):
    var += 1

a = 0

for i in range(3):
    func(a)
    print(a)

logically results in

0
0
0

By it doesn't seem to work the same when the input is numpy array:

import numpy as np

def func(var):
    var += 1

a = np.zeros(3)

for i in range(3):
    func(a)
    print(a)

Output:

[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]

Thus, all modifications were applied to array globally, not inside the function. Why is it happening? And, more generally, are there any special rules on how to handle np arrays as functions input?

Body:
+= for int (and float, str, ...) creates a new value. Such types are known as immutable, because each individual object cannot be changed.

>>> i = 1
>>> id(i)
4550541072
>>> i += 1
>>> id(i)  # different id
4550541104

This means incrementing such a value inside a function creates a new value inside the function. Any references outside of the function are unaffected.

+= for np.array (and list, Counter, ...) modifies the content. Such types are known as mutable, because each individual object can be changed.

>>> l = [0, 1, 2, 3]
>>> id(l)
4585425088
>>> l += [4]
>>> id(l)
4585425088

This means incrementing such a value inside a function changes the value of the object visible inside and outside of the function. Any references inside and outside of the function point to the exact same object, and show its changed value.


问:
Digital Image cropping in Python
Got this question from a professor, a physicist.

I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.

All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function.

I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise.

答:
While I agree with David that you should probably just use GIMP or some other image manipulation program, here is a script (as I took it to be an exercise to the reader) using pygame that does what you want.  You will need to install pygame as well as the PIL, usage would be:

```<code>scriptname.py <input_path> <output_path>
</code>```

Actual script:

```<code>import pygame, sys
from PIL import Image
pygame.init()

def displayImage( screen, px, topleft):
    screen.blit(px, px.get_rect())
    if topleft:
        pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1]))
    pygame.display.flip()

def setup(path):
    px = pygame.image.load(path)
    screen = pygame.display.set_mode( px.get_rect()[2:] )
    screen.blit(px, px.get_rect())
    pygame.display.flip()
    return screen, px

def mainLoop(screen, px):
    topleft = None
    bottomright = None
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                if not topleft:
                    topleft = event.pos
                else:
                    bottomright = event.pos
                    runProgram = False
        displayImage(screen, px, topleft)
    return ( topleft + bottomright )

if __name__ == "__main__":
    screen, px = setup(sys.argv[1])
    left, upper, right, lower = mainLoop(screen, px)
    im = Image.open(sys.argv[1])
    im = im.crop(( left, upper, right, lower))
    im.save(sys.argv[2])
</code>```

Hope this helps :)

OwnerDisplayName: becomingGuru

ContentLicense: CC BY-SA 2.5

Title: Digital Image cropping in Python

Body:
While I agree with David that you should probably just use GIMP or some other image manipulation program, here is a script (as I took it to be an exercise to the reader) using pygame that does what you want.  You will need to install pygame as well as the PIL, usage would be:

scriptname.py <input_path> <output_path>

Actual script:

import pygame, sys
from PIL import Image
pygame.init()

def displayImage( screen, px, topleft):
    screen.blit(px, px.get_rect())
    if topleft:
        pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1]))
    pygame.display.flip()

def setup(path):
    px = pygame.image.load(path)
    screen = pygame.display.set_mode( px.get_rect()[2:] )
    screen.blit(px, px.get_rect())
    pygame.display.flip()
    return screen, px

def mainLoop(screen, px):
    topleft = None
    bottomright = None
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                if not topleft:
                    topleft = event.pos
                else:
                    bottomright = event.pos
                    runProgram = False
        displayImage(screen, px, topleft)
    return ( topleft + bottomright )

if __name__ == "__main__":
    screen, px = setup(sys.argv[1])
    left, upper, right, lower = mainLoop(screen, px)
    im = Image.open(sys.argv[1])
    im = im.crop(( left, upper, right, lower))
    im.save(sys.argv[2])

Hope this helps :)

OwnerDisplayName: Andrew Cox


问:
Manipulate a Password
My Java application manipulates a password that is eventually used to encrypt a file.
I load it in a structure

```<code>public char[] password;
</code>```

because I saw it in swing JPasswordField.

I suppose that this adds some level of protection against the memory scanning for passwords.
I think that it is just a little "obscurity" level, not a real protection.
It seems to me that this is useful because it is effective against many trivial scanners.
Do things stand like this, or am I missing something?

答:
The reason why using char[] instead of String is preferred by some people is that the char[] can be cleared after use narrowing the window when the password appearing in core dumps or exposed through failure of bound checking reads from buffers.

However, it doesn't work so well for JPasswordField for a number of reasons:

GC can move the object without necessarily immediately blanking the original copy.

JPasswordField is often used with an ActionListener, which receives the password as the command string in the ActionEvent.

The Document implementation may make copies.

People forget to blank the JPasswordField after extracting the char[].

There's probably more important security things that you could be expending effort on (like airport screeners keeping an eye out for bottle of water and letting bomb parts through).

On the pro side, you get a tick list feature and don't have to explain yourself because you are doing Best Practice.

Title: Manipulate a Password

Body:
My Java application manipulates a password that is eventually used to encrypt a file.
I load it in a structure

public char[] password;

because I saw it in swing JPasswordField.

I suppose that this adds some level of protection against the memory scanning for passwords.
I think that it is just a little "obscurity" level, not a real protection.
It seems to me that this is useful because it is effective against many trivial scanners.
Do things stand like this, or am I missing something?


问:
if-throw precondition check effectiveness and the DRY principle
A lot of internet resources insist on checking preconditions in API functions via if (something_is_wrong) throw Exception{} instead of assert(!something_is_wrong) and I see some good points in it. However, I'm afraid such usage may result in doubling the same checks:

```<code>void foo(int positive) {
  if (positive < 1) {
    throw std::invalid_argument("param1 must be positive");
  }
}
void caller() {
  int number = get_number_somehow();
  if (number >= 1) {
    foo(number);
  }
}
</code>```

will probably execute like

```<code>int number = get_number_somehow();
if (number >= 1) {
  if (number < 1) {
    throw std::invalid_argument("param must be positive");
  }
}
</code>```

unless the call will actually be inlined and optimized by cutting out one of the ifs, I guess. Besides, writing the check twice (in foo() and in caller()) might be violating the DRY rule. Therefore, maybe I should go for

```<code>void caller() {
  int number = get_number_somehow();
  try {
    foo(number);
  } catch (std::invalid_argument const&) {
    // handle or whatever
  }
}
</code>```

to evade repeating myself with those precondition checks, providing a bit of performance and a lot of maintainability in case of a function contract change.

However, I can't always apply such logic. Imagine std::vector having only at() but not operator[]:

```<code>for (int i = 0; i < vector.size(); ++i) {
  bar(vector.at(i)); // each index is checked twice: by the loop and by at()
}
</code>```

This code results in extra O(N) checks! Isn't it too much? Even if it is optimized out the same way as above, what about such situations with indirect calls or long functions, which probably won't be inlined?

So, should my program be written according to the rules below?

if an API function probably won't be inlined or is expected to be called a lot of times with checks on the call site (see the vector example), assert() its preconditions (inside it);

try-catch throwing functions instead of checking their preconditions before the call (the latter seems to break DRY).

If not, why?

答:
So, there are two separate things you are talking about: DRY and performance.

DRY is about code maintenance and structure, and doesn't really apply to code you can't control. So, if the API is a black-box, and there happens to be code inside of it that you can't change, but you need to have separately, then I wouldn't think of it as not DRY to repeat it in your code.  Y is Yourself.

But, you could still care about performance. If you measure a performance problem then fix it with whatever makes sense -- even if it's anti-DRY (or it's ok if it is).

But, if you control both sides (the API and the client) and you really want a pure, no-repeat, performant solution, then there's a pattern something like this pseudocode.  I don't know the name, but I think of it as "Proof Providing"

```<code>let fn = precondition_check(myNum)
if fn != nil {
    // the existence of fn is proof that myNum meets preconditions
    fn()
}
</code>```

The API func precondition_check returns a function that captures the myNum in it and doesn't need to check if it meets preconditions because it was only created if it did.

Body:
A lot of internet resources insist on checking preconditions in API functions via if (something_is_wrong) throw Exception{} instead of assert(!something_is_wrong) and I see some good points in it. However, I'm afraid such usage may result in doubling the same checks:

void foo(int positive) {
  if (positive < 1) {
    throw std::invalid_argument("param1 must be positive");
  }
}
void caller() {
  int number = get_number_somehow();
  if (number >= 1) {
    foo(number);
  }
}

will probably execute like

int number = get_number_somehow();
if (number >= 1) {
  if (number < 1) {
    throw std::invalid_argument("param must be positive");
  }
}

unless the call will actually be inlined and optimized by cutting out one of the ifs, I guess. Besides, writing the check twice (in foo() and in caller()) might be violating the DRY rule. Therefore, maybe I should go for

void caller() {
  int number = get_number_somehow();
  try {
    foo(number);
  } catch (std::invalid_argument const&) {
    // handle or whatever
  }
}

to evade repeating myself with those precondition checks, providing a bit of performance and a lot of maintainability in case of a function contract change.

However, I can't always apply such logic. Imagine std::vector having only at() but not operator[]:

for (int i = 0; i < vector.size(); ++i) {
  bar(vector.at(i)); // each index is checked twice: by the loop and by at()
}

This code results in extra O(N) checks! Isn't it too much? Even if it is optimized out the same way as above, what about such situations with indirect calls or long functions, which probably won't be inlined?

So, should my program be written according to the rules below?

if an API function probably won't be inlined or is expected to be called a lot of times with checks on the call site (see the vector example), assert() its preconditions (inside it);

try-catch throwing functions instead of checking their preconditions before the call (the latter seems to break DRY).

If not, why?

Body:
So, there are two separate things you are talking about: DRY and performance.

DRY is about code maintenance and structure, and doesn't really apply to code you can't control. So, if the API is a black-box, and there happens to be code inside of it that you can't change, but you need to have separately, then I wouldn't think of it as not DRY to repeat it in your code.  Y is Yourself.

But, you could still care about performance. If you measure a performance problem then fix it with whatever makes sense -- even if it's anti-DRY (or it's ok if it is).

But, if you control both sides (the API and the client) and you really want a pure, no-repeat, performant solution, then there's a pattern something like this pseudocode.  I don't know the name, but I think of it as "Proof Providing"

let fn = precondition_check(myNum)
if fn != nil {
    // the existence of fn is proof that myNum meets preconditions
    fn()
}

The API func precondition_check returns a function that captures the myNum in it and doesn't need to check if it meets preconditions because it was only created if it did.


问:
How to solve Android MultiDex Apllication Instance Null Pointer Exception?
I want to do a core api service integration in my Android project.
My core service class is as follows:

```<code>public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}
</code>```

Then I create an instance from this core class. But here my constant getIntance value returns null.

```<code>TestApplication.getInstance().setupRetrofit();
</code>```

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?

答:
After Enabling Multidex

Replace With:-

public class Application extends MultiDexApplication {

```<code>public static final String TAG = Application.class.getSimpleName();

@Override
public void onCreate() {
    super.onCreate();

    ApplicationHelper.initDatabaseHelper(this);
    PostInteractor.getInstance(this).subscribeToNewPosts();
}
</code>```

}

Body:
I want to do a core api service integration in my Android project.
My core service class is as follows:

public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}

Then I create an instance from this core class. But here my constant getIntance value returns null.

TestApplication.getInstance().setupRetrofit();

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?

Body:
After Enabling Multidex

Replace With:-

public class Application extends MultiDexApplication {

public static final String TAG = Application.class.getSimpleName();

@Override
public void onCreate() {
    super.onCreate();

    ApplicationHelper.initDatabaseHelper(this);
    PostInteractor.getInstance(this).subscribeToNewPosts();
}

}


问:
How do i access state of one reducer in other in react redux. State flow between reducers and store
I'm an absolute beginner in react-redux and I watched many videos and articles,docs and couldn't understand how the state flows between reducers and between store to reducer.

I am having state for each reducer like this

const initState = {todos:[]}

cont reducer = (state=initState,action) ....

Reducer 2 similarly with different state

initState2 = {todo:" "}

reducer2 = (state=initState2,action) ...

And then I import and combine the reducers. Here I am using two different reducers which have different states and is it the right way of doing things ?  If so, How can redux be called single state if each reducer have its own individual state.

Don't we have a single state in the store which is accessed by all the reducers and dispatch actions to change state of store directly instead of changing the reducer's store. Any help is appreciated and it may seems like a silly question but filling the gaps is really important and many beginners have same doubt as mine and please do help. Thank you

答:
How can redux be called single state if each reducer have its own individual state.

Because the state is not saved in the reducers. The state is only saved in the store and there is only one store. That is why is called single state.

To create the store:

```<code>const store = createStore(myBeautifulReducers)
</code>```

In your case, myBeautifulReducers would be:

```<code>const myBeautifulReducers = combineReducers({reducer, reducer2});
</code>```

myBeautifulReducers will be an object that contains both reducers (reducer and reducer2) and the logic you wrote in each of them (switch statements and so on).

Body:
How can redux be called single state if each reducer have its own individual state.

Because the state is not saved in the reducers. The state is only saved in the store and there is only one store. That is why is called single state.

To create the store:

const store = createStore(myBeautifulReducers)

In your case, myBeautifulReducers would be:

const myBeautifulReducers = combineReducers({reducer, reducer2});

myBeautifulReducers will be an object that contains both reducers (reducer and reducer2) and the logic you wrote in each of them (switch statements and so on).


问:
Why Abstract=True dosen't inherit in Meta class of django model
I we have this models in django:

```<code>class FotherModel(models.Model):
    # Some fields goes here!
    class Meta:
        # Some fields goes here!
        abstract = True
class ChildModel(FotherModel):
    # Some fields goes here!
    class Meta(FotherModel.Meta):
        #s Some fields goes here!
</code>```

When we inherit a field from the meta class of Django models, that field  appears in child meta class, But this rule does not apply to abstract=True.

I know that if this happens, no table in database will be created, But I don't know how this inheritance didn't happen. Please explain this process for me.

答:
Because of the concept and effect of some fields in meta section in many cases it doesn't make sense that the field is inherited by chidren.

It has been described here

Body:
I we have this models in django:

class FotherModel(models.Model):
    # Some fields goes here!
    class Meta:
        # Some fields goes here!
        abstract = True
class ChildModel(FotherModel):
    # Some fields goes here!
    class Meta(FotherModel.Meta):
        #s Some fields goes here!

When we inherit a field from the meta class of Django models, that field  appears in child meta class, But this rule does not apply to abstract=True.

I know that if this happens, no table in database will be created, But I don't know how this inheritance didn't happen. Please explain this process for me.


问:
Unit Test a configuration class not working in Multi Maven Spring Boot project
I am working on multi module maven project with SpringBoot framework.
The project is divided in 4 modules: rest module,service module,repository module, domain module.
I am trying to write a unit test  for a configuration class in java which is located in the service module.
I have simplified the case to get rid of business logic complexity. The configuration class is like below:

```<code>@Configuration
@ConfigurationProperties(prefix = "x.y.feature", ignoreInvalidFields = false)
public class FeatureConfig {

        private String featureUrl;

        public String getFeatureUrl() {
            return featureUrl;
        }

        public void setFeatureUrl(String FeatureUrl) {
            this.featureUrl = featureUrl;
        }

}
</code>```

The properties file is application.properties.

```<code>x.y.feature.featureUrl=featureUrl
</code>```

And below is the unit test that is not working.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FeatureConfigTest.class })
public class FeatureConfigTest {
    @Autowired
    private FeatureConfig featureConfig;

    @Test
    public void testgetFeatureUrl() {
        String expected ="featureUrl";
        assertEquals(expected,featureConfig.getFeatureUrl());
    }
}

</code>```

When i run the unit test , it throws the exception below:

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
</code>```

答:
The problem  is that you are trying to use object of FeatureConfig
from the application context. You haven't initialized the application context.
When you use the @Autowire annotation, you are mapping field 'featureConfig'
with instance of type FeatureConfig class located in the application context.
To bypass this error you need initialize the application context.

First thing , create static class inside the test class that will help us not to load the
whole application context. Because for this test case you don't need to load the whole application.
First thing , create static class inside the test class that will help us not to load the
whole application context. Because for this test case you don't need to load the whole application.

```<code>    @EnableConfigurationProperties(FeatureConfig.class)
    public static class TestConfiguration {
    }
</code>```

After that you start the application context , but with passing as configuration the static class
you created. This is done not to load the whole application context.

@SpringBootTest(classes = { FeatureConfigTest.TestConfiguration class })

Copy and paste the changes below in your test class and everything should work ok.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FeatureConfigTest.TestConfiguration class })
public class FeatureConfigTest {
    @Autowired
    private FeatureConfig featureConfig;

    @Test
    public void testgetFeatureUrl() {
        String expected ="featureUrl";
        assertEquals(expected,featureConfig.getFeatureUrl());
    }

    @EnableConfigurationProperties(FeatureConfig.class)
    public static class TestConfiguration {
    }
}
</code>```

Body:
I am working on multi module maven project with SpringBoot framework.
The project is divided in 4 modules: rest module,service module,repository module, domain module.
I am trying to write a unit test  for a configuration class in java which is located in the service module.
I have simplified the case to get rid of business logic complexity. The configuration class is like below:

@Configuration
@ConfigurationProperties(prefix = "x.y.feature", ignoreInvalidFields = false)
public class FeatureConfig {

        private String featureUrl;

        public String getFeatureUrl() {
            return featureUrl;
        }

        public void setFeatureUrl(String FeatureUrl) {
            this.featureUrl = featureUrl;
        }

}

The properties file is application.properties.

x.y.feature.featureUrl=featureUrl

And below is the unit test that is not working.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FeatureConfigTest.class })
public class FeatureConfigTest {
    @Autowired
    private FeatureConfig featureConfig;

    @Test
    public void testgetFeatureUrl() {
        String expected ="featureUrl";
        assertEquals(expected,featureConfig.getFeatureUrl());
    }
}

When i run the unit test , it throws the exception below:

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)

Body:
The problem  is that you are trying to use object of FeatureConfig
from the application context. You haven't initialized the application context.
When you use the @Autowire annotation, you are mapping field 'featureConfig'
with instance of type FeatureConfig class located in the application context.
To bypass this error you need initialize the application context.

First thing , create static class inside the test class that will help us not to load the
whole application context. Because for this test case you don't need to load the whole application.
First thing , create static class inside the test class that will help us not to load the
whole application context. Because for this test case you don't need to load the whole application.

    @EnableConfigurationProperties(FeatureConfig.class)
    public static class TestConfiguration {
    }

After that you start the application context , but with passing as configuration the static class
you created. This is done not to load the whole application context.

@SpringBootTest(classes = { FeatureConfigTest.TestConfiguration class })

Copy and paste the changes below in your test class and everything should work ok.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { FeatureConfigTest.TestConfiguration class })
public class FeatureConfigTest {
    @Autowired
    private FeatureConfig featureConfig;

    @Test
    public void testgetFeatureUrl() {
        String expected ="featureUrl";
        assertEquals(expected,featureConfig.getFeatureUrl());
    }

    @EnableConfigurationProperties(FeatureConfig.class)
    public static class TestConfiguration {
    }
}


问:
Scraping data with jsoup
So I am scraping some data with jsoup library. Data is organized in html element table. I want to show relevant data in textView or in a listView. For starters, it needs to be in textView. When I try to display information from more than one table, textView just shows me the first one. I can't get my mind wrapped about this. Hope you could help me to point out what I am doing wrong.

Here is the code

```<code>
    TextView textView;
    Button dohvatiStranicu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textView);
        textView.setMovementMethod(new ScrollingMovementMethod());
        dohvatiStranicu = (Button)findViewById(R.id.getPageButton);

        dohvatiStranicu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new dohvatiStranicu().execute();
            }
        });

    }

    public class dohvatiStranicu extends AsyncTask<Void,Void,Void>{

        StringBuilder stringBuilder;

        @Override
        protected void onPreExecute() {
            stringBuilder = new StringBuilder();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try{
                Document doc = Jsoup.connect("https://inf.ffzg.unizg.hr/index.php/hr/studij/diplomski-studij/ispitni-rokovi?fbclid=IwAR0WuLXdooI_0wB8-vVbgZTs89jX-B0eNY0f4wmB9rScqojSqsA2oN-aQ6I").get();
                Elements tables = doc.select("table");
                for(Element table : tables){
                    stringBuilder.append("\n\n\n");
                    stringBuilder.append(parsirajTablicu(table));
                }

            }catch(Exception e){
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            textView.setText(stringBuilder);

        }
    }

    private static String parsirajTablicu(Element table){
        String text = "\n\n\n\n\n";

        Element nazivPredmeta = table.selectFirst("p");

        Elements naziviRokova = table.select("th");
        Elements datumiRokova = table.select("td");
        datumiRokova.remove(0);

        text += nazivPredmeta.text()+ "\n\n";
        text += naziviRokova.get(0).text() + "\n";
        text += "    " + datumiRokova.get(0).text() + "\n";
        text += "    " + datumiRokova.get(4).text() + "\n";
        text += "    " + datumiRokova.get(8).text() + "\n";

        text += naziviRokova.get(1).text() + "\n";
        text += "    " + datumiRokova.get(1).text() + "\n";
        text += "    " + datumiRokova.get(5).text() + "\n";
        text += "    " + datumiRokova.get(9).text() + "\n";

        text += naziviRokova.get(2).text() + "\n";
        text += "    " + datumiRokova.get(2).text() + "\n";
        text += "    " + datumiRokova.get(6).text() + "\n";
        text += "    " + datumiRokova.get(10).text() + "\n";

        text += naziviRokova.get(3).text() + "\n";
        text += "    " + datumiRokova.get(3).text() + "\n";
        text += "    " + datumiRokova.get(7).text() + "\n";
        text += "    " + datumiRokova.get(11).text() + "\n";

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

答:
The second table has no "th" elements, then naziviRokova is null and nazivPredmeta.text() results in a NullPointerException.

You also must be careful with datumiRokova.get(i) as it will result in IndexOutOfBoundsException if there are not enough elements.

As a general advice try to isolate "logic" and "android" integration code, it will allow you to test your code more effectively.

Full example:

```<code>package org.example;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SO_60092082 {

    private static String parsirajTablicu(Element table){
        String text = "\n\n\n\n\n";

        Element nazivPredmeta = table.selectFirst("p");

        Elements naziviRokova = table.select("th");
        Elements datumiRokova = table.select("td");
        datumiRokova.remove(0);

        if (nazivPredmeta!=null)
            text += nazivPredmeta.text()+ "\n\n";

        text += safeGetText(naziviRokova, 0) + "\n";
        text += "    " + safeGetText(datumiRokova, 0) + "\n";
        text += "    " + safeGetText(datumiRokova, 4) + "\n";
        text += "    " + safeGetText(datumiRokova, 8) + "\n";

        text += safeGetText(naziviRokova, 1) + "\n";
        text += "    " + safeGetText(datumiRokova, 1) + "\n";
        text += "    " + safeGetText(datumiRokova, 5) + "\n";
        text += "    " + safeGetText(datumiRokova, 9) + "\n";

        text += safeGetText(naziviRokova, 2) + "\n";
        text += "    " + safeGetText(datumiRokova, 2) + "\n";
        text += "    " + safeGetText(datumiRokova, 6) + "\n";
        text += "    " + safeGetText(datumiRokova, 10) + "\n";

        text += safeGetText(naziviRokova, 3) + "\n";
        text += "    " + safeGetText(datumiRokova, 3) + "\n";
        text += "    " + safeGetText(datumiRokova, 7) + "\n";
        text += "    " + safeGetText(datumiRokova, 11) + "\n";

        return text;
    }

    private static String safeGetText(Elements datumiRokova, int i) {
        return datumiRokova.size()>i ? datumiRokova.get(i).text() : "";
    }

    public static void main(String[] args) {

        try{
            StringBuilder stringBuilder = new StringBuilder();
            Document doc =  Jsoup.connect("https://inf.ffzg.unizg.hr/index.php/hr/studij/diplomski-studij/ispitni-rokovi?fbclid=IwAR0WuLXdooI_0wB8-vVbgZTs89jX-B0eNY0f4wmB9rScqojSqsA2oN-aQ6I").get();
            Elements tables = doc.select("table");
            for(Element table : tables){
                stringBuilder.append("\n\n\n");
                stringBuilder.append(parsirajTablicu(table));
            }

            System.out.println(stringBuilder);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

Title: Scraping data with jsoup

Body:
So I am scraping some data with jsoup library. Data is organized in html element table. I want to show relevant data in textView or in a listView. For starters, it needs to be in textView. When I try to display information from more than one table, textView just shows me the first one. I can't get my mind wrapped about this. Hope you could help me to point out what I am doing wrong.

Here is the code

    TextView textView;
    Button dohvatiStranicu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textView);
        textView.setMovementMethod(new ScrollingMovementMethod());
        dohvatiStranicu = (Button)findViewById(R.id.getPageButton);

        dohvatiStranicu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new dohvatiStranicu().execute();
            }
        });

    }

    public class dohvatiStranicu extends AsyncTask<Void,Void,Void>{

        StringBuilder stringBuilder;

        @Override
        protected void onPreExecute() {
            stringBuilder = new StringBuilder();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try{
                Document doc = Jsoup.connect("https://inf.ffzg.unizg.hr/index.php/hr/studij/diplomski-studij/ispitni-rokovi?fbclid=IwAR0WuLXdooI_0wB8-vVbgZTs89jX-B0eNY0f4wmB9rScqojSqsA2oN-aQ6I").get();
                Elements tables = doc.select("table");
                for(Element table : tables){
                    stringBuilder.append("\n\n\n");
                    stringBuilder.append(parsirajTablicu(table));
                }

            }catch(Exception e){
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            textView.setText(stringBuilder);

        }
    }

    private static String parsirajTablicu(Element table){
        String text = "\n\n\n\n\n";

        Element nazivPredmeta = table.selectFirst("p");

        Elements naziviRokova = table.select("th");
        Elements datumiRokova = table.select("td");
        datumiRokova.remove(0);

        text += nazivPredmeta.text()+ "\n\n";
        text += naziviRokova.get(0).text() + "\n";
        text += "    " + datumiRokova.get(0).text() + "\n";
        text += "    " + datumiRokova.get(4).text() + "\n";
        text += "    " + datumiRokova.get(8).text() + "\n";

        text += naziviRokova.get(1).text() + "\n";
        text += "    " + datumiRokova.get(1).text() + "\n";
        text += "    " + datumiRokova.get(5).text() + "\n";
        text += "    " + datumiRokova.get(9).text() + "\n";

        text += naziviRokova.get(2).text() + "\n";
        text += "    " + datumiRokova.get(2).text() + "\n";
        text += "    " + datumiRokova.get(6).text() + "\n";
        text += "    " + datumiRokova.get(10).text() + "\n";

        text += naziviRokova.get(3).text() + "\n";
        text += "    " + datumiRokova.get(3).text() + "\n";
        text += "    " + datumiRokova.get(7).text() + "\n";
        text += "    " + datumiRokova.get(11).text() + "\n";

        return text;
    }
}

Body:
The second table has no "th" elements, then naziviRokova is null and nazivPredmeta.text() results in a NullPointerException.

You also must be careful with datumiRokova.get(i) as it will result in IndexOutOfBoundsException if there are not enough elements.

As a general advice try to isolate "logic" and "android" integration code, it will allow you to test your code more effectively.

Full example:

package org.example;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SO_60092082 {

    private static String parsirajTablicu(Element table){
        String text = "\n\n\n\n\n";

        Element nazivPredmeta = table.selectFirst("p");

        Elements naziviRokova = table.select("th");
        Elements datumiRokova = table.select("td");
        datumiRokova.remove(0);

        if (nazivPredmeta!=null)
            text += nazivPredmeta.text()+ "\n\n";

        text += safeGetText(naziviRokova, 0) + "\n";
        text += "    " + safeGetText(datumiRokova, 0) + "\n";
        text += "    " + safeGetText(datumiRokova, 4) + "\n";
        text += "    " + safeGetText(datumiRokova, 8) + "\n";

        text += safeGetText(naziviRokova, 1) + "\n";
        text += "    " + safeGetText(datumiRokova, 1) + "\n";
        text += "    " + safeGetText(datumiRokova, 5) + "\n";
        text += "    " + safeGetText(datumiRokova, 9) + "\n";

        text += safeGetText(naziviRokova, 2) + "\n";
        text += "    " + safeGetText(datumiRokova, 2) + "\n";
        text += "    " + safeGetText(datumiRokova, 6) + "\n";
        text += "    " + safeGetText(datumiRokova, 10) + "\n";

        text += safeGetText(naziviRokova, 3) + "\n";
        text += "    " + safeGetText(datumiRokova, 3) + "\n";
        text += "    " + safeGetText(datumiRokova, 7) + "\n";
        text += "    " + safeGetText(datumiRokova, 11) + "\n";

        return text;
    }

    private static String safeGetText(Elements datumiRokova, int i) {
        return datumiRokova.size()>i ? datumiRokova.get(i).text() : "";
    }

    public static void main(String[] args) {

        try{
            StringBuilder stringBuilder = new StringBuilder();
            Document doc =  Jsoup.connect("https://inf.ffzg.unizg.hr/index.php/hr/studij/diplomski-studij/ispitni-rokovi?fbclid=IwAR0WuLXdooI_0wB8-vVbgZTs89jX-B0eNY0f4wmB9rScqojSqsA2oN-aQ6I").get();
            Elements tables = doc.select("table");
            for(Element table : tables){
                stringBuilder.append("\n\n\n");
                stringBuilder.append(parsirajTablicu(table));
            }

            System.out.println(stringBuilder);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


问:
Can't get out this while loop
I want this loop to break when user enters anything but y or Y. But, instead the Enter the new location prompt is returning again and again.

```<code>    def add_locations(self):
        while True:
            new = str(input("Enter the new loation: "))
            self.locations.append(new)
            ask = str(input("add new location? (y/n):  "))
            if ask == 'y' or 'Y':
                continue
            else:
                break
</code>```

答:
Alternatively, you can put all your positive values into a tuple:

while True:
    new = str(input("Enter the new location: "))
    self.locations.append(new)
    ask = str(input("add new location? (y/n):  "))
    if ask.lower() in ('y', 'yes'):
        continue
    else:
        break
```

Title: Can't get out this while loop

Body:
I want this loop to break when user enters anything but y or Y. But, instead the Enter the new location prompt is returning again and again.

    def add_locations(self):
        while True:
            new = str(input("Enter the new loation: "))
            self.locations.append(new)
            ask = str(input("add new location? (y/n):  "))
            if ask == 'y' or 'Y':
                continue
            else:
                break


问:
Kotlin Data class setter using class fields
I have a redis entity using a kotlin data class and its Id should be a combination of few other fields from the same class.
Can this be achieved by defining setter for Id field instead of computing it outside of data class?

```<code>@RedisHash("Game")
data class Game(
  @Id
  val generatedId: String = "Default_ID",
  val name: String,
  val location: String,
  val homeTeam: String,
  val awayTeam: String

)

// want something like this

var generatedId : String = "DEFAULT_ID"
  get() = "${name}${location}"

// or even better

var generated_Id : String =  "${name}${location}"
</code>```

答:
Did you try to do something like this?</p>

```<code>@RedisHash("Game")
data class Game(
    val name: String,
    val location: String,
    val homeTeam: String,
    val awayTeam: String,
    @Id
    val generatedId: String = "${name}${location}"
)
</code>```

Body:
I have a redis entity using a kotlin data class and its Id should be a combination of few other fields from the same class.
Can this be achieved by defining setter for Id field instead of computing it outside of data class?

@RedisHash("Game")
data class Game(
  @Id
  val generatedId: String = "Default_ID",
  val name: String,
  val location: String,
  val homeTeam: String,
  val awayTeam: String

)

// want something like this

var generatedId : String = "DEFAULT_ID"
  get() = "${name}${location}"

// or even better

var generated_Id : String =  "${name}${location}"

Body:
Did you try to do something like this?

@RedisHash("Game")
data class Game(
    val name: String,
    val location: String,
    val homeTeam: String,
    val awayTeam: String,
    @Id
    val generatedId: String = "${name}${location}"
)


问:
Replace end characters of current URL with bookmarklet
Is there a way to replace all characters after the last backslash in the currentURL with another string via javascript bookmarklet?

I'm doing a lot of auditing work with Sharepoint sites and having to manually look at the settings pages for sites by entering strings to the end of a URL.  For example, I might go to a site like:

https://site.com/..../default.aspx

And I replace the "default.aspx" with "_layouts/user.aspx" and reload the new page so it is now at:

https://site.com/..../_layouts/user.aspx

It's not always "default.aspx", so I can't just use a simple string replace.  I know there is a way to manipulate the URL via a javascript bookmarklet, but my knowledge of how to do that is limited at best.  Any help or guidance would be greatly appreciated

答:
I don't know if this is what you thought, but if you just want to change the last part of the url with something else, you could use this bookmarklet

```<code>javascript:(function(){

var curloc = document.location.href.split('/');
var urlEnding= '/_layouts/user.aspx';
curloc = curloc.splice(0,curloc.length-1).join('/')+urlEnding;
document.location.href = curloc;

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

You could replace the fixed url with

```<code>prompt('Enter your url:', '_layouts/user.aspx');
</code>```

if you need to change the last part each time.

I hope this helps.

Body:
I don't know if this is what you thought, but if you just want to change the last part of the url with something else, you could use this bookmarklet

javascript:(function(){

var curloc = document.location.href.split('/');
var urlEnding= '/_layouts/user.aspx';
curloc = curloc.splice(0,curloc.length-1).join('/')+urlEnding;
document.location.href = curloc;

})();

You could replace the fixed url with

prompt('Enter your url:', '_layouts/user.aspx');

if you need to change the last part each time.

I hope this helps.


问:
Handle concurrent async updates to local state
I have a series of asynchronous calls that read from a local state S, perform some computation based on its current value, and return a new, update value of the local state S'

All this happens at runtime, so I have very little control over the order of these operations. This is a simplified version of what I have.

type State = {
  state: number
}

let localState: State = {
  state: 1000
}

const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
  );

const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
  .then(res => {
    localState.state = res
    console.log(localState)
  })

post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000
```

<p>Playground link</p>

<p>This model is clearly broken, as both calls to <code>post</code> will read the same value of <code>localState</code>, while instead they should be performed sequentially.</p>

<p>If all calls were already determined at compile time, I could simply have something like</p>

<pre class="lang-js prettyprint-override"><code>post(1000, localState)
  .then(() => post(3000, localState)) // localState at call time is now 2000
</code>```

How would I go about solving this?

答:
This is a problem that I have personally encountered on many occasions. My solution is to create a queue class in charge of making sure that all Promise are executed in mutual exclusion. I call it PromiseQueue:

class PromiseQueue {
    constructor() {
        this._queue = new Array(); // Or an LinkedList for better performance
        this._usingQueue = false;
    }

    /**
     * Adds an element to the queue and runs the queue. It resolves when the promise has been executed and resolved.
     *
     * @param {Promise<any>} promise
     */
    add(promise) {
        const self = this;
        return new Promise((resolve, reject) => {
            const promiseData = {
                promise,
                resolve,
                reject,
            };
            self._queue.push(promiseData);
            self._runQueue();
        });
    }

    async _runQueue() {
        if (!this._usingQueue && this._queue.length > 0) {
            this._usingQueue = true;
            const nextPromiseData = this._queue.shift();
            const { promise, resolve, reject } = nextPromiseData;
            try {
                const result = await promise();
                resolve(result);
            } catch (e) {
                reject(e);
            }
            this._usingQueue = false;
            this._runQueue();
        }
    }
}
```

<p>Then you would use it like this (not tested):</p>

<pre class="lang-js prettyprint-override"><code>const myPromiseQueue = new PromiseQueue();

// This way you are making sure that the second post
// will be executed when the first one has finished
myPromiseQueue.add(async() => await post(1000, localState));
myPromiseQueue.add(async() => await post(3000, localState));
</code>```

Body:
I have a series of asynchronous calls that read from a local state S, perform some computation based on its current value, and return a new, update value of the local state S'

All this happens at runtime, so I have very little control over the order of these operations. This is a simplified version of what I have.

type State = {
  state: number
}

let localState: State = {
  state: 1000
}

const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
  );

const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
  .then(res => {
    localState.state = res
    console.log(localState)
  })

post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000

<a href="https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=23&pc=1#code/C4TwDgpgBAysCGxoF4oG8BQUoGcFIC4oA7AVwFsAjCAJwwF8MMAbCYKZgewGN5m5EEIgKRRUmbHkFEAjAAYFDJt07E8UMDU7kAljggAVHeQidS7VAApgxoSQrUaAGigA3PqTtkqtAJRiAPihLf2Qg4ggAdygABS1dfUssbGCaCBxOZlc7S2Iib0dQoNdOHQATItw2IxMzYEs0jKyIFxsTF3dmTygAaig2iF9k3wBuJgwVNXYwTjwiXPyHWhduUho04mARO23KuO09CAAeEvKgq2IVys0D-RrTc1yVgDopJF8Q5OfgAAsIYga6UC6GS2C4vH4+AgryhYigjVBUEmTWhXAA5pZwXxdsl6EMMDM8JZ5AoXFjIYJRgTZvUAMwKORknjYqFUjBAA" rel="nofollow noreferrer">Playground link

This model is clearly broken, as both calls to post will read the same value of localState, while instead they should be performed sequentially.

If all calls were already determined at compile time, I could simply have something like

post(1000, localState)
  .then(() => post(3000, localState)) // localState at call time is now 2000

How would I go about solving this?

Body:
This is a problem that I have personally encountered on many occasions. My solution is to create a queue class in charge of making sure that all Promise are executed in mutual exclusion. I call it PromiseQueue:

class PromiseQueue {
    constructor() {
        this._queue = new Array(); // Or an LinkedList for better performance
        this._usingQueue = false;
    }

    /**
     * Adds an element to the queue and runs the queue. It resolves when the promise has been executed and resolved.
     *
     * @param {Promise<any>} promise
     */
    add(promise) {
        const self = this;
        return new Promise((resolve, reject) => {
            const promiseData = {
                promise,
                resolve,
                reject,
            };
            self._queue.push(promiseData);
            self._runQueue();
        });
    }

    async _runQueue() {
        if (!this._usingQueue && this._queue.length > 0) {
            this._usingQueue = true;
            const nextPromiseData = this._queue.shift();
            const { promise, resolve, reject } = nextPromiseData;
            try {
                const result = await promise();
                resolve(result);
            } catch (e) {
                reject(e);
            }
            this._usingQueue = false;
            this._runQueue();
        }
    }
}

Then you would use it like this (not tested):

const myPromiseQueue = new PromiseQueue();

// This way you are making sure that the second post
// will be executed when the first one has finished
myPromiseQueue.add(async() => await post(1000, localState));
myPromiseQueue.add(async() => await post(3000, localState));


问:
How to store multiple files name into phpmyadmin database using foreach?
The code below does not work. What is the solution for this problem OR any suggestion and what is the most correct way to solve this problem?

HTML Code

```<code><form action="includes/galleryAddImagesCMS.inc.php" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td><div class="container">
                    <div class="upload-btn-wrapper">
                        <label>
                        <input type="hidden" name="albumName" value="<?php echo $albumName ?>"/>
                        <input type="file" id="uploadFile" name="uploadFile[]" multiple/>

                        Choose File
                        </label>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td><div id="image_preview"></div></td>
        </tr>
        <tr>
            <td>
                <input type="submit" class="btn btn-success" name='submitImage' value="Upload Image"/>
            </td>
        </tr>
    </table>
</form>
</code>```

The following below is PHP CODE

```<code><?php
if(isset($_POST['submitImage'])){
            $albumName = mysqli_real_escape_string($conn,$_POST['albumName']);
            $sqlAlbumname="INSERT INTO gallery (GalleryName, Creationdate) VALUES ('$albumName', CURRENT_TIMESTAMP())";

            if(mysqli_query($conn,$sqlAlbumname)){

                foreach ($_FILES["uploadFile"]["name"] as $key => $imagesname) {

                    $sqlPhotoGallery="INSERT INTO photogallery (PhotoName, Creationdate, GalleryID)
                    VALUES ('$imagesname', CURRENT_TIMESTAMP(), (SELECT last_insert_id() FROM gallery))";

                    if(mysqli_query($conn,$sqlPhotoGallery)){
                        echo "success";
                    }
                }
            }
        }
</code>```

答:
I think there is an syntax error in your query

```<code>\\You can use else condition to print the error of query
if(mysqli_query($conn,$sqlPhotoGallery)){
    echo "success";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
</code>```

in your current code if you have multiple files then it will store multiple records in database.

you can use JSON to store file in single row

Body:
The code below does not work. What is the solution for this problem OR any suggestion and what is the most correct way to solve this problem?

HTML Code

<form action="includes/galleryAddImagesCMS.inc.php" method="post" enctype="multipart/form-data">

                        <input type="hidden" name="albumName" value="<?php echo $albumName ?>"/>
                        <input type="file" id="uploadFile" name="uploadFile[]" multiple/>

                        Choose File

                <input type="submit" class="btn btn-success" name='submitImage' value="Upload Image"/>

</form>

The following below is PHP CODE

<?php
if(isset($_POST['submitImage'])){
            $albumName = mysqli_real_escape_string($conn,$_POST['albumName']);
            $sqlAlbumname="INSERT INTO gallery (GalleryName, Creationdate) VALUES ('$albumName', CURRENT_TIMESTAMP())";

            if(mysqli_query($conn,$sqlAlbumname)){

                foreach ($_FILES["uploadFile"]["name"] as $key => $imagesname) {

                    $sqlPhotoGallery="INSERT INTO photogallery (PhotoName, Creationdate, GalleryID)
                    VALUES ('$imagesname', CURRENT_TIMESTAMP(), (SELECT last_insert_id() FROM gallery))";

                    if(mysqli_query($conn,$sqlPhotoGallery)){
                        echo "success";
                    }
                }
            }
        }

Body:
I think there is an syntax error in your query

\\You can use else condition to print the error of query
if(mysqli_query($conn,$sqlPhotoGallery)){
    echo "success";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

in your current code if you have multiple files then it will store multiple records in database.

you can use JSON to store file in single row


问:
cucumber debugger not stopping
I'm trying to debug a simple BDD test using cucumber. In order to do that, I inserted a debugger statement where I would like to break the control flow. But it seems that cucumber ignores this statement.

I'm running the tests executing:

```<code>rake cucumber:wip
</code>```

It's rather simple, so I think the code isn' t worth pasting here. Thanks in advance

答:
You don't have the rails-debug gem installed and/or included.

Make sure rails-debug listed in your Gemfile

If it's still not being included, make sure you run cucumber like:

bundle exec cucumber ...

Title: cucumber debugger not stopping

Body:
I'm trying to debug a simple BDD test using cucumber. In order to do that, I inserted a debugger statement where I would like to break the control flow. But it seems that cucumber ignores this statement.

I'm running the tests executing:

rake cucumber:wip

It's rather simple, so I think the code isn' t worth pasting here. Thanks in advance


问:
Problems with a react application deployed on k8s
I have a problem with a simple react app that was created using npx create-react-app react-app. Once deployed on k8s, I got this:

Uncaught SyntaxError: Unexpected token '<'

However, if I would to kubectl port-forward to the pod and view the app at localhost:3000 (container's pod is at 3000, cluster ip service listening on 3000 and forwarding to 3000) no problem at all.

The ingress routing looks to be fine as I can get to other services to work within the cluster but not to the app. Some help would be greatly appreciated.

Deployment yaml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: react-app-deployment
  # namespace: gitlab-managed-apps
spec:
  replicas: 1
  selector:
    matchLabels:
      component: react-app
  template:
    metadata:
      labels:
        component: react-app
    spec:
      imagePullSecrets:
      - name: simpleweb-token-namespace
      containers:
      - name: react-app
        image: registry.gitlab.com/mttlong/sample/react-app
        env:
        - name: "PORT"
          value: "3000"
        ports:
        - containerPort: 3000
</code>```

Cluster ip service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: react-app-cluster-ip-service
spec:
  type: ClusterIP
  selector:
    component: react-app
  ports:
  - port: 3000
    targetPort: 3000
</code>```

Dockerfile:

```<code>FROM node:10.15.3-alpine as builder
WORKDIR '/app'
COPY ./package.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx
EXPOSE 3000
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/build /usr/share/nginx/html
</code>```

Ingress Service:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: orion-ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2

spec:
  rules:
    - host: horizon.zeezum.com
      http:
        paths:
          - path: /
            backend:
              serviceName: react-app-cluster-ip-service
              servicePort: 3000
          - path: /api(/|$)(.*)
            backend:
              serviceName: simple-api-nodeport-service
              servicePort: 3050
</code>```

答:
This is most likely the result of a 404 page or a redirect to a page that serves regular html instead of the expected JavaScript files. (A HTML page starts with  or a <!DOCTYPE...> therefore the < as unexpected token)

Make sure that you have correctly build the image and you access the page correctly. You can verify by manually accessing the URL with the browser or look into the network tab of your browser development tools to inspect the response.
(I assume that either you have cached the index.html and try to access old assets, check your cache header, or that the paths to not match. In that case inspect your image and access the URLs manually)

Body:
I have a problem with a simple react app that was created using npx create-react-app react-app. Once deployed on k8s, I got this:

Uncaught SyntaxError: Unexpected token '<'

However, if I would to kubectl port-forward to the pod and view the app at localhost:3000 (container's pod is at 3000, cluster ip service listening on 3000 and forwarding to 3000) no problem at all.

The ingress routing looks to be fine as I can get to other services to work within the cluster but not to the app. Some help would be greatly appreciated.

Deployment yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: react-app-deployment
  # namespace: gitlab-managed-apps
spec:
  replicas: 1
  selector:
    matchLabels:
      component: react-app
  template:
    metadata:
      labels:
        component: react-app
    spec:
      imagePullSecrets:
      - name: simpleweb-token-namespace
      containers:
      - name: react-app
        image: registry.gitlab.com/mttlong/sample/react-app
        env:
        - name: "PORT"
          value: "3000"
        ports:
        - containerPort: 3000

Cluster ip service:

apiVersion: v1
kind: Service
metadata:
  name: react-app-cluster-ip-service
spec:
  type: ClusterIP
  selector:
    component: react-app
  ports:
  - port: 3000
    targetPort: 3000

Dockerfile:

FROM node:10.15.3-alpine as builder
WORKDIR '/app'
COPY ./package.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx
EXPOSE 3000
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/build /usr/share/nginx/html

Ingress Service:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: orion-ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2

spec:
  rules:
    - host: horizon.zeezum.com
      http:
        paths:
          - path: /
            backend:
              serviceName: react-app-cluster-ip-service
              servicePort: 3000
          - path: /api(/|$)(.*)
            backend:
              serviceName: simple-api-nodeport-service
              servicePort: 3050

Body:
This is most likely the result of a 404 page or a redirect to a page that serves regular html instead of the expected JavaScript files. (A HTML page starts with <html> or a <!DOCTYPE...> therefore the < as unexpected token)

Make sure that you have correctly build the image and you access the page correctly. You can verify by manually accessing the URL with the browser or look into the network tab of your browser development tools to inspect the response.
(I assume that either you have cached the index.html and try to access old assets, check your cache header, or that the paths to not match. In that case inspect your image and access the URLs manually)


问:
How to manage Interactions among Visuals in two different dash boards in Power Bi?
I have a bar chart like this :

For privacy Reasons I had to obscure labels. So let's call them Label 1 Label 2 etc. If I click on one of them I want to have returned the relative rows in this matrix, that is placed in another dashboards (the second page of my report) :

If I put this table on the same page of the report I do not get any problem. But if I put this table on another page of my report nothing is happening. I read already some reports about synchronization but I still have some issues.

答:
Just Solved. Being relatively new to Power BI it was not clear what I was searching for. I solved by  drill-through. I just chosen the page to drill out putting on the drill-through space on the right side of the page the set of variable of interest. </p>

<p>I found this page  and this you-tube video to be very helpful </p>

Body:
Just Solved. Being relatively new to Power BI it was not clear what I was searching for. I solved by  drill-through. I just chosen the page to drill out putting on the drill-through space on the right side of the page the set of variable of interest.

I found this page  and this you-tube video to be very helpful


答:
The Model metaclass resets abstract in a model's Meta class. In this document you can see:

Django does make one adjustment to the Meta class of an abstract base
  class: before installing the Meta attribute, it sets abstract=False.
  This means that children of abstract base classes don’t automatically
  become abstract classes themselves.

Also, you can see the source code of this process in this link:

```<code>if abstract:
    # Abstract base models can't be instantiated and don't appear in
    # the list of models for an app. We do the final setup for them a
    # little differently from normal models.
    attr_meta.abstract = False
    new_class.Meta = attr_meta
    return new_class
</code>```

Title: Why Abstract=True dosen't inherit in Meta class of django model

Body:
I we have this models in django:

class FotherModel(models.Model):
    # Some fields goes here!
    class Meta:
        # Some fields goes here!
        abstract = True
class ChildModel(FotherModel):
    # Some fields goes here!
    class Meta(FotherModel.Meta):
        #s Some fields goes here!

When we inherit a field from the meta class of Django models, that field  appears in child meta class, But this rule does not apply to abstract=True.

I know that if this happens, no table in database will be created, But I don't know how this inheritance didn't happen. Please explain this process for me.

Body:
The Model metaclass resets abstract in a model's Meta class. In this document you can see:

Django does make one adjustment to the Meta class of an abstract base
  class: before installing the Meta attribute, it sets abstract=False.
  This means that children of abstract base classes don’t automatically
  become abstract classes themselves.

Also, you can see the source code of this process in this link:

if abstract:
    # Abstract base models can't be instantiated and don't appear in
    # the list of models for an app. We do the final setup for them a
    # little differently from normal models.
    attr_meta.abstract = False
    new_class.Meta = attr_meta
    return new_class