问:
Get the first 6 or 7 (conditional) characters of an object
Im trying to get the first 6 or 7 character of an object. This object have the name of Panel object and, I want to pass this characters to another variable to work whit them.

This is my code.

```<code>Dim p1Name
Dim paParent
Dim clickedPanel

Private Sub ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem.Click

    clickedPanel = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ContextMenuStrip).SourceControl, Panel)
    p1Name = clickedPanel.Name

    If Len(p1Name) = 7 Then
        paParent = clickedPanel.name
    Else
        paParent = clickedPanel.name.Substring(0, 7)
    End If

End Sub

Private Sub SwPan()

    Dim varE As String = paParent
    Dim PanelParent As Panel = paParent

        Dim p3 = DirectCast(PanelParent.Controls.Find(p1Name, True).FirstOrDefault(), Panel)
        If p3 Is Nothing Then Throw New ArgumentException("index1")
end sub
</code>```

When I try to run, send the next error message.

```<code>index and length must refer to a location within the string parameter name length vb.net
</code>```

Please, could you help me to fix or guide me?

Thank you in advance.

Update I do the next.

This is to get (cut)

```<code>Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click

    clickedPanel = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ContextMenuStrip).SourceControl, Panel)

p1Name = clickedPanel.Name

    paParent = clickedPanel.parent

End Sub
</code>```

this is to do (paste)

```<code>Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
    clickedPanel = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ContextMenuStrip).SourceControl, Panel)

    p2Name = clickedPanel.Name

    pbParent = clickedPanel.parent

    Call Swap()

End Sub
</code>```

This is to swap panels

```<code>Private Sub Swap()

        '' build the panel names
        Dim varA As String = p1Name.ToString
        Dim varC As String = p2Name.ToString

        Dim PanelParent As Panel = paParent
        Dim PanelParent_b As Panel = pbParent

        Dim p3 = DirectCast(PanelParent.Controls.Find(p1Name, True).FirstOrDefault(), Panel)
        If p3 Is Nothing Then Throw New ArgumentException("index1")

        Dim p4 = DirectCast(PanelParent_b.Controls.Find(p2Name, True).FirstOrDefault(), Panel)
        If p4 Is Nothing Then Throw New ArgumentException("index2")

        Dim positionA As Integer = Panel1.AutoScrollPosition.X

        Panel1.AutoScroll = False

        Dim temp = p4.Location
        p4.Location = p3.Location
        p3.Location = temp

        Panel1.AutoScroll = True

        Panel1.AutoScrollPosition = New Point(positionA, Panel1.VerticalScroll.Maximum)

    End Sub
</code>```

答:
Good day.

Sorry for this delay, but I found the solution to this problem.

Attach the updated code.

Thank you all for the effort and time.

Regards

```<code>Private Sub Swap()

        Dim PanelParent As Panel = paParent
        Dim PanelParent_b As Panel = pbParent

        Dim p3 = DirectCast(PanelParent.Controls.Find(p1Name, True).FirstOrDefault(), Panel)
        If p3 Is Nothing Then Throw New ArgumentException("index1")

        Dim p4 = DirectCast(PanelParent_b.Controls.Find(p2Name, True).FirstOrDefault(), Panel)
        If p4 Is Nothing Then Throw New ArgumentException("index2")

        Dim positionA As Integer = Panel1.AutoScrollPosition.X

        Panel1.AutoScroll = False

        Dim temp = p4.Location
        Dim temp_b = p3.Location

        With p3
            .Parent = PanelParent_b
            .Location = temp
        End With

        With p4
            .Parent = PanelParent
            .Location = temp_b
        End With

        Panel1.AutoScroll = True

        Panel1.AutoScrollPosition = New Point(positionA, Panel1.VerticalScroll.Maximum)

    End Sub
</code>```

Body:
Im trying to get the first 6 or 7 character of an object. This object have the name of Panel object and, I want to pass this characters to another variable to work whit them.

This is my code.

Dim p1Name
Dim paParent
Dim clickedPanel

Private Sub ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem.Click

    clickedPanel = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ContextMenuStrip).SourceControl, Panel)
    p1Name = clickedPanel.Name

    If Len(p1Name) = 7 Then
        paParent = clickedPanel.name
    Else
        paParent = clickedPanel.name.Substring(0, 7)
    End If

End Sub

Private Sub SwPan()

    Dim varE As String = paParent
    Dim PanelParent As Panel = paParent

        Dim p3 = DirectCast(PanelParent.Controls.Find(p1Name, True).FirstOrDefault(), Panel)
        If p3 Is Nothing Then Throw New ArgumentException("index1")
end sub

When I try to run, send the next error message.

index and length must refer to a location within the string parameter name length vb.net

Please, could you help me to fix or guide me?

Thank you in advance.

Update I do the next.

This is to get (cut)

Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click

    clickedPanel = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ContextMenuStrip).SourceControl, Panel)

p1Name = clickedPanel.Name

    paParent = clickedPanel.parent

End Sub

this is to do (paste)

Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
    clickedPanel = DirectCast(DirectCast(DirectCast(sender, ToolStripMenuItem).Owner, ContextMenuStrip).SourceControl, Panel)

    p2Name = clickedPanel.Name

    pbParent = clickedPanel.parent

    Call Swap()

End Sub

This is to swap panels

Private Sub Swap()

        '' build the panel names
        Dim varA As String = p1Name.ToString
        Dim varC As String = p2Name.ToString

        Dim PanelParent As Panel = paParent
        Dim PanelParent_b As Panel = pbParent

        Dim p3 = DirectCast(PanelParent.Controls.Find(p1Name, True).FirstOrDefault(), Panel)
        If p3 Is Nothing Then Throw New ArgumentException("index1")

        Dim p4 = DirectCast(PanelParent_b.Controls.Find(p2Name, True).FirstOrDefault(), Panel)
        If p4 Is Nothing Then Throw New ArgumentException("index2")

        Dim positionA As Integer = Panel1.AutoScrollPosition.X

        Panel1.AutoScroll = False

        Dim temp = p4.Location
        p4.Location = p3.Location
        p3.Location = temp

        Panel1.AutoScroll = True

        Panel1.AutoScrollPosition = New Point(positionA, Panel1.VerticalScroll.Maximum)

    End Sub

Body:
Good day.

Sorry for this delay, but I found the solution to this problem.

Attach the updated code.

Thank you all for the effort and time.

Regards

Private Sub Swap()

        Dim PanelParent As Panel = paParent
        Dim PanelParent_b As Panel = pbParent

        Dim p3 = DirectCast(PanelParent.Controls.Find(p1Name, True).FirstOrDefault(), Panel)
        If p3 Is Nothing Then Throw New ArgumentException("index1")

        Dim p4 = DirectCast(PanelParent_b.Controls.Find(p2Name, True).FirstOrDefault(), Panel)
        If p4 Is Nothing Then Throw New ArgumentException("index2")

        Dim positionA As Integer = Panel1.AutoScrollPosition.X

        Panel1.AutoScroll = False

        Dim temp = p4.Location
        Dim temp_b = p3.Location

        With p3
            .Parent = PanelParent_b
            .Location = temp
        End With

        With p4
            .Parent = PanelParent
            .Location = temp_b
        End With

        Panel1.AutoScroll = True

        Panel1.AutoScrollPosition = New Point(positionA, Panel1.VerticalScroll.Maximum)

    End Sub


来源: stackexchange

问:
Wrong result using ST_Intersection with postgis
I am trying to do a simple intersection with postgis, but the result I get is wrong. There is a segment missing of about 7 meters at the start of the feature.

Here is the sql-command that I use for the intersection:

```<code>select ST_Intersection(t2.wkb_geometry,
                     t1.wkb_geometry), t2.sde_id as s_sde, t2.mtb_id,
ST_Length(ST_Intersection(t1.wkb_geometry,t2.wkb_geometry))
from
public.mountainbike_pavement_temp2 t1 inner join public.mountainbike_strecken_temp2 t2 on
t1.wkb_geometry && t2.wkb_geometry;
</code>```

The result-length should be about 187 meters, but the result-length is only about 180 meters. I have tried a lot, but I cannot find any reason, why this happens, and thus how to fix it.

When I do this intersection in ArcGis, everything works as intended.

I tried this with
postgres 9.6.15 and postgis 2.4

and also with

postgres 12.1 and postgis 3.0, same results.

Tables and data can be found here:

https://pastebin.com/4vHqRYx5

https://pastebin.com/RAfzXXW6

Tablenames:
mountainbike_pavement_temp2
public.mountainbike_strecken_temp2

The distance of the first vertices from mountainbike_pavement_temp2 to mountainbike_strecken_temp2 is all 0, calculated with ST_Distance in postgis (see comment below). So I would assume, that there is an intersection.

答:
The problem is that the pavement lines do not exactly coincide with the strecken lines.  Specifically, they contain a vertex POINT ( -43663.049707713886 245429.5072260416 ) which does not lie on the strecken linestring.  This means the intersection does not include the entire length of the strecken line.

The picture below shows this (with the point location magnified to show the difference).  pavement is red, strecken is blue.

This may work in ArcGIS because it may use some snapping heuristic when computing the intersection.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do a simple intersection with postgis, but the result I get is wrong. There is a segment missing of about 7 meters at the start of the feature.

Here is the sql-command that I use for the intersection:

select ST_Intersection(t2.wkb_geometry,
                     t1.wkb_geometry), t2.sde_id as s_sde, t2.mtb_id,
ST_Length(ST_Intersection(t1.wkb_geometry,t2.wkb_geometry))
from
public.mountainbike_pavement_temp2 t1 inner join public.mountainbike_strecken_temp2 t2 on
t1.wkb_geometry && t2.wkb_geometry;

The result-length should be about 187 meters, but the result-length is only about 180 meters. I have tried a lot, but I cannot find any reason, why this happens, and thus how to fix it.

When I do this intersection in ArcGis, everything works as intended.

I tried this with
postgres 9.6.15 and postgis 2.4

and also with

postgres 12.1 and postgis 3.0, same results.

Tables and data can be found here:

https://pastebin.com/4vHqRYx5

https://pastebin.com/RAfzXXW6

Tablenames:
mountainbike_pavement_temp2
public.mountainbike_strecken_temp2

The distance of the first vertices from mountainbike_pavement_temp2 to mountainbike_strecken_temp2 is all 0, calculated with ST_Distance in postgis (see comment below). So I would assume, that there is an intersection.


问:
#1045 - Access denied for user 'root'@'localhost' (using password: YES)
This might seem redundant but I was unable to find a correct solution.

I was unable to login to mysql using the mysql console.It is asking for a password and I have no clue what I actually entered.(Is there a way to get the password or change it?)
This is how my config.inc look.

When I try to open phpmyadmin I get this error(#1045 - Access denied for user 'root'@'localhost' (using password: YES))

```<code><?php

/* Servers configuration */
$i = 0;

/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
 $cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'prakash123';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/* End of servers configuration */

$cfg['DefaultLang'] = 'en-utf-8';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

/* rajk - for blobstreaming */
$cfg['Servers'][$i]['bs_garbage_threshold'] = 50;
$cfg['Servers'][$i]['bs_repository_threshold'] = '32M';
$cfg['Servers'][$i]['bs_temp_blob_timeout'] = 600;
$cfg['Servers'][$i]['bs_temp_log_threshold'] = '32M';

?>
</code>```

I have tried to uninstall( Plus Deleted all the related files)  WAMP and reinstall.It didn't help either.
While reinstalling WAMP server it is not asking for any username password stuff I don't know why.
Any help is highly appreciated.

答:
```<code>php artisan serve
</code>```

this command get the env contents for the first time and if you update .env file need to restart it.

in my case my username and dbname is valid and php artisan migrate worked

but need to cntrl+c , to cancel php artisan serve , and run it again

```<code>php artisan serve
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This might seem redundant but I was unable to find a correct solution.

I was unable to login to mysql using the mysql console.It is asking for a password and I have no clue what I actually entered.(Is there a way to get the password or change it?)
This is how my config.inc look.

When I try to open phpmyadmin I get this error(#1045 - Access denied for user 'root'@'localhost' (using password: YES))

<?php

/* Servers configuration */
$i = 0;

/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
 $cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'prakash123';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/* End of servers configuration */

$cfg['DefaultLang'] = 'en-utf-8';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

/* rajk - for blobstreaming */
$cfg['Servers'][$i]['bs_garbage_threshold'] = 50;
$cfg['Servers'][$i]['bs_repository_threshold'] = '32M';
$cfg['Servers'][$i]['bs_temp_blob_timeout'] = 600;
$cfg['Servers'][$i]['bs_temp_log_threshold'] = '32M';

?>

I have tried to uninstall( Plus Deleted all the related files)  WAMP and reinstall.It didn't help either.
While reinstalling WAMP server it is not asking for any username password stuff I don't know why.
Any help is highly appreciated.

Body:
php artisan serve

this command get the env contents for the first time and if you update .env file need to restart it.

in my case my username and dbname is valid and php artisan migrate worked

but need to cntrl+c , to cancel php artisan serve , and run it again

php artisan serve


问:
wxGlade: Set the initial size based on number of characters inside wxGlade
I have a wx.Choice control in glade however I am not sure how I would be able to set the default size of the control to be equivalent to x number of characters.

Is there a way to set the initial size of the widget inside wxGlade, to be the length of an expected string (in pixels)?

wx.Choice.SetInitialSize(dc.GetTextExtent("expected string")[0])

答:
In short, there is no such option, there might be added in the future, however currently wxGlade does not provide a convenient way to specify an initial size in terms of number of characters.

Adding the code of

```<code>wx.Choice.SetInitialSize(dc.GetTextExtent("expected string")[0])
</code>```

In the code section within wxGlade is one way of doing this, the other is to add it in manually within the Python code.

Body:
In short, there is no such option, there might be added in the future, however currently wxGlade does not provide a convenient way to specify an initial size in terms of number of characters.

Adding the code of

wx.Choice.SetInitialSize(dc.GetTextExtent("expected string")[0])

In the code section within wxGlade is one way of doing this, the other is to add it in manually within the Python code.


问:
JavaScript Debugging
I am using Visual Studio 2010 Express Developer edition. Developing a Website. I'm using JavaScript in my .aspx pages. How to put breakpoints in Javascript.

Any help is highly appreciated.

Thank You

答:
You can use your browser's debugger :

For Firefox, you can use Firebug (http://getfirebug.com).

Chrome contains an embedded debugger.

Title: JavaScript Debugging


问:
sqlalchemy psycopg2.errors.InsufficientPrivilege: permission denied for relation <
>
I've read over 20 different questions with the same problem - and the suggested answers didn't solve my problem. I'm still getting sqlalchemy psycopg2.errors.InsufficientPrivilege: permission denied for relation <
>

Environment: EC2, debian 8, postgresql, flask, sqlalchemy
my table in postgresql:

```<code>Create table Members(
id BIGSERIAL PRIMARY KEY,
joinDate TIMESTAMPTZ DEFAULT Now(),
password TEXT NOT NULL
);
</code>```

directly in postgresql: INSERT INTO members (password) VALUES('123')  RETURNING id; works perfect

I've granted my user all possible grants

```<code>grant all privileges on database <my_db> to <my_user>
grant all privileges on all table in schema public to <my_user>
grant all privileges on all relations in schema public to <my_user>
</code>```

I've also created a .htaccess file under var/www/html with Header set Access-Control-Allow-Origin "*"

my table mapped with sqlalchemy member.py

```<code>from datetime import datetime
from sqlalchemy import create_engine, Column, String, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from marshmallow import Schema, fields
from sqlalchemy.schema import UniqueConstraint
import sqlalchemy as sa

Engine = create_engine('postgresql://<my_user>:<my_psw>@<my_db_url>/<my_dn_name>')
Session = sessionmaker(bind=Engine)
Base = declarative_base()

class MemberSchema(Schema):
    id = fields.Number()
    password = fields.Str()

class Member(Base):
    __tablename__ = 'members'

    id = Column(Integer, primary_key=True)
    password = Column(String)

    def __init__(self, password):
        self.password = password
</code>```

the code receiving the POST and doing the insert in test.py:

```<code>from flask import Flask, render_template, request,jsonify
from flask_cors import CORS, cross_origin
import logging

def register_member(password):
    session = Session()
    newMember = Member(password)
    session.add(newMember)
    session.commit()
    return newMember

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/register", methods=["GET", "POST"])
@cross_origin()
def register():
    try:
        formData = request.form
        register_member(formData['password'])
        return jsonify({"message":"Regsitrated successfully!"})
    except Exception as ex:
        logging.debug(ex)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1234, debug=True)
</code>```

executing this code results in exception with these errors

```<code>DEBUG:root:(psycopg2.errors.InsufficientPrivilege) permission denied for relation members

[SQL: INSERT INTO members (password) VALUES (%(password)s) RETURNING members.id]
[parameters: {'password': '4444'}]
</code>```

and

```<code>TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
</code>```

Any help would be appreciated

答:
Not sure if you're manually testing with psql or pgAdmin, but ensure you're testing with the same account used in your code.

Even if the user has access to a table/relation in the schema, they also need access to the schema itself:
grant usage on schema public to <myuser>

Also, I noticed use of BIGSERIAL which involves a sequence.  You'll probably need a grant usage on all sequences in schema public to <myuser>.

Title: sqlalchemy psycopg2.errors.InsufficientPrivilege: permission denied for relation <<table>>

Body:
I've read over 20 different questions with the same problem - and the suggested answers didn't solve my problem. I'm still getting sqlalchemy psycopg2.errors.InsufficientPrivilege: permission denied for relation <
>

Environment: EC2, debian 8, postgresql, flask, sqlalchemy
my table in postgresql:

Create table Members(
id BIGSERIAL PRIMARY KEY,
joinDate TIMESTAMPTZ DEFAULT Now(),
password TEXT NOT NULL
);

directly in postgresql: INSERT INTO members (password) VALUES('123')  RETURNING id; works perfect

I've granted my user all possible grants

grant all privileges on database <my_db> to <my_user>
grant all privileges on all table in schema public to <my_user>
grant all privileges on all relations in schema public to <my_user>

I've also created a .htaccess file under var/www/html with Header set Access-Control-Allow-Origin "*"

my table mapped with sqlalchemy member.py

from datetime import datetime
from sqlalchemy import create_engine, Column, String, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from marshmallow import Schema, fields
from sqlalchemy.schema import UniqueConstraint
import sqlalchemy as sa

Engine = create_engine('postgresql://<my_user>:<my_psw>@<my_db_url>/<my_dn_name>')
Session = sessionmaker(bind=Engine)
Base = declarative_base()

class MemberSchema(Schema):
    id = fields.Number()
    password = fields.Str()

class Member(Base):
    __tablename__ = 'members'

    id = Column(Integer, primary_key=True)
    password = Column(String)

    def __init__(self, password):
        self.password = password

the code receiving the POST and doing the insert in test.py:

from flask import Flask, render_template, request,jsonify
from flask_cors import CORS, cross_origin
import logging

def register_member(password):
    session = Session()
    newMember = Member(password)
    session.add(newMember)
    session.commit()
    return newMember

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/register", methods=["GET", "POST"])
@cross_origin()
def register():
    try:
        formData = request.form
        register_member(formData['password'])
        return jsonify({"message":"Regsitrated successfully!"})
    except Exception as ex:
        logging.debug(ex)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1234, debug=True)

executing this code results in exception with these errors

DEBUG:root:(psycopg2.errors.InsufficientPrivilege) permission denied for relation members

[SQL: INSERT INTO members (password) VALUES (%(password)s) RETURNING members.id]
[parameters: {'password': '4444'}]

and

TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

Any help would be appreciated


问:
Cut out or remove the pixels from an image that run into the black pixels of a mask
I'm trying to cut out two images with OpenCV using Python.

The idea is to use an image like this one:

As a mask. Note: this is only an example.

So if I subtract this mask to another image, I will get an image with the original pixels only in the same location as the white rectangle in the mask. So, the idea is to remove the pixels from the first image that run into the same location that the black ones in the mask.

How can I do it?

Maybe I can do an AND operation between the two images (the mask will have only 0 (for black) and 1 (for white pixels).

答:
If what you are asking is how to make the image transparent where the mask is black and opaque where the mask is white, then just add the mask to the alpha channel of the input. Here is how to do that in Python/OpenCV. (Revised per comment by Mark Setchell)

Input:

Mask:

```<code>import cv2
import numpy as np

# load image
img = cv2.imread('lena.png')

# load mask as grayscale
mask = cv2.imread('rect_mask.png', cv2.COLOR_BGR2GRAY)

# put mask into alpha channel of image
#result = img.copy()
#result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
#result[:, :, 3] = mask
result = np.dstack((img, mask))

# save resulting masked image
cv2.imwrite('lena_masked.png', result)
</code>```

Result:

Body:
If what you are asking is how to make the image transparent where the mask is black and opaque where the mask is white, then just add the mask to the alpha channel of the input. Here is how to do that in Python/OpenCV. (Revised per comment by Mark Setchell)

Input:

Mask:

import cv2
import numpy as np

# load image
img = cv2.imread('lena.png')

# load mask as grayscale
mask = cv2.imread('rect_mask.png', cv2.COLOR_BGR2GRAY)

# put mask into alpha channel of image
#result = img.copy()
#result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
#result[:, :, 3] = mask
result = np.dstack((img, mask))

# save resulting masked image
cv2.imwrite('lena_masked.png', result)

Result:


问:
Compiling error when importing a custom library
I'm currently developing a library that use DevExtreme to show some grids.

I've created the library and this is what the project package.json looks like:

```<code>"dependencies": {
    "@angular/animations": "^8.2.14",
    "@angular/common": "^8.2.14",
    "@angular/compiler": "^8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "^8.2.14",
    "@angular/platform-browser": "^8.2.14",
    "@angular/platform-browser-dynamic": "^8.2.14",
    "@angular/router": "^8.2.14",
    "devextreme": "18.2.8",
    "devextreme-angular": "18.2.8",
    "rxjs": "^6.5.2",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1",
    "jquery": "3.4.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.19",
    "@angular-devkit/build-ng-packagr": "~0.803.19",
    "@angular/cli": "^8.3.25",
    "@angular/compiler-cli": "^8.2.14",
    "@angular/language-service": "^8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "ng-packagr": "^5.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tsickle": "^0.37.0",
    "tslint": "~5.15.0",
    "typescript": "^3.5.3"
  }
</code>```

This is the library's package.json

```<code>{
  "name": "data-grid-lib",
  "version": "0.0.1",
  "peerDependencies": {
  }
}
</code>```

This is the module:

```<code>@NgModule({
  declarations: [DataGridLibComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    DxDataGridModule,
    DxTextBoxModule
  ],
  exports: [DataGridLibComponent]
})
export class DataGridLibModule {
  public static forRoot(config): ModuleWithProviders<DataGridLibModule> {
    return {
      ngModule: DataGridLibModule,
      providers: [DataGridLibService, {provide: DataGridServiceConfig, useValue: config}]
    };
  }
}
</code>```

The code stuff is irrelevant.
If I build this library and import it into a project it gives me this error :

ERROR in The target entry-point "data-grid-lib" has missing
  dependencies:
   - devextreme/data/custom_store
   - devextreme-angular

The solution to solve this error is simple yet non-sense to me:

Install the devExtreme dependencies into the project as well.

What I'm not getting is this:

The library holds the DevExtreme logic, the project doesn't. So am I doing something wrong or both the library and the project must have the same dependencies?

package.json of the test project where I get the error:

```<code>"dependencies": {
    "@angular/animations": "^9.0.0",
    "@angular/common": "~9.0.0-rc.9",
    "@angular/compiler": "~9.0.0-rc.9",
    "@angular/core": "~9.0.0-rc.9",
    "@angular/forms": "~9.0.0-rc.9",
    "@angular/platform-browser": "~9.0.0-rc.9",
    "@angular/platform-browser-dynamic": "~9.0.0-rc.9",
    "@angular/router": "~9.0.0-rc.9",
    "ngx-toastr": "^12.0.0",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.0-rc.10",
    "@angular/cli": "~9.0.0-rc.10",
    "@angular/compiler-cli": "~9.0.0-rc.9",
    "@angular/language-service": "~9.0.0-rc.9",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.2",
    "toastr": "^2.1.4",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.7.4"
  }
</code>```

答:
I think you have installed devextreme-angular but you didn't install it's dependencies.
try installing dependencies using npm install devextreme@19.2. Here i'm using current version. I think that should solve your problem.

Body:
I'm currently developing a library that use DevExtreme to show some grids.

I've created the library and this is what the project package.json looks like:

"dependencies": {
    "@angular/animations": "^8.2.14",
    "@angular/common": "^8.2.14",
    "@angular/compiler": "^8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "^8.2.14",
    "@angular/platform-browser": "^8.2.14",
    "@angular/platform-browser-dynamic": "^8.2.14",
    "@angular/router": "^8.2.14",
    "devextreme": "18.2.8",
    "devextreme-angular": "18.2.8",
    "rxjs": "^6.5.2",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1",
    "jquery": "3.4.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.19",
    "@angular-devkit/build-ng-packagr": "~0.803.19",
    "@angular/cli": "^8.3.25",
    "@angular/compiler-cli": "^8.2.14",
    "@angular/language-service": "^8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "ng-packagr": "^5.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tsickle": "^0.37.0",
    "tslint": "~5.15.0",
    "typescript": "^3.5.3"
  }

This is the library's package.json

{
  "name": "data-grid-lib",
  "version": "0.0.1",
  "peerDependencies": {
  }
}

This is the module:

@NgModule({
  declarations: [DataGridLibComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    DxDataGridModule,
    DxTextBoxModule
  ],
  exports: [DataGridLibComponent]
})
export class DataGridLibModule {
  public static forRoot(config): ModuleWithProviders<DataGridLibModule> {
    return {
      ngModule: DataGridLibModule,
      providers: [DataGridLibService, {provide: DataGridServiceConfig, useValue: config}]
    };
  }
}

The code stuff is irrelevant.
If I build this library and import it into a project it gives me this error :

ERROR in The target entry-point "data-grid-lib" has missing
  dependencies:
   - devextreme/data/custom_store
   - devextreme-angular

The solution to solve this error is simple yet non-sense to me:

Install the devExtreme dependencies into the project as well.

What I'm not getting is this:

The library holds the DevExtreme logic, the project doesn't. So am I doing something wrong or both the library and the project must have the same dependencies?

package.json of the test project where I get the error:

"dependencies": {
    "@angular/animations": "^9.0.0",
    "@angular/common": "~9.0.0-rc.9",
    "@angular/compiler": "~9.0.0-rc.9",
    "@angular/core": "~9.0.0-rc.9",
    "@angular/forms": "~9.0.0-rc.9",
    "@angular/platform-browser": "~9.0.0-rc.9",
    "@angular/platform-browser-dynamic": "~9.0.0-rc.9",
    "@angular/router": "~9.0.0-rc.9",
    "ngx-toastr": "^12.0.0",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.0-rc.10",
    "@angular/cli": "~9.0.0-rc.10",
    "@angular/compiler-cli": "~9.0.0-rc.9",
    "@angular/language-service": "~9.0.0-rc.9",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.2",
    "toastr": "^2.1.4",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.7.4"
  }


问:
What's the string equivalent of np.nan?
I have a dataframe, and want to add a blank column. If it's for numbers, I would use df["new_column"] = pd.np.nan. But what if I want the column to (a) hold strings, and (b) be filterable with pd.isnull()? Is there a better idea than df["new_column"] = ""?

答:
It is my understanding that Python doesn't have a Null string. Python does have a None value but it isn't a string it is A None that can be applied to all variables - not just those which are originally defined as a string.

You could use NoneType but the column would then not be a string but an object type. You could still insert strings in the column, but changing the type of the column to string would simply consider None values as the string 'None'

please see this too: What is the difference between NaN and None?

```<code>test_df = pd.DataFrame(data={'numbers_column':np.nan,
                             'strings_column':[None, None, None,'random_str']},
                              index=[1,2,3, 4])
</code>```

Hope this helps.

Title: What's the string equivalent of np.nan?

Body:
It is my understanding that Python doesn't have a Null string. Python does have a None value but it isn't a string it is A None that can be applied to all variables - not just those which are originally defined as a string.

You could use NoneType but the column would then not be a string but an object type. You could still insert strings in the column, but changing the type of the column to string would simply consider None values as the string 'None'

please see this too: What is the difference between NaN and None?

test_df = pd.DataFrame(data={'numbers_column':np.nan,
                             'strings_column':[None, None, None,'random_str']},
                              index=[1,2,3, 4])

Hope this helps.


问:
How to convert Python datetime dates to decimal/float years
I am looking for a way to convert datetime objects to decimal(/float) year, including fractional part. Example:

```<code>>>> obj = SomeObjet()
>>> obj.DATE_OBS
datetime.datetime(2007, 4, 14, 11, 42, 50)
</code>```

How do I convert datetime.datetime(2007, 4, 14, 11, 42, 50) to decimal years. By decimal format I mean the float value 2007.4523, where the fractional part is the number of seconds from the beginning of the year (2007-01-01 till 2007-04-14), divided by the total number of seconds in that year (2007-01-01 till 2008-01-01).

(NOTE: in statistical modeling (e.g. for linear regression), this is called "time index")

答:
If you want to include the minutes and seconds
use this:</p>

```<code>YearF=[(x.timetuple().tm_yday-1+x.timetuple().tm_hour/24+x.timetuple().tm_min/(60*24)+x.timetuple().tm_sec/(24*3600))/(365+((x.timetuple().tm_year//4)==(x.timetuple().tm_year/4)))+x.timetuple().tm_year for x in DateArray]
</code>```

Body:
I am looking for a way to convert datetime objects to decimal(/float) year, including fractional part. Example:

>>> obj = SomeObjet()
>>> obj.DATE_OBS
datetime.datetime(2007, 4, 14, 11, 42, 50)

How do I convert datetime.datetime(2007, 4, 14, 11, 42, 50) to decimal years. By decimal format I mean the float value 2007.4523, where the fractional part is the number of seconds from the beginning of the year (2007-01-01 till 2007-04-14), divided by the total number of seconds in that year (2007-01-01 till 2008-01-01).

(NOTE: in statistical modeling (e.g. for linear regression), this is called "time index")

Body:
If you want to include the minutes and seconds
use this:

YearF=[(x.timetuple().tm_yday-1+x.timetuple().tm_hour/24+x.timetuple().tm_min/(60*24)+x.timetuple().tm_sec/(24*3600))/(365+((x.timetuple().tm_year//4)==(x.timetuple().tm_year/4)))+x.timetuple().tm_year for x in DateArray]


答:
From memory you will need to do the following to get JS debugging in Visual Studio:

Ensure that Internet Explorer has script debugging enabled (somewhere in tools -> options) - this is the bit most people don't know about.

Then go into the .aspx and add a breakpoint by clicking in the left margin of the line of Javascript you want to debug.

Launch the website project in debug mode (F5) and hit the page using IE - your breakpoint should then hit.

As noted by other people you can use a host of other (usually better) tools that come with other browsers.

Title: JavaScript Debugging

Body:
I am using Visual Studio 2010 Express Developer edition. Developing a Website. I'm using JavaScript in my .aspx pages. How to put breakpoints in Javascript.

Any help is highly appreciated.

Thank You


问:
MFC EditBrowse control does not display the folder icon at runtime
I have a dialog type application that includes a MFC EditBrowse Control.  This control includes a folder/magnifier icon on the right side where the user is supposed to click to bring up a folder browser pop-up.

That folder/magnifier icon displays properly in the dialog editor within Visual Studio, but at runtime it displays as a plain flat button. It behaves properly otherwise - that is, the browser pop-up pops up and the selected folder is displayed when the user clicks OK.

When run with the debugger a message is displayed in the VS Output Window saying "Can't load bitmap: 4299".  That message is displayed after the CDialogEx::OnInitDialog() line within my OnInitDialog().

I've written test programs and they display the icon properly. I've also added additional EditBrowse controls in my original program, but they experience the same problem and just add another line of "can't load bitmap".  I've also added other MFC controls and some of them also do not display their icons (or other stuff).

I've managed to affect the problem slightly by making calls to EnableBrowseButton() and EnableFolderBrowswButton() from my OnInitDialog.  If I do that, I get an icon that looks like 3 horizontal dots:

which is better, but I'd prefer the folder/magnifier icon.

It's a complicated enough application I'd rather not re-write it from the beginning and furthermore I'd like to understand what is going on.  I'm fairly certain this is a result of adding/deleting controls as the app was developed, but don't have a good idea on where to begin tracking down where things went awry.

Thoughts on how to debug this? BTW, this is VS 2010.

答:
CMFCEditBrowseCtrl uses the Visual Manager to load the bitmap from MFC resources.

This resource is loaded in "afxribbon.rc"

Make sure the following these lines are included in the main *.rc file (this is how VS Wizard creates the *.rc file)

```<code>#if !defined(_AFXDLL)
#include "afxribbon.rc"   // MFC ribbon and control bar resources
#endif
</code>```

(I guess you can omit the #if/end statement, but it's probably there for a reason)

Alternatively, CMFCEditBrowseCtrl::SetBrowseButtonImage can be used to assign user icon.

Body:
CMFCEditBrowseCtrl uses the Visual Manager to load the bitmap from MFC resources.

This resource is loaded in "afxribbon.rc"

Make sure the following these lines are included in the main *.rc file (this is how VS Wizard creates the *.rc file)

#if !defined(_AFXDLL)
#include "afxribbon.rc"   // MFC ribbon and control bar resources
#endif

(I guess you can omit the #if/end statement, but it's probably there for a reason)

Alternatively, CMFCEditBrowseCtrl::SetBrowseButtonImage can be used to assign user icon.


问:
Can't save data from firestore event listener
Hello guys and thanks you for your time.

So in my app, I'm trying to fetch data in real time from my firestore database with a SnapshotListener and then save it in a global variable.
The fetching itself works fine, but when I try to save it into an array it fails. It says the array is empty afterwards.

Can you guys explain me what's wrong since I'm still starting on this firestore thing?

Here's the part of the code I think is helpfull:

```<code>// Get barbershops nearby from google firestore
        MainActivity.db.collection("barbershops")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot value,
                                        @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            Log.w(TAG, "Listen failed.", e);
                            return;
                        }

                        for (QueryDocumentSnapshot doc : value) {
                            Log.d(TAG, doc.getId() + " => " + doc.getData());
                            Barbershop bbs = doc.toObject(Barbershop.class);
                            barbershops.add(bbs);
                        }
                    }
                });

        progressBar.setVisibility(View.GONE);

        // Set up the recycler view
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);

        // use a linear layout manager
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        mAdapter = new MyAdapter(barbershops, getContext(), this);
        recyclerView.setAdapter(mAdapter);

        return view;
</code>```

and then I also have a global variable:

private ArrayList<Barbershop> barbershops;

Thanks!

答: addSnapshotListener is asynchronous and returns immediately.  The callback is invoked some time later with the results of the query.  That means barbershops won't be populated right away.  It's not clear from your question what "the array is empty afterwards" actually means, but if you try to use barbershops before the callback has been invoked, you will not see the data from those documents.  You should only use that list after the callback is invoked.

Body:
Hello guys and thanks you for your time.

So in my app, I'm trying to fetch data in real time from my firestore database with a SnapshotListener and then save it in a global variable.
The fetching itself works fine, but when I try to save it into an array it fails. It says the array is empty afterwards.

Can you guys explain me what's wrong since I'm still starting on this firestore thing?

Here's the part of the code I think is helpfull:

// Get barbershops nearby from google firestore
        MainActivity.db.collection("barbershops")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot value,
                                        @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            Log.w(TAG, "Listen failed.", e);
                            return;
                        }

                        for (QueryDocumentSnapshot doc : value) {
                            Log.d(TAG, doc.getId() + " => " + doc.getData());
                            Barbershop bbs = doc.toObject(Barbershop.class);
                            barbershops.add(bbs);
                        }
                    }
                });

        progressBar.setVisibility(View.GONE);

        // Set up the recycler view
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);

        // use a linear layout manager
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        mAdapter = new MyAdapter(barbershops, getContext(), this);
        recyclerView.setAdapter(mAdapter);

        return view;

and then I also have a global variable:

private ArrayList<Barbershop> barbershops;

Thanks!


问:
How do I use Object.entries(...).forEach.every?
I'm filtering a list using a const queryModifier = {price: "lessThan", weight: "greaterThan"}

const queryKeys = keys: {
      price: '1000',
      weight: '1000'
    }

const list = [
  {
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-11-05 10:48:18",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-11-08 10:46:37",
    "driver": "",
    "dropOff": "Kögel Trailer GmbH & Co. KG, Am Kögel-Werk, Burtenbach, Germany",
    "height": 0,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "7e249529-d089-47bb-b0ad-470f850dd8cf",
    "notes": "",
    "orderId": "",
    "pickUp": "Altenberge, Germany",
    "price": 500,
    "quantity": 1,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "engl. Anschlüsse",
    "vehicleId": "505123",
    "vehicleReadyDate": "2019-11-05 10:47:57",
    "weight": 0
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-10-14 16:32:12",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-10-19 16:26:35",
    "driver": "",
    "dropOff": "Marville-Moutiers-Brûlé, France",
    "height": 600,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "9b7f57fd-f95e-4038-b120-a0301fdf3f31",
    "notes": "",
    "orderId": "",
    "pickUp": "Altenberge, Germany",
    "price": 0,
    "quantity": 1,
    "trailer": "2er Pack",
    "vehicle": "Anhänger",
    "vehicleClass": "50",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-10-16 16:31:26",
    "weight": 12000
  },
  {
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-10-14 16:25:54",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-10-19 16:24:13",
    "driver": "",
    "dropOff": "Vendenheim, France",
    "height": 0,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "7e4f233f-695b-40eb-a0ca-fd78f3fa43cd",
    "notes": "",
    "orderId": "",
    "pickUp": "Altenberge, Germany",
    "price": 793,
    "quantity": 1,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "Standard",
    "vehicleId": "3340731",
    "vehicleReadyDate": "2019-10-15 16:24:58",
    "weight": 0
  },
  {
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-26 18:32:18",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-20 18:31:45",
    "driver": "Michal Kucharski",
    "dropOff": "Logroño, Spain",
    "height": 0,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "388113f5-3927-4fe3-80d5-f2fcf1c7cedd",
    "notes": "",
    "orderId": "",
    "pickUp": "16671 Butano Place, Fontana, CA, USA",
    "price": 0,
    "quantity": 1,
    "trailer": "2er Pack",
    "vehicle": "Sattel",
    "vehicleClass": "Standard",
    "vehicleId": "efgefg",
    "vehicleReadyDate": "2019-09-27 18:32:08",
    "weight": 0
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-06 22:57:55",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-07 22:57:03",
    "driver": "Eugeniusz Galinski",
    "dropOff": "12345 Lamplight Village Avenue, Austin, TX, USA",
    "height": 32,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "ac3cf14e-b43b-45e4-9168-ad4997b6415d",
    "notes": "Nzube I am adding notes here",
    "pickUp": "16671 Butano Place, Fontana, CA, USA",
    "price": 100,
    "quantity": 3,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "Mega",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-09-26 22:57:36",
    "weight": 12
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-06 22:46:25",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-06 22:45:45",
    "driver": "Michal Kucharski",
    "dropOff": "QEW, Niagara Falls, ON, Canada",
    "height": 67,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "d0ec3b82-2279-4d11-8e35-a9307713ae5a",
    "notes": "This is coming along",
    "pickUp": "Avenida Callao 1234, Buenos Aires, Argentina",
    "price": 100,
    "quantity": 1,
    "trailer": "2er Pack",
    "vehicle": "Sattel",
    "vehicleClass": "Mega",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-09-25 22:45:57",
    "weight": 12
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-04 18:06:18",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-05 18:05:51",
    "driver": "Chibuzo ilogu",
    "dropOff": "Asda Park Royal Superstore, Western Road, London, UK",
    "height": 453,
    "isPreparingTrailer": true,
    "isSmsSent": true,
    "isTrailerReady": true,
    "key": "96ee9410-4d70-4bbc-8016-5d7c9e5ecec1",
    "notes": "ewriupoi ",
    "pickUp": "Avenida Juan Bautista Alberdi 1233, Buenos Aires, Argentina",
    "price": 234,
    "quantity": 1,
    "trailer": "3er Pack",
    "vehicle": "Anhänger",
    "vehicleClass": "50",
    "vehicleId": "543",
    "vehicleReadyDate": "2019-09-21 18:06:03",
    "weight": 453
  },
  {
    "additionalPrices": 0,
    "companyName": "Test Company",
    "completeDate": "2019-09-04 18:02:27",
    "createdAt": "2019-09-04 18:01:30",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-04 18:01:09",
    "driver": "Chibuzo ilogu",
    "dropOff": "La Cabaña 123, Las Condes, Chile",
    "height": 123,
    "isPreparingTrailer": false,
    "isSmsSent": true,
    "isTrailerReady": true,
    "key": "bcd50f43-0644-49a7-8bdc-009a4572341b",
    "notes": "qewqe",
    "pickUp": "La Cabaña 123, Las Condes, Chile",
    "price": 123,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "Standard",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-10-02 18:01:19",
    "weight": 123
  }
];

export const handleFilterModifier = (value, compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
    }

    if (modifier === 'equals') {
        return value === compareValue;
    }

    if (modifier === 'greaterThan') {
        return value < compareValue;
    }

    return null;
};

const resultList = list.filter(
            item => Object.entries(queryModifiers).every(([filterKey, filterVal]) => {
                const compareValue = item[filterKey];
                const value = Object.values(queryKeys);
                const result = handleFilterModifier(
                    parseFloat(value),
                    compareValue,
                    filterVal
                );
                return result;
            })
        );
```

This operation fails when either of the queryModifiers has "equals" in its value pair. Anything else returns the actual true result. I don't understand why it fails on "equals".

I feel like there should be a forEach somewhere but I don't know where to put it and maybe there's something wrong with the code. I need help figuring it out.

答:
I think you should replace this

const queryKeys = keys: {
   price: '1000',
   weight: '1000'
}
```

<p>with </p>

<pre class="lang-js prettyprint-override"><code>const queryKeys = {
   price: '1000',
   weight: '1000'
}
</code>```

and replace this

const value = Object.values(queryKeys);
```

<p>with </p>

<pre class="lang-js prettyprint-override"><code>const value = queryKeys[filterKey];
</code>```

Body:
I'm filtering a list using a const queryModifier = {price: "lessThan", weight: "greaterThan"}

const queryKeys = keys: {
      price: '1000',
      weight: '1000'
    }

const list = [
  {
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-11-05 10:48:18",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-11-08 10:46:37",
    "driver": "",
    "dropOff": "Kögel Trailer GmbH & Co. KG, Am Kögel-Werk, Burtenbach, Germany",
    "height": 0,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "7e249529-d089-47bb-b0ad-470f850dd8cf",
    "notes": "",
    "orderId": "",
    "pickUp": "Altenberge, Germany",
    "price": 500,
    "quantity": 1,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "engl. Anschlüsse",
    "vehicleId": "505123",
    "vehicleReadyDate": "2019-11-05 10:47:57",
    "weight": 0
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-10-14 16:32:12",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-10-19 16:26:35",
    "driver": "",
    "dropOff": "Marville-Moutiers-Brûlé, France",
    "height": 600,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "9b7f57fd-f95e-4038-b120-a0301fdf3f31",
    "notes": "",
    "orderId": "",
    "pickUp": "Altenberge, Germany",
    "price": 0,
    "quantity": 1,
    "trailer": "2er Pack",
    "vehicle": "Anhänger",
    "vehicleClass": "50",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-10-16 16:31:26",
    "weight": 12000
  },
  {
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-10-14 16:25:54",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-10-19 16:24:13",
    "driver": "",
    "dropOff": "Vendenheim, France",
    "height": 0,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "7e4f233f-695b-40eb-a0ca-fd78f3fa43cd",
    "notes": "",
    "orderId": "",
    "pickUp": "Altenberge, Germany",
    "price": 793,
    "quantity": 1,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "Standard",
    "vehicleId": "3340731",
    "vehicleReadyDate": "2019-10-15 16:24:58",
    "weight": 0
  },
  {
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-26 18:32:18",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-20 18:31:45",
    "driver": "Michal Kucharski",
    "dropOff": "Logroño, Spain",
    "height": 0,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "388113f5-3927-4fe3-80d5-f2fcf1c7cedd",
    "notes": "",
    "orderId": "",
    "pickUp": "16671 Butano Place, Fontana, CA, USA",
    "price": 0,
    "quantity": 1,
    "trailer": "2er Pack",
    "vehicle": "Sattel",
    "vehicleClass": "Standard",
    "vehicleId": "efgefg",
    "vehicleReadyDate": "2019-09-27 18:32:08",
    "weight": 0
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-06 22:57:55",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-07 22:57:03",
    "driver": "Eugeniusz Galinski",
    "dropOff": "12345 Lamplight Village Avenue, Austin, TX, USA",
    "height": 32,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "ac3cf14e-b43b-45e4-9168-ad4997b6415d",
    "notes": "Nzube I am adding notes here",
    "pickUp": "16671 Butano Place, Fontana, CA, USA",
    "price": 100,
    "quantity": 3,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "Mega",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-09-26 22:57:36",
    "weight": 12
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-06 22:46:25",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-06 22:45:45",
    "driver": "Michal Kucharski",
    "dropOff": "QEW, Niagara Falls, ON, Canada",
    "height": 67,
    "isPreparingTrailer": false,
    "isSmsSent": false,
    "isTrailerReady": false,
    "key": "d0ec3b82-2279-4d11-8e35-a9307713ae5a",
    "notes": "This is coming along",
    "pickUp": "Avenida Callao 1234, Buenos Aires, Argentina",
    "price": 100,
    "quantity": 1,
    "trailer": "2er Pack",
    "vehicle": "Sattel",
    "vehicleClass": "Mega",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-09-25 22:45:57",
    "weight": 12
  },
  {
    "additionalPrices": 0,
    "clientOrderNumber": "N / A",
    "companyName": "Test Company",
    "createdAt": "2019-09-04 18:06:18",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-05 18:05:51",
    "driver": "Chibuzo ilogu",
    "dropOff": "Asda Park Royal Superstore, Western Road, London, UK",
    "height": 453,
    "isPreparingTrailer": true,
    "isSmsSent": true,
    "isTrailerReady": true,
    "key": "96ee9410-4d70-4bbc-8016-5d7c9e5ecec1",
    "notes": "ewriupoi ",
    "pickUp": "Avenida Juan Bautista Alberdi 1233, Buenos Aires, Argentina",
    "price": 234,
    "quantity": 1,
    "trailer": "3er Pack",
    "vehicle": "Anhänger",
    "vehicleClass": "50",
    "vehicleId": "543",
    "vehicleReadyDate": "2019-09-21 18:06:03",
    "weight": 453
  },
  {
    "additionalPrices": 0,
    "companyName": "Test Company",
    "completeDate": "2019-09-04 18:02:27",
    "createdAt": "2019-09-04 18:01:30",
    "createdBy": "test@test.com",
    "deliveryDate": "2019-09-04 18:01:09",
    "driver": "Chibuzo ilogu",
    "dropOff": "La Cabaña 123, Las Condes, Chile",
    "height": 123,
    "isPreparingTrailer": false,
    "isSmsSent": true,
    "isTrailerReady": true,
    "key": "bcd50f43-0644-49a7-8bdc-009a4572341b",
    "notes": "qewqe",
    "pickUp": "La Cabaña 123, Las Condes, Chile",
    "price": 123,
    "trailer": "einzeln",
    "vehicle": "Sattel",
    "vehicleClass": "Standard",
    "vehicleId": "123",
    "vehicleReadyDate": "2019-10-02 18:01:19",
    "weight": 123
  }
];

export const handleFilterModifier = (value, compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
    }

    if (modifier === 'equals') {
        return value === compareValue;
    }

    if (modifier === 'greaterThan') {
        return value < compareValue;
    }

    return null;
};

const resultList = list.filter(
            item => Object.entries(queryModifiers).every(([filterKey, filterVal]) => {
                const compareValue = item[filterKey];
                const value = Object.values(queryKeys);
                const result = handleFilterModifier(
                    parseFloat(value),
                    compareValue,
                    filterVal
                );
                return result;
            })
        );

This operation fails when either of the queryModifiers has "equals" in its value pair. Anything else returns the actual true result. I don't understand why it fails on "equals".

I feel like there should be a forEach somewhere but I don't know where to put it and maybe there's something wrong with the code. I need help figuring it out.

Body:
I think you should replace this

const queryKeys = keys: {
   price: '1000',
   weight: '1000'
}

with

const queryKeys = {
   price: '1000',
   weight: '1000'
}

and replace this

const value = Object.values(queryKeys);

with

const value = queryKeys[filterKey];


问:
Transforming a data frame with one column to many columns in R
Currently my data frame consists of 1 column with 2326 rows. I want to transform my data frame to consist of 11 rows. More specifically, my current data frame look like

```<code>John Doe
7
45
42
978
3
6
8
9
0
11
Sally Jenkins
2
</code>```

etc.

I want my data frame to look like:

```<code>John Doe        7  45  42  978  3  6  8  9  0  11
Sally Jenkins   2
</code>```

Each person is a row and then their statistics are each a separate column in the row. Some people are missing a statistic so I can not separate based on the number of rows between each person's name.

I have tried using t() as well as reshape(transform()). Do you have any suggestions on where to go next?

答:
Using DF defined reproducibly in the Note at the end, ensure that DF[[1]] is character.  Then use grep to create a logical variable g with one element per input row which is TRUE for each heading and FALSE otherwise.  Then remove the headings and and split it up using the setNames to set the names of the resulting list.  Finally convert each list component to a numeric ts series as such series can be cbind'ed even if they have different lengths.  Now cbind those together and transpose.  No packages are used.

```<code>DF[[1]] <- as.character(DF[[1]])
g <- grepl("\\D", DF[[1]])
s <- setNames(split(DF[[1]][!g], cumsum(g)[!g]), DF[[1]][g])
t(do.call("cbind", lapply(s, function(x) ts(as.numeric(x)))))
</code>```

giving:

```<code>              [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
John Doe         7   45   42  978    3    6    8    9    0    11
Sally Jenkins    2   NA   NA   NA   NA   NA   NA   NA   NA    NA
</code>```

Note

The input in reproducible form is assumed to be:

```<code>Lines <- "John Doe
7
45
42
978
3
6
8
9
0
11
Sally Jenkins
2"
DF <- read.table(text = Lines, as.is = TRUE, sep = ";")
</code>```

Body:
Currently my data frame consists of 1 column with 2326 rows. I want to transform my data frame to consist of 11 rows. More specifically, my current data frame look like

John Doe
7
45
42
978
3
6
8
9
0
11
Sally Jenkins
2

etc.

I want my data frame to look like:

John Doe        7  45  42  978  3  6  8  9  0  11
Sally Jenkins   2

Each person is a row and then their statistics are each a separate column in the row. Some people are missing a statistic so I can not separate based on the number of rows between each person's name.

I have tried using t() as well as reshape(transform()). Do you have any suggestions on where to go next?

Body:
Using DF defined reproducibly in the Note at the end, ensure that DF[[1]] is character.  Then use grep to create a logical variable g with one element per input row which is TRUE for each heading and FALSE otherwise.  Then remove the headings and and split it up using the setNames to set the names of the resulting list.  Finally convert each list component to a numeric ts series as such series can be cbind'ed even if they have different lengths.  Now cbind those together and transpose.  No packages are used.

DF[[1]] <- as.character(DF[[1]])
g <- grepl("\\D", DF[[1]])
s <- setNames(split(DF[[1]][!g], cumsum(g)[!g]), DF[[1]][g])
t(do.call("cbind", lapply(s, function(x) ts(as.numeric(x)))))

giving:

              [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
John Doe         7   45   42  978    3    6    8    9    0    11
Sally Jenkins    2   NA   NA   NA   NA   NA   NA   NA   NA    NA

Note

The input in reproducible form is assumed to be:

Lines <- "John Doe
7
45
42
978
3
6
8
9
0
11
Sally Jenkins
2"
DF <- read.table(text = Lines, as.is = TRUE, sep = ";")


问:
How to Copy twitter account image to server?
I am using the twitter api to access some account details. It's been made clear that you can easily get the twitter account image:

http://a0.twimg.com/profile_images/1260994338/P3030586-2_bigger.jpg

However, when i try to copy() this image in PHP to my local server it doesn't work. It seems you can't even ping the address as 'could not find host'.

How can I copy the twitter account image to my local server?

答:
```<code>$twitsImg ='http://a0.twimg.com/profile_images/1260994338/P3030586-2_bigger.jpg';

$twit=file_get_contents($twitsImg);
$new_img = basename($twitsImg);

file_put_contents($new_img,$twit);
</code>```


问:
Is it possible to write plugins for KeystoneJS?
I'm on a project where we are thinking of using KeystoneJS for our CMS.  One of the points I've been tasked with answering is whether KeystoneJS allows one to write custom plugins. I've googled and can't seem to find an answer, which would indicate that perhaps there is no way to do so.

I see that KeystoneJS has two plugins listed in their documentation, but I'm unclear whether they have a way for us to write our own.

Any info, or links to documentation or examples, would be most welcome!

答:
KeystoneJs has only list plugins support which you saw on documentation page

atTracking and byTracking.

at this time these only support to extend the list config before creating the list object internally. List plugins can be used to have reusable template fields and validation logic

above two plugin only adds two fields each. atTracking adds fields for tracking created and updated timestamp whereas byTracking adds user info for creation and updation of item.

keystone passes on full list of createlist listconfig parameter to the plugin, this plugin must return the full config for keystone to continue creating list.

EDIT

I found some examples which cane be used, will be adding to keystonejs-contrib packages.

IpTracking plugin which adds ip of person creating or updating the list -
https://github.com/MadeByMike/keystone-ip-tracking-plugin/blob/master/index.js

Access Control plugin, which helps define roles based access control
 - https://github.com/MadeByMike/keystone-access-control-demo/blob/master/plugin-access-control.js

both are made by core team member Mike Riethmuller - https://github.com/MadeByMike


问:
Getting unique hardware ID changes everytime C#
I want to make a program and sell it, so I was thinking to make some kind of licensing system. What I've found on google is this:

http://www.codeproject.com/Articles/28678/Generating-Unique-Key-Finger-Print-for-a-Computer

I am running Windows 7 (32 bit) in VirtualBox from Ubuntu. I get the same UID, but when I restart my Windows, I get a new UID. I am just thinking that some people will buy my program and they may run it from VirtualBox, so it would be a problem.

Do you guys have any suggestions?

Even if it's an easier way, but something that won't change even if I restart my VBox.

答:
Even if a lot of time has passed, I want to add a possible solution to this question, pointing out something that happened to me trying to generate a fingerprint with exactly that code and facing the same problem.

The identifier function retrieves only the first not-empty value of wmiProperty for each wmiClass. The first important thing you should be aware of is this: what is returned for every wmiClass might not belong to the same ManagementObject. Hence, if something changes to "not the first object", this might affect also your fingerprint.

Be advised that using Win32_DiskDrive as wmiClass is dangerous since plugging in a USB device often results in this device being recognized as the first one (instead of your hard drive), changing the fingerprint as you plug-in or out your device. Even if this doesn't happen, still one of the wmiProperty could be taken from your USB device if your main drive has it empty (e.g. the disk signature, which happened to me).

A possible solution to that would be excluding all USB devices by checking InterfaceType and excluding all those who match "USB", or at least that's what I did.


问:
division work and sum in jquery not work?
i have a datatable with checkbox and a button add, i want when i click on button add, console display salaire and prime and sold which calculate like that sold = (salaire / 24) + prime.

index.php

```<code><script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div id="form2">
<table class="table table-bordered" id="mytable">
  <tr>
    <th><input type="checkbox" id="check_all"></th>
    <th>nom</th>
    <th>salaire</th>
    <th>adresse</th>
    <th>prime</th>
  </tr>
  <tr>
    <td><input type="checkbox" class="checkbox"></td>
    <td>najib</td>
    <td>5000</td>
    <td>tihit</td>
    <td><input type="text" name="prime" class="form-control prime" value="0"></td>
  </tr>
  <tr>
    <td><input type="checkbox" class="checkbox"></td>
    <td>adil</td>
    <td>4000</td>
    <td>tagmast</td>
    <td><input type="text" name="prime" class="form-control prime" value="0"></td>
  </tr>
</table>
<div class="form-group col-md-offset-5 ">
  <button class="btn btn-success " type="submit" id="add">Pointage men</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
  $("#add").click(function(){
    var items = [];
    $("tr").each(function(i,r){
        let salaire = r.cells[2].innerText;
        let prime = $(r).find(".prime").val();
        let sold = ((salaire)/24) + prime;
        if ( i > 0 && $(r).find("input").first().prop("checked")){
           items.push({ "salaire" : salaire , "prime" : prime , "sold" : sold });
        }
    })
console.log(items);
  })
})
</script>
</code>```

答:
This happens since variables salaire and prime are actually returned in code as string and thus when you do this:

console.log( ('5000'/24) + '100' )```
</div>
</div>
</p>

<p>then answer is also returned as a string like <code>"208.33333333333334100"</code></p>

<p>So, you just need to convert them to integer first and it should work fine like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let salaire = '5000'
let prime = '100'
let sold = ((+salaire) / 24) + +prime;
console.log(sold)</code>```

Body:
i have a datatable with checkbox and a button add, i want when i click on button add, console display salaire and prime and sold which calculate like that sold = (salaire / 24) + prime.

index.php

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <input type="checkbox" id="check_all">
    nom
    salaire
    adresse
    prime

    <input type="checkbox" class="checkbox">
    najib
    5000
    tihit
    <input type="text" name="prime" class="form-control prime" value="0">

    <input type="checkbox" class="checkbox">
    adil
    4000
    tagmast
    <input type="text" name="prime" class="form-control prime" value="0">

  <button class="btn btn-success " type="submit" id="add">Pointage men</button>

Body:
This happens since variables salaire and prime are actually returned in code as string and thus when you do this:

console.log( ('5000'/24) + '100' )

then answer is also returned as a string like "208.33333333333334100"

So, you just need to convert them to integer first and it should work fine like:

let salaire = '5000'
let prime = '100'
let sold = ((+salaire) / 24) + +prime;
console.log(sold)


问:
Converting equatorial to alt-az coordinates is very slow
I'm trying to convert the equatorial coordinates of an object to alt-az coordinates for a given time & location in (hopefully) <5 sec runtime, or more ideally, <1 sec runtime.

Following the astropy tutorial for coordinate transformations, I set up the following code:

```<code>from astropy import units as u
from astropy.coordinates import SkyCoord,EarthLocation, AltAz
from astropy.time import Time

target = SkyCoord(9.81625*u.deg, 0.88806*u.deg, frame='icrs')

location = EarthLocation(lat='31d57.5m', lon='-111d35.8m', height=0*u.m)
obs_time = Time('2010-12-21 1:00')

alt_az_frame = AltAz(location=location, obstime=obs_time)
target_alt_az = target.transform_to(alt_az_frame)

print(target_alt_az.alt, target_alt_az.az)
</code>```

This code takes 20 seconds to run, almost all of which comes from the target.transform_to(alt_az_frame) line.

Is there a more appropriate way to use the transform_to function to speed up the code, or should I abandon using astropy altogether and write code from scratch? I understand there's a lot of extra functionality built into SkyCoord objects, much of which I likely don't need -- it's just convenient to use pre-built, standardized code.

答:
After some debugging, it seems that it happens because astropy.utils.iers.iers's conf.iers_auto_url is a bad url. Here is my simple solution for your problem.

```<code>from astropy.utils.iers.iers import conf
# The desired url may change in the future
conf.iers_auto_url = 'ftp://cddis.gsfc.nasa.gov/pub/products/iers/finals2000A.all'

# Run your code here
</code>```

Alternatively, you can do things like conf.remote_timeout = 0.1 or conf.auto_download = False(use backup data).

I couldn't find a document directly relevant to this issue but reading this page may help.  This problem was discussed in the issue. I think this problem happens of only certain versions of the library, so updating the library to the latest version could be a solution.

Body:
I'm trying to convert the equatorial coordinates of an object to alt-az coordinates for a given time & location in (hopefully) <5 sec runtime, or more ideally, <1 sec runtime.

Following the astropy tutorial for coordinate transformations, I set up the following code:

from astropy import units as u
from astropy.coordinates import SkyCoord,EarthLocation, AltAz
from astropy.time import Time

target = SkyCoord(9.81625*u.deg, 0.88806*u.deg, frame='icrs')

location = EarthLocation(lat='31d57.5m', lon='-111d35.8m', height=0*u.m)
obs_time = Time('2010-12-21 1:00')

alt_az_frame = AltAz(location=location, obstime=obs_time)
target_alt_az = target.transform_to(alt_az_frame)

print(target_alt_az.alt, target_alt_az.az)

This code takes 20 seconds to run, almost all of which comes from the target.transform_to(alt_az_frame) line.

Is there a more appropriate way to use the transform_to function to speed up the code, or should I abandon using astropy altogether and write code from scratch? I understand there's a lot of extra functionality built into SkyCoord objects, much of which I likely don't need -- it's just convenient to use pre-built, standardized code.

Body:
After some debugging, it seems that it happens because astropy.utils.iers.iers's conf.iers_auto_url is a bad url. Here is my simple solution for your problem.

from astropy.utils.iers.iers import conf
# The desired url may change in the future
conf.iers_auto_url = 'ftp://cddis.gsfc.nasa.gov/pub/products/iers/finals2000A.all'

# Run your code here

Alternatively, you can do things like conf.remote_timeout = 0.1 or conf.auto_download = False(use backup data).

I couldn't find a document directly relevant to this issue but reading this page may help.  This problem was discussed in the issue. I think this problem happens of only certain versions of the library, so updating the library to the latest version could be a solution.


问:
CSS - Fixed button on expanding
I am trying to make the search bar expand on device size < 768px. GIF Image.
How to fixed button when I click expand?

```<code>@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;

    .search-bar {
      max-width: 3em;
      margin-left: auto;

      &:focus-within {
        max-width: 100%;

        .search-bar__input {
          width: auto;
          padding: 0 1em;
        }
      }
    }

    .search-bar__input {
      width: 0;
      padding: 0;
    }
  }
}
</code>```

Here is my codepen:
https://codepen.io/phamtien990819/pen/PoqGwEv

答:
I suggest remove the line width:auto in &:focus-within .search-bar__input.
Moreover, you can add padding transition to .search-bar__input to make the transition smoother

```<code>@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;

    .search-bar {
      max-width: 3em;
      margin-left: auto;

      &:focus-within {
        max-width: 100%;

        .search-bar__input {
          /*Remove width: auto*/
          padding: 0 1em;
        }
      }
    }

    .search-bar__input {
      width: 0;
      padding: 0;

      /*Add padding transition*/
      transition: padding 3s
    }

    .search-bar__btn { }
  }
}
</code>```

Title: CSS - Fixed button on expanding

Body:
I am trying to make the search bar expand on device size < 768px. GIF Image.
How to fixed button when I click expand?

@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;

    .search-bar {
      max-width: 3em;
      margin-left: auto;

      &:focus-within {
        max-width: 100%;

        .search-bar__input {
          width: auto;
          padding: 0 1em;
        }
      }
    }

    .search-bar__input {
      width: 0;
      padding: 0;
    }
  }
}

Here is my codepen:
https://codepen.io/phamtien990819/pen/PoqGwEv

Body:
I suggest remove the line width:auto in &:focus-within .search-bar__input.
Moreover, you can add padding transition to .search-bar__input to make the transition smoother

@media (max-width: 768px) {
  .header-search {
    margin-left: 1em;

    .search-bar {
      max-width: 3em;
      margin-left: auto;

      &:focus-within {
        max-width: 100%;

        .search-bar__input {
          /*Remove width: auto*/
          padding: 0 1em;
        }
      }
    }

    .search-bar__input {
      width: 0;
      padding: 0;

      /*Add padding transition*/
      transition: padding 3s
    }

    .search-bar__btn { }
  }
}


答:
If you are using Web Developer Express you can do this within Visual Studio - here are the instructions.

If you are using a different Express edition, you will have to use a browser tool for client side debugging - for example Firebug. IE and Chrome have built in developer tools that have this kind of functionality.

Title: JavaScript Debugging


问:
How to send message by message to Kafka
I'm new to reactive programming and I try to implement a very basic scenario.
I want to send a message to kafka each time a file is dropped to a specific folder.
I think that I don't understand well the basics things... so please could you help me?

So I have a few questions :
What is the difference between smallrye-reactive-messaging and smallrye-reactive-streams-operators ?

I have this simple code :

```<code>@Outgoing( "my-topic" )
public PublisherBuilder<Message<MessageWrapper>> generate() {
     if(Objects.isNull(currentMessage)){
          //currentMessage is an instance variable which is null when I start the application
          return ReactiveStreams.of(new MessageWrapper()).map(Message::of);
     }
     else {
          //currentMessage has been correctly set with the file information
          LOGGER.info(currentMessage);
          return ReactiveStreams.of(currentMessage).map(Message::of);
     }
}
</code>```

When the code goes in the if statement, everything is ok and I got a JSON serialization of my object will null values. However I don't understand why when my code goes to the else statement, nothing goes to the topic? It seems that the .of instructions of the if statement has broke the streams or something like that...

How to keep a continuous streams that 'react' to the new dropped files ? (or other events like HTTP GET request or something like that) ...

If I don't return an instance of PublisherBuilder but an Integer for example, then my kafka topic will be populated by a very huge stream of Integer value. This is why examples are using some intervals when sending messages...

Should I use some CompletationStage or CompletableFuture ? RxJAva2? It's a bit confusing which lib to use (vertx, smallrye, rxjava2, microprofile, ...)

What are the differences between :

ReactiveStreams.fromCompletionStage

ReactiveStreams.fromProcessor

ReactiveStreams.fromPublisher

ReactiveStreams.fromSubscriber

Which one to use on which scenario ?

Thank you very much !

答:
Let's start with the difference between smallrye-reactive-messaging & smallrye-reactive-streams-operators: smallrye-reactive-streams-operators is the same as smallrye-reactive-messaging but in addition it has a support to MicroProfile-context-propagation. Since most reactive-messaging providers use Vert.x behind the scene, it will process your message in an event-loop style, which means it will run in separate thread. Sometimes you need to propagate some ctx from your base thread into the new thread (ex: populating CDI and Tx context to execute some JPA Entity manager logic). Here where ctx propagation help.

For method signatures. You can take a look at the official documentation of SmallRye-reactive-streams sections 3,4 & 5. Each one has a different use case. It is up to you which flavor do you want to use.

When to use what ? If you are not running within reactive context, you can use the below to send messages.

@Inject
      @Channel("my-channel")
      Emitter emitter;

For Message consumption you can use method signature like this :

@Incoming("channel-2")
      public CompletionStage doSomething(Message anEvent)

Or

@Incoming("channel-2")
      public void doSomething(String anEvent)

Hope that helps.

Title: How to send message by message to Kafka

Body:
I'm new to reactive programming and I try to implement a very basic scenario.
I want to send a message to kafka each time a file is dropped to a specific folder.
I think that I don't understand well the basics things... so please could you help me?

So I have a few questions :
What is the difference between smallrye-reactive-messaging and smallrye-reactive-streams-operators ?

I have this simple code :

@Outgoing( "my-topic" )
public PublisherBuilder<Message<MessageWrapper>> generate() {
     if(Objects.isNull(currentMessage)){
          //currentMessage is an instance variable which is null when I start the application
          return ReactiveStreams.of(new MessageWrapper()).map(Message::of);
     }
     else {
          //currentMessage has been correctly set with the file information
          LOGGER.info(currentMessage);
          return ReactiveStreams.of(currentMessage).map(Message::of);
     }
}

When the code goes in the if statement, everything is ok and I got a JSON serialization of my object will null values. However I don't understand why when my code goes to the else statement, nothing goes to the topic? It seems that the .of instructions of the if statement has broke the streams or something like that...

How to keep a continuous streams that 'react' to the new dropped files ? (or other events like HTTP GET request or something like that) ...

If I don't return an instance of PublisherBuilder but an Integer for example, then my kafka topic will be populated by a very huge stream of Integer value. This is why examples are using some intervals when sending messages...

Should I use some CompletationStage or CompletableFuture ? RxJAva2? It's a bit confusing which lib to use (vertx, smallrye, rxjava2, microprofile, ...)

What are the differences between :

ReactiveStreams.fromCompletionStage

ReactiveStreams.fromProcessor

ReactiveStreams.fromPublisher

ReactiveStreams.fromSubscriber

Which one to use on which scenario ?

Thank you very much !


问:
Printing integers in the ascending order recursively
Today, I have taken an exam, and there was a question:

Write a method which prints integer numbers in the ascending order recursively from 1 to n:

```<code>public class PrintIntegersAscendingOrder {

    static int counter = 0;
    public static void PrintIntegersAscendingOrder (int n)
    {
        if (n == 1)
        {

            System.out.printf("%d\n", ++counter);
        }
        else
        {
            System.out.printf("%d ", ++counter);
            PrintIntegersAscendingOrder(n-1);
        }

    }
    public static void main (String args[])
    {
        PrintIntegersAscendingOrder(5);
    }
}
</code>```

Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?

答:
Do it as follows:

```<code>public class Main {
    public static void printIntegersAscendingOrder(int n) {
        if (n == 0) {
            return;
        }
        printIntegersAscendingOrder(n - 1);
        System.out.printf("%d ", n);
    }

    public static void main(String args[]) {
        printIntegersAscendingOrder(5);
    }
}
</code>```

Output:

```<code>1 2 3 4 5
</code>```

As @RobOhRob has already pointed out, the counter defeats the purpose of recursion in your code. When you are calling a function recursively, you need to analyse three important things:

When to stop the recursive call

Processing before making the recursive call

Processing before making the recursive call

Since you are already decreasing the parameter by 1 and passing it to the method to call it recursively, you can simply make use of this parameter instead of creating an additional variable (e.g. counter).

Body:
Today, I have taken an exam, and there was a question:

Write a method which prints integer numbers in the ascending order recursively from 1 to n:

public class PrintIntegersAscendingOrder {

    static int counter = 0;
    public static void PrintIntegersAscendingOrder (int n)
    {
        if (n == 1)
        {

            System.out.printf("%d\n", ++counter);
        }
        else
        {
            System.out.printf("%d ", ++counter);
            PrintIntegersAscendingOrder(n-1);
        }

    }
    public static void main (String args[])
    {
        PrintIntegersAscendingOrder(5);
    }
}

Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?

Body:
Do it as follows:

public class Main {
    public static void printIntegersAscendingOrder(int n) {
        if (n == 0) {
            return;
        }
        printIntegersAscendingOrder(n - 1);
        System.out.printf("%d ", n);
    }

    public static void main(String args[]) {
        printIntegersAscendingOrder(5);
    }
}

Output:

1 2 3 4 5

As @RobOhRob has already pointed out, the counter defeats the purpose of recursion in your code. When you are calling a function recursively, you need to analyse three important things:

When to stop the recursive call

Processing before making the recursive call

Processing before making the recursive call

Since you are already decreasing the parameter by 1 and passing it to the method to call it recursively, you can simply make use of this parameter instead of creating an additional variable (e.g. counter).


问:
jQuery event after a PDF loads?
I have a modal dialog that allows users to generate a customized PDF. After they click a "Start" button, the page redirects with window.location to a controller, which then creates the PDF and returns it.

Because of how long it takes the PDF to return, I want to display a modal "Generating PDF" dialog that automatically closes once the PDF is complete and is returned.

The problem is I can't figure out how/when to execute that final function to close the "Generating PDF" dialog. Since the controller returns an application/pdf type, there is no document object event to attach to, right? What is the best way to do this?

答:
Thank you for your responses. @PGill was on the right track. I've simplified his approach:

User clicks the Start button

The "Generating PDF" modal dialog is displayed

An AJAX request is sent to Controller 1 to generate the PDF

Controller 1 creates the PDF (which takes 5-60 seconds), stores it in a secure location, and returns a unique key

The "Generating PDF" modal dialog is hidden

The browser is redirected to Controller 2 and sent the unique key

Controller 2 verifies the key, retrieves the PDF from the secure location, and returns it

The solution here was to separate the Generation of the PDF from the Download of the PDF into 2 steps, so that between them, the modal dialog can be hidden.

which verifies it, retrieves the PDF rom the secure location and returns it.

```<code>ShowModalDialog();

$.ajax({
  type: "GET",
  url: 'GeneratePDFReportForDownload?' + params,
  success: function (pdfkey, textStatus, jqXHR) {
      HideModalDialog();
      window.location = 'DownloadPDFReport?key=' + pdfkey;
  },
  async: true,
  datatype: 'json'
});
</code>```

Title: jQuery event after a PDF loads?

Body:
Thank you for your responses. @PGill was on the right track. I've simplified his approach:

User clicks the Start button

The "Generating PDF" modal dialog is displayed

An AJAX request is sent to Controller 1 to generate the PDF

Controller 1 creates the PDF (which takes 5-60 seconds), stores it in a secure location, and returns a unique key

The "Generating PDF" modal dialog is hidden

The browser is redirected to Controller 2 and sent the unique key

Controller 2 verifies the key, retrieves the PDF from the secure location, and returns it

The solution here was to separate the Generation of the PDF from the Download of the PDF into 2 steps, so that between them, the modal dialog can be hidden.

which verifies it, retrieves the PDF rom the secure location and returns it.

ShowModalDialog();

$.ajax({
  type: "GET",
  url: 'GeneratePDFReportForDownload?' + params,
  success: function (pdfkey, textStatus, jqXHR) {
      HideModalDialog();
      window.location = 'DownloadPDFReport?key=' + pdfkey;
  },
  async: true,
  datatype: 'json'
});


问:
multiplying 2 2d matrices and get a 3d matrix out
```<code>import numpy as np

a = np.array([[1,2],[3,4]])

print(a.shape)

c = np.array([[1,2,3]])

print(c.shape)

#wanted result multiplication of a*c would return 2,2,3 shape matrix

final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])

print(final.shape)
print(final)
</code>```

I would like to multiply two matrices with different shapes and basically get a result which would be a 3d matrix. I hope you get the pattern from the code. Is there any simple numpyic way for this? I would appreciate it.

Body:
import numpy as np

a = np.array([[1,2],[3,4]])

print(a.shape)

c = np.array([[1,2,3]])

print(c.shape)

#wanted result multiplication of a*c would return 2,2,3 shape matrix

final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])

print(final.shape)
print(final)

I would like to multiply two matrices with different shapes and basically get a result which would be a 3d matrix. I hope you get the pattern from the code. Is there any simple numpyic way for this? I would appreciate it.

Body:
Try np.einsum

out = np.einsum('ij,kl->klj',c,a)

Out[35]:
array([[[ 1,  2,  3],
        [ 2,  4,  6]],

       [[ 3,  6,  9],
        [ 4,  8, 12]]])

In [36]: out.shape
Out[36]: (2, 2, 3)


问:
Inconsistent event firing on mapbox zoomstart and zoomend
I'm working on mapbox js-gl, version 1.7.0. I have tied the showing and hiding of a crosshairs div on my page to the zoomstart and zoomend events.

```<code>map.on('zoomstart', function (e)
{
    $("#crosshairs-container").show();
    console.log("Zooming started...");
});

map.on('zoomend', function (e)
{
    $("#crosshairs-container").hide();
    console.log("Zooming finished...");
    var zoomLevel = map.getZoom();
    renderMap();
});
</code>```

The problem is: the referenced div doesn't appear and disappear reliably and consistently.

On desktop (Linux/Chrome): the mouse wheel's individual "incremental jumps" (most mice have them, if not all of the nowadays) are sometimes registered as the zoomend event, and sometimes not.
This means, that sometimes zooming finishes after one "wobble" of the mouse wheel - even though I'm still zooming by continuing to turn the mouse wheel. Other times, the zooming continues as I continue to turn the mouse wheel - the behaviour I'd expect.

On mobile (Android/Chrome): Similar behaviour, though, here, the crosshairs overlay pretty much disappears completely while zooming (in or out).

I have observed that, when zooming in and out (trying to reproduce and observe this behaviour) several times over the same part of the map (which has already loaded and added layers), the desktop seems to "find its groove", so to speak.

My question is: since it's rather unlikely that I have used the wrong events - I don't think this is a coding issue - has anyone else seen this behaviour ? Is this a hardware issue, in the sense that the pinch zoom on mobile does things "intermittently", as does a "incremental wobbles" mouse wheel ? So what - to the user - looks and feels continuous, is actually, behind the scenes, many inidividually triggered events "stitched together" ?

Incidentally, the drag events work flawlessly on desktop & mobile.

答:
I solved this issue by switching from the dragstart end dragend events to the movestart and moveend events. This seems to avoid all problems, including having to debounce or throttle the event handlers.
Thanks to @Steve Bennett for the tip.

Body:
I'm working on mapbox js-gl, version 1.7.0. I have tied the showing and hiding of a crosshairs div on my page to the zoomstart and zoomend events.

map.on('zoomstart', function (e)
{
    $("#crosshairs-container").show();
    console.log("Zooming started...");
});

map.on('zoomend', function (e)
{
    $("#crosshairs-container").hide();
    console.log("Zooming finished...");
    var zoomLevel = map.getZoom();
    renderMap();
});

The problem is: the referenced div doesn't appear and disappear reliably and consistently.

On desktop (Linux/Chrome): the mouse wheel's individual "incremental jumps" (most mice have them, if not all of the nowadays) are sometimes registered as the zoomend event, and sometimes not.
This means, that sometimes zooming finishes after one "wobble" of the mouse wheel - even though I'm still zooming by continuing to turn the mouse wheel. Other times, the zooming continues as I continue to turn the mouse wheel - the behaviour I'd expect.

On mobile (Android/Chrome): Similar behaviour, though, here, the crosshairs overlay pretty much disappears completely while zooming (in or out).

I have observed that, when zooming in and out (trying to reproduce and observe this behaviour) several times over the same part of the map (which has already loaded and added layers), the desktop seems to "find its groove", so to speak.

My question is: since it's rather unlikely that I have used the wrong events - I don't think this is a coding issue - has anyone else seen this behaviour ? Is this a hardware issue, in the sense that the pinch zoom on mobile does things "intermittently", as does a "incremental wobbles" mouse wheel ? So what - to the user - looks and feels continuous, is actually, behind the scenes, many inidividually triggered events "stitched together" ?

Incidentally, the drag events work flawlessly on desktop & mobile.


问:
Auto create directories after uploading with PHP
I'm creating a php site where a company will upload a lot of images. I'd like one folder to contain upto 500-1000 files and PHP automatically creates a new one if previous contains more that 1000 files.

For example, px300 has folder dir1 which stores 500 files, then a new one dir2 will be created.

Are there any existed a solutions?

答:
A common approach is to create one-letter directories based on the file name. This works particularly well if you assign random names to files (and random names are good to avoid name conflicts in user uploads):</p>

```<code>/files/a/c/acbd18db4cc2f85cedef654fccc4a4d8
/files/3/7/37b51d194a7513e45b56f6524f2d51f2
</code>```

Body:
A common approach is to create one-letter directories based on the file name. This works particularly well if you assign random names to files (and random names are good to avoid name conflicts in user uploads):

/files/a/c/acbd18db4cc2f85cedef654fccc4a4d8
/files/3/7/37b51d194a7513e45b56f6524f2d51f2