问:
Tkinter Make Grid Fit Frame Size
I am wondering if there is a way to make a grids rows and columns fit the size of the Frame that is set. So that if I create a Frame and set its size that the grid will fit the size of the Frame.

This is what I tried so far:

window = Tk()

frame = Frame(window)
frame.place(x=0, y=0, width=200, height=200)
title = Label(frame, text="The Title", bg="cornflower blue", height=2)
title.grid(row=0, column=0, sticky=NSEW)
sort_button = Button(frame, text="The Button", relief="groove", height=2, bg="maroon1",)
sort_button.grid(row=1, column=0, sticky=NSEW)

window.mainloop()
```

For example this is the output of my current code:

But this is what I want:

答:
You can set a weight to the columns of your frame.</p>

```<code>from tkinter import *

window = Tk()

frame = Frame(window,bg="yellow")

...

frame.grid_columnconfigure(0, weight=1)

window.mainloop()
</code>```

Title: Tkinter Make Grid Fit Frame Size

Body:
I am wondering if there is a way to make a grids rows and columns fit the size of the Frame that is set. So that if I create a Frame and set its size that the grid will fit the size of the Frame.

This is what I tried so far:

window = Tk()

frame = Frame(window)
frame.place(x=0, y=0, width=200, height=200)
title = Label(frame, text="The Title", bg="cornflower blue", height=2)
title.grid(row=0, column=0, sticky=NSEW)
sort_button = Button(frame, text="The Button", relief="groove", height=2, bg="maroon1",)
sort_button.grid(row=1, column=0, sticky=NSEW)

window.mainloop()

For example this is the output of my current code:

But this is what I want:

Body:
You can set a weight to the columns of your frame.

from tkinter import *

window = Tk()

frame = Frame(window,bg="yellow")

...

frame.grid_columnconfigure(0, weight=1)

window.mainloop()


来源: stackexchange

问:
Error appear related to JS for Toggle Button
I already declare ID in my
, however an error appear, how to solve this error.

Below is my Code for reference

HTML

```<code><div class="row">
 <div>
  <input type="checkbox" data-column="0" class="toggle-vis" data-label-text="No" checked/>
  <input type="checkbox" data-column="1" class="toggle-vis" data-label-text="Region" checked>
  <input type="checkbox" data-column="2" class="toggle-vis" data-label-text="IBSE Node" checked/>
 </div>
<div>
 <table class="data-table stripe hover multiple-select-row nowrap" id="example">
  <thead>
   <tr>
    <th class="table-plus datatable-nosort">No</th>
    <th>Region</th>
    <th>IBSE Node</th>
   </tr>
  </thead>
 </table>
</div>
</code>```

JS

```<code><script>
    $(function(){
        $.fn.bootstrapSwitch.defaults.onColor = 'success';
        $.fn.bootstrapSwitch.defaults.offColor = 'danger';
        $.fn.bootstrapSwitch.defaults.size = 'mini';
        $.fn.bootstrapSwitch.defaults.state = 'false';
        $.fn.bootstrapSwitch.defaults.inverse = 'true';
        $(".toggle-vis").bootstrapSwitch();
            var table = $('#example').DataTable();
        $('.toggle-vis').on('switchChange.bootstrapSwitch', function(event, state) {
            event.preventDefault();
            var column = table.column($(this).attr('data-column'));
            column.visible( ! column.visible() );
        });
    });
</script>
</code>```

答:
You cant reinitialize datatable you need to destroy it before initialize again.
add this lines inside your toggle function.</p>

```<code>$("#example").dataTable().fnDestroy();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I already declare ID in my
, however an error appear, how to solve this error.

Below is my Code for reference

HTML

  <input type="checkbox" data-column="0" class="toggle-vis" data-label-text="No" checked/>
  <input type="checkbox" data-column="1" class="toggle-vis" data-label-text="Region" checked>
  <input type="checkbox" data-column="2" class="toggle-vis" data-label-text="IBSE Node" checked/>

    No
    Region
    IBSE Node

JS

Body:
You cant reinitialize datatable you need to destroy it before initialize again.
add this lines inside your toggle function.

$("#example").dataTable().fnDestroy();


问:
Automation of different parts of a framework
I have a software framework consisting of multiple components which need to run sequentially. For example, I have a Python script which parses data, another Python script which POSTs the data through a REST API and persists it into a DB, and a Java program which retrieves the parsed data from the DB and performs some analysis on it. So one output is linked to the input of the other component.

I want to know how I can automate these tasks to run one after the other sequentially on a Windows platform. Is PowerShell a good tool to achieve this sort of sequential execution of programs with inter-related input/output flow?

If PowerShell is a suitable choice, it would be great if someone could give me an example of how to achieve this sort of sequential application execution. I have never used PowerShell before and the tutorials I looked up on PowerShell didn't specifically mention this sort of task.

答:
Why don't you start with a batch file for simplicity, then you can decide if you require the flexibility and control of powershell. Powershell is definitely worth learning in the long run.

First create your batch file. For Example, create a new text file and rename it MyBatchFile.CMD

Then open it notepad (my favourite editor is currently Visual Studio Code, I recommend it)

How do we run python from here? First we google it:

http://www.cs.bu.edu/courses/cs108/guides/runpython.html

This gives us this example:

```<code>C:\python27\python.exe Z:\code\hw01\script.py
</code>```

Which you will obviously need to adjust for your setup. You'll probably also need to quote it to allow for spaces

Now add a pause to the end so that the window doesn't disappear:

```<code>"C:\python27\python.exe" "Z:\code\hw01\script.py"
PAUSE
</code>```

Save this file and double click it. Did it work? No? adjust it till it does.

Now add your second python file and make sure that it doesn't start till the other one finishes:

```<code>"C:\python27\python.exe" "Z:\code\hw01\script.py"
"C:\python27\python.exe" "Z:\code\hw01\script2.py"
PAUSE
</code>```

Now work out how to run java from the command line:

How do I run a Java program from the command line on Windows?

```<code>"C:\python27\python.exe" "Z:\code\hw01\script.py"
"C:\python27\python.exe" "Z:\code\hw01\script2.py"
"C:\Program Files\Java\jdk1.5.0_09\bin\java" "C:\myjars\filenamehere.java"
PAUSE
</code>```

Now... you can decide if you want to make this batch file more sophisticated with variables, or consider using powershell instead

If you go ahead with a batch file and want to schedule this, make sure you remove the PAUSE from it

Body:
Why don't you start with a batch file for simplicity, then you can decide if you require the flexibility and control of powershell. Powershell is definitely worth learning in the long run.

First create your batch file. For Example, create a new text file and rename it MyBatchFile.CMD

Then open it notepad (my favourite editor is currently Visual Studio Code, I recommend it)

How do we run python from here? First we google it:

http://www.cs.bu.edu/courses/cs108/guides/runpython.html

This gives us this example:

C:\python27\python.exe Z:\code\hw01\script.py

Which you will obviously need to adjust for your setup. You'll probably also need to quote it to allow for spaces

Now add a pause to the end so that the window doesn't disappear:

"C:\python27\python.exe" "Z:\code\hw01\script.py"
PAUSE

Save this file and double click it. Did it work? No? adjust it till it does.

Now add your second python file and make sure that it doesn't start till the other one finishes:

"C:\python27\python.exe" "Z:\code\hw01\script.py"
"C:\python27\python.exe" "Z:\code\hw01\script2.py"
PAUSE

Now work out how to run java from the command line:

How do I run a Java program from the command line on Windows?

"C:\python27\python.exe" "Z:\code\hw01\script.py"
"C:\python27\python.exe" "Z:\code\hw01\script2.py"
"C:\Program Files\Java\jdk1.5.0_09\bin\java" "C:\myjars\filenamehere.java"
PAUSE

Now... you can decide if you want to make this batch file more sophisticated with variables, or consider using powershell instead

If you go ahead with a batch file and want to schedule this, make sure you remove the PAUSE from it


问:
cannot import name "app" of a circular import issue
I have suffered from some problems with my code for a some hours.

I'm sure that it is caused by a circular import issue, but I have another question.

I have two blueprint, auth and main. I just return a render_template without any data passing, and things all go good. But when I try to shwo something in my main.index, suddenly an error occured.

I wonder why it works fine just in auth.views while there does have a circular import issue?

my tree struct

```<code>app
  |- auth
       |- __init__.py
       |- forms.py
       |- views.py
  |- main
       |- __init__.py
       |- forms.py
       |- views.py
  |- template
  |- __init__.py
  |- models.py
config.py
manage.py
datta.sqlite
</code>```

In auth.__init__.py:

from flask import Blueprint

auth = Blueprint("auth", __name__)

from . import views
```

<p>and in auth.views.py</p>

```from app.auth import auth
from app.models import *
from manage import app

@auth.route('/')
def index():
    page = request.args.get("page", 1, type=int)
    articles = Article.query.order_by(Article.update_time.desc()).paginate(
        page, app.config["ARTICLES_PER_PAGE"], False)

    next_url = url_for('auth.index', page=articles.next_num if articles.has_next else None)
    prev_url = url_for('auth.index', page=articles.prev_num if articles.has_prev else None)
    return render_template('index.html', articles=articles.items,
                           next_url=next_url, prev_url=prev_url)
```

<p>In <code>main.__init__.py</code>:</p>

<pre class="lang-py prettyprint-override"><code>from flask import Blueprint

main = Blueprint("main", __name__)

from . import views

</code>```

In main.views.py:

from app.main import main
from app.models import *
from manage import app

@main.route('/')
def index():
    page = request.args.get("page", 1, type=int)
    articles = Article.query.order_by(Article.update_time.desc()).paginate(
        page, app.config["ARTICLES_PER_PAGE"], False)

    next_url = url_for('main.index', page=articles.next_num if articles.has_next else None)
    prev_url = url_for('main.index', page=articles.prev_num if articles.has_prev else None)
    return render_template('index.html', articles=articles.items,
                           next_url=next_url, prev_url=prev_url)
```

<p>In <code>app.__init__.py</code>:</p>

<pre class="lang-py prettyprint-override"><code>def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    Config.init_app(app)
    ...
    from app.main import main
    app.register_blueprint(main)

    from app.auth import auth
    app.register_blueprint(auth, url_prefix='/auth')

    return app
</code>```

in manage.py

```<code>from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell

from app import create_app, db
from app.models import *

app = create_app()
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

def make_shell_context():
    return dict(db=db, ArticleType=ArticleType, Source=Source,
                Article=Article, User=User, Menu=Menu,
                ArticleTypeSetting=ArticleTypeSetting)

manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand)

if __name__ == '__main__':
    app.run(debug=True)

</code>```

And my traceback are as follow:

```<code>Traceback (most recent call last):
  File "C:/Users/bohn/Desktop/1pycharm workspace/BlogPoweredByFlask/manage.py", line 7, in <module>
    app = create_app()
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\__init__.py", line 30, in create_app
    from app.main import main
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\main\__init__.py", line 5, in <module>
    from . import views
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\main\views.py", line 5, in <module>
    from manage import app
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\manage.py", line 7, in <module>
    app = create_app()
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\__init__.py", line 33, in create_app
    from app.auth import auth
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\auth\__init__.py", line 5, in <module>
    from . import views
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\auth\views.py", line 9, in <module>
    from manage import app
ImportError: cannot import name 'app'
</code>```

答:
The way past this is to use flask.current_app instead of trying to import app.

In main.views, replace

```<code>from manage import app
</code>```

with

```<code>from flask import current_app
</code>```

then, instead of app.config[...], use current_app.config[...]

Body:
I have suffered from some problems with my code for a some hours.

I'm sure that it is caused by a circular import issue, but I have another question.

I have two blueprint, auth and main. I just return a render_template without any data passing, and things all go good. But when I try to shwo something in my main.index, suddenly an error occured.

I wonder why it works fine just in auth.views while there does have a circular import issue?

my tree struct

app
  |- auth
       |- __init__.py
       |- forms.py
       |- views.py
  |- main
       |- __init__.py
       |- forms.py
       |- views.py
  |- template
  |- __init__.py
  |- models.py
config.py
manage.py
datta.sqlite

In auth.__init__.py:

from flask import Blueprint

auth = Blueprint("auth", __name__)

from . import views

and in auth.views.py

from app.auth import auth
from app.models import *
from manage import app

@auth.route('/')
def index():
    page = request.args.get("page", 1, type=int)
    articles = Article.query.order_by(Article.update_time.desc()).paginate(
        page, app.config["ARTICLES_PER_PAGE"], False)

    next_url = url_for('auth.index', page=articles.next_num if articles.has_next else None)
    prev_url = url_for('auth.index', page=articles.prev_num if articles.has_prev else None)
    return render_template('index.html', articles=articles.items,
                           next_url=next_url, prev_url=prev_url)

In main.__init__.py:

from flask import Blueprint

main = Blueprint("main", __name__)

from . import views

In main.views.py:

from app.main import main
from app.models import *
from manage import app

@main.route('/')
def index():
    page = request.args.get("page", 1, type=int)
    articles = Article.query.order_by(Article.update_time.desc()).paginate(
        page, app.config["ARTICLES_PER_PAGE"], False)

    next_url = url_for('main.index', page=articles.next_num if articles.has_next else None)
    prev_url = url_for('main.index', page=articles.prev_num if articles.has_prev else None)
    return render_template('index.html', articles=articles.items,
                           next_url=next_url, prev_url=prev_url)

In app.__init__.py:

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    Config.init_app(app)
    ...
    from app.main import main
    app.register_blueprint(main)

    from app.auth import auth
    app.register_blueprint(auth, url_prefix='/auth')

    return app

in manage.py

from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell

from app import create_app, db
from app.models import *

app = create_app()
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

def make_shell_context():
    return dict(db=db, ArticleType=ArticleType, Source=Source,
                Article=Article, User=User, Menu=Menu,
                ArticleTypeSetting=ArticleTypeSetting)

manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand)

if __name__ == '__main__':
    app.run(debug=True)

And my traceback are as follow:

Traceback (most recent call last):
  File "C:/Users/bohn/Desktop/1pycharm workspace/BlogPoweredByFlask/manage.py", line 7, in <module>
    app = create_app()
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\__init__.py", line 30, in create_app
    from app.main import main
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\main\__init__.py", line 5, in <module>
    from . import views
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\main\views.py", line 5, in <module>
    from manage import app
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\manage.py", line 7, in <module>
    app = create_app()
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\__init__.py", line 33, in create_app
    from app.auth import auth
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\auth\__init__.py", line 5, in <module>
    from . import views
  File "C:\Users\bohn\Desktop\1pycharm workspace\BlogPoweredByFlask\app\auth\views.py", line 9, in <module>
    from manage import app
ImportError: cannot import name 'app'

Body:
The way past this is to use flask.current_app instead of trying to import app.

In main.views, replace

from manage import app

with

from flask import current_app

then, instead of app.config[...], use current_app.config[...]


问:
Mxmlc generates different binary on same source
I'm compiling a single .as file into swf using mxmlc.

Whenever I run mxmlc, results are different in size even when the source code is not changed.

For example,

```<code>// Test.as
package
{
    public class Test
    {
    }
}
</code>```

And generates .swf using mxmlc :

```<code>mxmlc Test.as
</code>```

and result size differs from 461 to 465 bytes.

I suppose that it's because of timestamp-like things in compiler, but I could not find how to fix or disable that. Any ideas on generating "same binary from same source" ? Thanks!

答:
You need to override the metadata the compiler is writing into the resulting swf file. You can do this with the -raw-metadata compiler aguement.

Usage:

```<code>mxmlc -raw-metadata <XML_String> Test.as
</code>```

Example:

```<code>mxmlc -raw-metadata '' Test.as
</code>```

(Resulting swf is always 190 bytes).

ContentLicense: CC BY-SA 3.0

Body:
I'm compiling a single .as file into swf using mxmlc.

Whenever I run mxmlc, results are different in size even when the source code is not changed.

For example,

// Test.as
package
{
    public class Test
    {
    }
}

And generates .swf using mxmlc :

mxmlc Test.as

and result size differs from 461 to 465 bytes.

I suppose that it's because of timestamp-like things in compiler, but I could not find how to fix or disable that. Any ideas on generating "same binary from same source" ? Thanks!

Body:
You need to override the metadata the compiler is writing into the resulting swf file. You can do this with the -raw-metadata compiler aguement.

Usage:

mxmlc -raw-metadata <XML_String> Test.as

Example:

mxmlc -raw-metadata '' Test.as

(Resulting swf is always 190 bytes).


问:
Is it possible to know if the node where a Kubernetes Pod is being scheduled is master or worker?
I'm currently using Kubernetes to schedule a DaemonSet on both master and worker nodes.

The DaemonSet definition is the same for both node types (same image, same volumes, etc), the only difference is that when the entrypoint is executed, I need to write a different configuration file (which is generated in Python with some dynamic values) if the node is a master or a worker.

Currently, to overcome this I'm using two different DaemonSet definitions with an env value which tells if the node is a master or not. Here's the yaml file (only relevant parts):

```<code>apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: worker-ds
  namespace: kube-system
  labels:
    k8s-app: worker
spec:
  ...
    spec:
      hostNetwork: true
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "false"
      ...
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: master-ds
  namespace: kube-system
  labels:
    k8s-app: master
spec:
  ...
    spec:
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "true"
      ...
</code>```

However, since the only difference is the IS_MASTER value, I want to collapse both the definitions in a single one that programmatically understands if the current node where the pod is being scheduled is a master or a worker.

Is there any way to know this information about the node programmatically (even reading a configuration file [for example something that only the master has or viceversa] in the node or something like that)?

Thanks in advance.

答:
Unfortunately, there is not a convenient way to access the node information in pod.

If you only want a single DaemonSet definition, you can add a sidecar container to your pod, the sidecar container can access the k8s api, then your main container can get something useful from the sidecar.

By the way, I think your current solution is properly :)

Body:
I'm currently using Kubernetes to schedule a DaemonSet on both master and worker nodes.

The DaemonSet definition is the same for both node types (same image, same volumes, etc), the only difference is that when the entrypoint is executed, I need to write a different configuration file (which is generated in Python with some dynamic values) if the node is a master or a worker.

Currently, to overcome this I'm using two different DaemonSet definitions with an env value which tells if the node is a master or not. Here's the yaml file (only relevant parts):

apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: worker-ds
  namespace: kube-system
  labels:
    k8s-app: worker
spec:
  ...
    spec:
      hostNetwork: true
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "false"
      ...
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: master-ds
  namespace: kube-system
  labels:
    k8s-app: master
spec:
  ...
    spec:
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      containers:
        - name: my-image
          ...
          env:
            - name: NODE_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            - name: IS_MASTER
              value: "true"
      ...

However, since the only difference is the IS_MASTER value, I want to collapse both the definitions in a single one that programmatically understands if the current node where the pod is being scheduled is a master or a worker.

Is there any way to know this information about the node programmatically (even reading a configuration file [for example something that only the master has or viceversa] in the node or something like that)?

Thanks in advance.


答:
One option is to get the row index (.I) of the rows where the 'Years_service is max for each 'ID', then using that, get the minimum index of 'month_1' to subset the 'Date' corresponding to that value grouped by 'ID', and join on with the original data on the 'ID' column to create the 'Date_1' column

```<code>i1 <- data[, .I[Years_service == max(Years_service)], ID]$V1
data[data[i1, Date[which.min(month_1)], ID], Date_1 :=V1, on = .(ID)]
data
#     ID       Date Years_service month_1     Date_1
#  1:  1 2009-01-01            19       1 2016-06-01
#  2:  1 2009-02-01            19       2 2016-06-01
#  3:  1 2009-03-01            19       3 2016-06-01
#  4:  1 2009-04-01            19       4 2016-06-01
#  5:  1 2009-05-01            19       5 2016-06-01
# ---
#146:  2 2016-06-01            12       6 2016-08-01
#147:  2 2016-07-01            12       7 2016-08-01
#148:  2 2016-08-01            13       8 2016-08-01
#149:  2 2016-09-01            13       9 2016-08-01
#150:  2 2016-10-01            13      10 2016-08-01
</code>```

Or extract the 'Date' corresponding to minimum 'month_1' from within the Subset of Data.table

```<code>data[, Date_1 := .SD[Years_service == max(Years_service),
                  Date[which.min(month_1)]], ID]
</code>```

Or another option is to an order and assign 'Date_1' as the first 'Date' grouped by 'ID'

```<code>data[order(-Years_service, month_1), Date_1 := Date[1], ID]
</code>```

Or using tidyverse

```<code>library(tidyverse)
data %>%
   group_by(ID) %>%
   arrange(desc(Years_service), month_1) %>%
   mutate(Date_1 = first(Date))
</code>```

Title: Get index of date with max years and min month

Body:
I have a dataset of 3 variables: ID, Date and Years_service. Like this:

library(data.table)
data <- structure(list(ID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), Date = structure(c(1230768000,
1233446400, 1235865600, 1238544000, 1241136000, 1243814400, 1246406400,
1249084800, 1251763200, 1254355200, 1257033600, 1259625600, 1262304000,
1264982400, 1267401600, 1270080000, 1272672000, 1275350400, 1277942400,
1280620800, 1283299200, 1285891200, 1288569600, 1291161600, 1293840000,
1296518400, 1298937600, 1301616000, 1304208000, 1306886400, 1309478400,
1312156800, 1314835200, 1317427200, 1320105600, 1322697600, 1325376000,
1328054400, 1330560000, 1333238400, 1335830400, 1338508800, 1341100800,
1343779200, 1346457600, 1349049600, 1351728000, 1354320000, 1356998400,
1359676800, 1362096000, 1364774400, 1367366400, 1370044800, 1372636800,
1375315200, 1377993600, 1380585600, 1383264000, 1385856000, 1388534400,
1391212800, 1393632000, 1396310400, 1398902400, 1401580800, 1404172800,
1406851200, 1409529600, 1412121600, 1414800000, 1417392000, 1420070400,
1422748800, 1425168000, 1427846400, 1430438400, 1433116800, 1435708800,
1438387200, 1441065600, 1443657600, 1446336000, 1448928000, 1451606400,
1454284800, 1456790400, 1459468800, 1462060800, 1464739200, 1467331200,
1470009600, 1472688000, 1475280000, 1330560000, 1333238400, 1335830400,
1338508800, 1341100800, 1343779200, 1346457600, 1349049600, 1351728000,
1354320000, 1356998400, 1359676800, 1362096000, 1364774400, 1367366400,
1370044800, 1372636800, 1375315200, 1377993600, 1380585600, 1383264000,
1385856000, 1388534400, 1391212800, 1393632000, 1396310400, 1398902400,
1401580800, 1404172800, 1406851200, 1409529600, 1412121600, 1414800000,
1417392000, 1420070400, 1422748800, 1425168000, 1427846400, 1430438400,
1433116800, 1435708800, 1438387200, 1441065600, 1443657600, 1446336000,
1448928000, 1451606400, 1454284800, 1456790400, 1459468800, 1462060800,
1464739200, 1467331200, 1470009600, 1472688000, 1475280000), class =
c("POSIXct",
"POSIXt"), tzone = "UTC"), Years_service = c(19, 19, 19, 19,
19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 8, 8, 8, 8, 8, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13),
month_1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), .Names = c("ID", "Date",
"Years_service", "month_1"), row.names = c(NA, -150L), class =
c("data.table",
"data.frame"))

I want a new variable that contains for each ID the date for which years of service is maximum and the month of date is minimum. Something like this:

     ID       Date Years_service    Date_1
  1:  1 2009-01-01            19    2016-06-01
  2:  1 2009-02-01            19    2016-06-01
  3:  1 2009-03-01            19    2016-06-01
  4:  1 2009-04-01            19    2016-06-01
  5:  1 2009-05-01            19    2016-06-01
 ---
  146:  2 2016-06-01            12    2016-08-01
  147:  2 2016-07-01            12    2016-08-01
  148:  2 2016-08-01            13    2016-08-01
  149:  2 2016-09-01            13    2016-08-01
  150:  2 2016-10-01            13    2016-08-01

My desired output is Date_1

I tried this:

data[,Date_1 := Date[which.max(Years_service) & which.min(month_1)], by = ID]

but didn't work.
How can I achieve this?

Body:
One option is to get the row index (.I) of the rows where the 'Years_service is max for each 'ID', then using that, get the minimum index of 'month_1' to subset the 'Date' corresponding to that value grouped by 'ID', and join on with the original data on the 'ID' column to create the 'Date_1' column

i1 <- data[, .I[Years_service == max(Years_service)], ID]$V1
data[data[i1, Date[which.min(month_1)], ID], Date_1 :=V1, on = .(ID)]
data
#     ID       Date Years_service month_1     Date_1
#  1:  1 2009-01-01            19       1 2016-06-01
#  2:  1 2009-02-01            19       2 2016-06-01
#  3:  1 2009-03-01            19       3 2016-06-01
#  4:  1 2009-04-01            19       4 2016-06-01
#  5:  1 2009-05-01            19       5 2016-06-01
# ---
#146:  2 2016-06-01            12       6 2016-08-01
#147:  2 2016-07-01            12       7 2016-08-01
#148:  2 2016-08-01            13       8 2016-08-01
#149:  2 2016-09-01            13       9 2016-08-01
#150:  2 2016-10-01            13      10 2016-08-01

Or extract the 'Date' corresponding to minimum 'month_1' from within the Subset of Data.table

data[, Date_1 := .SD[Years_service == max(Years_service),
                  Date[which.min(month_1)]], ID]

Or another option is to an order and assign 'Date_1' as the first 'Date' grouped by 'ID'

data[order(-Years_service, month_1), Date_1 := Date[1], ID]

Or using tidyverse

library(tidyverse)
data %>%
   group_by(ID) %>%
   arrange(desc(Years_service), month_1) %>%
   mutate(Date_1 = first(Date))


问:
Unable to restore NuGet Package: "Failed to find api location for area: nuget id: 9D3A4E8E"
I am unable to publish new packages to (or restore packages from) my own NuGet Feed in Azure DevOps .  It started a few days ago and, since I have created a brand new feed (out of curiosity). Still, it fails with the same error:

Failed to find api location for area: nuget id:
  9D3A4E8E-2F8F-4AE1-ABC2-B461A51CB3B3

```<code>2019-05-27T22:09:46.8693807Z ##[section]Starting: dotnet push (Common)
2019-05-27T22:09:46.8802338Z ==============================================================================
2019-05-27T22:09:46.8802573Z Task         : .NET Core
2019-05-27T22:09:46.8802607Z Description  : Build, test, package, or publish a dotnet application, or run a custom dotnet command. For package commands, supports NuGet.org and authenticated feeds like Package Management and MyGet.
2019-05-27T22:09:46.8802660Z Version      : 2.151.1
2019-05-27T22:09:46.8802692Z Author       : Microsoft Corporation
2019-05-27T22:09:46.8802724Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=832194)
2019-05-27T22:09:46.8802931Z ==============================================================================
2019-05-27T22:09:47.4837790Z [command]C:\windows\system32\chcp.com 65001
2019-05-27T22:09:47.4924880Z Active code page: 65001
2019-05-27T22:09:47.4964761Z SYSTEMVSSCONNECTION exists true
2019-05-27T22:09:47.5770818Z SYSTEMVSSCONNECTION exists true
2019-05-27T22:09:50.7225430Z SYSTEMVSSCONNECTION exists true
2019-05-27T22:09:50.7673768Z ##[warning]Can\'t find loc string for key: Warning_SessionCreationFailed
2019-05-27T22:09:50.7683040Z ##[warning]Warning_SessionCreationFailed {}
2019-05-27T22:09:52.3193091Z ##[error]Error: Error: Failed to find api location for area: nuget id: 9D3A4E8E-2F8F-4AE1-ABC2-B461A51CB3B3
2019-05-27T22:09:52.3194182Z ##[error]Packages failed to publish
2019-05-27T22:09:52.3294148Z ##[section]Finishing: dotnet push (Common)
</code>```

How can I fix this error?

答:
Unable to restore NuGet Package: “Failed to find api location for area: nuget id: 9D3A4E8E”

The reason for the above error is a wrong specification of the URL of the service to use.

So, to resolve this issue, please try to double check if the source of nuget feed is correct.

If the source of nuget feed is correct and this issue is also occurred on the other nuget feed(which is worked before.), you can try to delete the brand new feed, then check if this issue is resolved.

If this issue only occurred on the brand new feed, please try to check if your feed configured correctly and check if the agent has any proxy setting.

Check the ticket VSTS - Cannot Push Nuget Package to VSTS Package Feed from Private Agent Behind Web Proxy

Hope this helps.

Body:
I am unable to publish new packages to (or restore packages from) my own NuGet Feed in Azure DevOps .  It started a few days ago and, since I have created a brand new feed (out of curiosity). Still, it fails with the same error:

Failed to find api location for area: nuget id:
  9D3A4E8E-2F8F-4AE1-ABC2-B461A51CB3B3

2019-05-27T22:09:46.8693807Z ##[section]Starting: dotnet push (Common)
2019-05-27T22:09:46.8802338Z ==============================================================================
2019-05-27T22:09:46.8802573Z Task         : .NET Core
2019-05-27T22:09:46.8802607Z Description  : Build, test, package, or publish a dotnet application, or run a custom dotnet command. For package commands, supports NuGet.org and authenticated feeds like Package Management and MyGet.
2019-05-27T22:09:46.8802660Z Version      : 2.151.1
2019-05-27T22:09:46.8802692Z Author       : Microsoft Corporation
2019-05-27T22:09:46.8802724Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=832194)
2019-05-27T22:09:46.8802931Z ==============================================================================
2019-05-27T22:09:47.4837790Z [command]C:\windows\system32\chcp.com 65001
2019-05-27T22:09:47.4924880Z Active code page: 65001
2019-05-27T22:09:47.4964761Z SYSTEMVSSCONNECTION exists true
2019-05-27T22:09:47.5770818Z SYSTEMVSSCONNECTION exists true
2019-05-27T22:09:50.7225430Z SYSTEMVSSCONNECTION exists true
2019-05-27T22:09:50.7673768Z ##[warning]Can\'t find loc string for key: Warning_SessionCreationFailed
2019-05-27T22:09:50.7683040Z ##[warning]Warning_SessionCreationFailed {}
2019-05-27T22:09:52.3193091Z ##[error]Error: Error: Failed to find api location for area: nuget id: 9D3A4E8E-2F8F-4AE1-ABC2-B461A51CB3B3
2019-05-27T22:09:52.3194182Z ##[error]Packages failed to publish
2019-05-27T22:09:52.3294148Z ##[section]Finishing: dotnet push (Common)

How can I fix this error?


问:
Is there a synchronous version of child_process.fork() in node.js?
There is spawn and spawnSync, but there is no forkSync for fork. Or did I fail to find it? If not, why is there no forkSync?

答:
fork is only synchronous, returning ChildProcess. There is no callback involved, nor a promise to be fulfilled.

(i.e. There is no child_process.forkSync for the same reason there is no console.logSync)

EDIT: In comparison to spawn and spawnSync - the purpose of spawnSync is to wait till the child process is done, not just to launch it. The sole difference between fork and spawn is the existence of a communication channel between the parent and the child process, which is useless if the parent is frozen in time. Thus, forkSync in that context would make no sense (as different than spawnSync).


问:
How to change tab bar item text color

How can I change the color of "More.." text in tabbar to match with its icon color.  (Right now Performance is selected in the tab bar)

I tried to set TitleTextAttributes.

```<code>[moreItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor],NSForegroundColorAttributeName , nil]
</code>```

But it the text color is always set to yellow. even when the item is selected. Like this

I am trying set to white when selected and when unselected it should match with icon color.
Thanks..
Any suggestions will be really helpful.

答:
This worked for me on Swift 5.

In AppDelegate :

```<code> UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.red], for: .selected)
</code>```

Title: How to change tab bar item text color

Body:
How can I change the color of "More.." text in tabbar to match with its icon color.  (Right now Performance is selected in the tab bar)

I tried to set TitleTextAttributes.

[moreItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor],NSForegroundColorAttributeName , nil]

But it the text color is always set to yellow. even when the item is selected. Like this

I am trying set to white when selected and when unselected it should match with icon color.
Thanks..
Any suggestions will be really helpful.

Body:
This worked for me on Swift 5.

In AppDelegate :

 UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.red], for: .selected)


问:
Does document reference increase read count?
I have a users collection and a rentals collection. A rental document has a field for the user who is renting the item, stored as a document reference (rentalDocumentSnapshot['renter'] = /users/<some id here>). To query all the rentals where you are the renter, I just pass into a stream:

```<code>Firestore.instance.collection('rentals')
    .where('renter', isEqualTo: Firestore.instance.collection('users').document(myUserID))
    .snapshots()
</code>```

Does calling Firestore.instance.collection('users').document(myUserID) create a read? So would it be better to store the user ID in the rental as a string instead of a document reference?

答:
Creating a DoucumentReference doesn't incur a read.  You have to actually get() that document in order to read it.  You can think of a reference as just a pointer to a document.

Storing a reference instead of an ID or path is not necessarily better or worse.  It's mostly a matter of convenience and preference.  References are generally easier to use, since you don't have to build that reference, but as I said, building that reference is free.  A reference will generally store more data, as it's storing the entire path to the document, not just the ID.

Body:
I have a users collection and a rentals collection. A rental document has a field for the user who is renting the item, stored as a document reference (rentalDocumentSnapshot['renter'] = /users/<some id here>). To query all the rentals where you are the renter, I just pass into a stream:

Firestore.instance.collection('rentals')
    .where('renter', isEqualTo: Firestore.instance.collection('users').document(myUserID))
    .snapshots()

Does calling Firestore.instance.collection('users').document(myUserID) create a read? So would it be better to store the user ID in the rental as a string instead of a document reference?


问:
How to filter blueprint urls from url rules?
I want to make Website Menu and allow administrator to choose from known url in flask-admin for this I have main blueprint and it has some endpoints, I want to make function which will return known endpoints for Menu model for administrator to choose right url and pack it with data.

I have tried for loop for rule in app.url_map.iter_rules():

```<code>@app.route("/site-map")
def site_map():
    links = []
    for rule in app.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters

        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
        links.append(rule.endpoint)

    return render_template("all_links.html", links=links)
</code>```

But the code above is giving me all routes also for flask-admin

答:
Simply add an additional test to filter out endpoints for admin.:

```<code>if "GET" in rule.methods \
  and has_no_empty_params(rule) \
  and not rule.endpoint.startswith("admin."):
    # Add link to list of links
</code>```

Body:
I want to make Website Menu and allow administrator to choose from known url in flask-admin for this I have main blueprint and it has some endpoints, I want to make function which will return known endpoints for Menu model for administrator to choose right url and pack it with data.

I have tried for loop for rule in app.url_map.iter_rules():

@app.route("/site-map")
def site_map():
    links = []
    for rule in app.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters

        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
        links.append(rule.endpoint)

    return render_template("all_links.html", links=links)

But the code above is giving me all routes also for flask-admin

Body:
Simply add an additional test to filter out endpoints for admin.:

if "GET" in rule.methods \
  and has_no_empty_params(rule) \
  and not rule.endpoint.startswith("admin."):
    # Add link to list of links


问:
How to type Redux actions and Redux reducers in TypeScript?
What is the best way to cast the action parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:

```<code>interface IAction {
    type: string
}

interface IActionA extends IAction {
    a: string
}

interface IActionB extends IAction {
    b: string
}

const reducer = (action: IAction) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) // property 'a' does not exists on type IAction

        case 'b':
            return console.info('action b: ', action.b) // property 'b' does not exists on type IAction
    }
}
</code>```

The problem is that action needs to be cast as a type that has access to both IActionA and IActionB so the reducer can use both action.a and action.a without throwing an error.

I have several ideas how to work around this issue:

Cast action to any.

Use optional interface members.

example:

```<code>interface IAction {
    type: string
    a?: string
    b?: string
}
</code>```

Use different reducers for every action type.

What is the best way to organize Action/Reducers in typescript? Thank you in advance!

答:
I suggest using AnyAction because according to Redux FAQ, every reducer is ran on every action. This is why we end up just returning the input state if the action is not one of the types. Otherwise we would never have a default case in our switches in our reducers.

See: https://redux.js.org/faq/performance#won-t-calling-all-my-reducers-for-each-action-be-slow

So therefore it is fine to just do:

```<code>import { AnyAction } from 'redux';

function myReducer(state, action: AnyAction) {
  // ...
}
</code>```

Body:
What is the best way to cast the action parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:

interface IAction {
    type: string
}

interface IActionA extends IAction {
    a: string
}

interface IActionB extends IAction {
    b: string
}

const reducer = (action: IAction) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) // property 'a' does not exists on type IAction

        case 'b':
            return console.info('action b: ', action.b) // property 'b' does not exists on type IAction
    }
}

The problem is that action needs to be cast as a type that has access to both IActionA and IActionB so the reducer can use both action.a and action.a without throwing an error.

I have several ideas how to work around this issue:

Cast action to any.

Use optional interface members.

example:

interface IAction {
    type: string
    a?: string
    b?: string
}

Use different reducers for every action type.

What is the best way to organize Action/Reducers in typescript? Thank you in advance!

Body:
I suggest using AnyAction because according to Redux FAQ, every reducer is ran on every action. This is why we end up just returning the input state if the action is not one of the types. Otherwise we would never have a default case in our switches in our reducers.

See: https://redux.js.org/faq/performance#won-t-calling-all-my-reducers-for-each-action-be-slow

So therefore it is fine to just do:

import { AnyAction } from 'redux';

function myReducer(state, action: AnyAction) {
  // ...
}


问:
Laravel 5.7: When I dump $query (Builder obj.) it shows only global scope while local scope is applied but now shown. Is this intended behaviour?
Without going to deep into details, everything in my code works as expected but the dump results aren't consistent with the logic.

So here within my repository class I dump a model.

```<code>$query = $this->model->customerWithCentralBillingChildren($customer);

dd($query);
</code>```

The customerWithCentralBillingChildren is a local scope defined within Model.

```<code>public function scopeCustomerWithCentralBillingChildren($query, Customer $customer)
{
    $accdes = [CUT] // doesn't matter

    return $query->whereIn('accde', $accdes);
}
</code>```

There's also a global scope that is applied via class that implements Scope. Located in \App\Scopes:

```<code>class SyncActive implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('sync_active', '=', true);
    }
}
</code>```

My issue is that when I dump the $query it shows me only global scopes within array.

```<code>Builder {#858 ▼
  #query: Builder {#859 ▶}
  #model: Transaction {#676 ▶}
  #eagerLoad: []
  #localMacros: []
  #onDelete: null
  #passthru: array:13 [▶]
  #scopes: array:1 [▼
    "App\Scopes\SyncActive" => SyncActive {#677} <- global scope here, but why no local one?
  ]
  #removedScopes: []
}
</code>```

Then only way for me to see that dumped query has also local scope is to dump:

```<code>dd($query->toSql());
</code>```

Which gives:

```<code>"select * from `sync_transactions` where `accde` in (?, ?, ?, ?, ?, ?) and `sync_active` = ?"
</code>```

then I see local scope:

```<code>where `accde` in (?, ?, ?, ?, ?, ?)
</code>```

as well as global scope:

```<code>`sync_active` = ?
</code>```

Is this intended behaviour? Why dumped scopes array item holds only global scope?

答:
As per Laravel class documentation, it is clearly mentioned the scoped attribute will contains theGlobal Scopes`. No mentioned about the local scope anywhere.

```<code>protected array $scopes - Applied global scopes.
protected array $removedScopes - Removed global scopes.
</code>```

Src: https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Builder.html

Thought behind including global scope with query build, because of global scope applied automatically with each query that's why it specified with builder > attributes for the quick visibility.

While you'll have to call the local scope explicitly by adding yourself with each query.

Also with Global Scopes it has provided some extending features like extend, replace, remove, exclude etc. That attribute feature also could help to debug in such case.

Note: It's just the personal thought based on facts provided with documentation. No where officially mentioned the caused behind this. But I'm sure this would be the initial thought

Hopefully this could help you to clarify your concern.

Body:
Without going to deep into details, everything in my code works as expected but the dump results aren't consistent with the logic.

So here within my repository class I dump a model.

$query = $this->model->customerWithCentralBillingChildren($customer);

dd($query);

The customerWithCentralBillingChildren is a local scope defined within Model.

public function scopeCustomerWithCentralBillingChildren($query, Customer $customer)
{
    $accdes = [CUT] // doesn't matter

    return $query->whereIn('accde', $accdes);
}

There's also a global scope that is applied via class that implements Scope. Located in \App\Scopes:

class SyncActive implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('sync_active', '=', true);
    }
}

My issue is that when I dump the $query it shows me only global scopes within array.

Builder {#858 ▼
  #query: Builder {#859 ▶}
  #model: Transaction {#676 ▶}
  #eagerLoad: []
  #localMacros: []
  #onDelete: null
  #passthru: array:13 [▶]
  #scopes: array:1 [▼
    "App\Scopes\SyncActive" => SyncActive {#677} <- global scope here, but why no local one?
  ]
  #removedScopes: []
}

Then only way for me to see that dumped query has also local scope is to dump:

dd($query->toSql());

Which gives:

"select * from `sync_transactions` where `accde` in (?, ?, ?, ?, ?, ?) and `sync_active` = ?"

then I see local scope:

where `accde` in (?, ?, ?, ?, ?, ?)

as well as global scope:

`sync_active` = ?

Is this intended behaviour? Why dumped scopes array item holds only global scope?

Body:
As per Laravel class documentation, it is clearly mentioned the scoped attribute will contains theGlobal Scopes`. No mentioned about the local scope anywhere.

protected array $scopes - Applied global scopes.
protected array $removedScopes - Removed global scopes.

Src: https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Builder.html

Thought behind including global scope with query build, because of global scope applied automatically with each query that's why it specified with builder > attributes for the quick visibility.

While you'll have to call the local scope explicitly by adding yourself with each query.

Also with Global Scopes it has provided some extending features like extend, replace, remove, exclude etc. That attribute feature also could help to debug in such case.

Note: It's just the personal thought based on facts provided with documentation. No where officially mentioned the caused behind this. But I'm sure this would be the initial thought

Hopefully this could help you to clarify your concern.


问:
PDO bindParam not working in IN binding for sql query
I'm trying to get some videos according to some attributes (age, year, countries). For some reason, even though I'm binding parameters to the query properly and have specified the query properly (u.country NOT IN ($countries_count)), I still get results for the country = U.S.A. Is there something work with my bindParam. Please Help.

```<code><?php
    $parameters = json_decode(file_get_contents('php://input'), true);
    $age = $parameters["age"];
    $year = $parameters["year"];
    $countries = sizeof($parameters["countries"]) == 0 ? array("0") : $parameters["countries"];
    $countries_count = implode(",", array_fill(0, sizeof($countries), "?"));

    $sql = "SELECT
                v.title, u.name
            FROM
                video AS v JOIN user AS u ON v.id_user = u.id
            WHERE
                u.age <= ? AND YEAR(v.upload_date) >= ? AND
                u.country NOT IN ($countries_count);";

    $connection = new PDO("mysql:host=localhost;dbname=data_base", "root", "");
    $statement = $connection->prepare($sql);
    $statement->bindParam(1, $age, PDO::PARAM_INT);
    $statement->bindParam(2, $year, PDO::PARAM_INT);
    foreach ($countries as $k => $x) {
        $statement->bindParam($k+3, $x, PDO::PARAM_STR);
    }
    $statement->execute();
    echo json_encode($statement->fetchAll());
?>
</code>```

答:
Your problem is that you are binding all the IN parameters to the same variable ($x) so they all end up with the same value. You can work around that by either changing to bindValue or by binding to the actual array value I.e.

```<code>$statement->bindParam($k+3, $countries[$k], PDO::PARAM_STR);
</code>```

Body:
I'm trying to get some videos according to some attributes (age, year, countries). For some reason, even though I'm binding parameters to the query properly and have specified the query properly (u.country NOT IN ($countries_count)), I still get results for the country = U.S.A. Is there something work with my bindParam. Please Help.

<?php
    $parameters = json_decode(file_get_contents('php://input'), true);
    $age = $parameters["age"];
    $year = $parameters["year"];
    $countries = sizeof($parameters["countries"]) == 0 ? array("0") : $parameters["countries"];
    $countries_count = implode(",", array_fill(0, sizeof($countries), "?"));

    $sql = "SELECT
                v.title, u.name
            FROM
                video AS v JOIN user AS u ON v.id_user = u.id
            WHERE
                u.age <= ? AND YEAR(v.upload_date) >= ? AND
                u.country NOT IN ($countries_count);";

    $connection = new PDO("mysql:host=localhost;dbname=data_base", "root", "");
    $statement = $connection->prepare($sql);
    $statement->bindParam(1, $age, PDO::PARAM_INT);
    $statement->bindParam(2, $year, PDO::PARAM_INT);
    foreach ($countries as $k => $x) {
        $statement->bindParam($k+3, $x, PDO::PARAM_STR);
    }
    $statement->execute();
    echo json_encode($statement->fetchAll());
?>

Body:
Your problem is that you are binding all the IN parameters to the same variable ($x) so they all end up with the same value. You can work around that by either changing to bindValue or by binding to the actual array value I.e.

$statement->bindParam($k+3, $countries[$k], PDO::PARAM_STR);


问:
Laravel email with queue 550 error (too many emails per second)
Our emails are failing to send using Laravel with a Redis Queue.

The code that triggers the error is this: ->onQueue('emails')

```<code>$job = (new SendNewEmail($sender, $recipients))->onQueue('emails');
$job_result = $this->dispatch($job);
</code>```

In combination with this in the job:

```<code>use InteractsWithQueue;
</code>```

Our error message is:

```<code>Feb 09 17:15:57 laravel: message repeated 7947 times: [ production.ERROR: exception 'Swift_TransportException' with message 'Expected response code 354 but got code "550", with message "550 5.7.0 Requested action not taken: too many emails per second "' in /home/laravel/app/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383 Stack trace: #0 /home/laravel/app/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(281):
</code>```

Our error only happens using Sendgrid and not Mailtrap, which spoofs emailing sending. I've talked with Sendgrid and the emails never touched their servers and their service was fully active when my error occurred. So, the error appears to be on my end.

Any thoughts?

答:
I achieved this on Laravel v5.8 by setting the Authentication routes manually. The routes are located on the file routes\web.php. Below are the routes that needs to be added to that file:

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

Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');

Route::group(['middleware' => 'throttle:1,1'], function(){
    Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
});
</code>```

Explanation:

Do not pass any parameter to the route Auth::routes(); to let configure the authentication routes manually.

Wrap the route email/resend inside a Route::group with the middleware throttle:1,1 (the two numbers represents the max retry attempts and the time in minutes for those max retries)

I also removed a line of code in the file app\Http\Controllers\Auth\VerificationController.php in the __construct function.

I removed this:

```<code>$this->middleware('throttle:6,1')->only('verify', 'resend');
</code>```

Body:
Our emails are failing to send using Laravel with a Redis Queue.

The code that triggers the error is this: ->onQueue('emails')

$job = (new SendNewEmail($sender, $recipients))->onQueue('emails');
$job_result = $this->dispatch($job);

In combination with this in the job:

use InteractsWithQueue;

Our error message is:

Feb 09 17:15:57 laravel: message repeated 7947 times: [ production.ERROR: exception 'Swift_TransportException' with message 'Expected response code 354 but got code "550", with message "550 5.7.0 Requested action not taken: too many emails per second "' in /home/laravel/app/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383 Stack trace: #0 /home/laravel/app/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(281):

Our error only happens using Sendgrid and not Mailtrap, which spoofs emailing sending. I've talked with Sendgrid and the emails never touched their servers and their service was fully active when my error occurred. So, the error appears to be on my end.

Any thoughts?

Body:
I achieved this on Laravel v5.8 by setting the Authentication routes manually. The routes are located on the file routes\web.php. Below are the routes that needs to be added to that file:

Auth::routes();

Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');

Route::group(['middleware' => 'throttle:1,1'], function(){
    Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
});

Explanation:

Do not pass any parameter to the route Auth::routes(); to let configure the authentication routes manually.

Wrap the route email/resend inside a Route::group with the middleware throttle:1,1 (the two numbers represents the max retry attempts and the time in minutes for those max retries)

I also removed a line of code in the file app\Http\Controllers\Auth\VerificationController.php in the __construct function.

I removed this:

$this->middleware('throttle:6,1')->only('verify', 'resend');


问:
How to get the corresponding comma-separated text for a string of comma separated codes?
I've a table, there is a column called "locations" which is in type of varchar(max). It carries string of comma-separated code, e.g. '1, 3, 4'. On the other hand, I've a table which map these code to some locations, e.g.

```<code>1 -- British
2 -- New Zealand
3 -- Hong Kong
4 -- Taiwan
</code>```

My problem is, I'm making a VIEW which will map and replace the content of the column "locations" to the corresponding comma-separated text, e.g. '1, 3, 4' will be 'British, Hong Kong, Taiwan'

This is really urgent for the company project, please kindly advise.

Thank you!

Regards,
William

答:
There might be simpler solutions to do this but here is one way.

Table structure

```<code>create table Locations(LocationID int, Location varchar(50))
create table OtherTable(ID int, Locations varchar(max))
</code>```

Test data

```<code>insert into Locations values(1, 'Location <1>')
insert into Locations values(2, 'Location <2>')
insert into Locations values(3, 'Location <3>')
insert into Locations values(4, 'Location <4>')
insert into Locations values(5, 'Location <5>')

insert into OtherTable values (1, '')
insert into OtherTable values (2, '2')
insert into OtherTable values (3, '1, 3 ,5')
</code>```

Query

```<code>;with cte as
(
  select
    T.ID,
    coalesce(L.Location, '') as Location
  from OtherTable as T
    cross apply
      (select cast('<r>'+replace(T.Locations, ',', '</r><r>')+'</r>' as xml)) LocXML(XMLCol)
    cross apply
      LocXML.XMLCol.nodes('r') LocID(IDCol)
    left outer join Locations as L
      on L.LocationID = LocID.IDCol.value('.', 'int')
)
select
  C1.ID,
  stuff((select ', '+C2.Location
         from cte as C2
         where C1.ID = C2.ID
         for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as Locations
from cte as C1
group by C1.ID
</code>```

Result

```<code>ID  Locations
--- ----------------------------------------
1
2   Location <2>
3   Location <1>, Location <3>, Location <5>
</code>```

Body:
I've a table, there is a column called "locations" which is in type of varchar(max). It carries string of comma-separated code, e.g. '1, 3, 4'. On the other hand, I've a table which map these code to some locations, e.g.

1 -- British
2 -- New Zealand
3 -- Hong Kong
4 -- Taiwan

My problem is, I'm making a VIEW which will map and replace the content of the column "locations" to the corresponding comma-separated text, e.g. '1, 3, 4' will be 'British, Hong Kong, Taiwan'

This is really urgent for the company project, please kindly advise.

Thank you!

Regards,
William

Body:
There might be simpler solutions to do this but here is one way.

Table structure

create table Locations(LocationID int, Location varchar(50))
create table OtherTable(ID int, Locations varchar(max))

Test data

insert into Locations values(1, 'Location <1>')
insert into Locations values(2, 'Location <2>')
insert into Locations values(3, 'Location <3>')
insert into Locations values(4, 'Location <4>')
insert into Locations values(5, 'Location <5>')

insert into OtherTable values (1, '')
insert into OtherTable values (2, '2')
insert into OtherTable values (3, '1, 3 ,5')

Query

;with cte as
(
  select
    T.ID,
    coalesce(L.Location, '') as Location
  from OtherTable as T
    cross apply
      (select cast('<r>'+replace(T.Locations, ',', '</r><r>')+'</r>' as xml)) LocXML(XMLCol)
    cross apply
      LocXML.XMLCol.nodes('r') LocID(IDCol)
    left outer join Locations as L
      on L.LocationID = LocID.IDCol.value('.', 'int')
)
select
  C1.ID,
  stuff((select ', '+C2.Location
         from cte as C2
         where C1.ID = C2.ID
         for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as Locations
from cte as C1
group by C1.ID

Result

ID  Locations
--- ----------------------------------------
1
2   Location <2>
3   Location <1>, Location <3>, Location <5>


问:
How to speed up grep/awk command?
I am going to process the text file (>300 GB) and split it into small text files (~1 GB). I want to speed up grep/awk commands.

I need to grep the line which has values on column b, here are my ways:

```<code># method 1:
awk -F',' '$2 ~ /a/ { print }' input

# method 2:
grep -e ".a" < inpuy
</code>```

Both of ways cost 1min for each file. So how can I speed up this operation?

Sample of input file:

```<code>a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
9,,3,12
10,0,34,45
24,4a83944,3,22
45,,435,34
</code>```

Expected output file:

```<code>a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
24,4a83944,3,22
</code>```

答:
How to speed up grep/awk command?

Are you so sure that grep or awk is the culprit of your perceived slowness ? Do you know about cut(1) or sed(1) ? Have you benchmarked the time to run wc(1) on your data? Probably the textual I/O is taking a lot of time.

Please benchmark several times, and use time(1) to benchmark your program.

I have a high-end Debian desktop (with a AMD 2970WX, 64Gb RAM, 1Tbyte SSD system disk, multi-terabyte 7200RPM SATA data disks) and just running wc on a 25Gbyte file (some *.tar.xz archive) sitting on a hard disk takes more than 10 minutes (measured with time), and wc is doing some really simple textual processing by reading that file sequentially so should run faster than grep (but, to my surprise, does not!) or awk on the same data :

```<code>wc /big/basile/backup.tar.xz  640.14s user 4.58s system 99% cpu 10:49.92 total
</code>```

and (using grep on the same file to count occurrences of a)

```<code>grep -c a /big/basile/backup.tar.xz  38.30s user 7.60s system 33% cpu 2:17.06 total
</code>```

general answer to your question:

Just write cleverly (with efficient O(log n) time complexity data structures: red-black trees, or hash tables, etc ...) an equivalent program in C or C++ or Ocaml or most other good language and implementation. Or buy more RAM to increase your page cache. Or buy an SSD to hold your data. And repeat your benchmarks more than once (because of the page cache).

suggestion for your problem : use a relational database

It is likely that using a plain textual file of 300Gb is not the best approach. Having huge textual files is usually wrong and is likely to be wrong once you need to process several times the same data. You'll better pre-process it somehow..

If you repeat the same grep search or awk execution on the same data file more than once, consider instead using sqlite (see also this answer) or even some other real relational database (e.g. with PostGreSQL or some other good RDBMS) to store then process your original data.

So a possible approach (if you have enough disk space) might be to write some program (in C, Python, Ocaml etc...), fed by your original data, and filling some sqlite database. Be sure to have clever database indexes and take time to design a good enough database schema, being aware of database normalization.

Title: How to speed up grep/awk command?

Body:
I am going to process the text file (>300 GB) and split it into small text files (~1 GB). I want to speed up grep/awk commands.

I need to grep the line which has values on column b, here are my ways:

# method 1:
awk -F',' '$2 ~ /a/ { print }' input

# method 2:
grep -e ".a" < inpuy

Both of ways cost 1min for each file. So how can I speed up this operation?

Sample of input file:

a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
9,,3,12
10,0,34,45
24,4a83944,3,22
45,,435,34

Expected output file:

a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
24,4a83944,3,22

Body:
How to speed up grep/awk command?

Are you so sure that grep or awk is the culprit of your perceived slowness ? Do you know about cut(1) or sed(1) ? Have you benchmarked the time to run wc(1) on your data? Probably the textual I/O is taking a lot of time.

Please benchmark several times, and use time(1) to benchmark your program.

I have a high-end Debian desktop (with a AMD 2970WX, 64Gb RAM, 1Tbyte SSD system disk, multi-terabyte 7200RPM SATA data disks) and just running wc on a 25Gbyte file (some *.tar.xz archive) sitting on a hard disk takes more than 10 minutes (measured with time), and wc is doing some really simple textual processing by reading that file sequentially so should run faster than grep (but, to my surprise, does not!) or awk on the same data :

wc /big/basile/backup.tar.xz  640.14s user 4.58s system 99% cpu 10:49.92 total

and (using grep on the same file to count occurrences of a)

grep -c a /big/basile/backup.tar.xz  38.30s user 7.60s system 33% cpu 2:17.06 total

general answer to your question:

Just write cleverly (with efficient O(log n) time complexity data structures: red-black trees, or hash tables, etc ...) an equivalent program in C or C++ or Ocaml or most other good language and implementation. Or buy more RAM to increase your page cache. Or buy an SSD to hold your data. And repeat your benchmarks more than once (because of the page cache).

suggestion for your problem : use a relational database

It is likely that using a plain textual file of 300Gb is not the best approach. Having huge textual files is usually wrong and is likely to be wrong once you need to process several times the same data. You'll better pre-process it somehow..

If you repeat the same grep search or awk execution on the same data file more than once, consider instead using sqlite (see also this answer) or even some other real relational database (e.g. with PostGreSQL or some other good RDBMS) to store then process your original data.

So a possible approach (if you have enough disk space) might be to write some program (in C, Python, Ocaml etc...), fed by your original data, and filling some sqlite database. Be sure to have clever database indexes and take time to design a good enough database schema, being aware of database normalization.


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答: C++ is a multi-paradigm language. Many people associate C++ strictly with OOP.</p>

OwnerDisplayName: rajKumar

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: starblue

OwnerDisplayName: cdv

LastEditorDisplayName: cdv


问:
JSF: How to let #{...} expansion not be escaped?
I have a custom EL function (defined in myfunctions.taglib.xml) which returns a chunk of HTML, I want to copy it verbatim to the output,

```<code><f:verbatim>
    #{mylib:generateHtml()}
</f:verbatim>
</code>```

however, the expansion of #{...} is always escaped. How to make it not be escaped?

答:
I believe there is an option for escape characters with verbatim.</p>

```<code><f:verbatim escape="#{boolean}" />
</code>```

Body:
I have a custom EL function (defined in myfunctions.taglib.xml) which returns a chunk of HTML, I want to copy it verbatim to the output,

<f:verbatim>
    #{mylib:generateHtml()}
</f:verbatim>

however, the expansion of #{...} is always escaped. How to make it not be escaped?

Body:
I believe there is an option for escape characters with verbatim.

<f:verbatim escape="#{boolean}" />


问:
I want to always redirect to home page
I am testing an app, and at each changes I do in js, I would like that it load the home page.

Right now, if I am on a specific route, it will hot reload that route.

Is there a way to force homepage on refresh in angular ?

答:
One approach may be to add a route guard that checks for some global variable.

For example; first create a service:

```<code>import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class MyRedirectCheckService {
  redirectToHomePage = true;
}
</code>```

Create a route guard that uses the service, something like this:

```<code>import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({
  providedIn: 'root',
})
export class checkFirstLoadGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
    myRedirectCheckService: MyRedirectCheckService ): boolean {
    return myRedirectCheckService.redirectToHomePage;
  }
}
</code>```

Then add the canActivate route guard to your router:

```<code>const routes: Routes = [
          { path: 'main', component: MainComponent },
          { path: 'child', component: ChildComponent, canActivate: [CheckFirstLoadGuard]},
          { path: '**', component: AdminDashboardComponent }
        ]
];
</code>```

In your main component constructor, be sure to toggle the value:

```<code>constructor(myRedirectCheckService: MyRedirectCheckService) {
  myRedirectCheckService.redirectToHomePage = false;
}
</code>```

This is just one approach, and code is not tested in the context of an actual app.

Title: I want to always redirect to home page

Body:
One approach may be to add a route guard that checks for some global variable.

For example; first create a service:

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class MyRedirectCheckService {
  redirectToHomePage = true;
}

Create a route guard that uses the service, something like this:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({
  providedIn: 'root',
})
export class checkFirstLoadGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
    myRedirectCheckService: MyRedirectCheckService ): boolean {
    return myRedirectCheckService.redirectToHomePage;
  }
}

Then add the canActivate route guard to your router:

const routes: Routes = [
          { path: 'main', component: MainComponent },
          { path: 'child', component: ChildComponent, canActivate: [CheckFirstLoadGuard]},
          { path: '**', component: AdminDashboardComponent }
        ]
];

In your main component constructor, be sure to toggle the value:

constructor(myRedirectCheckService: MyRedirectCheckService) {
  myRedirectCheckService.redirectToHomePage = false;
}

This is just one approach, and code is not tested in the context of an actual app.


问:
Xamarin iOS Control Event creating duplicates
I have been trying to create a TouchDown event for my Button in Xamarin for iOS. I have created a simple xib file with 2 buttons in it.

In Visual Studio, the IDE I am currently using, I selected the first button in the xib and in the Events tab in the Properties window, I wrote OnClick and pressed the Add button for the TouchDown event.

This created the event and works as you would expect. The OnClick method in the code behind gets called when the button is pressed.

So naturally I for the second Button I went again to the Events tab and instead of writing the OnClick function again, I selected the OnClick event from the dropdown, expecting the same function to get called.

However, when I press now I get the infamous unrecognized selector sent to instance error. This is because in the generated file, a second method was created.

```<code>[Action ("OnKeyPress")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void OnKeyPressed ();

[Action ("OnKeyPress")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void OnKeyPressed (UIKit.UIButton sender);
</code>```

The method with the sender parameter is obviously the correctly generated method which the first button connected to. And the second method is invalid, since it does not contain the sender parameter. My question now is, how can I prevent Visual Studio from creating the corrupted method?

答:
My question now is, how can I prevent Visual Studio from creating the
  corrupted method?

I just tested it on my side, and I found after you create a second button:

If you select the OnClick event from the dropdown, it will create a second method.

If you writing the OnClick function again instead of select the OnClick event from the dropdown, it will not generate a a second method.

So you could choose the write the function name again and create the function in code behind like this:

```<code>partial void OnClick(UIKit.UIButton sender) {

}
</code>```

Body:
I have been trying to create a TouchDown event for my Button in Xamarin for iOS. I have created a simple xib file with 2 buttons in it.

In Visual Studio, the IDE I am currently using, I selected the first button in the xib and in the Events tab in the Properties window, I wrote OnClick and pressed the Add button for the TouchDown event.

This created the event and works as you would expect. The OnClick method in the code behind gets called when the button is pressed.

So naturally I for the second Button I went again to the Events tab and instead of writing the OnClick function again, I selected the OnClick event from the dropdown, expecting the same function to get called.

However, when I press now I get the infamous unrecognized selector sent to instance error. This is because in the generated file, a second method was created.

[Action ("OnKeyPress")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void OnKeyPressed ();

[Action ("OnKeyPress")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void OnKeyPressed (UIKit.UIButton sender);

The method with the sender parameter is obviously the correctly generated method which the first button connected to. And the second method is invalid, since it does not contain the sender parameter. My question now is, how can I prevent Visual Studio from creating the corrupted method?

Body:
My question now is, how can I prevent Visual Studio from creating the
  corrupted method?

I just tested it on my side, and I found after you create a second button:

If you select the OnClick event from the dropdown, it will create a second method.

If you writing the OnClick function again instead of select the OnClick event from the dropdown, it will not generate a a second method.

So you could choose the write the function name again and create the function in code behind like this:

partial void OnClick(UIKit.UIButton sender) {

}


答:
use

```<code>window.location = ''
</code>```

instead of

```<code>this.router.navigate([''])
</code>```

to force refresh

if using inside  element, use href attribute instead of routerLink attribute

Title: I want to always redirect to home page

Body:
I am testing an app, and at each changes I do in js, I would like that it load the home page.

Right now, if I am on a specific route, it will hot reload that route.

Is there a way to force homepage on refresh in angular ?

Body:
use

window.location = ''

instead of

this.router.navigate([''])

to force refresh

if using inside  element, use href attribute instead of routerLink attribute


问:
can't create checkbox widget without tristate property
I can't create checkbox widget without tristate propertym this code generate a error:

```<code> body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Lunes'),
                Checkbox(
                  value: monday,
                  onChanged: (bool value){
                    setState(() {
                      monday = value;
                    });
                  },
                )
              ],
            ),
</code>```

this code works fine:

```<code> body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Lunes'),
                Checkbox(
                  tristate: true,
                  value: monday,
                  onChanged: (bool value){
                    setState(() {
                      monday = value;
                    });
                  },
                )
              ],
            ),
</code>```

Why i need tristate?

答: "monday" needs to be non-null (bool). I presume it has not been initialized when defined or in initState(), but you don't appear to have shown that code.</p>

Body:
I can't create checkbox widget without tristate propertym this code generate a error:

 body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Lunes'),
                Checkbox(
                  value: monday,
                  onChanged: (bool value){
                    setState(() {
                      monday = value;
                    });
                  },
                )
              ],
            ),

this code works fine:

 body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Lunes'),
                Checkbox(
                  tristate: true,
                  value: monday,
                  onChanged: (bool value){
                    setState(() {
                      monday = value;
                    });
                  },
                )
              ],
            ),

Why i need tristate?


问:
why we include path before using pip command
When ever we try to run the command pip intall nltk or pip install numpy we get error that pip is not recognized as internal or external command then we add pip to the path. I want to know that what is path and why we add link in path. Any one help please.

答:
From the Linux Information Project:

PATH is an environmental variable in Linux and other Unix-like operating systems that tells the shell which directories to search for executable files (i.e., ready-to-run programs) in response to commands issued by a user. It increases both the convenience and the safety of such operating systems and is widely considered to be the single most important environmental variable.

So basically it's a list of directories in which the shell looks to find commands.

Let's say your pip is installed at /usr/local/bin/pip, and /usr/local/bin/ is not in your PATH variable, the shell won't be able to find pip.

If you're using Python virtual environment, like python3 -m venv my-venv, you usually have to source bin/activate under my-venv, which adds all scripts under my-venv/bin to your PATH variable for the current shell. Then your shell will be able to find the virtual environment-specific scripts.

Since PATH is set by the login shell, when you close the current shell and open a new one, the variable gets reset. Then you have to call source bin/activate under my-venv again to get shell look into your virtual environment.


问:
Why can't Anaconda find pdfminer for uninstall?
I installed the package pdfminer3k in an Anaconda environment (called "tractatus").

I can load it. Anaconda knows it's there.

```<code>$ python
Python 3.7.2 (default, Dec 29 2018, 00:00:04)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdfminer
>>>
(tractatus) ~/src/tractatus
$ conda list pdfminer
# packages in environment at /anaconda3/envs/tractatus:
#
# Name                    Version                   Build  Channel
pdfminer3k                1.3.1                    pypi_0    pypi
$ ll /anaconda3/envs/tractatus/lib/python3.7/site-packages/pdfminer3k-1.3.1-py3.7.egg/
total 0
drwxr-xr-x   9 wmcneill  staff  288 Feb  4 14:12 EGG-INFO
drwxr-xr-x  26 wmcneill  staff  832 Feb  4 14:12 pdfminer
</code>```

Now I want to delete it, but Anaconda's remove command can't find the package.

```<code>$ conda remove pdfminer
Collecting package metadata: done
Solving environment: failed

PackagesNotFoundError: The following packages are missing from the target environment:
  - pdfminer

(tractatus) ~/src/tractatus
$ conda remove pdfminer3k
Collecting package metadata: done
Solving environment: failed

PackagesNotFoundError: The following packages are missing from the target environment:
  - pdfminer3k
</code>```

pdfminer also does not appear in the installed packages list shown for this environment in the Anaconda Navigator UI.

Is this a bug in Anaconda, or am I doing something wrong?

答:
I guess when you install pdfminer pkg, you are using 'pip install', so by the time you want to remove it, it can not be found at any of your conda env folder.

Instead of

```<code>conda remove pdfminer
</code>```

try:

```<code>pip uninstall pdfminer
</code>```

It works for me.

Body:
I installed the package pdfminer3k in an Anaconda environment (called "tractatus").

I can load it. Anaconda knows it's there.

$ python
Python 3.7.2 (default, Dec 29 2018, 00:00:04)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdfminer
>>>
(tractatus) ~/src/tractatus
$ conda list pdfminer
# packages in environment at /anaconda3/envs/tractatus:
#
# Name                    Version                   Build  Channel
pdfminer3k                1.3.1                    pypi_0    pypi
$ ll /anaconda3/envs/tractatus/lib/python3.7/site-packages/pdfminer3k-1.3.1-py3.7.egg/
total 0
drwxr-xr-x   9 wmcneill  staff  288 Feb  4 14:12 EGG-INFO
drwxr-xr-x  26 wmcneill  staff  832 Feb  4 14:12 pdfminer

Now I want to delete it, but Anaconda's remove command can't find the package.

$ conda remove pdfminer
Collecting package metadata: done
Solving environment: failed

PackagesNotFoundError: The following packages are missing from the target environment:
  - pdfminer

(tractatus) ~/src/tractatus
$ conda remove pdfminer3k
Collecting package metadata: done
Solving environment: failed

PackagesNotFoundError: The following packages are missing from the target environment:
  - pdfminer3k

pdfminer also does not appear in the installed packages list shown for this environment in the Anaconda Navigator UI.

Is this a bug in Anaconda, or am I doing something wrong?

Body:
I guess when you install pdfminer pkg, you are using 'pip install', so by the time you want to remove it, it can not be found at any of your conda env folder.

Instead of

conda remove pdfminer

try:

pip uninstall pdfminer

It works for me.


问:
When is a variable declaration in another class actually ran?
I've never really found out when exactly a variable declaration is actually ran in a program, when the variable resides in another class.

For instance:

  public static void main(String[] args) {
        int x = 1;
        System.out.println(x);
    }
```

<p>This program seems fairly simplistic to understand in terms of when the declaration is ran.</p>

<p>However consider this:</p>

<pre class="lang-java prettyprint-override"><code>public class Test {
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        Test2 test2 = new Test2();
        System.out.println(test2.y);
    }
}
public class Test2 {
    public int y = 1;
}
</code>```

and:

public class Test {
    public static void main(String[] args) {
        System.out.println(Test2.y);
    }
}
public class Test2 {
    public static int y = 1;
}
```

<p>When is the </p>

<pre class="lang-java prettyprint-override"><code>public int y = 1;
</code>```

declaration ever ran in this program? It is only ever directly called, but isn't actually ran sequentially like the first example. Some clarification on how this actually works would be appreciated.

答: When you write this Test2 test2 = new Test2(); at that an object for with reference test2 was created in the memory, that object has one property as y with value assigned to it as 1. So during the creation of object 'test2' , the line public int y = 1; was executed.

Body:
I've never really found out when exactly a variable declaration is actually ran in a program, when the variable resides in another class.

For instance:

  public static void main(String[] args) {
        int x = 1;
        System.out.println(x);
    }

This program seems fairly simplistic to understand in terms of when the declaration is ran.

However consider this:

public class Test {
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        Test2 test2 = new Test2();
        System.out.println(test2.y);
    }
}
public class Test2 {
    public int y = 1;
}

and:

public class Test {
    public static void main(String[] args) {
        System.out.println(Test2.y);
    }
}
public class Test2 {
    public static int y = 1;
}

When is the

public int y = 1;

declaration ever ran in this program? It is only ever directly called, but isn't actually ran sequentially like the first example. Some clarification on how this actually works would be appreciated.


问:
Why is jpegData not saving my resized image? UPDATED
I am taking a photo from the camera or the Photo gallery and saving it in my application. I don't need such a large image so I am using an extension to reduce it. Then I am saving it to the application space. But the size reduction is not saved.

I have tried various permutations on size change, delete and save.

```<code>            let path = "/var/mobile/Containers/Data/Application/0595DE63-AE43-4DCF-9BD0-FB552844ECF5/Documents/tour15/H25.jpg"
            print("A",hotspotImage.image!.size)
            hotspotImage.image = hotspotImage.image!.resizeImage(2048, opaque: true)
            print("B",hotspotImage.image!.size)
            let fileManager  = FileManager.default
            try! fileManager.removeItem(atPath: path)
            try! hotspotImage.image!.jpegData(compressionQuality: 0.8)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
            print("C",hotspotImage.image!.size)
            let  imageTest = UIImage(contentsOfFile: path)
            print("D",imageTest!.size)
</code>```

The results are ...

A (4032.0, 3024.0)

B (2048.0, 1536.0)

C (2048.0, 1536.0)

D (4096.0, 3072.0)

When I retrieve the "updated" image it has the original size. You cannot see this but the image has definitely been replaced.

Obviously I am missing something fundamental - please put me out of my misery.

Apologies to those kind people who responded previously - but I have now discovered some extra and important information. The example size was fooling us all. When I changed the reduced size to 200 (and not exactly half the original size) I get the following results:

A (4032 3024)

B (200 150)

C (200 150)

D (400 300)

So what ever is happening is doubling the size - not - as I previously thought - not updating with the new size.

Does this make it clearer or more of a puzzle?

And talking of puzzles I got a -1 but no one said why.

答:
UIImage(named:) caches images. You're not reading from disk the second time you call it (I guess you called it somewhere before with the same path). To bypass the cache you need to  use init(contentsOfFile:)

The following should work as intended:

```<code>let path = getAppFolder() + photoUrl
print("A",hotspotImage.image!.size)
hotspotImage.image = hotspotImage.image!.resizeImage(2048, opaque: true)
print("B",hotspotImage.image!.size)
let fileManager  = FileManager.default
try! fileManager.removeItem(atPath: path)
try! hotspotImage.image!.jpegData(compressionQuality: 0.8)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
print("C",hotspotImage.image!.size)
let  imageTest = UIImage(contentsOfFile: path)
print("D",imageTest!.size)
</code>```

Body:
I am taking a photo from the camera or the Photo gallery and saving it in my application. I don't need such a large image so I am using an extension to reduce it. Then I am saving it to the application space. But the size reduction is not saved.

I have tried various permutations on size change, delete and save.

            let path = "/var/mobile/Containers/Data/Application/0595DE63-AE43-4DCF-9BD0-FB552844ECF5/Documents/tour15/H25.jpg"
            print("A",hotspotImage.image!.size)
            hotspotImage.image = hotspotImage.image!.resizeImage(2048, opaque: true)
            print("B",hotspotImage.image!.size)
            let fileManager  = FileManager.default
            try! fileManager.removeItem(atPath: path)
            try! hotspotImage.image!.jpegData(compressionQuality: 0.8)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
            print("C",hotspotImage.image!.size)
            let  imageTest = UIImage(contentsOfFile: path)
            print("D",imageTest!.size)

The results are ...

A (4032.0, 3024.0)

B (2048.0, 1536.0)

C (2048.0, 1536.0)

D (4096.0, 3072.0)

When I retrieve the "updated" image it has the original size. You cannot see this but the image has definitely been replaced.

Obviously I am missing something fundamental - please put me out of my misery.

Apologies to those kind people who responded previously - but I have now discovered some extra and important information. The example size was fooling us all. When I changed the reduced size to 200 (and not exactly half the original size) I get the following results:

A (4032 3024)

B (200 150)

C (200 150)

D (400 300)

So what ever is happening is doubling the size - not - as I previously thought - not updating with the new size.

Does this make it clearer or more of a puzzle?

And talking of puzzles I got a -1 but no one said why.

Body:
UIImage(named:) caches images. You're not reading from disk the second time you call it (I guess you called it somewhere before with the same path). To bypass the cache you need to  use init(contentsOfFile:)

The following should work as intended:

let path = getAppFolder() + photoUrl
print("A",hotspotImage.image!.size)
hotspotImage.image = hotspotImage.image!.resizeImage(2048, opaque: true)
print("B",hotspotImage.image!.size)
let fileManager  = FileManager.default
try! fileManager.removeItem(atPath: path)
try! hotspotImage.image!.jpegData(compressionQuality: 0.8)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
print("C",hotspotImage.image!.size)
let  imageTest = UIImage(contentsOfFile: path)
print("D",imageTest!.size)


问:
How can I Read a list from a sharepoint site and make the contents globaly available in my code?
My code works, when I redundantly put it in objects like button_click or comboBoxApp_SelectedIndexChanged, but when I try to put it in a centralized location i get "The name 'items' does not exist in the current context"</p>

```<code>       ''' ClientContext context = new ClientContext("https://MySharePointSite/ServerMaintenance/");

        List ChangeList = context.Web.Lists.GetByTitle("Server Maintenance Windows");
        CamlQuery query = CamlQuery.CreateAllItemsQuery(1505);

        ListItemCollection items = ChangeList.GetItems(query);
        context.Load(items);
        context.ExecuteQuery();'''
</code>```

答:
Create a static method to return ListItemCollection object and then you can call this function anywhere you want, here is the code snippet for your reference:</p>

```<code> static void Main(string[] args)
    {
        ListItemCollection items = GetItems();
        foreach (ListItem item in items)
        {
            Console.WriteLine(item["Title"]);
        }

    }
    private static ListItemCollection GetItems()
    {
        ClientContext context = new ClientContext("http://sp/sites/Jerry");

        List ChangeList = context.Web.Lists.GetByTitle("TestList");
        CamlQuery query = CamlQuery.CreateAllItemsQuery(1505);

        ListItemCollection items = ChangeList.GetItems(query);
        context.Load(items);
        context.ExecuteQuery();
        return items;
    }
</code>```

Body:
My code works, when I redundantly put it in objects like button_click or comboBoxApp_SelectedIndexChanged, but when I try to put it in a centralized location i get "The name 'items' does not exist in the current context"

       ''' ClientContext context = new ClientContext("https://MySharePointSite/ServerMaintenance/");

        List ChangeList = context.Web.Lists.GetByTitle("Server Maintenance Windows");
        CamlQuery query = CamlQuery.CreateAllItemsQuery(1505);

        ListItemCollection items = ChangeList.GetItems(query);
        context.Load(items);
        context.ExecuteQuery();'''

Body:
Create a static method to return ListItemCollection object and then you can call this function anywhere you want, here is the code snippet for your reference:

 static void Main(string[] args)
    {
        ListItemCollection items = GetItems();
        foreach (ListItem item in items)
        {
            Console.WriteLine(item["Title"]);
        }

    }
    private static ListItemCollection GetItems()
    {
        ClientContext context = new ClientContext("http://sp/sites/Jerry");

        List ChangeList = context.Web.Lists.GetByTitle("TestList");
        CamlQuery query = CamlQuery.CreateAllItemsQuery(1505);

        ListItemCollection items = ChangeList.GetItems(query);
        context.Load(items);
        context.ExecuteQuery();
        return items;
    }