问:
Failed to build an existing application due to lack of jcenter certificate - blocked by gradle
I tried to build an andruid application using latest andruid studio
Seems that gradle is blocked due to lack of jcenter certificate in local machine certstore. My colleguee succeed to build it on his machine so the problem is in the configuration and not the application code

Configuration :  andruid studio 3.0.1, gradle 3.0.0 ?, windows 7

I also tried to workaround ssl handshake by replacing jcenter() in build.gradle with

```<code> maven {
            url  "http://jcenter.bintray.com"
        }
</code>```

but it didn't solve the problem

My build.gradle below:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Gradle console:

```<code>Executing tasks: [assemble]

Configuration on demand is an incubating feature.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'PDA'.
> Could not resolve all files for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:3.0.0.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:3.0.0.
         > Could not get resource 'http://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
            > Could not HEAD 'http://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
               > Connect to repo.jfrog.org:80 [repo.jfrog.org/52.72.224.151, repo.jfrog.org/34.204.33.255] failed: Connection timed out: connect
</code>```

答:
Besides as @GabrieleMariotti alreay said, that library will not be found at JCenter, you should not get Connection timed out: connect but a message that the library was not found.

Connection timed out: connect hints, that you cannot access that URL from your machine. My best guess is that you have to use some Proxy to access this URL that properly configured for your colleague, but not for you.

Body:
I tried to build an andruid application using latest andruid studio
Seems that gradle is blocked due to lack of jcenter certificate in local machine certstore. My colleguee succeed to build it on his machine so the problem is in the configuration and not the application code

Configuration :  andruid studio 3.0.1, gradle 3.0.0 ?, windows 7

I also tried to workaround ssl handshake by replacing jcenter() in build.gradle with

 maven {
            url  "http://jcenter.bintray.com"
        }

but it didn't solve the problem

My build.gradle below:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Gradle console:

Executing tasks: [assemble]

Configuration on demand is an incubating feature.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'PDA'.
> Could not resolve all files for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:3.0.0.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:3.0.0.
         > Could not get resource 'http://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
            > Could not HEAD 'http://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
               > Connect to repo.jfrog.org:80 [repo.jfrog.org/52.72.224.151, repo.jfrog.org/34.204.33.255] failed: Connection timed out: connect


来源: stackexchange

问:
Time delay for addChild in for loop is causing error! Swift
This loop I have works fine, but I want to have the images from the arrays come in one after the other with a specific set amount of time between them.

```<code>if transitionSprite.name == nil || transitionSprite.name == "rd-d2c" || transitionSprite.name == "rd-f2c" {
        for (index, roadImage) in cityArrays[randomIndex].enumerated() {

            roadSprite = SKSpriteNode(imageNamed: roadImage)
            roadSprite.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            roadSprite.position = CGPoint(x: 0, y: CGFloat(screenCounter) * roadSprite.size.height)
            roadSprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: self.size.height))
            roadSprite.physicsBody?.categoryBitMask = PhysicsCategory.RoadImageCategory.rawValue
            roadSprite.physicsBody?.collisionBitMask = PhysicsCategory.NoCollisionsCategory.rawValue
            roadSprite.physicsBody?.contactTestBitMask = PhysicsCategory.BroomCategory.rawValue
            roadSprite.physicsBody?.affectedByGravity = false

            roadSprite.zPosition = 1
            roadSprite.name = "Road \(index)"

            // RUNNING THE SKACTION DELAY ON THIS
            self.addChild(roadSprite)

            addCollectables()
            addJerryCans()

            if roadImage == "rdc-02_05" {
                addBackgroundDetail(detailType: "cityBridge2")
            }
            screenCounter += 1
        }
</code>```

I've created this SKAction which I've added to the loop,

```<code>    loopDelay = SKAction.wait(forDuration: Double(index + 1))
    let addRoad = SKAction.run {self.addChild(self.roadSprite)}
    let action = SKAction.sequence([loopDelay, addRoad])
    self.run(action)
</code>```

Not sure what would cause this, but when I run it with the SKAction delay I've created it crashes and gives me this error,

```<code>Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Attemped to add a SKNode which already has a parent:
<SKSpriteNode> name:'Road 4' texture:[<SKTexture> 'rdc-02_05' (750 x
1334)] position:{0, 6670} scale:{1.00, 1.00} size:{750, 1334}
anchor:{0.5, 0.5} rotation:0.00'
</code>```

Any ideas of why the delay would be causing this? Thanks

答:
Your problem is that you store roadSprite using a property. So at each iteration of the for-in loop you replace what's stored in that property with a new Sprite.

When each delay passes they will all try to addChild using the same Sprite (which is the last one you created), hence the first time it gets added and the second time it gives you the error above: "Attempted to add a SKNode which already has a parent".

What you want here is to create the sprite as a local variable instead and capture that variable in the SKAction.run closure:

```<code>let roadSprite = SKSpriteNode(imageNamed: roadImage)

...

let addRoad = SKAction.run {self.addChild(roadSprite)} //capture the local variable in your closure here
</code>```

If you still want a reference to all of these Sprites then maybe you should stick them into an array instead of overriding the same property.

ContentLicense: CC BY-SA 3.0

Body:
This loop I have works fine, but I want to have the images from the arrays come in one after the other with a specific set amount of time between them.

if transitionSprite.name == nil || transitionSprite.name == "rd-d2c" || transitionSprite.name == "rd-f2c" {
        for (index, roadImage) in cityArrays[randomIndex].enumerated() {

            roadSprite = SKSpriteNode(imageNamed: roadImage)
            roadSprite.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            roadSprite.position = CGPoint(x: 0, y: CGFloat(screenCounter) * roadSprite.size.height)
            roadSprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: self.size.height))
            roadSprite.physicsBody?.categoryBitMask = PhysicsCategory.RoadImageCategory.rawValue
            roadSprite.physicsBody?.collisionBitMask = PhysicsCategory.NoCollisionsCategory.rawValue
            roadSprite.physicsBody?.contactTestBitMask = PhysicsCategory.BroomCategory.rawValue
            roadSprite.physicsBody?.affectedByGravity = false

            roadSprite.zPosition = 1
            roadSprite.name = "Road \(index)"

            // RUNNING THE SKACTION DELAY ON THIS
            self.addChild(roadSprite)

            addCollectables()
            addJerryCans()

            if roadImage == "rdc-02_05" {
                addBackgroundDetail(detailType: "cityBridge2")
            }
            screenCounter += 1
        }

I've created this SKAction which I've added to the loop,

    loopDelay = SKAction.wait(forDuration: Double(index + 1))
    let addRoad = SKAction.run {self.addChild(self.roadSprite)}
    let action = SKAction.sequence([loopDelay, addRoad])
    self.run(action)

Not sure what would cause this, but when I run it with the SKAction delay I've created it crashes and gives me this error,

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Attemped to add a SKNode which already has a parent:
<SKSpriteNode> name:'Road 4' texture:[<SKTexture> 'rdc-02_05' (750 x
1334)] position:{0, 6670} scale:{1.00, 1.00} size:{750, 1334}
anchor:{0.5, 0.5} rotation:0.00'

Any ideas of why the delay would be causing this? Thanks

Body:
Your problem is that you store roadSprite using a property. So at each iteration of the for-in loop you replace what's stored in that property with a new Sprite.

When each delay passes they will all try to addChild using the same Sprite (which is the last one you created), hence the first time it gets added and the second time it gives you the error above: "Attempted to add a SKNode which already has a parent".

What you want here is to create the sprite as a local variable instead and capture that variable in the SKAction.run closure:

let roadSprite = SKSpriteNode(imageNamed: roadImage)

...

let addRoad = SKAction.run {self.addChild(roadSprite)} //capture the local variable in your closure here

If you still want a reference to all of these Sprites then maybe you should stick them into an array instead of overriding the same property.


问:
How we can Convert large size of decimal values to float and without exponential values
When I try to convert values from decimal to float, they are shown with exponential values

When I converted numeric to decimal values then they show with .00 fractional,
but I required only in numeric.

check blow mention query.

```<code>select  cast(CAST(435468867990778789.89 as decimal(35, 2))as float) as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select CAST(43546886799090787.89 as float)
</code>```

Above Query result are

```<code>4.35468867990779E+17
43546886799090787.00
43546886799090787.00
4.35468867990908E+16
</code>```

But I require a result like "435468867990778789.89".

答:
Could you try the below query?.

You might need a case statement for this

```<code>select case when ceiling(43546886799090787.89) = floor(43546886799090787.89)
       then      CONVERT(varchar, CAST(43546886799090787.89 as decimal))
       else      CONVERT(varchar, 43546886799090787.89)
       end
o/p --> 43546886799090787.89

select case when ceiling(43546886799090787.00) = floor(43546886799090787.00)
   then      CONVERT(varchar, CAST(43546886799090787.00 as decimal))
   else      CONVERT(varchar, 43546886799090787.00)
   end
o/p --> 43546886799090787
</code>```

If you want to round the value to nearest whole number, use the below script.

```<code>select  CAST(CAST(43546886799090787.89 AS decimal) AS varchar)
--O/P -> 43546886799090788
</code>```

Please check the script and let me know if you face any issues.

Body:
When I try to convert values from decimal to float, they are shown with exponential values

When I converted numeric to decimal values then they show with .00 fractional,
but I required only in numeric.

check blow mention query.

select  cast(CAST(435468867990778789.89 as decimal(35, 2))as float) as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select CAST(43546886799090787.89 as float)

Above Query result are

4.35468867990779E+17
43546886799090787.00
43546886799090787.00
4.35468867990908E+16

But I require a result like "435468867990778789.89".

Body:
Could you try the below query?.

You might need a case statement for this

select case when ceiling(43546886799090787.89) = floor(43546886799090787.89)
       then      CONVERT(varchar, CAST(43546886799090787.89 as decimal))
       else      CONVERT(varchar, 43546886799090787.89)
       end
o/p --> 43546886799090787.89

select case when ceiling(43546886799090787.00) = floor(43546886799090787.00)
   then      CONVERT(varchar, CAST(43546886799090787.00 as decimal))
   else      CONVERT(varchar, 43546886799090787.00)
   end
o/p --> 43546886799090787

If you want to round the value to nearest whole number, use the below script.

select  CAST(CAST(43546886799090787.89 AS decimal) AS varchar)
--O/P -> 43546886799090788

Please check the script and let me know if you face any issues.


问:
Visual Basic has stopped working vb6 window 10
I'm extremely new to this programming stuff and here is my problem.
Every time I open my VB6, I open a new project and select a Standard EXE, everything works totally fine.

I can add anything to from the toolbox to the form. But this error comes out everytime double click on the object (eg. button)

答: VB6 is in "It just works" state of support in Microsoft. You don't have to double click, Click once then drow the button with you mouse pressed on the form</p>


问:
Django MongoEngine CORS Error
I'm using django 1.11.7 and I've installed django-cors-hearders. I've been trying to send custom headers in POST request to my DRF application but I'm getting the following error:

Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:3000' is therefore not allowed
  access. The response had HTTP status code 400

localhost:3000 is where the calling application is hosted.
The javascript POST request has the following headers:

```<code>headers.append('Access-Control-Allow-Origin','*');
headers.append("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
headers.append("Access-Control-Allow-Headers","Origin, header-one, X-Requested-With, Content-Type, Accept, Authorization, If-Modified-Since, Cache-Control, Pragma");
headers.append('Content-Type', 'application/json');
headers.append('header-one', "value@123");
</code>```

I have tried the following:

1) Modified my django app views function

```<code>if str(request.method).lower() == 'options':
        headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "HTTP_HEADER_ONE"
        }
        return Response({}, headers=headers, status=status.HTTP_200_OK)
</code>```

2) Commented out this line in MIDDLEWARE = [...] of settings.py:

```<code>'django.middleware.clickjacking.XFrameOptionsMiddleware'
</code>```

because apparently it intereferes with the cors middleware.

3) Added the following code to settings.py

```<code>INSTALLED_APPS = [....
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
</code>```

4) CORS configuration:

```<code>CORS_ORIGIN_ALLOW_ALL = True

from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = default_headers + (
    'header-one',
)
</code>```

And now I get this error:

Request header field Access-Control-Allow-Origin is not allowed by
  Access-Control-Allow-Headers in preflight response.

5) Server configuration (in settings.py itself)

```<code>from connector import Server

def load_server_list():
    for s in SERVER_LIST:  # from CUSTOM_SETTINGS_MAPPINGS  # noqa
        server = (len(s) > 2) and unicode(s[2]) or None
        Server(host=unicode(s[0]), port=int(s[1]), server=server)
    Server.freeze()
load_server_list()
</code>```

This also throws an error saying 'no module named connector'. I did some more research related to 'connector' and apparently that's for MySQL type databases, but I'm using mongodb (mongoengine to work with django).

What am I doing wrong?

答:
I figured this out.

1) On the client side the headers should only include the custom headers which would make the code:

```<code>headers.append('Content-Type', 'application/json');
headers.append('header-one', "value@123");
</code>```

2) Make no changes in the django app views. So remove the following lines from your view function if it is there:

```<code>if str(request.method).lower() == 'options':
        headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "HTTP_HEADER_ONE"
        }
        return Response({}, headers=headers, status=status.HTTP_200_OK)
</code>```

3) Add these lines in your settings.py:

(to use CORS settings when running your django app)

```<code>INSTALLED_APPS = [....
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
</code>```

(for urls accessing your django app)

```<code>CORS_ORIGIN_ALLOW_ALL = True
</code>```

or

```<code>CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ('tuple of urls allowed to access your app')
</code>```

(for request object headers coming from the client side)

```<code>from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = default_headers + (
    'header-one',
)
</code>```

(for response object headers being sent to the client side)

```<code>CORS_EXPOSE_HEADERS = ['list of headers to send']
</code>```

4) load_server_list() function using connector.Server is not required

These headers will be accessible at your project level so every view function will not need to explicitly return a response for OPTIONS request. django-cors-headers takes care of it for you. For more explicit configuration settings check out: https://github.com/ottoyiu/django-cors-headers

Title: Django MongoEngine CORS Error

Body:
I'm using django 1.11.7 and I've installed django-cors-hearders. I've been trying to send custom headers in POST request to my DRF application but I'm getting the following error:

Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:3000' is therefore not allowed
  access. The response had HTTP status code 400

localhost:3000 is where the calling application is hosted.
The javascript POST request has the following headers:

headers.append('Access-Control-Allow-Origin','*');
headers.append("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
headers.append("Access-Control-Allow-Headers","Origin, header-one, X-Requested-With, Content-Type, Accept, Authorization, If-Modified-Since, Cache-Control, Pragma");
headers.append('Content-Type', 'application/json');
headers.append('header-one', "value@123");

I have tried the following:

1) Modified my django app views function

if str(request.method).lower() == 'options':
        headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "HTTP_HEADER_ONE"
        }
        return Response({}, headers=headers, status=status.HTTP_200_OK)

2) Commented out this line in MIDDLEWARE = [...] of settings.py:

'django.middleware.clickjacking.XFrameOptionsMiddleware'

because apparently it intereferes with the cors middleware.

3) Added the following code to settings.py

INSTALLED_APPS = [....
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]

4) CORS configuration:

CORS_ORIGIN_ALLOW_ALL = True

from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = default_headers + (
    'header-one',
)

And now I get this error:

Request header field Access-Control-Allow-Origin is not allowed by
  Access-Control-Allow-Headers in preflight response.

5) Server configuration (in settings.py itself)

from connector import Server

def load_server_list():
    for s in SERVER_LIST:  # from CUSTOM_SETTINGS_MAPPINGS  # noqa
        server = (len(s) > 2) and unicode(s[2]) or None
        Server(host=unicode(s[0]), port=int(s[1]), server=server)
    Server.freeze()
load_server_list()

This also throws an error saying 'no module named connector'. I did some more research related to 'connector' and apparently that's for MySQL type databases, but I'm using mongodb (mongoengine to work with django).

What am I doing wrong?

Body:
I figured this out.

1) On the client side the headers should only include the custom headers which would make the code:

headers.append('Content-Type', 'application/json');
headers.append('header-one', "value@123");

2) Make no changes in the django app views. So remove the following lines from your view function if it is there:

if str(request.method).lower() == 'options':
        headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "HTTP_HEADER_ONE"
        }
        return Response({}, headers=headers, status=status.HTTP_200_OK)

3) Add these lines in your settings.py:

(to use CORS settings when running your django app)

INSTALLED_APPS = [....
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]

(for urls accessing your django app)

CORS_ORIGIN_ALLOW_ALL = True

or

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ('tuple of urls allowed to access your app')

(for request object headers coming from the client side)

from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = default_headers + (
    'header-one',
)

(for response object headers being sent to the client side)

CORS_EXPOSE_HEADERS = ['list of headers to send']

4) load_server_list() function using connector.Server is not required

These headers will be accessible at your project level so every view function will not need to explicitly return a response for OPTIONS request. django-cors-headers takes care of it for you. For more explicit configuration settings check out: https://github.com/ottoyiu/django-cors-headers


问:
Can i set a breakpoint inside Qt itself?
As a sub-question to this, I want to know, since Qt5 is distributed with full source code, is it possible to set up debugger break-points inside Qt itself?

Is there a symbol file shipped with Qt5 for the binary build? Do I have to build my own Qt to do this?

What is the fastest way to have breakpoints inside Qt5 working with QtCreator on Ubuntu?

答:
You need to configure and build qt yourself with debug symbols. (-debug)

Then in QtCreator you can go to Options > Debugger > General and "Add the Qt-Sources".


问:
Angular 5 / Typescript - How to cast complex json object to a class
I'm trying to cast a complex (multiple type classes) json response object ( which i receive from my nodejs/mongoose backend) to a typescript class.

A moment class contains an author of type user and a comments array of type comment.

moment.model.ts

```<code>    import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    _author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    _comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;

    constructor(data?: Moment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

    public get author(): User {
        return this._author;
    }
    public set author(data: User) {
        this._author = new User(data);
    }

    public get comments(): Comment[] {
        return this._comments;
    }
    public set comments(data: Comment[]) {
        this._comments = data.map(c => new Comment(c));
    }
}
</code>```

comment.model.ts

```<code>    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}
</code>```

user.model.ts

```<code> export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;

    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }
</code>```

moment.service.ts

```<code>    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}
</code>```

moment-detail.component.ts

```<code>this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});
</code>```

When i call my service i assign the json to a new class of Moment. In the component i then try to print this.moment. Everything is fine except for the author and a comments which are null/empty.

答:
You can try something like

this[key]=( key=='_author' ? new User(data[key]):(key=='_comments'?new Comment(data[key]): data[key]))

Or

```<code>if(key=='_author')
    this[key]=new User(data[key]);
else if(key=='_comments')
    this[key]=new Comment(data[key]);
else
    this[key]=data[key]
</code>```

Body:
I'm trying to cast a complex (multiple type classes) json response object ( which i receive from my nodejs/mongoose backend) to a typescript class.

A moment class contains an author of type user and a comments array of type comment.

moment.model.ts

    import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    _author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    _comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;

    constructor(data?: Moment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

    public get author(): User {
        return this._author;
    }
    public set author(data: User) {
        this._author = new User(data);
    }

    public get comments(): Comment[] {
        return this._comments;
    }
    public set comments(data: Comment[]) {
        this._comments = data.map(c => new Comment(c));
    }
}

comment.model.ts

    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}

user.model.ts

 export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;

    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

moment.service.ts

    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}

moment-detail.component.ts

this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});

When i call my service i assign the json to a new class of Moment. In the component i then try to print this.moment. Everything is fine except for the author and a comments which are null/empty.

Body:
You can try something like

this[key]=( key=='_author' ? new User(data[key]):(key=='_comments'?new Comment(data[key]): data[key]))

Or

if(key=='_author')
    this[key]=new User(data[key]);
else if(key=='_comments')
    this[key]=new Comment(data[key]);
else
    this[key]=data[key]


问:
React has no exported member LinkHTMLAttributes

I am building a react application using vs2017 , npm and webpack.

I can't get vs to build my solution because of the error described in my title:

Error TS2694  Build:Namespace 'React' has no exported member
  'LinkHTMLAttributes'. SpyStore.React  C:\Work\Development\React\Spystore\SpyStore.React\SpyStore.React\node_modules\@types\react-router\lib\Link.d.ts 10

Js File : \node_modules\@types\react-router\lib\Link.d.ts

```<code>import * as React from 'react';
import Router from './Router';

declare const Link: Link;
type Link = Link.Link;

export default Link;

declare namespace Link {
    interface LinkProps extends React.LinkHTMLAttributes<Link> {
        activeStyle?: React.CSSProperties;
        activeClassName?: string;
        onlyActiveOnIndex?: boolean;
        to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor);
    }

    interface Link extends React.ComponentClass<LinkProps> {}
    interface LinkElement extends React.ReactElement<LinkProps> {}
}
</code>```

These are the dependencies and devdependencies inside my package.json:

```<code>"dependencies": {
    "jquery": "3.1.1",
    "react": "15.4.2",
    "react-dom": "15.4.2",
    "react-router": "3.0.2"
  },
  "devDependencies": {
    "@types/jquery": "1.10.31",
    "@types/react": "0.0.0",
    "@types/react-router": "^2.0.41",
    "typescript": "2.1.6",
    "tslint": "4.4.2",
    "webpack": "2.2.1",
    "webpack-dev-middleware": "1.10.0",
    "webpack-dev-server": "2.3.0",
    "webpack-md5-hash": "0.0.5",
    "webpack-merge": "2.6.1",
    "awesome-typescript-loader": "3.0.4-rc.2",
    "url-loader": "0.5.7",
    "ts-helpers": "1.1.2",
    "ts-loader": "2.0.0",
    "ts-node": "2.1.0",
    "tslint-loader": "3.3.0",
    "open-browser-webpack-plugin": "0.0.3",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.10.0",
    "html-loader": "0.4.4",
    "html-webpack-plugin": "2.28.0",
    "compression-webpack-plugin": "0.3.2",
    "copy-webpack-plugin": "4.0.1",
    "source-map-loader": "0.1.6"
  }
</code>```

I have tried to delete my node_modules and install them again.

Without success.
Any ideas how to solve this?

答:
Well, clearly I didn't search long enough.. Impatient me..

My visual studio didn't show any intellisense on the error, but after some trying I only had to update my react-router to a newer version ;)

Body:
I am building a react application using vs2017 , npm and webpack.

I can't get vs to build my solution because of the error described in my title:

Error TS2694  Build:Namespace 'React' has no exported member
  'LinkHTMLAttributes'. SpyStore.React  C:\Work\Development\React\Spystore\SpyStore.React\SpyStore.React\node_modules\@types\react-router\lib\Link.d.ts 10

Js File : \node_modules\@types\react-router\lib\Link.d.ts

import * as React from 'react';
import Router from './Router';

declare const Link: Link;
type Link = Link.Link;

export default Link;

declare namespace Link {
    interface LinkProps extends React.LinkHTMLAttributes<Link> {
        activeStyle?: React.CSSProperties;
        activeClassName?: string;
        onlyActiveOnIndex?: boolean;
        to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor);
    }

    interface Link extends React.ComponentClass<LinkProps> {}
    interface LinkElement extends React.ReactElement<LinkProps> {}
}

These are the dependencies and devdependencies inside my package.json:

"dependencies": {
    "jquery": "3.1.1",
    "react": "15.4.2",
    "react-dom": "15.4.2",
    "react-router": "3.0.2"
  },
  "devDependencies": {
    "@types/jquery": "1.10.31",
    "@types/react": "0.0.0",
    "@types/react-router": "^2.0.41",
    "typescript": "2.1.6",
    "tslint": "4.4.2",
    "webpack": "2.2.1",
    "webpack-dev-middleware": "1.10.0",
    "webpack-dev-server": "2.3.0",
    "webpack-md5-hash": "0.0.5",
    "webpack-merge": "2.6.1",
    "awesome-typescript-loader": "3.0.4-rc.2",
    "url-loader": "0.5.7",
    "ts-helpers": "1.1.2",
    "ts-loader": "2.0.0",
    "ts-node": "2.1.0",
    "tslint-loader": "3.3.0",
    "open-browser-webpack-plugin": "0.0.3",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.10.0",
    "html-loader": "0.4.4",
    "html-webpack-plugin": "2.28.0",
    "compression-webpack-plugin": "0.3.2",
    "copy-webpack-plugin": "4.0.1",
    "source-map-loader": "0.1.6"
  }

I have tried to delete my node_modules and install them again.

Without success.
Any ideas how to solve this?


问:
Laravel Delete function not work
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

```<code> public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}
</code>```

Model  :

```<code>protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}
</code>```

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

```<code>Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });
</code>```

答:
As others have suggested, you can use onDelete method to prevent the error. But I dont recommend to actually delete your records in the database.

You can use SoftDeletes to delete records by adding a deleted_at timestamp field to your table schema. Then all your queries will only fetch rows where deleted_at IS null

To enable this in your models, make sure that your tables has $table->softDeletes(). This will add the necessary deleted_at field to your tables.

Next, add the Illuminate\Database\Eloquent\SoftDeletes trait to your models like this.

```<code>use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Foo extends Model {
    use SoftDeletes;
}
</code>```

Aaannd, that's it! Every time you perform a query with Foo, all non-null deleted_at value will be ignored.

```<code>$foos = Foo::all();
</code>```

And whenever you perform delete(), it will simply update deleted_at to the current timestamp.

Title: Laravel Delete function not work

Body:
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

 public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}

Model  :

protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });

Body:
As others have suggested, you can use onDelete method to prevent the error. But I dont recommend to actually delete your records in the database.

You can use SoftDeletes to delete records by adding a deleted_at timestamp field to your table schema. Then all your queries will only fetch rows where deleted_at IS null

To enable this in your models, make sure that your tables has $table->softDeletes(). This will add the necessary deleted_at field to your tables.

Next, add the Illuminate\Database\Eloquent\SoftDeletes trait to your models like this.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Foo extends Model {
    use SoftDeletes;
}

Aaannd, that's it! Every time you perform a query with Foo, all non-null deleted_at value will be ignored.

$foos = Foo::all();

And whenever you perform delete(), it will simply update deleted_at to the current timestamp.


问:
inconsistent behaviour in jQuery selector
```<code>$('#a.b') // doesn't work

document.getElementById('a.b') // works

$('[id="a.b"]') // works
</code>```

Can anyone explain why $('#a.b') doesn't work.

答:
You should use the escaping operator as follows:

```<code>$('#a\\.b')
</code>```

jQuery does not allow meta-characters as a literal part of a name, and those must be escaped with two backslashes \\.

Body:
$('#a.b') // doesn't work

document.getElementById('a.b') // works

$('[id="a.b"]') // works

Can anyone explain why $('#a.b') doesn't work.

Body:
You should use the escaping operator as follows:

$('#a\\.b')

jQuery does not allow meta-characters as a literal part of a name, and those must be escaped with two backslashes \\.


问:
determinate which css is loaded with jQuery
I have html page that loads different css, depending on screen width (targeting pc, tablets and phones):

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 1200px)" href="css/desktop-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 769px) and (max-width: 1199px)" href="css/tablet-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 100px) and (max-width: 768px)" href="css/phone-style.css" >
</code>```

I heavily depend on jQuery, and functions should be chosen depending on active css. Is there a way in JavaScript of jQuery to determinate which css is active?
Or should I use jQuery to determinate browser width, and make further functions depending on width output?
Thank you.

答:
You can check if this thread helps.

You can also think of using media queries inside a css file and load the same file for different screen variants.

Body:
I have html page that loads different css, depending on screen width (targeting pc, tablets and phones):

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 1200px)" href="css/desktop-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 769px) and (max-width: 1199px)" href="css/tablet-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 100px) and (max-width: 768px)" href="css/phone-style.css" >

I heavily depend on jQuery, and functions should be chosen depending on active css. Is there a way in JavaScript of jQuery to determinate which css is active?
Or should I use jQuery to determinate browser width, and make further functions depending on width output?
Thank you.


问:
error in Generic
Why following code does not work?</p>

```<code>public void getData<T>(T ConnectionStirng)
{
    OleDbConnection con = new OleDbConnection(connectionString);  \\compile error
}
</code>```

答:
Because OleDbConnection expects a string and you've passed a T.

Looking at the code you don't actually need generics. Surely this is enough:

```<code>public void getData(string connectionString)
{
   OleDbConnection con = new OleDbConnection(connectionString);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: error in Generic

Body:
Why following code does not work?

public void getData<T>(T ConnectionStirng)
{
    OleDbConnection con = new OleDbConnection(connectionString);  \\compile error
}

Body:
Because OleDbConnection expects a string and you've passed a T.

Looking at the code you don't actually need generics. Surely this is enough:

public void getData(string connectionString)
{
   OleDbConnection con = new OleDbConnection(connectionString);
}


问:
Fancybox event is not fired
i have my login in a fancybox and fancybox div is in a controller. problem is if click the button nothing happens event isnt fired.
this is my controller.ascx

```<code><div id="inline1" style="width:400px;">
<ul class="forms">
    <li class="inputfield"><asp:TextBox ID="kullanıcı_adi" runat="server"></asp:TextBox></li>
</ul>
<ul>
    <li><asp:TextBox ID="sifre" runat="server"></asp:TextBox></li>
</ul>
<ul>
    <li>
        <asp:Button ID="Button1" runat="server" Text="Giriş Yap"
            onclick="Login_Authenticate" />
        <asp:Button ID="Button2" runat="server" Text="Vazgeç"/>
    </li>
</ul>
    </div>
</code>```

and this is my cotroller.ascx.cs

```<code>    protected void Login_Authenticate(object sender, EventArgs e)
    {
        bool authenticated = AuthenticateMe(kullanıcı_adi.Text, sifre.Text, true);

        if (authenticated)
        {
            FormsAuthentication.RedirectFromLoginPage(kullanıcı_adi.Text, true);
        }
    }
</code>```

and this is the default.aspx

```<code><li class="gallery"><a id="various1" href="#inline1">Üye ol/Giriş Yap</a></li>

<div style="display: none;">
    <co:c_login ID="id_c_login" runat="server" EnableViewState=true />
</div>
</code>```

I found the solution. Same question asked before.
Fancybox - ASP.NET button not working  Thank you for your answers.

答:
We can solve fancybox 2 event not firing issue by using parent property of fancybox.
for example -</p>

```<code>$("#buttonClick").fancybox({
            parent: "form:first",//Asp.net Button click event not working issue solved by using this statement
            ......your fancybox config options
        });
</code>```

Title: Fancybox event is not fired

Body:
i have my login in a fancybox and fancybox div is in a controller. problem is if click the button nothing happens event isnt fired.
this is my controller.ascx

<asp:TextBox ID="kullanıcı_adi" runat="server"></asp:TextBox>

<asp:TextBox ID="sifre" runat="server"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" Text="Giriş Yap"
            onclick="Login_Authenticate" />
        <asp:Button ID="Button2" runat="server" Text="Vazgeç"/>

and this is my cotroller.ascx.cs

    protected void Login_Authenticate(object sender, EventArgs e)
    {
        bool authenticated = AuthenticateMe(kullanıcı_adi.Text, sifre.Text, true);

        if (authenticated)
        {
            FormsAuthentication.RedirectFromLoginPage(kullanıcı_adi.Text, true);
        }
    }

and this is the default.aspx

Üye ol/Giriş Yap

    <co:c_login ID="id_c_login" runat="server" EnableViewState=true />

I found the solution. Same question asked before.
Fancybox - ASP.NET button not working  Thank you for your answers.

Body:
We can solve fancybox 2 event not firing issue by using parent property of fancybox.
for example -

$("#buttonClick").fancybox({
            parent: "form:first",//Asp.net Button click event not working issue solved by using this statement
            ......your fancybox config options
        });


问:
Symfony generate cdn friendly asset url
I have a symfony application that gets served by a cdn (eg. akamai) and I generate the asset url on the templates with:

```<code>{{ asset('myJs.js') }}
</code>```

When I do I want to generate a url like (supposing that the site is served by www.example.com) :

www.example.com/myJs.js?v=321321312312

Where the v parameter get a deployed version in order to force cdn (eg. akamai network) to cache me newer version. Is it a good way to dynamically generate the v parameter?

Title: Symfony generate cdn friendly asset url

Body:
I have a symfony application that gets served by a cdn (eg. akamai) and I generate the asset url on the templates with:

{{ asset('myJs.js') }}

When I do I want to generate a url like (supposing that the site is served by www.example.com) :

www.example.com/myJs.js?v=321321312312

Where the v parameter get a deployed version in order to force cdn (eg. akamai network) to cache me newer version. Is it a good way to dynamically generate the v parameter?

Body: src="www.example.com/myJs.js?v={{ random() }}"


问:
Better way of getting time in milliseconds in javascript?
Is there an alternative in JavaScript of getting time in milliseconds using the date object, or at least a way to reuse that object, without having to instantiate a new object every time I need to get this value? I am asking this because I am trying to make a simple game engine in JavaScript, and when calculating the "delta frame time", I have to create a new Date object every frame. While I am not too worried about the performance implications of this, I am having some problems with the reliability of the exact time returned by this object.

I get some strange "jumping" in the animation, every second or so, and I am not sure if this is related to JavaScript's Garbage Collection or a limitation of the Date object when updating so fast. If I set the delta value to some constant, then the animation if perfectly smooth, so I am fairly sure this "jumping" is related to the way I get the time.

The only relevant code I can give is the way I calculate the delta time :

```<code>prevTime = curTime;
curTime = (new Date()).getTime();
deltaTime = curTime - prevTime;
</code>```

When calculating movement / animation I multiply a constant value with the delta time.

If there is no way to avoid getting the time in milliseconds by using the Date object, would a function that increments a variable (being the elapsed time in milliseconds since the game started), and which is called using the SetTimer function at a rate of once every milliseconds be an efficient and reliable alternative?

Edit : I have tested now my code in different browsers and it seems that this "jump" is really only apparent in Chrome, not in Firefox. But it would still be nice if there were a method that worked in both browsers.

答:
If you have date object like

```<code>var date = new Date('2017/12/03');
</code>```

then there is inbuilt method in javascript for getting date in milliseconds format which is valueOf()

```<code>date.valueOf(); //1512239400000 in milliseconds format
</code>```

Body:
Is there an alternative in JavaScript of getting time in milliseconds using the date object, or at least a way to reuse that object, without having to instantiate a new object every time I need to get this value? I am asking this because I am trying to make a simple game engine in JavaScript, and when calculating the "delta frame time", I have to create a new Date object every frame. While I am not too worried about the performance implications of this, I am having some problems with the reliability of the exact time returned by this object.

I get some strange "jumping" in the animation, every second or so, and I am not sure if this is related to JavaScript's Garbage Collection or a limitation of the Date object when updating so fast. If I set the delta value to some constant, then the animation if perfectly smooth, so I am fairly sure this "jumping" is related to the way I get the time.

The only relevant code I can give is the way I calculate the delta time :

prevTime = curTime;
curTime = (new Date()).getTime();
deltaTime = curTime - prevTime;

When calculating movement / animation I multiply a constant value with the delta time.

If there is no way to avoid getting the time in milliseconds by using the Date object, would a function that increments a variable (being the elapsed time in milliseconds since the game started), and which is called using the SetTimer function at a rate of once every milliseconds be an efficient and reliable alternative?

Edit : I have tested now my code in different browsers and it seems that this "jump" is really only apparent in Chrome, not in Firefox. But it would still be nice if there were a method that worked in both browsers.

Body:
If you have date object like

var date = new Date('2017/12/03');

then there is inbuilt method in javascript for getting date in milliseconds format which is valueOf()

date.valueOf(); //1512239400000 in milliseconds format


问:
Alter data in object of arrays
In a React app, I have this type of data:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}
</code>```

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}
</code>```

I'm trying something like this, but it returns undefined instead of the altered data:

```<code>const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above
</code>```

https://jsfiddle.net/x5aspec2/

答:
Try using this way, it works:</p>

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
  let newObj = {}

    for(let key in data) {
        const objProp = data[key];
        newObj[key] = objProp.map((item, idx) => ({
              ...item,
              type: 'alert'
            }))
    }

  return newObj;
}

const result = expandData(data)
console.log(result)
</code>```

Title: Alter data in object of arrays

Body:
In a React app, I have this type of data:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}

I'm trying something like this, but it returns undefined instead of the altered data:

const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above

https://jsfiddle.net/x5aspec2/

Body:
Try using this way, it works:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
  let newObj = {}

    for(let key in data) {
        const objProp = data[key];
        newObj[key] = objProp.map((item, idx) => ({
              ...item,
              type: 'alert'
            }))
    }

  return newObj;
}

const result = expandData(data)
console.log(result)


问:
Is using a cached "this" faster than "this" when accessing methods of the same object?
if I access this.something multiple times from another method, would it be faster to cache "this" and access something() or should I just use this.something() over and over?</p>

```<code><script type="text/javascript">
var Foo = (function() {
    return {
        something: function() {
            // Do something
        },
        stuff: function(obj) {
            this.something(obj);
            // ...
            this.something(obj);

            /* OR should I cache this? */
            var $that = this;
            $that.something(obj);
            // ...
            $that.something(obj);
        }
    };
}());
</script>
</code>```

答: Only profiling will answer here. But before doing such micro-optimizations, ask yourself if you really need to.</p>


问:
Ignore all hidden div but not one in jQuery validation
I am using jQuery validation in my form
http://jqueryvalidation.org/documentation/

I want to add the validation to all my fields but I want to ignore the hidden div's that have the class my_item.

So here is my jQuery:

```<code> $("#myform").validate({
    ignore: ":hidden"
 });
</code>```

How is it possible to exclude from this ignore case, the divs that have the class my_item. So something like $(":hidden").not(.my_item).

答:
Accepted answer is perfectly fine but when you need some more control than the jQuery selector provides.
You could pass a function that tests each element.

for example:

```<code>ignore: function (index, el) {
   var $el = $(el);

   if ($el.hasClass('always-validate')) {
       return false;
   }

   // Default behavior
   return $el.is(':hidden');
},
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using jQuery validation in my form
http://jqueryvalidation.org/documentation/

I want to add the validation to all my fields but I want to ignore the hidden div's that have the class my_item.

So here is my jQuery:

 $("#myform").validate({
    ignore: ":hidden"
 });

How is it possible to exclude from this ignore case, the divs that have the class my_item. So something like $(":hidden").not(.my_item).

Body:
Accepted answer is perfectly fine but when you need some more control than the jQuery selector provides.
You could pass a function that tests each element.

for example:

ignore: function (index, el) {
   var $el = $(el);

   if ($el.hasClass('always-validate')) {
       return false;
   }

   // Default behavior
   return $el.is(':hidden');
},


问:
ng-repeat and ng-if to set value of td
I am trying to set td value based on condition, here is my code

```<code><td>
<span ng-init="tdValue=true;"></span>
<span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
<span ng-init="tdValue=false;">{{value.Completed}}</span>
</span>
<span ng-if="tdValue">0</span>
</td>
</code>```

In the following code I am checking
1. If the condition matches set the value to value.completed
2. If not keep default value as zero

But the result i am getting is
14 0

14 is value.completes and 0 is default value (Both the values are getting printed)

答:
Then you have to apply if condition on span tag in which you are using ng-repeat.</p>

```<code><td>
  <span ng-init="tdValue=true"></span>
  <span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
     <span ng-init="$parent.$parent.tdValue=false">{{value.Completed}}</span>
  </span>
  <span ng-if="tdValue==true">0</span>
</td>
</code>```

Title: ng-repeat and ng-if to set value of td

Body:
I am trying to set td value based on condition, here is my code

{{value.Completed}}

0

In the following code I am checking
1. If the condition matches set the value to value.completed
2. If not keep default value as zero

But the result i am getting is
14 0

14 is value.completes and 0 is default value (Both the values are getting printed)

Body:
Then you have to apply if condition on span tag in which you are using ng-repeat.

<td>
  <span ng-init="tdValue=true"></span>
  <span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
     <span ng-init="$parent.$parent.tdValue=false">{{value.Completed}}</span>
  </span>
  <span ng-if="tdValue==true">0</span>
</td>


问:
Background Location Update issue When I minimized my app
When I Minimized my app background location is not updating when it opens it will be updating.

While updating location after few minutes app gets restarted.

```<code>public  void onLocationChanged(Location location) {

    ArrayList<Activity> activities = new ArrayList<Activity>();

    activities.add(StartTravel.StartTravelActivity);

    boolean isAppRunning = false;
    for (Activity activity : activities) {
        if (activity != null)
            isAppRunning = true;
    }
    if (isAppRunning) {
        startLocationUpdates();
    }
    if (!isAppRunning) {
        startLocationUpdates();
    }
    curLat = location.getLatitude();
    curLng = location.getLongitude();
    curLat1 = location.getLatitude();
    curLng1 = location.getLongitude();

    if (curLat != 0.0 && curLng != 0.0) {
        callWebservice();
    }
    Log.e("IN","Track Location :: " + curLat + curLng);
//  boolean isInserted1 = myDb.INSERT(String.format("%.6f",location.getLatitude()),String.format("%.6f",location.getLongitude()));
}
</code>```

答: try to put your code in onPause().</p>

Body:
When I Minimized my app background location is not updating when it opens it will be updating.

While updating location after few minutes app gets restarted.

public  void onLocationChanged(Location location) {

    ArrayList<Activity> activities = new ArrayList<Activity>();

    activities.add(StartTravel.StartTravelActivity);

    boolean isAppRunning = false;
    for (Activity activity : activities) {
        if (activity != null)
            isAppRunning = true;
    }
    if (isAppRunning) {
        startLocationUpdates();
    }
    if (!isAppRunning) {
        startLocationUpdates();
    }
    curLat = location.getLatitude();
    curLng = location.getLongitude();
    curLat1 = location.getLatitude();
    curLng1 = location.getLongitude();

    if (curLat != 0.0 && curLng != 0.0) {
        callWebservice();
    }
    Log.e("IN","Track Location :: " + curLat + curLng);
//  boolean isInserted1 = myDb.INSERT(String.format("%.6f",location.getLatitude()),String.format("%.6f",location.getLongitude()));
}

Body: try to put your code in onPause().


问:
I can't install my npm package globally
I want to create npm package that can be installed globally. I can publish the package, publish new version, but when I want to install it globally, it is not working.

yarn global add <package> outputs:

```<code>success Installed "pentest-tool-lite@0.0.3" with binaries:
  - pentest-tool-lite
</code>```

npm install -g <package> outputs:

```<code>npm ERR! path /nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall chmod
npm ERR! enoent ENOENT: no such file or directory, chmod 'nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR! _logs/2017-12-03T16_00_34_926Z-debug.log
</code>```

debug log:

```<code>7877 info linkStuff pentest-tool-lite@0.0.3
7878 silly linkStuff pentest-tool-lite@0.0.3 has /Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules as its parent node_modules
7879 silly linkStuff pentest-tool-lite@0.0.3 is part of a global install
7880 silly linkStuff pentest-tool-lite@0.0.3 is installed into a global node_modules
7881 silly linkStuff pentest-tool-lite@0.0.3 is installed into the top-level global node_modules
7882 verbose linkBins pentest-tool-lite@0.0.3
7883 verbose linkBins [ { 'pentest-tool-lite': './lib/index' },
7883 verbose linkBins   '/Users/juffalow/.nvm/versions/node/v8.7.0/bin',
7883 verbose linkBins   true ]
7884 verbose linkMans pentest-tool-lite@0.0.3
7885 verbose unlock done using /Users/juffalow/.npm/_locks/staging-fa43d53d0ab27b11.lock for /Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/.staging
7886 verbose stack Error: ENOENT: no such file or directory, chmod '/Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index'
7887 verbose cwd /Users/juffalow/NetBeansProjects/pentest-tool-lite
7888 verbose Darwin 16.0.0
7889 verbose argv "/Users/juffalow/.nvm/versions/node/v8.7.0/bin/node" "/Users/juffalow/.nvm/versions/node/v8.7.0/bin/npm" "install" "-g" "pentest-tool-lite"
7890 verbose node v8.7.0
7891 verbose npm  v5.4.2
7892 error path /Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index
7893 error code ENOENT
7894 error errno -2
7895 error syscall chmod
7896 error enoent ENOENT: no such file or directory, chmod '/Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index'
7897 error enoent This is related to npm not being able to find a file.
7898 verbose exit [ -2, true ]
</code>```

Yarn seems to install it successfully, but not. NPM shows error but I really don't know why? Do you have any experience with module?

答:
Ok, I found the problem. When you want to publish global module to npm, you have to publish build version ( e.g. bin or lib folder ). I had this version but ignored in .gitignore because it need not to be in repo. And when you don't have .npmignore npm uses .gitignore file, so the module was published without build version, therefore without executable files.

Solution: add .npmignore file to the root of the project with:

```<code>node_modules/
coverage/
</code>```

Title: I can't install my npm package globally

Body:
I want to create npm package that can be installed globally. I can publish the package, publish new version, but when I want to install it globally, it is not working.

yarn global add <package> outputs:

success Installed "pentest-tool-lite@0.0.3" with binaries:
  - pentest-tool-lite

npm install -g <package> outputs:

npm ERR! path /nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall chmod
npm ERR! enoent ENOENT: no such file or directory, chmod 'nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR! _logs/2017-12-03T16_00_34_926Z-debug.log

debug log:

7877 info linkStuff pentest-tool-lite@0.0.3
7878 silly linkStuff pentest-tool-lite@0.0.3 has /Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules as its parent node_modules
7879 silly linkStuff pentest-tool-lite@0.0.3 is part of a global install
7880 silly linkStuff pentest-tool-lite@0.0.3 is installed into a global node_modules
7881 silly linkStuff pentest-tool-lite@0.0.3 is installed into the top-level global node_modules
7882 verbose linkBins pentest-tool-lite@0.0.3
7883 verbose linkBins [ { 'pentest-tool-lite': './lib/index' },
7883 verbose linkBins   '/Users/juffalow/.nvm/versions/node/v8.7.0/bin',
7883 verbose linkBins   true ]
7884 verbose linkMans pentest-tool-lite@0.0.3
7885 verbose unlock done using /Users/juffalow/.npm/_locks/staging-fa43d53d0ab27b11.lock for /Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/.staging
7886 verbose stack Error: ENOENT: no such file or directory, chmod '/Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index'
7887 verbose cwd /Users/juffalow/NetBeansProjects/pentest-tool-lite
7888 verbose Darwin 16.0.0
7889 verbose argv "/Users/juffalow/.nvm/versions/node/v8.7.0/bin/node" "/Users/juffalow/.nvm/versions/node/v8.7.0/bin/npm" "install" "-g" "pentest-tool-lite"
7890 verbose node v8.7.0
7891 verbose npm  v5.4.2
7892 error path /Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index
7893 error code ENOENT
7894 error errno -2
7895 error syscall chmod
7896 error enoent ENOENT: no such file or directory, chmod '/Users/juffalow/.nvm/versions/node/v8.7.0/lib/node_modules/pentest-tool-lite/lib/index'
7897 error enoent This is related to npm not being able to find a file.
7898 verbose exit [ -2, true ]

Yarn seems to install it successfully, but not. NPM shows error but I really don't know why? Do you have any experience with module?

Body:
Ok, I found the problem. When you want to publish global module to npm, you have to publish build version ( e.g. bin or lib folder ). I had this version but ignored in .gitignore because it need not to be in repo. And when you don't have .npmignore npm uses .gitignore file, so the module was published without build version, therefore without executable files.

Solution: add .npmignore file to the root of the project with:

node_modules/
coverage/


问:
How to allow only integers in a textbox?
In my form I want to allow typing of integer values only in a textbox. How to do that?</p>

答:
I would use ASP.NET Ajax Filter TextBoxExtender control

https://www.aspsnippets.com/Articles/ASPNet-AJAX-FilteredTextBoxExtender-Control-Example.aspx


问:
How to find a string in char Array without using string functions?(c++)
I have following code:

```<code>char x[30]="computer";
char y[30]="put";
</code>```

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

答:
Since you are using C++ you can use std::string:</p>

```<code>#include <string>
#include <iostream>

const std::string stringToSearch("computer");
const std::string stringToFind("put");

if (stringToSearch.find(stringToFind) == std::string::npos) {
    std::cout << "not found\n";
} else {
    std::cout << "found \n";
}
</code>```

Body:
I have following code:

char x[30]="computer";
char y[30]="put";

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

Body:
Since you are using C++ you can use std::string:

#include <string>
#include <iostream>

const std::string stringToSearch("computer");
const std::string stringToFind("put");

if (stringToSearch.find(stringToFind) == std::string::npos) {
    std::cout << "not found\n";
} else {
    std::cout << "found \n";
}


问:
Fatal error: Class 'PHPMailer' not found

I tried :include_once('C:\Inetpub\wwwroot\php\PHPMailer\PHPMailerAutoload.php');

Fatal error: Class 'PHPMailer' not found in C:\Inetpub\wwwroot\php\index.php on line 151

I place the PHPMailerAutoload.php in the same directory as my script.

Can someone help me with this ?

答:
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:</p>

```<code>use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';
</code>```

Body:
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';


问:
How to reference multiple files for javascript IntelliSense in VS2010
I have large solution with about 40 separate javascript files, which are referenced to web page via special js-service. I want to use new IntelliSense features in VS2010, but it is very hard to add about 40 individual references like this:

```<code>/// <reference path="../../lib/jquery-1.3.2.js" />
</code>```

to each js file in solution. Maybe there is some way to reference all files in folder? I've tried something like this:

```<code>/// <reference path="../../lib/*.*" />
</code>```

but it is not working...
Thanks.

Update:
Maybe there are some add-in, which could help with this?

答:
Add the references to one js file, ideally one that all the others rely on or use.  Then everywhere else, include a reference to just that one js file.

ie, file1.js contains:

```<code>/// <reference path="file2.js" />
/// <reference path="file3.js" />
...
/// <reference path="file40.js" />
</code>```

And every other file contains just one reference:

```<code>/// <reference path="file1.js" />
</code>```

Update for Visual Studio 2012:  You can now put global references in the _references.js file so that intellisense is available automatically in other js files.  You can also specify intellisense files in the tools dialog under "Tools" > "Options" > "Text Editor" > "JavaScript" > "Intellisense" > "References".

More detail in this blog post: JavaScript Intellisense in VS 2012, The _references.js File

Body:
I have large solution with about 40 separate javascript files, which are referenced to web page via special js-service. I want to use new IntelliSense features in VS2010, but it is very hard to add about 40 individual references like this:

/// <reference path="../../lib/jquery-1.3.2.js" />

to each js file in solution. Maybe there is some way to reference all files in folder? I've tried something like this:

/// <reference path="../../lib/*.*" />

but it is not working...
Thanks.

Update:
Maybe there are some add-in, which could help with this?

Body:
Add the references to one js file, ideally one that all the others rely on or use.  Then everywhere else, include a reference to just that one js file.

ie, file1.js contains:

/// <reference path="file2.js" />
/// <reference path="file3.js" />
...
/// <reference path="file40.js" />

And every other file contains just one reference:

/// <reference path="file1.js" />

Update for Visual Studio 2012:  You can now put global references in the _references.js file so that intellisense is available automatically in other js files.  You can also specify intellisense files in the tools dialog under "Tools" > "Options" > "Text Editor" > "JavaScript" > "Intellisense" > "References".

More detail in this blog post: JavaScript Intellisense in VS 2012, The _references.js File


问:
Double-Loop in msbuild?
I'm writing a script for msbuild which should make two batches in one step.

Example: 2 ItemGroups

```<code><ItemGroup>
 <GroupOne Include="1" />
 <GroupOne Include="2" />
</ItemGroup>

<ItemGroup>
 <GroupTwo Include="A" />
 <GroupTwo Include="B" />
</ItemGroup>
</code>```

These two groups should be looped within each other:

```<code><Message Text="%(GroupOne.Identity) %(GroupTwo.Identity)" />
</code>```

I hoped that msbuild makes the result up of both batches giving

```<code>1 A
2 A
1 B
2 B
</code>```

as result.

But that didn't happen. Instead, it returned the following useless crap:

```<code>1
2
  A
  B
</code>```

Doing it the way the blog from the link below proposes (using a local propertygroup) like

```<code><PropertyGroup>
  <GroupOneStep>%(GroupOne.Identity)</GroupOneStep>
</PropertyGroup>
<Message Text="$(GroupOneStep) %(GroupTwo.Identity)" />
</code>```

makes

```<code>2 A
2 B
</code>```

Any hints? I'm going mad. :-(

PS: Here's a blogpost about the topic - unfortunately it doesn't work as propsed there:
http://blogs.msdn.com/b/giuliov/archive/2010/04/30/gotcha-msbuild-nested-loops-double-batching.aspx

答:
For two nested loops this works:

```<code><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <ItemGroup>
        <GroupOne Include="1" />
        <GroupOne Include="2" />
    </ItemGroup>

    <ItemGroup>
        <GroupTwo Include="A" />
        <GroupTwo Include="B" />
    </ItemGroup>

    <Target Name="Exec"
        Outputs="%(GroupOne.Identity)">
        <Message Text="Building @(GroupOne->'%(Identity)') %(GroupTwo.Identity)"/>
    </Target>

</Project>
</code>```

Results in:

```<code>Project "D:\tmp\msbuildtest\test.xml" on node 0 (default targets).
  Building 1 A
  Building 1 B
Exec:
  Building 2 A
  Building 2 B
Done Building Project "D:\tmp\msbuildtest\test.xml" (default targets).
</code>```

Title: Double-Loop in msbuild?

Body:
I'm writing a script for msbuild which should make two batches in one step.

Example: 2 ItemGroups

<ItemGroup>
 <GroupOne Include="1" />
 <GroupOne Include="2" />
</ItemGroup>

<ItemGroup>
 <GroupTwo Include="A" />
 <GroupTwo Include="B" />
</ItemGroup>

These two groups should be looped within each other:

<Message Text="%(GroupOne.Identity) %(GroupTwo.Identity)" />

I hoped that msbuild makes the result up of both batches giving

1 A
2 A
1 B
2 B

as result.

But that didn't happen. Instead, it returned the following useless crap:

1
2
  A
  B

Doing it the way the blog from the link below proposes (using a local propertygroup) like

<PropertyGroup>
  <GroupOneStep>%(GroupOne.Identity)</GroupOneStep>
</PropertyGroup>
<Message Text="$(GroupOneStep) %(GroupTwo.Identity)" />

makes

2 A
2 B

Any hints? I'm going mad. :-(

PS: Here's a blogpost about the topic - unfortunately it doesn't work as propsed there:
http://blogs.msdn.com/b/giuliov/archive/2010/04/30/gotcha-msbuild-nested-loops-double-batching.aspx

Body:
For two nested loops this works:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <ItemGroup>
        <GroupOne Include="1" />
        <GroupOne Include="2" />
    </ItemGroup>

    <ItemGroup>
        <GroupTwo Include="A" />
        <GroupTwo Include="B" />
    </ItemGroup>

    <Target Name="Exec"
        Outputs="%(GroupOne.Identity)">
        <Message Text="Building @(GroupOne->'%(Identity)') %(GroupTwo.Identity)"/>
    </Target>

</Project>

Results in:

Project "D:\tmp\msbuildtest\test.xml" on node 0 (default targets).
  Building 1 A
  Building 1 B
Exec:
  Building 2 A
  Building 2 B
Done Building Project "D:\tmp\msbuildtest\test.xml" (default targets).


问:
Kivy - Editable RecycleView
I'm trying to create an editable table with the RecycleView widget using a TextInput widget as the individual element in Kivy. By looking at the examples and some posts on the web, I was able to write a table that takes input from the user.

Now I'm trying to get which row did the user edit. I could find events for on_text of the text input but that doesn't give information about the row number. Also I tried looking at the events available for the RecycleView but couldn't get much help from it.

Could anyone of you guide me in the right path. I'm fairly new to kivy. I have attached herewith, a simple example that I'm working on.

```<code>from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.lang import Builder

Builder.load_string('''
<Row@BoxLayout>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    itemText: ''
    TextInput:
        id:CellText
        text:root.itemText

<RV>:
    id: rv
    viewclass: 'Row'
    scroll_type: ['bars', 'content']
    scroll_wheel_distance: dp(114)
    bar_width: dp(10)
    RecycleGridLayout:
        cols:3
        default_size: None, dp(30)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        spacing: dp(1)
''')

class RV(RecycleView):

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'itemText':'1'}, {'itemText':'John'}, {'itemText':'K'}, {'itemText':'2'}, {'itemText':'David'}, {'itemText':'P'}]

class rvTestApp(App):

    def build(self):
        return RV()

if __name__ == '__main__':
    rvTestApp().run()
</code>```

答:
I don't know if the following is recommandable but, to do that when I add a box in the recycle view data i pass it the recycle view instance and when the box is created I add it to a list of the recycle view so you can control the rv from each box and you can control each box from the rv:</p>

```<code>from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty, ListProperty
from kivy.clock import Clock

Builder.load_string('''
<Row>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    itemText: ''
    TextInput:
        id:CellText
        text:root.itemText

<RV>:
    id: rv
    viewclass: 'Row'
    scroll_type: ['bars', 'content']
    scroll_wheel_distance: dp(114)
    bar_width: dp(10)
    RecycleGridLayout:
        cols:3
        default_size: None, dp(30)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        spacing: dp(1)
''')

class RV(RecycleView):
    list_items = ListProperty([])

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'itemText': '1', 'paren': self, 'index':0}, {'itemText': 'John', 'paren': self, 'index':1},
                 {'itemText': 'K', 'paren': self, 'index':2}, {'itemText': '2', 'paren': self, 'index':3},
                 {'itemText': 'David', 'paren': self, 'index':4}, {'itemText': 'P', 'paren': self, 'index':5}]

    def which_edit(self, *args):
        '''This will print the index of the box which is currently edited'''
        print args[0].parent.index

class Row(BoxLayout):
    paren = ObjectProperty() #the instance of the rv

    def __init__(self, **kwargs):
        super(Row, self).__init__(**kwargs)
        Clock.schedule_once(self.update)

    def update(self, *args):
        self.paren.list_items.append(self)
        self.ids.CellText.bind(text=self.paren.which_edit)

class TestApp(App):

    def build(self):
        return RV()

if __name__ == '__main__':
    TestApp().run()
</code>```

Title: Kivy - Editable RecycleView

Body:
I'm trying to create an editable table with the RecycleView widget using a TextInput widget as the individual element in Kivy. By looking at the examples and some posts on the web, I was able to write a table that takes input from the user.

Now I'm trying to get which row did the user edit. I could find events for on_text of the text input but that doesn't give information about the row number. Also I tried looking at the events available for the RecycleView but couldn't get much help from it.

Could anyone of you guide me in the right path. I'm fairly new to kivy. I have attached herewith, a simple example that I'm working on.

from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.lang import Builder

Builder.load_string('''
<Row@BoxLayout>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    itemText: ''
    TextInput:
        id:CellText
        text:root.itemText

<RV>:
    id: rv
    viewclass: 'Row'
    scroll_type: ['bars', 'content']
    scroll_wheel_distance: dp(114)
    bar_width: dp(10)
    RecycleGridLayout:
        cols:3
        default_size: None, dp(30)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        spacing: dp(1)
''')

class RV(RecycleView):

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'itemText':'1'}, {'itemText':'John'}, {'itemText':'K'}, {'itemText':'2'}, {'itemText':'David'}, {'itemText':'P'}]

class rvTestApp(App):

    def build(self):
        return RV()

if __name__ == '__main__':
    rvTestApp().run()

Body:
I don't know if the following is recommandable but, to do that when I add a box in the recycle view data i pass it the recycle view instance and when the box is created I add it to a list of the recycle view so you can control the rv from each box and you can control each box from the rv:

from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty, ListProperty
from kivy.clock import Clock

Builder.load_string('''
<Row>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    itemText: ''
    TextInput:
        id:CellText
        text:root.itemText

<RV>:
    id: rv
    viewclass: 'Row'
    scroll_type: ['bars', 'content']
    scroll_wheel_distance: dp(114)
    bar_width: dp(10)
    RecycleGridLayout:
        cols:3
        default_size: None, dp(30)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        spacing: dp(1)
''')

class RV(RecycleView):
    list_items = ListProperty([])

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'itemText': '1', 'paren': self, 'index':0}, {'itemText': 'John', 'paren': self, 'index':1},
                 {'itemText': 'K', 'paren': self, 'index':2}, {'itemText': '2', 'paren': self, 'index':3},
                 {'itemText': 'David', 'paren': self, 'index':4}, {'itemText': 'P', 'paren': self, 'index':5}]

    def which_edit(self, *args):
        '''This will print the index of the box which is currently edited'''
        print args[0].parent.index

class Row(BoxLayout):
    paren = ObjectProperty() #the instance of the rv

    def __init__(self, **kwargs):
        super(Row, self).__init__(**kwargs)
        Clock.schedule_once(self.update)

    def update(self, *args):
        self.paren.list_items.append(self)
        self.ids.CellText.bind(text=self.paren.which_edit)

class TestApp(App):

    def build(self):
        return RV()

if __name__ == '__main__':
    TestApp().run()


问:
Angular 5 / Typescript - How to cast complex json object to a class
I'm trying to cast a complex (multiple type classes) json response object ( which i receive from my nodejs/mongoose backend) to a typescript class.

A moment class contains an author of type user and a comments array of type comment.

moment.model.ts

```<code>    import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    _author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    _comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;

    constructor(data?: Moment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

    public get author(): User {
        return this._author;
    }
    public set author(data: User) {
        this._author = new User(data);
    }

    public get comments(): Comment[] {
        return this._comments;
    }
    public set comments(data: Comment[]) {
        this._comments = data.map(c => new Comment(c));
    }
}
</code>```

comment.model.ts

```<code>    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}
</code>```

user.model.ts

```<code> export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;

    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }
</code>```

moment.service.ts

```<code>    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}
</code>```

moment-detail.component.ts

```<code>this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});
</code>```

When i call my service i assign the json to a new class of Moment. In the component i then try to print this.moment. Everything is fine except for the author and a comments which are null/empty.

答: Your deserialize method in Moment is treating every field the same way and just copying the value from the JSON. This means it never constructs User or Comment objects. You should probably write it "by hand" to deal with each property correct, instead of using a loop.

Body:
I'm trying to cast a complex (multiple type classes) json response object ( which i receive from my nodejs/mongoose backend) to a typescript class.

A moment class contains an author of type user and a comments array of type comment.

moment.model.ts

    import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    _author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    _comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;

    constructor(data?: Moment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

    public get author(): User {
        return this._author;
    }
    public set author(data: User) {
        this._author = new User(data);
    }

    public get comments(): Comment[] {
        return this._comments;
    }
    public set comments(data: Comment[]) {
        this._comments = data.map(c => new Comment(c));
    }
}

comment.model.ts

    export class Comment {

    _id?: string = null;
    body?: string = null;
    moment?: any = null;
    author?: any = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    parent?: any = null;
    replies?: any = null;
    updated_at?: string = null;
    created_at?: string = null;

    constructor(data?: Comment) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Comment) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

}

user.model.ts

 export class User {

    _id?: string = null
    updated_at?: string = null;
    created_at?: string = null;
    profile?: any = null;
    phone?: any = null;
    email?: any = null;
    followers: any[] = [];
    following: any[] = [];
    isOnline: any = null;
    socketId: any = null;

    constructor(data?: User) {
        console.log(data);
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: User) {
        const keys = Object.keys(this);

        for (const key of keys) {
            if (data.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

moment.service.ts

    get(moment_id) {

    let endpoint = this.path + moment_id;

    return this.apiService.get(endpoint)
        .map((res) => new Moment(res.data));

}

moment-detail.component.ts

this.route.params.switchMap((params) => {
    let moment_id = params['id'];
    return this.momentService.get(moment_id);
}).subscribe((res) => {

    this.moment = res;
    console.log(this.moment);
});

When i call my service i assign the json to a new class of Moment. In the component i then try to print this.moment. Everything is fine except for the author and a comments which are null/empty.


问:
Import methods and their advantages
As far as I understand, in Python there are 3 ways to import:

from name_module import name_class

import name_module

from name_module import *

In all other ways, there is no point, as if this class is already in our module. But for some reason they do not recommend using the third way, explaining this by the fact that there is a possibility of a name conflict between the names of the imported module's class and the module in which we are located.

Why does this not happen when we import the 2nd way. After all, there and there is the import of the entire file and the creation of the same variables in our namespace or not?

What is better to use in what case?

答:
No. Python is not C or C++ where the compiler essentially copy-pastes included files to the top of the including code. import 'name_module' loads/adds a reference to name_module to the accessible namespace, and classes/methods/variables defined in it are accessed by name_module.name.

Choose what works best for you except for the "star import". Never choose the "star import". Why is "import *" bad?

Title: Import methods and their advantages