问:
Equations involving angle constraints
I'm trying to solve a system of equations using sympy.

from sympy import *
def get_angles(a, b, c, d):
    theta, phi, lamb = symbols('\\theta \\phi \\lambda', real=True)
    a_eq = Eq(cos(theta / 2), a)
    b_eq = Eq(exp(I * phi) * sin(theta / 2), b)
    c_eq = Eq(-exp(I * lamb) * sin(theta / 2), c)
    d_eq = Eq(exp(I * (phi + lamb)) * cos(theta / 2), d)
    # theta_constr1 = Eq(theta >= 0)
    # theta_constr2 = Eq(theta <= pi)
    # phi_constr1 = Eq(phi >= 0)
    # phi_constr2 = Eq(phi < 2 * pi)
    res = solve([
        a_eq, b_eq, c_eq, d_eq,
        #theta_constr1, theta_constr2, phi_constr1, phi_constr2,
    ],
        theta,
        phi,
        lamb,
        check=False,
        dict=True)
    return res
```

<p>The function returns the right results as it is, but it doesn't work if I try to put the constraint on the angles inside the system of equations (the commented parts). Is there any way to have them?</p>

<p>At the moment, I'm using a simple solution to overcome this limitation: I pass the result of the previous function to the following one to filter out unwanted results</p>

```def _final_constraint(result):
    res = []
    for sol in result:
        to_add = True
        for k, v in sol.items():
            if str(k) == '\\theta' and (v < 0 or v > pi):
                to_add = False
                break
            elif str(k) == '\\phi' and (v < 0 or v >= 2 * pi):
                to_add = False
                break
        if to_add:
            res.append(simplify(sol))
    return res
```

答:
Eq stands for Equality and is not an equation (though there is discussion of adding such an object to SymPy). So your uncommented Eq get interpreted as you intended, but the commented ones don't. You could try replacing theta_constr1 = Eq(theta >= 0) with theta_constr1 = theta >= 0 but then you will run into problems with the the inequality solver -- it complains about there being more than one symbol of interest amongst the inequalities. So what about re-writing the inequalities like x >= 0 as Eq(x + eps, 0) where eps is a nonnegative Symbol:

```<code>def get_angles(a, b, c, d):
    theta, phi, lamb = symbols('\\theta \\phi \\lambda', real=True)
    eps = Symbol('eps', nonnegative=True)
    a_eq = Eq(cos(theta / 2), a)
    b_eq = Eq(exp(I * phi) * sin(theta / 2), b)
    c_eq = Eq(-exp(I * lamb) * sin(theta / 2), c)
    d_eq = Eq(exp(I * (phi + lamb)) * cos(theta / 2), d)
    theta_constr1 = theta + eps
    theta_constr2 = pi - theta + eps
    phi_constr1 = phi  + eps
    phi_constr2 = 2 * pi - phi + eps
    res = solve([
        a_eq, b_eq, c_eq, d_eq,
        theta_constr1, theta_constr2, phi_constr1, phi_constr2,
        ],
        theta,
        phi,
        lamb,
        check=False,
        set=True)
    return res

>>> print(filldedent(get_angles(11,2,3,4)))

([\lambda, \phi, \theta], {(pi, 0, 4*pi - 2*acos(11)), (0, pi,
2*acos(11)), (0, pi, 4*pi - 2*acos(11)), (0, 0, 4*pi - 2*acos(11)),
(0, 0, 2*acos(11)), (pi, pi, 4*pi - 2*acos(11)), (pi, pi, 2*acos(11)),
(pi, 0, 2*acos(11))})
</code>```

You would have to work out which side of theta and phi -- if any -- satisfied your equations.

Title: Equations involving angle constraints

Body:
I'm trying to solve a system of equations using sympy.

from sympy import *
def get_angles(a, b, c, d):
    theta, phi, lamb = symbols('\\theta \\phi \\lambda', real=True)
    a_eq = Eq(cos(theta / 2), a)
    b_eq = Eq(exp(I * phi) * sin(theta / 2), b)
    c_eq = Eq(-exp(I * lamb) * sin(theta / 2), c)
    d_eq = Eq(exp(I * (phi + lamb)) * cos(theta / 2), d)
    # theta_constr1 = Eq(theta >= 0)
    # theta_constr2 = Eq(theta <= pi)
    # phi_constr1 = Eq(phi >= 0)
    # phi_constr2 = Eq(phi < 2 * pi)
    res = solve([
        a_eq, b_eq, c_eq, d_eq,
        #theta_constr1, theta_constr2, phi_constr1, phi_constr2,
    ],
        theta,
        phi,
        lamb,
        check=False,
        dict=True)
    return res

The function returns the right results as it is, but it doesn't work if I try to put the constraint on the angles inside the system of equations (the commented parts). Is there any way to have them?

At the moment, I'm using a simple solution to overcome this limitation: I pass the result of the previous function to the following one to filter out unwanted results

def _final_constraint(result):
    res = []
    for sol in result:
        to_add = True
        for k, v in sol.items():
            if str(k) == '\\theta' and (v < 0 or v > pi):
                to_add = False
                break
            elif str(k) == '\\phi' and (v < 0 or v >= 2 * pi):
                to_add = False
                break
        if to_add:
            res.append(simplify(sol))
    return res

Body:
Eq stands for Equality and is not an equation (though there is discussion of adding such an object to SymPy). So your uncommented Eq get interpreted as you intended, but the commented ones don't. You could try replacing theta_constr1 = Eq(theta >= 0) with theta_constr1 = theta >= 0 but then you will run into problems with the the inequality solver -- it complains about there being more than one symbol of interest amongst the inequalities. So what about re-writing the inequalities like x >= 0 as Eq(x + eps, 0) where eps is a nonnegative Symbol:

def get_angles(a, b, c, d):
    theta, phi, lamb = symbols('\\theta \\phi \\lambda', real=True)
    eps = Symbol('eps', nonnegative=True)
    a_eq = Eq(cos(theta / 2), a)
    b_eq = Eq(exp(I * phi) * sin(theta / 2), b)
    c_eq = Eq(-exp(I * lamb) * sin(theta / 2), c)
    d_eq = Eq(exp(I * (phi + lamb)) * cos(theta / 2), d)
    theta_constr1 = theta + eps
    theta_constr2 = pi - theta + eps
    phi_constr1 = phi  + eps
    phi_constr2 = 2 * pi - phi + eps
    res = solve([
        a_eq, b_eq, c_eq, d_eq,
        theta_constr1, theta_constr2, phi_constr1, phi_constr2,
        ],
        theta,
        phi,
        lamb,
        check=False,
        set=True)
    return res

>>> print(filldedent(get_angles(11,2,3,4)))

([\lambda, \phi, \theta], {(pi, 0, 4*pi - 2*acos(11)), (0, pi,
2*acos(11)), (0, pi, 4*pi - 2*acos(11)), (0, 0, 4*pi - 2*acos(11)),
(0, 0, 2*acos(11)), (pi, pi, 4*pi - 2*acos(11)), (pi, pi, 2*acos(11)),
(pi, 0, 2*acos(11))})

You would have to work out which side of theta and phi -- if any -- satisfied your equations.


来源: stackexchange

问:
Slow the movement of circle collision resolution
I have written a collision detection and resolution system for the game I am currently working on. The collision resolution doesn't work quite as intended though. Occasionally I spawn one circle inside of the other, when this happens I'd like the inside circle to slowly move out of the other's diameter, but currently the code that I have working does it quite quickly and jarringly. It instantly teleports outside of the circle, rather than a slow transition.

I know that the code I am currently using tells the circle where it SHOULD be, so I just need to slowly move the circle to that position. But that is proving to be difficult.

I've tried a couple of solutions, one is included in the code below. I have also tried using linear interpolation to move the circle to its current position, to where the collision algorithm is telling it it should be. That didn't work correctly either.

```<code>//r is the radius of the circle
var dx = cell.x - cell2.x;
var dy = cell.y - cell2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < cell.r + cells2.r && cell.r > cells2.r){
var unitX = dx/distance;
var unitY = dy/distance;

cell.x = cells2.x + (cell.r + cells2.r + 1) * unitX;
cell.y = cells2.y + (cell.r + cells2.r + 1) * unitY;
//Ive tried below, but the results were not correct.
//cell.x += (cells2.x + (cell.r + cells2.r + 1) * unitX)*0.5;
//cell.y += (cells2.y + (cell.r + cells2.r + 1) * unitY)*0.5;
}
</code>```

答:
To move cell apart from cell2, you don't need to add cells2 coordinates

```<code> cell.x += (cell.r + cells2.r + 1) * unitX;
</code>```

To move slowly, make speed smaller

```<code>//calculate once:
v = 0.01 * (cell.r + cells2.r - distance);
// at every step:
cell.x += v * unitX;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written a collision detection and resolution system for the game I am currently working on. The collision resolution doesn't work quite as intended though. Occasionally I spawn one circle inside of the other, when this happens I'd like the inside circle to slowly move out of the other's diameter, but currently the code that I have working does it quite quickly and jarringly. It instantly teleports outside of the circle, rather than a slow transition.

I know that the code I am currently using tells the circle where it SHOULD be, so I just need to slowly move the circle to that position. But that is proving to be difficult.

I've tried a couple of solutions, one is included in the code below. I have also tried using linear interpolation to move the circle to its current position, to where the collision algorithm is telling it it should be. That didn't work correctly either.

//r is the radius of the circle
var dx = cell.x - cell2.x;
var dy = cell.y - cell2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < cell.r + cells2.r && cell.r > cells2.r){
var unitX = dx/distance;
var unitY = dy/distance;

cell.x = cells2.x + (cell.r + cells2.r + 1) * unitX;
cell.y = cells2.y + (cell.r + cells2.r + 1) * unitY;
//Ive tried below, but the results were not correct.
//cell.x += (cells2.x + (cell.r + cells2.r + 1) * unitX)*0.5;
//cell.y += (cells2.y + (cell.r + cells2.r + 1) * unitY)*0.5;
}

Body:
To move cell apart from cell2, you don't need to add cells2 coordinates

 cell.x += (cell.r + cells2.r + 1) * unitX;

To move slowly, make speed smaller

//calculate once:
v = 0.01 * (cell.r + cells2.r - distance);
// at every step:
cell.x += v * unitX;


问:
SSH git clone is forbidden for Bitbucket on Windows
I am setting up SSH keys to establish SSH connection to my company's private company. But I still cannot clone the repository. I am using Windows 10.

I generate the key using the ssh-keygen command following the instructions for Windows in this link, https://confluence.atlassian.com/bitbucket/set-up-an-ssh-key-728138079.html.

Then I also run following command in Bash command

```<code>$ eval $(ssh-agent)
</code>```

I set the private key for the above command

```<code>ssh-add ~/.ssh/<private_key_file>
</code>```

Everything went well. Then I copy the public key id_rsa.pub key to the Bitbucket SSH key setting with a label.

When I clone, I am still getting the following error.

```<code>Cloning into 'my-repo-les'...
ssh: connect to host bitbucket.org port 22: Network is unreachable
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

In the source tree, I can see all the remote repositories of my organization/ company. But when I clone, I got the following error.

```<code>Command: git -c diff.mnemonicprefix=false -c core.quotepath=false ls-remote https://wai-yan-hein@bitbucket.org/lbresearch/frontendplatform.git
Output:
Error: remote: Forbidden
fatal: unable to access 'https://wai-yan-hein@bitbucket.org/lbresearch/frontendplatform.git/': The requested URL returned error: 403
</code>```

Before I had an account set up. I was using it with for Github. Now I set up for Bitbucket. Could that be the issue?

When I run this command, the connection has timed out.

```<code>ssh -T hg@bitbucket.org
</code>```

答:
Bitbucket also exposes its SSH service on an alternate port, to handle networks (like yours) that block port 22. Try ssh -Tp443 hg@altssh.bitbucket.org - that port is typically used for HTTPS, so it's rarely blocked.

If altssh.bitbucket.org:443 returns your username, then you'll need to use a different URL scheme in your clone command: git clone ssh://git@altssh.bitbucket.org:443/owner/repo.git

HTTP status 403 is not related to your SSH issues; that status indicates that you're able to reach Bitbucket, and that your credentials are valid, but that you do not have permission to do what you're trying to do.

Body:
I am setting up SSH keys to establish SSH connection to my company's private company. But I still cannot clone the repository. I am using Windows 10.

I generate the key using the ssh-keygen command following the instructions for Windows in this link, https://confluence.atlassian.com/bitbucket/set-up-an-ssh-key-728138079.html.

Then I also run following command in Bash command

$ eval $(ssh-agent)

I set the private key for the above command

ssh-add ~/.ssh/<private_key_file>

Everything went well. Then I copy the public key id_rsa.pub key to the Bitbucket SSH key setting with a label.

When I clone, I am still getting the following error.

Cloning into 'my-repo-les'...
ssh: connect to host bitbucket.org port 22: Network is unreachable
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

In the source tree, I can see all the remote repositories of my organization/ company. But when I clone, I got the following error.

Command: git -c diff.mnemonicprefix=false -c core.quotepath=false ls-remote https://wai-yan-hein@bitbucket.org/lbresearch/frontendplatform.git
Output:
Error: remote: Forbidden
fatal: unable to access 'https://wai-yan-hein@bitbucket.org/lbresearch/frontendplatform.git/': The requested URL returned error: 403

Before I had an account set up. I was using it with for Github. Now I set up for Bitbucket. Could that be the issue?

When I run this command, the connection has timed out.

ssh -T hg@bitbucket.org


问:
AVAssetExportSession causes audio video to desync when trying to merge multiple video/audio clips
I am trying to merge a bunch of video clips containing both audio and video into one longer video file.

AVMutableComposition *mainComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *compositionVideoTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

```<code>AVMutableCompositionTrack *soundtrackTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
CMTime insertTime = kCMTimeZero;

NSArray *videoFileNames;
for (NSString  *videoPathString in videoFileNames) {

    AVAsset *videoAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"/Volumes/videoClips/CLIPS/%@",videoPathString]]];

                NSError *err1;
                NSError *err2;
                [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:insertTime error:&err1];

                [soundtrackTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:insertTime error:&err2];
                insertTime = CMTimeAdd(insertTime, videoAsset.duration);
}

NSURL *outptVideoUrl = [NSURL fileURLWithPath:@"/Volumes/mergedVideo/finalizedMoviev.mp4"];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mainComposition presetName:AVAssetExportPreset1280x720];

exporter.outputURL= outptVideoUrl;
exporter.outputFileType = AVFileTypeMPEG4;
exporter.shouldOptimizeForNetworkUse = NO;
[exporter exportAsynchronouslyWithCompletionHandler:^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Completed video export");
    });
}];`
</code>```

This works however there is a desync between the audio and video after the first clip. Video if you watch the first clip the audio is perfectly synced then if you skip ahead towards the 15 minute mark you will notice a definite desync between video and audio.  After a little bit of searching I was able to this postiOS AVFoundation audio/video out of sync

Which has a link inside of it that explains what is going on that audio enques blank samples when compressing. On both the front and back of the compressed audio file. Technical Note TN2258
AAC Audio - Encoder Delay and Synchronization

Now I think what I can do to solve this problem is set up an AVAssetReader with both video and audio outputs read through each CMSamplebuffer of audio and video frame decompress them then and put it into an AVAssetWritter and repeat this for each clip.  But what I am unsure of is how to keep audio and video synced the whole time.  Am I just taking each audio frame and adding it in as is or am I trying to trim out the blank priming and remainding packets frames?

Thanks for any help!

答: I was right in what I assumed by looking at each frame individually and writing them through an avassetwriter does work.  However if clips are not the same audio sample rate you run into trouble thats the new issue I am working through now.</p>

Body:
I am trying to merge a bunch of video clips containing both audio and video into one longer video file.

AVMutableComposition *mainComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *compositionVideoTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

AVMutableCompositionTrack *soundtrackTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
CMTime insertTime = kCMTimeZero;

NSArray *videoFileNames;
for (NSString  *videoPathString in videoFileNames) {

    AVAsset *videoAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"/Volumes/videoClips/CLIPS/%@",videoPathString]]];

                NSError *err1;
                NSError *err2;
                [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:insertTime error:&err1];

                [soundtrackTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:insertTime error:&err2];
                insertTime = CMTimeAdd(insertTime, videoAsset.duration);
}

NSURL *outptVideoUrl = [NSURL fileURLWithPath:@"/Volumes/mergedVideo/finalizedMoviev.mp4"];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mainComposition presetName:AVAssetExportPreset1280x720];

exporter.outputURL= outptVideoUrl;
exporter.outputFileType = AVFileTypeMPEG4;
exporter.shouldOptimizeForNetworkUse = NO;
[exporter exportAsynchronouslyWithCompletionHandler:^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Completed video export");
    });
}];`

This works however there is a desync between the audio and video after the first clip. Video if you watch the first clip the audio is perfectly synced then if you skip ahead towards the 15 minute mark you will notice a definite desync between video and audio.  After a little bit of searching I was able to this postiOS AVFoundation audio/video out of sync

Which has a link inside of it that explains what is going on that audio enques blank samples when compressing. On both the front and back of the compressed audio file. Technical Note TN2258
AAC Audio - Encoder Delay and Synchronization

Now I think what I can do to solve this problem is set up an AVAssetReader with both video and audio outputs read through each CMSamplebuffer of audio and video frame decompress them then and put it into an AVAssetWritter and repeat this for each clip.  But what I am unsure of is how to keep audio and video synced the whole time.  Am I just taking each audio frame and adding it in as is or am I trying to trim out the blank priming and remainding packets frames?

Thanks for any help!


问:
Apply log2 transformation only to numeric columns of a data.frame
I am trying to run a log2 transformation on my data set but I keep getting an error that says "non-numeric variable(s) in data frame". My data has row.names = 1 and header = TRUE and is of class data.frame()

I tried adding lappy(na.strings) but this does not fix the problem

```<code>Shared_DEGs <- cbind(UT.Degs_heatmap[2:11], MT.Degs_heatmap[2:11], HT.Degs_heatmap[2:11])
Shared_DEGs1 <- `row.names<-`(Shared_DEGs, (UT.Degs_heatmap[,1]))
MyData.INF.log2 <- log2(Shared_DEGs1)
</code>```

The data should be log2 transformed as an output

答:
Do not try to run log2 (or other numeric computations) on a data.frame as a whole, instead you need to do it per column. Since we don't have your data, I'll generate something to fully demonstrate:

mydf <- data.frame(num = pi, int = 5L, chr = "A", lgl = TRUE, stringsAsFactors = FALSE)
mydf
#        num int chr  lgl
# 1 3.141593   5   A TRUE
```
<pre class="lang-r prettyprint-override"><code>isnum <- sapply(mydf, is.numeric)
isnum
#   num   int   chr   lgl
#  TRUE  TRUE FALSE FALSE
mydf[,isnum] <- lapply(mydf[,isnum], log2)
mydf
#        num      int chr  lgl
# 1 1.651496 2.321928   A TRUE
</code>```

What I'm doing here:

isnum is the subset of columns that are numeric (integer or float). This logical indexing can be extended to include things like "nothing negative" or "no NAs", completely up to you.

mydf[,isnum] subsets the data to just those columns

lapply(mydf[,isnum], log2) runs the function log2 against each column of the sub-frame, each column individually; what is passed to log2 is a vector of numbers, not a data.frame as in your attempt

mydf[,isnum] <- lapply(...): normally, if we do mydf <- lapply(...), we will be storing a list, which overwrites your previously instance (losing non-number columns) and no longer a frame, so using the underlying R function [<- (assigns to a subset), we replace the components of the frame (a) preserving other columns, and (b) without losing the "class" of the parent frame.

Body:
I am trying to run a log2 transformation on my data set but I keep getting an error that says "non-numeric variable(s) in data frame". My data has row.names = 1 and header = TRUE and is of class data.frame()

I tried adding lappy(na.strings) but this does not fix the problem

Shared_DEGs <- cbind(UT.Degs_heatmap[2:11], MT.Degs_heatmap[2:11], HT.Degs_heatmap[2:11])
Shared_DEGs1 <- `row.names<-`(Shared_DEGs, (UT.Degs_heatmap[,1]))
MyData.INF.log2 <- log2(Shared_DEGs1)

The data should be log2 transformed as an output

Body:
Do not try to run log2 (or other numeric computations) on a data.frame as a whole, instead you need to do it per column. Since we don't have your data, I'll generate something to fully demonstrate:

mydf <- data.frame(num = pi, int = 5L, chr = "A", lgl = TRUE, stringsAsFactors = FALSE)
mydf
#        num int chr  lgl
# 1 3.141593   5   A TRUE

isnum <- sapply(mydf, is.numeric)
isnum
#   num   int   chr   lgl
#  TRUE  TRUE FALSE FALSE
mydf[,isnum] <- lapply(mydf[,isnum], log2)
mydf
#        num      int chr  lgl
# 1 1.651496 2.321928   A TRUE

What I'm doing here:

isnum is the subset of columns that are numeric (integer or float). This logical indexing can be extended to include things like "nothing negative" or "no NAs", completely up to you.

mydf[,isnum] subsets the data to just those columns

lapply(mydf[,isnum], log2) runs the function log2 against each column of the sub-frame, each column individually; what is passed to log2 is a vector of numbers, not a data.frame as in your attempt

mydf[,isnum] <- lapply(...): normally, if we do mydf <- lapply(...), we will be storing a list, which overwrites your previously instance (losing non-number columns) and no longer a frame, so using the underlying R function [<- (assigns to a subset), we replace the components of the frame (a) preserving other columns, and (b) without losing the "class" of the parent frame.


问:
Transition to view through the timer
I need to implement a smooth transition to another View using a timer.

For example, when I click on the start button and after 15 seconds pass, the automatic transition to another View takes place.

答:
In start button action start a timer with an incrementing counter variable. In the timer execution block if the count reaches 15, invalidate the timer and navigate to next view controller</p>

```<code>@objc func startBtnAction(_ sender: UIButton) {
    var count = 0
    let target = 15
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
        self?.label.text = String(format: "%02d:%02d", count/60,count%60)
        if count == target {
            timer.invalidate()
            self?.performSegue(withIdentifier: "NextScreen", sender: self)
        } else {
            count += 1
        }
    }
}
</code>```

Title: Transition to view through the timer

Body:
In start button action start a timer with an incrementing counter variable. In the timer execution block if the count reaches 15, invalidate the timer and navigate to next view controller

@objc func startBtnAction(_ sender: UIButton) {
    var count = 0
    let target = 15
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
        self?.label.text = String(format: "%02d:%02d", count/60,count%60)
        if count == target {
            timer.invalidate()
            self?.performSegue(withIdentifier: "NextScreen", sender: self)
        } else {
            count += 1
        }
    }
}


问:
How can I change the order in subscribe?
How can I change the order of execution? I have an array this.friend, I need work with this array, but it takes to fill up with data

```<code>this.listUserService.getUsers().subscribe(
    async (data: any) => {
           this.listUsers = data;
           await data.forEach((current: any) => {
                 if (current.name === userSession) {
                      this.user = current;
                      this.friendsService.getFriends(this.user.id).subscribe(response => {
                                console.log('last', response);//this runs second
                                this.friends = response;
                            });
                        }
                    });
                    console.log('friends', this.friends); //friend is clear,
this runs first
                    this.listUsers = this.listUsers.filter(user => !this.friends.some(relationship => relationship[0].friend.id !== user.id));
                }
            );
</code>```

The console messages are shown in reverse order, how can I change the order, once it's full I want to use the Filter function

答:
There is no need to mix promises with observables. In addition, it is not a good idea to nest subscribe() methods within each other. I would recommend you to handle the above operation with RxJS operators.

First, we use mergeMap to map over the observable values from the getUsers() method from the service, into an inner observable.

Then, we use forkJoin to wait the Array.forEach() loop to be completed before returning all the observables. Since you seem to be familiar with the usage of Promises in JavaScript, it is actually similar to Promise.all.

Last but not least, we handle the filtering of the listUsers at the subscribe() block. This will ensure that your asynchronous code is properly handle.

```<code>this.listUserService.getUsers().pipe(
  mergeMap(data => {
    this.listUsers = data;
    const observablesList = [];
    data.forEach((current: any) => {
      if (current.name === userSession) {
        observablesList.push(this.friendsService.getFriends(current.id));
      }
    });
    return forkJoin(observablesList);
  })
).subscribe(response => {
  // console.log(response) will give you the returned values from the looped getFriends()
  // handle the rest here

});
</code>```

Body:
How can I change the order of execution? I have an array this.friend, I need work with this array, but it takes to fill up with data

this.listUserService.getUsers().subscribe(
    async (data: any) => {
           this.listUsers = data;
           await data.forEach((current: any) => {
                 if (current.name === userSession) {
                      this.user = current;
                      this.friendsService.getFriends(this.user.id).subscribe(response => {
                                console.log('last', response);//this runs second
                                this.friends = response;
                            });
                        }
                    });
                    console.log('friends', this.friends); //friend is clear,
this runs first
                    this.listUsers = this.listUsers.filter(user => !this.friends.some(relationship => relationship[0].friend.id !== user.id));
                }
            );

The console messages are shown in reverse order, how can I change the order, once it's full I want to use the Filter function

Body:
There is no need to mix promises with observables. In addition, it is not a good idea to nest subscribe() methods within each other. I would recommend you to handle the above operation with RxJS operators.

First, we use mergeMap to map over the observable values from the getUsers() method from the service, into an inner observable.

Then, we use forkJoin to wait the Array.forEach() loop to be completed before returning all the observables. Since you seem to be familiar with the usage of Promises in JavaScript, it is actually similar to Promise.all.

Last but not least, we handle the filtering of the listUsers at the subscribe() block. This will ensure that your asynchronous code is properly handle.

this.listUserService.getUsers().pipe(
  mergeMap(data => {
    this.listUsers = data;
    const observablesList = [];
    data.forEach((current: any) => {
      if (current.name === userSession) {
        observablesList.push(this.friendsService.getFriends(current.id));
      }
    });
    return forkJoin(observablesList);
  })
).subscribe(response => {
  // console.log(response) will give you the returned values from the looped getFriends()
  // handle the rest here

});


问:
Trying to use Async and Await from different functions
While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.

I am using PouchDB, which is a great Javascript database that syncs with CouchDB. PouchDB uses promises for many of its functions, and has native support for Async and Await.  As an example, to retrieve the basic information about a database, you would use the following code:

```<code>    db.info().then(function (info) {
  console.log(info);
})
</code>```

I understand this, and it works.  But if I try and put this inside a function, and then call that function, things go haywire. And I'm sure it's me and not PouchDB that is the problem...

```<code>function getLocalDBInfo(db){

  try {
    db.info().then(function (info) {
      return info;
    });
  } catch (error) {
    console.log("can't get local DB info: ", error);
  }
}

async function testing(db){
  try {
    var info=await getLocalDBInfo(db);
    await console.log("DB info=", info);
    await console.log("Doc count= ", info.doc_count);
  }
  catch(err){
    console.log("error=",err);
  }

  //info contains...
    //{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}

testing(MY_db);
</code>```

If I log info inside the getLocalDBInfo function, it eventually (ie. after the promise fulfills) logs info to the console.  But, the logs inside the testing function return immediately with undefined.  It makes sense to me that they are returning undefined because they are returning immediately, but I was trying to have them wait for info by using async and await.  Any suggestions as to what I am doing wrong?

答:
getLocalDBInfo() is not returning a promise, so you can't await for it.

with async/await you could:

```<code>async function getLocalDBInfo(db){
    try{
       return await db.info()
    } catch (err){
       console.log("can't get local DB info: ", error);
    }
}
</code>```

you can also use new promise

Body:
While I thought I was using Async and Await keywords properly, it appears as though I am doing something wrong.

I am using PouchDB, which is a great Javascript database that syncs with CouchDB. PouchDB uses promises for many of its functions, and has native support for Async and Await.  As an example, to retrieve the basic information about a database, you would use the following code:

    db.info().then(function (info) {
  console.log(info);
})

I understand this, and it works.  But if I try and put this inside a function, and then call that function, things go haywire. And I'm sure it's me and not PouchDB that is the problem...

function getLocalDBInfo(db){

  try {
    db.info().then(function (info) {
      return info;
    });
  } catch (error) {
    console.log("can't get local DB info: ", error);
  }
}

async function testing(db){
  try {
    var info=await getLocalDBInfo(db);
    await console.log("DB info=", info);
    await console.log("Doc count= ", info.doc_count);
  }
  catch(err){
    console.log("error=",err);
  }

  //info contains...
    //{"doc_count":0,"update_seq":0,"db_name":"kittens"}
}

testing(MY_db);

If I log info inside the getLocalDBInfo function, it eventually (ie. after the promise fulfills) logs info to the console.  But, the logs inside the testing function return immediately with undefined.  It makes sense to me that they are returning undefined because they are returning immediately, but I was trying to have them wait for info by using async and await.  Any suggestions as to what I am doing wrong?

Body:
getLocalDBInfo() is not returning a promise, so you can't await for it.

with async/await you could:

async function getLocalDBInfo(db){
    try{
       return await db.info()
    } catch (err){
       console.log("can't get local DB info: ", error);
    }
}

you can also use new promise


问:
Convertering JavaScript POST request to Google Apps Script code
I have tried everything and google wont answer my specific questions so here goes.

I want to convert the following code to Apps Script syntax, the code below works as it is.

```<code>var request = new XMLHttpRequest();

request.open('POST', 'https://.......');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('X-Token', 'myTokenHere');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'fromDate': '2019-01-01T13:54:51+0200',
  'toDate': '2019-05-01T13:54:51+0200'
};

request.send(JSON.stringify(body));
</code>```

What i have tried is for example this:
(all i get is a 500 error)

```<code>function req(){
  var url = "https://.......";
  var options = {
    "method": "post",
    "muteHttpExceptions": true,
    "headers": {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-Token": "myTokenHere"
    },
    "payload": {
      "fromDate": "2019-01-01T13:54:51+0200",
      "toDate": "2019-05-01T13:54:51+0200"
    }
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}
</code>```

Thanks in advance!

Peace =)

答:
You have two issues.

The first, as mentioned in the comments, is that the payload is not a JSON string. Your content type is application/json so your payload needs to be formatted to match that mimetype.

Use the JSON.stringify() method (its supported in Apps Script) to achieve that as follows:

```<code>....
"payload":JSON.Stringify({
    "fromDate": "2019-01-01T13:54:51+0200",
    "toDate": "2019-05-01T13:54:51+0200"
}),
....
</code>```

Your second problem is setting the contentType header. It's goes against convention somewhat, but you set the content type as a property on the options object (NOT the headers object) like so:

```<code>var options = {
    ...
    "contentType":"application/json",
    "headers":{
        "Accept": "application/json",
        "X-Token": "myTokenHere"
    },
    ...
}
</code>```

Body:
I have tried everything and google wont answer my specific questions so here goes.

I want to convert the following code to Apps Script syntax, the code below works as it is.

var request = new XMLHttpRequest();

request.open('POST', 'https://.......');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('X-Token', 'myTokenHere');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'fromDate': '2019-01-01T13:54:51+0200',
  'toDate': '2019-05-01T13:54:51+0200'
};

request.send(JSON.stringify(body));

What i have tried is for example this:
(all i get is a 500 error)

function req(){
  var url = "https://.......";
  var options = {
    "method": "post",
    "muteHttpExceptions": true,
    "headers": {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "X-Token": "myTokenHere"
    },
    "payload": {
      "fromDate": "2019-01-01T13:54:51+0200",
      "toDate": "2019-05-01T13:54:51+0200"
    }
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

Thanks in advance!

Peace =)

Body:
You have two issues.

The first, as mentioned in the comments, is that the payload is not a JSON string. Your content type is application/json so your payload needs to be formatted to match that mimetype.

Use the JSON.stringify() method (its supported in Apps Script) to achieve that as follows:

....
"payload":JSON.Stringify({
    "fromDate": "2019-01-01T13:54:51+0200",
    "toDate": "2019-05-01T13:54:51+0200"
}),
....

Your second problem is setting the contentType header. It's goes against convention somewhat, but you set the content type as a property on the options object (NOT the headers object) like so:

var options = {
    ...
    "contentType":"application/json",
    "headers":{
        "Accept": "application/json",
        "X-Token": "myTokenHere"
    },
    ...
}


问:
Salesforce SOQL How can i target an id that is in another table
i am trying to figure out how to do a specific query but i am limited by my knowledge. So any help would be deeply appreciated.

I have some objects: Employee, Employee role assignment, Student group etc..

What i am trying to do is:

Inside every Employee personal page, create a table, that has student info of students that have picked the student group that is assigned to the specific employee. The relationship between objects are Employee to employee role assignment(one to many), employee role assignment to Student group(many to one). Each Employee is assigned many roles and each role is assigned a student group.

What i am trying to do is something like this:

```<code>SELECT Opportunity__r.Name, Opportunity__r.Email__c, Opportunity__r.Phone__c, Opportunity__r.Parent_Guardian_Email__c, Student_group__r.Name, Opportunity__r.Personal_Statement__c FROM Content__c WHERE Student_group_r.Employee_role_assignment__r.Employee__r.Id = :id
</code>```

The last part, after the WHERE, is what i am stuck at. Is there a way to pass the id?

答:
In Salesforce terminology, Employee Role Assignment is a junction object.

You're adding in a couple of extra objects here that make this more challenging. It looks like you have a lookup relationship from Content__c to Opportunity and also from Content__c to Student_Group__c, and most of the data that you want is actually located on the Opportunity. Content__c is something like a second junction object here.

You want to filter your Opportunities based on whether they are associated with a Content that is associated with a Student Group that is associated with the Employee whose page this is. Whew.

If I understood your data model correctly, you can achieve this using a semi-join sub-select.
It would look something like this:

```<code>List<Content__c> results = [
    SELECT Opportunity__r.Name, Opportunity__r.Email__c, Opportunity__r.Phone__c ...
    FROM Content__c
    WHERE Student_Group__c IN (
        SELECT Student_Group__c
        FROM Employee_Role_Assignment__c
        WHERE Employee__c = :thisEmployeeId
    )
];
</code>```

The Apex binding with : in the inner WHERE clause is what injects the Id of the Employee, stored in some local variable, into the query.

Body:
i am trying to figure out how to do a specific query but i am limited by my knowledge. So any help would be deeply appreciated.

I have some objects: Employee, Employee role assignment, Student group etc..

What i am trying to do is:

Inside every Employee personal page, create a table, that has student info of students that have picked the student group that is assigned to the specific employee. The relationship between objects are Employee to employee role assignment(one to many), employee role assignment to Student group(many to one). Each Employee is assigned many roles and each role is assigned a student group.

What i am trying to do is something like this:

SELECT Opportunity__r.Name, Opportunity__r.Email__c, Opportunity__r.Phone__c, Opportunity__r.Parent_Guardian_Email__c, Student_group__r.Name, Opportunity__r.Personal_Statement__c FROM Content__c WHERE Student_group_r.Employee_role_assignment__r.Employee__r.Id = :id

The last part, after the WHERE, is what i am stuck at. Is there a way to pass the id?

Body:
In Salesforce terminology, Employee Role Assignment is a junction object.

You're adding in a couple of extra objects here that make this more challenging. It looks like you have a lookup relationship from Content__c to Opportunity and also from Content__c to Student_Group__c, and most of the data that you want is actually located on the Opportunity. Content__c is something like a second junction object here.

You want to filter your Opportunities based on whether they are associated with a Content that is associated with a Student Group that is associated with the Employee whose page this is. Whew.

If I understood your data model correctly, you can achieve this using a semi-join sub-select.
It would look something like this:

List<Content__c> results = [
    SELECT Opportunity__r.Name, Opportunity__r.Email__c, Opportunity__r.Phone__c ...
    FROM Content__c
    WHERE Student_Group__c IN (
        SELECT Student_Group__c
        FROM Employee_Role_Assignment__c
        WHERE Employee__c = :thisEmployeeId
    )
];

The Apex binding with : in the inner WHERE clause is what injects the Id of the Employee, stored in some local variable, into the query.


问:
file input MVC 3 Client-side validation for required
Simple question... Is it possible to use client side MVC 3 validation on inputs of type file?

To explain: MVC 3 uses its model validation with IClientValidatable and unobtrusive javascript to allow you to write validation on the server side and have it render the client side using jquery validate using Microsoft's plugins. To make a property required you add the attribute below

```<code>[Required]
public HttpPostedFileBase CvFile {get; set;}
</code>```

As long as client side val and unobtrusive javascript is on in the config this should all fire on the client.

However HttpPostedFileBase (i.e. <input type="file" name="Model.CvFile" />) will not run required on the client side.

Any ideas how this can be achieved keeping the relationship with the server side validation

答:
Simple answer: A HttpPostedFileBase renders "file" input type which is a security issue and, AFAIK, is not scriptable. There's no support for this "out of the box".

Edit: this seems to be a very popular topic online.
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

ContentLicense: CC BY-SA 3.0

Body:
Simple question... Is it possible to use client side MVC 3 validation on inputs of type file?

To explain: MVC 3 uses its model validation with IClientValidatable and unobtrusive javascript to allow you to write validation on the server side and have it render the client side using jquery validate using Microsoft's plugins. To make a property required you add the attribute below

[Required]
public HttpPostedFileBase CvFile {get; set;}

As long as client side val and unobtrusive javascript is on in the config this should all fire on the client.

However HttpPostedFileBase (i.e. <input type="file" name="Model.CvFile" />) will not run required on the client side.

Any ideas how this can be achieved keeping the relationship with the server side validation


答:
You could try instead using RxJS operators such as switchMap, map, and tap to control the flow of the observable including performing side effects like setting class properties.

This answer assumes that there is only a single current user resulting from if (current.name === userSession) { inside the forEach() and subsequently that this.friendsService.getFriends(user.id) only executes once.

```<code>import { map, switchMap, tap } from 'rxjs/operators'; // need to import operators

// ...

this.listUserService.getUsers().pipe(
  tap(users => this.listUsers = users), // side effect to set this.listUsers
  map(users => users.find(user => user.name === userSession)), // find current user
  switchMap(user => this.friendsService.getFriends(user.id)), // get friends of current user
  tap(friends => this.friends = friends), // side effect to set this.friends
  map(friends => this.listUsers.filter(user => this.friends.some(relationship => relationship[0].friend.id !== user.id)))
).subscribe(listUsers => {
  this.listUsers = listUsers;
});
</code>```

You should definitely review the RxJS documentation for more information and examples of the various operators. Also you will definitely need to improve error handling in case situations like a current user is not found or any of the service/api calls fail.

Hopefully that helps!

Title: How can I change the order in subscribe?

Body:
You could try instead using RxJS operators such as switchMap, map, and tap to control the flow of the observable including performing side effects like setting class properties.

This answer assumes that there is only a single current user resulting from if (current.name === userSession) { inside the forEach() and subsequently that this.friendsService.getFriends(user.id) only executes once.

import { map, switchMap, tap } from 'rxjs/operators'; // need to import operators

// ...

this.listUserService.getUsers().pipe(
  tap(users => this.listUsers = users), // side effect to set this.listUsers
  map(users => users.find(user => user.name === userSession)), // find current user
  switchMap(user => this.friendsService.getFriends(user.id)), // get friends of current user
  tap(friends => this.friends = friends), // side effect to set this.friends
  map(friends => this.listUsers.filter(user => this.friends.some(relationship => relationship[0].friend.id !== user.id)))
).subscribe(listUsers => {
  this.listUsers = listUsers;
});

You should definitely review the RxJS documentation for more information and examples of the various operators. Also you will definitely need to improve error handling in case situations like a current user is not found or any of the service/api calls fail.

Hopefully that helps!


问:
How to get address of a pointer in c/c++?
How to get address of a pointer in c/c++?

Eg: I have below code.

```<code>int a =10;
int *p = &a;
</code>```

So how do I get address of pointer p?
Now I want to print address of p, what should I do?

print("%s",???) what I pass to ???.

答:
In C++ you can do:

```<code>// Declaration and assign variable a
int a = 7;
// Declaration pointer b
int* b;
// Assign address of variable a to pointer b
b = &a;

// Declaration pointer c
int** c;
// Assign address of pointer b to pointer c
c = &b;

std::cout << "a: " << a << "\n";       // Print value of variable a
std::cout << "&a: " << &a << "\n";     // Print address of variable a

std::cout << "" << "" << "\n";

std::cout << "b: " << b << "\n";       // Print address of variable a
std::cout << "*b: " << *b << "\n";     // Print value of variable a
std::cout << "&b: " << &b << "\n";     // Print address of pointer b

std::cout << "" << "" << "\n";

std::cout << "c: " << c << "\n";       // Print address of pointer b
std::cout << "**c: " << **c << "\n";   // Print value of variable a
std::cout << "*c: " << *c << "\n";     // Print address of variable a
std::cout << "&c: " << &c << "\n";     // Print address of pointer c
</code>```

Body:
How to get address of a pointer in c/c++?

Eg: I have below code.

int a =10;
int *p = &a;

So how do I get address of pointer p?
Now I want to print address of p, what should I do?

print("%s",???) what I pass to ???.

Body:
In C++ you can do:

// Declaration and assign variable a
int a = 7;
// Declaration pointer b
int* b;
// Assign address of variable a to pointer b
b = &a;

// Declaration pointer c
int** c;
// Assign address of pointer b to pointer c
c = &b;

std::cout << "a: " << a << "\n";       // Print value of variable a
std::cout << "&a: " << &a << "\n";     // Print address of variable a

std::cout << "" << "" << "\n";

std::cout << "b: " << b << "\n";       // Print address of variable a
std::cout << "*b: " << *b << "\n";     // Print value of variable a
std::cout << "&b: " << &b << "\n";     // Print address of pointer b

std::cout << "" << "" << "\n";

std::cout << "c: " << c << "\n";       // Print address of pointer b
std::cout << "**c: " << **c << "\n";   // Print value of variable a
std::cout << "*c: " << *c << "\n";     // Print address of variable a
std::cout << "&c: " << &c << "\n";     // Print address of pointer c


问:
Imageio unable to read webcam at correct framerate
I'm trying to read frames from a webcam and analyze them in realtime, but since my function AnalyzeFrame() is faster than the framerate, it ends up pulling the same frame 1-4 times in a row, messing up my data. Here's basically what I'm running.

```<code>import imageio

cam = imageio.get_reader('<video0>', fps=30)

while not cam.closed:
    print(AnalyzeFrame(cam.get_next_data()))
</code>```

A few notes: My webcam should be able to handle 30fps, but I'm averaging 12-14 fps. I've timed each individual process and there's very little regularity to the framerate. Some frames only get analyzed once, because they're in the buffer for 20 or so milliseconds. Others get analyzed 4 times over a span of 100+ ms. Is there something in my code that's causing this framerate problem?

答:
From what I understood from some tests, when you call get_next_data() it is then that your script grabs the frame from the webcam. Therefore, setting a fps is useless.

To find the reason why you cannot reach 30 fps should reside in the time your function AnalyzeFrame takes.

Body:
I'm trying to read frames from a webcam and analyze them in realtime, but since my function AnalyzeFrame() is faster than the framerate, it ends up pulling the same frame 1-4 times in a row, messing up my data. Here's basically what I'm running.

import imageio

cam = imageio.get_reader('<video0>', fps=30)

while not cam.closed:
    print(AnalyzeFrame(cam.get_next_data()))

A few notes: My webcam should be able to handle 30fps, but I'm averaging 12-14 fps. I've timed each individual process and there's very little regularity to the framerate. Some frames only get analyzed once, because they're in the buffer for 20 or so milliseconds. Others get analyzed 4 times over a span of 100+ ms. Is there something in my code that's causing this framerate problem?


问:
Validation with input[type="radio"] return always false
I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.

I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)

not exactly what i have, but...

```<code><input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
</code>```

and in JS i have...

```<code>var rdObj = document.getElementByName("radioGrp");
var selectedValue;

for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
        alert("Select one option");
        return false;
    }else{
        //do something with value of radio checked value
    }
}
</code>```

This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.

Any hel will be very appreciated

答:
You can try this:

function validateForm() {
  var radios = document.getElementsByName("radioGrp");
  var formValid = false;

  for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
      formValid = true;
      break;
    }
  }

  if (!formValid) {
    alert("Select one option");
  }

  return formValid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form1" action="#" onsubmit="return validateForm();" method="post">

    <input type="radio" id="rd1" name="radioGrp">opt1
    <br>
    <input type="radio" id="rd2" name="radioGrp">opt2
    <br>
    <input type="submit" value="Submit">

</form></code>```

Body:
I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.

I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)

not exactly what i have, but...

<input type="radio" id="rd1" name="radioGrp">opt1

<input type="radio" id="rd2" name="radioGrp">opt2

and in JS i have...

var rdObj = document.getElementByName("radioGrp");
var selectedValue;

for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
        alert("Select one option");
        return false;
    }else{
        //do something with value of radio checked value
    }
}

This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.

Any hel will be very appreciated

Body:
You can try this:

function validateForm() {
  var radios = document.getElementsByName("radioGrp");
  var formValid = false;

  for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
      formValid = true;
      break;
    }
  }

  if (!formValid) {
    alert("Select one option");
  }

  return formValid;
}

<form name="form1" action="#" onsubmit="return validateForm();" method="post">

    <input type="radio" id="rd1" name="radioGrp">opt1
    <br>
    <input type="radio" id="rd2" name="radioGrp">opt2
    <br>
    <input type="submit" value="Submit">

</form>


问:
shell script to generate a map
I'd like to have a script (bash) to generate an img (gif, jpg, etc.) of a (openstreetmap or googlemap) map given a location, like this:

```<code>$ genmap.sh 45.5 9.5
</code>```

(parameters are lat & long)

or:

```<code>$ genmap.sh 45.5 9.5 12
</code>```

(parameters are lat & long and zoom)

etc. etc.

can you point me to something on the net?

thank you

答:
Google Maps provides an API you can use for generating maps. See their documentation on the API for static maps.

Latitudes and Longitudes

Zoom Levels

A basic example script which accept lat as first, long as second and an optional zoom as third. It outputs an PNG image with a filename like lat-long-zoom-width-height.png and echo's the filename:

```<code>#!/bin/bash
width=400
height=400
lat="$1"
long="$2"
zoom=12
if [ -n "$3" ]; then
    zoom="$3"
fi
filename="$lat-$long-$zoom-${width}x$height.png"
wget "http://maps.google.com/maps/api/staticmap?center=$lat,$long&zoom=$zoom&size=${width}x${height}&sensor=false" -O "$filename"
# small error checking
if [ $? -ne 0 ]; then
    echo "An error occured" >&2
    exit 1
fi
echo "$filename"
</code>```

You might need to add additional tweaks to check the error response.

Title: shell script to generate a map

Body:
I'd like to have a script (bash) to generate an img (gif, jpg, etc.) of a (openstreetmap or googlemap) map given a location, like this:

$ genmap.sh 45.5 9.5

(parameters are lat & long)

or:

$ genmap.sh 45.5 9.5 12

(parameters are lat & long and zoom)

etc. etc.

can you point me to something on the net?

thank you

Body:
Google Maps provides an API you can use for generating maps. See their documentation on the API for static maps.

Latitudes and Longitudes

Zoom Levels

A basic example script which accept lat as first, long as second and an optional zoom as third. It outputs an PNG image with a filename like lat-long-zoom-width-height.png and echo's the filename:

#!/bin/bash
width=400
height=400
lat="$1"
long="$2"
zoom=12
if [ -n "$3" ]; then
    zoom="$3"
fi
filename="$lat-$long-$zoom-${width}x$height.png"
wget "http://maps.google.com/maps/api/staticmap?center=$lat,$long&zoom=$zoom&size=${width}x${height}&sensor=false" -O "$filename"
# small error checking
if [ $? -ne 0 ]; then
    echo "An error occured" >&2
    exit 1
fi
echo "$filename"

You might need to add additional tweaks to check the error response.


问:
bulma menu toggle in gatsbyjs not working
GatsbyJS beginner here, trying to get the Bulma responsive menu toggle to apply the "is-active" class to the menu (gatsby v2 with gatsby starter netlify cms). all code here: https://github.com/pddew/gatsby-starter-netlify-cms

Currently the toggle button and script tags appear but the button doesn't respond.

There is a working version of this in the gatsby starter business- when I inspect and compare my site with this, I can't spot the error, only that there is no event listener on toggle button, when it seems there should be.
When I inspect the site, the toggle.js script is being called and put in before the closing body tag, and the viewed.

I have tried building and deploying with no luck, clearing caches and swapping the scripts for bulma's suggested code.

Here is the relevant code.
Any help with this greatly appreciated; I'm a bit stuck!

in Layout.js:

```<code>    import React from 'react' import Helmet from 'react-helmet'

import Navbar from '../components/Navbar' import Footer from '../components/Footer' import './all.sass'

const TemplateWrapper = ({ children }) => (   <div>
    <Helmet title="Immediate Start Jobs" />
    <Navbar />
    <div>{children}</div>
    <Footer />   </div> )

export default TemplateWrapper
</code>```

in Navbar:

```<code><button className="button navbar-burger" data-target="navMenu">
      <span />
      <span />
      <span />
    </button>
  </div>
  <div className="navbar-menu" id="navMenu">
    <div className="navbar-start">
      <Link className="navbar-item" to="/about">
        About
      </Link>
      <Link className="navbar-item" to="/products">
        Products
      </Link>
      <Link className="navbar-item" to="/blog">
      Blog
    </Link>
    </div>
</code>```

in html.js

```<code>    import React from "react"
import PropTypes from "prop-types"

export default class HTML extends React.Component {
  render() {
    return (
      <html {...this.props.htmlAttributes}>
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          {this.props.headComponents}
        </head>
        <body {...this.props.bodyAttributes}>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
          <script src={__PATH_PREFIX__ + '/js/toggle.js'} />

        </body>
      </html>
    )
  }
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}
</code>```

And my toggle.js, stored in static/js/

```<code>    document.addEventListener('DOMContentLoaded', function () {
  // Get all "navbar-burger" elements
  var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0)
  // Check if there are any navbar burgers
  if ($navbarBurgers.length > 0) {
    // Add a click event on each of them
    $navbarBurgers.forEach(function ($el) {
      $el.addEventListener('click', function () {
        // Get the target from the "data-target" attribute
        var target = $el.dataset.target
        var $target = document.getElementById(target)
        // Toggle the className on both the "navbar-burger" and the "navbar-menu"
        $el.classList.toggle('is-active')
        $target.classList.toggle('is-active')
      })
    })
  }
})
</code>```

答:
That's just my two pennies' worth: https://nhpcr.codesandbox.io/

src/Navbar.js

```<code>
import React from 'react';
import PropTypes from 'prop-types';

const NavbarItem = props => (
  <a className="navbar-item is-capitalized" href={`#${props.page}`}>
    {props.page}
  </a>
);
const NavbarBurger = props => (
  <button
    onClick={props.toggleMenu}
    className={`button navbar-burger ${props.active ? 'is-active' : ''}`}
  >
    <span />
    <span />
    <span />
  </button>
);

export default class Navbar extends React.Component {
  state = {
    activeMenu: false,
  };
  toggleMenu = () => {
    this.setState({
      activeMenu: !this.state.activeMenu,
    });
  };
  render() {
    let { pages = [], color } = this.props;
    let navbarItems = pages.map(page => <NavbarItem page={page} key={page} />);
    return (
      <nav className={`navbar is-fixed-top is-${color}`}>
        <div className="navbar-brand">
          <NavbarItem page="logo" />
          <NavbarBurger
            active={this.state.activeMenu}
            toggleMenu={this.toggleMenu}
          />
        </div>
        <div
          className={`navbar-menu ${this.state.activeMenu ? 'is-active' : ''}`}
        >
          <div className="navbar-start">{navbarItems}</div>
        </div>
      </nav>
    );
  }
}

Navbar.propTypes = {
  pages: PropTypes.array.isRequired,
  color: PropTypes.string,
};
</code>```

src/index.js

```<code>import React from 'react';
import { render } from 'react-dom';

import Navbar from './Navbar';

import 'bulma/css/bulma.css';

const styles = {
  fontFamily: 'sans-serif',
  textAlign: 'center',
};

const pages = ['about', 'contact', 'sitemap'];
const App = () => (
  <div style={styles}>
    <Navbar pages={pages} />
  </div>
);

render(<App />, document.getElementById('root'));
</code>```

Body:
GatsbyJS beginner here, trying to get the Bulma responsive menu toggle to apply the "is-active" class to the menu (gatsby v2 with gatsby starter netlify cms). all code here: https://github.com/pddew/gatsby-starter-netlify-cms

Currently the toggle button and script tags appear but the button doesn't respond.

There is a working version of this in the gatsby starter business- when I inspect and compare my site with this, I can't spot the error, only that there is no event listener on toggle button, when it seems there should be.
When I inspect the site, the toggle.js script is being called and put in before the closing body tag, and the viewed.

I have tried building and deploying with no luck, clearing caches and swapping the scripts for bulma's suggested code.

Here is the relevant code.
Any help with this greatly appreciated; I'm a bit stuck!

in Layout.js:

    import React from 'react' import Helmet from 'react-helmet'

import Navbar from '../components/Navbar' import Footer from '../components/Footer' import './all.sass'

const TemplateWrapper = ({ children }) => (

    <Helmet title="Immediate Start Jobs" />
    <Navbar />

{children}

 )

export default TemplateWrapper

in Navbar:

<button className="button navbar-burger" data-target="navMenu">

    </button>

      <Link className="navbar-item" to="/about">
        About
      </Link>
      <Link className="navbar-item" to="/products">
        Products
      </Link>
      <Link className="navbar-item" to="/blog">
      Blog
    </Link>

in html.js

    import React from "react"
import PropTypes from "prop-types"

export default class HTML extends React.Component {
  render() {
    return (

          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          {this.props.headComponents}

          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}

Body:
That's just my two pennies' worth: https://nhpcr.codesandbox.io/

src/Navbar.js

import React from 'react';
import PropTypes from 'prop-types';

const NavbarItem = props => (
  <a className="navbar-item is-capitalized" href={`#${props.page}`}>
    {props.page}
  </a>
);
const NavbarBurger = props => (
  <button
    onClick={props.toggleMenu}
    className={`button navbar-burger ${props.active ? 'is-active' : ''}`}
  >
    <span />
    <span />
    <span />
  </button>
);

export default class Navbar extends React.Component {
  state = {
    activeMenu: false,
  };
  toggleMenu = () => {
    this.setState({
      activeMenu: !this.state.activeMenu,
    });
  };
  render() {
    let { pages = [], color } = this.props;
    let navbarItems = pages.map(page => <NavbarItem page={page} key={page} />);
    return (
      <nav className={`navbar is-fixed-top is-${color}`}>
        <div className="navbar-brand">
          <NavbarItem page="logo" />
          <NavbarBurger
            active={this.state.activeMenu}
            toggleMenu={this.toggleMenu}
          />
        </div>
        <div
          className={`navbar-menu ${this.state.activeMenu ? 'is-active' : ''}`}
        >
          <div className="navbar-start">{navbarItems}</div>
        </div>
      </nav>
    );
  }
}

Navbar.propTypes = {
  pages: PropTypes.array.isRequired,
  color: PropTypes.string,
};

src/index.js

import React from 'react';
import { render } from 'react-dom';

import Navbar from './Navbar';

import 'bulma/css/bulma.css';

const styles = {
  fontFamily: 'sans-serif',
  textAlign: 'center',
};

const pages = ['about', 'contact', 'sitemap'];
const App = () => (
  <div style={styles}>
    <Navbar pages={pages} />
  </div>
);

render(<App />, document.getElementById('root'));


问:
Proper way to get current User ID in Entity Framework Core
There are a bunch of different answers floating around here for the different RC's of ASP.NET Core on how to get the ID of the currently logged in user. I wanted to ask the definite question here. Please note that project.json now has "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0"

With RC1, you could do something like this:

```<code>using Microsoft.AspNet.Identity;
using System.Security.Claims;

User.GetUserId();
</code>```

But with the newly released version 1 of EF Core, Microsoft.AspNet.Identity is not the right version.

There was suggestions to use UserManager, which seems like a lot just to get the currently logged in user:

```<code>private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

var user = await GetCurrentUserAsync();
var userId = user?.Id;
</code>```

Another method that I found was:

```<code>private readonly UserManager<ApplicationUser> _userManager;
_userManager.GetUserId(User)
</code>```

So with ASP.NET Core 1 RTM and EF Core 1 with the following libraries in project.json, what is the proper way to get the id of the currently logged in user?

```<code>"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
</code>```

答:
You can get UserId by this way also.

```<code>public class Program
   {
           private readonly SignInManager<ApplicationUser> _signInManager;

           public Program(SignInManager<ApplicationUser> signInManager)
           {
               _signInManager = signInManager;
              var UserId = _signInManager.Context.User.Claims.FirstOrDefault().Value;
           }
   }
</code>```

Where ApplicationUser class is given below....

```<code>public class ApplicationUser:IdentityUser
    {
        [Column(TypeName = "Nvarchar(500)")]
        public string FirstName { get; set; }
        [Column(TypeName = "Nvarchar(500)")]
        public string MiddleName { get; set; }
        [Column(TypeName = "Nvarchar(500)")]
        public string LastName { get; set; }
        [Column(TypeName = "DateTime")]
        public DateTime? LastAccess { get; set; }
    }
</code>```

And Your ApplicationUser class should inherited by IdentityUser.

Body:
There are a bunch of different answers floating around here for the different RC's of ASP.NET Core on how to get the ID of the currently logged in user. I wanted to ask the definite question here. Please note that project.json now has "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0"

With RC1, you could do something like this:

using Microsoft.AspNet.Identity;
using System.Security.Claims;

User.GetUserId();

But with the newly released version 1 of EF Core, Microsoft.AspNet.Identity is not the right version.

There was suggestions to use UserManager, which seems like a lot just to get the currently logged in user:

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

var user = await GetCurrentUserAsync();
var userId = user?.Id;

Another method that I found was:

private readonly UserManager<ApplicationUser> _userManager;
_userManager.GetUserId(User)

So with ASP.NET Core 1 RTM and EF Core 1 with the following libraries in project.json, what is the proper way to get the id of the currently logged in user?

"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",

Body:
You can get UserId by this way also.

public class Program
   {
           private readonly SignInManager<ApplicationUser> _signInManager;

           public Program(SignInManager<ApplicationUser> signInManager)
           {
               _signInManager = signInManager;
              var UserId = _signInManager.Context.User.Claims.FirstOrDefault().Value;
           }
   }

Where ApplicationUser class is given below....

public class ApplicationUser:IdentityUser
    {
        [Column(TypeName = "Nvarchar(500)")]
        public string FirstName { get; set; }
        [Column(TypeName = "Nvarchar(500)")]
        public string MiddleName { get; set; }
        [Column(TypeName = "Nvarchar(500)")]
        public string LastName { get; set; }
        [Column(TypeName = "DateTime")]
        public DateTime? LastAccess { get; set; }
    }

And Your ApplicationUser class should inherited by IdentityUser.


问:
Why is the regular expression not matching the last part of the string?
Why does this regular expression:

```<code>Summary:(\r\n\t\t\/\/     (.+))+
</code>```

not match the last line of the following string? (NOTE the whitespace at the beginning of each line is two tab characters but has been converted to all spaces, at least in my browser--it's correct in edit mode, though.)  Shouldn't the + quantifier cause the part of the pattern in the outer-most parens to match the last line too?

```
        //
        // Summary:
        //     Do absolutely nothing and don't do anything else other than to do nothing at
        //     all.
```

Here's the result on http://regexstorm.net/tester:

答:
I'm guessing that what we likely want to have here is an expression to pass new lines, such as maybe this one:

```<code>Summary:([\s\S]*)
</code>```

or

```<code>Summary:([\w\W]*)
</code>```

or

```<code>Summary:([\d\D]*)
</code>```

DEMO

Body:
Why does this regular expression:

Summary:(\r\n\t\t\/\/     (.+))+

not match the last line of the following string? (NOTE the whitespace at the beginning of each line is two tab characters but has been converted to all spaces, at least in my browser--it's correct in edit mode, though.)  Shouldn't the + quantifier cause the part of the pattern in the outer-most parens to match the last line too?

        //
        // Summary:
        //     Do absolutely nothing and don't do anything else other than to do nothing at
        //     all.

Here's the result on http://regexstorm.net/tester:

Body:
I'm guessing that what we likely want to have here is an expression to pass new lines, such as maybe this one:

Summary:([\s\S]*)

or

Summary:([\w\W]*)

or

Summary:([\d\D]*)

DEMO


问:
Inconsistent JSON
I am trying to parse JSON in C# which is inconsistent, i.e
Below are the example of JSON that I am getting.

```<code>    {
    "Timestamp" : "2019-05-09T11:24:25.000Z",
    "Channel" : "web",
    "Supplier" : "kunde",
    "Generator" : "survey",
    "Type" : "hudtest",
    "Data" :{
        "Alder" : "20-29",
        "Køn" : "Kvinde",
        "Hudtype" : "sensitiv",
        "Hudtilstand" : "mixet"
       }
}
</code>```

and variation of this JSON is like this:

```<code>    {
    "Timestamp" : "2019-05-09T11:24:25.000Z",
    "Channel" : "web",
    "Supplier" : "kunde",
    "Generator" : "survey",
    "Type" : "hudtest",
    "Data" :{
        "Alder" : "20-29",
        "Køn" : "Kvinde",
        "Hudtype" : "sensitiv",
        "Hudtilstand" : "mixet",
        "materialistID" : 61234,
        "Anbefalede produkter" : [ 100225, 725125 ]
    }
}
</code>```

As you can see in both example I have different values in Data key. How can I parse this JSON in C#?

FYI: The Data key can have different value from the example i shared above. Not only "Anbefalede produkter. It can contain number of different values.
I have tried making it dynamic or parsing into anonymous type as well. But I also want to validate my JSON schema, Except Data Key other keys must be validated and they are mandatory.

答:
You can do like this

```<code>      class Program
    {
        static void Main(string[] args)
        {

            string jsonData = @"{  'Timestamp': '2019-05-09T11:24:25.000Z',
    'Channel': 'web',
    'Supplier': 'kunde',
    'Generator': 'survey',
    'Type': 'hudtest',
    'Data': {
        'Alder': '20-29',
        'Køn': 'Kvinde',
        'Hudtype': 'sensitiv',
        'Hudtilstand': 'mixet',
        'materialistID': 61234,
        'Anbefalede produkter': [100225, 725125]
    }
}";

            var b = JsonConvert.DeserializeObject<Rootobject>(jsonData);

            //Console.WriteLine(b.Data.Hudtype);
            //or
            Console.WriteLine(b.Data["Hudtype"]);

            Console.ReadKey();

        }

    }

    public class Rootobject
    {
        public DateTime Timestamp { get; set; }
        public string Channel { get; set; }
        public string Supplier { get; set; }
        public string Generator { get; set; }
        public string Type { get; set; }
        public Dictionary<string, object> Data { get; set; }
    }
</code>```

Hope this will solve your problem.
Thanks

Title: Inconsistent JSON

Body:
I am trying to parse JSON in C# which is inconsistent, i.e
Below are the example of JSON that I am getting.

    {
    "Timestamp" : "2019-05-09T11:24:25.000Z",
    "Channel" : "web",
    "Supplier" : "kunde",
    "Generator" : "survey",
    "Type" : "hudtest",
    "Data" :{
        "Alder" : "20-29",
        "Køn" : "Kvinde",
        "Hudtype" : "sensitiv",
        "Hudtilstand" : "mixet"
       }
}

and variation of this JSON is like this:

    {
    "Timestamp" : "2019-05-09T11:24:25.000Z",
    "Channel" : "web",
    "Supplier" : "kunde",
    "Generator" : "survey",
    "Type" : "hudtest",
    "Data" :{
        "Alder" : "20-29",
        "Køn" : "Kvinde",
        "Hudtype" : "sensitiv",
        "Hudtilstand" : "mixet",
        "materialistID" : 61234,
        "Anbefalede produkter" : [ 100225, 725125 ]
    }
}

As you can see in both example I have different values in Data key. How can I parse this JSON in C#?

FYI: The Data key can have different value from the example i shared above. Not only "Anbefalede produkter. It can contain number of different values.
I have tried making it dynamic or parsing into anonymous type as well. But I also want to validate my JSON schema, Except Data Key other keys must be validated and they are mandatory.

Body:
You can do like this

      class Program
    {
        static void Main(string[] args)
        {

            string jsonData = @"{  'Timestamp': '2019-05-09T11:24:25.000Z',
    'Channel': 'web',
    'Supplier': 'kunde',
    'Generator': 'survey',
    'Type': 'hudtest',
    'Data': {
        'Alder': '20-29',
        'Køn': 'Kvinde',
        'Hudtype': 'sensitiv',
        'Hudtilstand': 'mixet',
        'materialistID': 61234,
        'Anbefalede produkter': [100225, 725125]
    }
}";

            var b = JsonConvert.DeserializeObject<Rootobject>(jsonData);

            //Console.WriteLine(b.Data.Hudtype);
            //or
            Console.WriteLine(b.Data["Hudtype"]);

            Console.ReadKey();

        }

    }

    public class Rootobject
    {
        public DateTime Timestamp { get; set; }
        public string Channel { get; set; }
        public string Supplier { get; set; }
        public string Generator { get; set; }
        public string Type { get; set; }
        public Dictionary<string, object> Data { get; set; }
    }

Hope this will solve your problem.
Thanks


答:
That's because you're using RxJS streams in the wrong way. You setup your stream first, so any other console.log would run first. The Rx stream is async by itself, so you don't need async await. The other console.log will run when the stream actually is called and receives data.

The RxJS way would be to .pipe() your filter() inside the Rx stream.

It's not so much an Angular problem, it's more RxJS related. Here's an example of what it could look like:

```<code>   this.listUserService
  .getUsers()
  .pipe(
    tap(listUserData => {
      this.listUsers = listUserData;
    }),
    switchMap(data => {
      return this.friendsService.getFriends(data.id).pipe(
        tap(friends => {
          this.friends = friends;
        })
      );
    })
  )
  .subscribe();

</code>```

The switchMap switches to another observable underwater, so you don't need two subscriptions. This is considered good practice!

I would highly recommend spending some time learning RxJS, it'll make your experiences in Angular much more enjoyable and productive!

I can help you out with that if you'd like!

Body:
How can I change the order of execution? I have an array this.friend, I need work with this array, but it takes to fill up with data

this.listUserService.getUsers().subscribe(
    async (data: any) => {
           this.listUsers = data;
           await data.forEach((current: any) => {
                 if (current.name === userSession) {
                      this.user = current;
                      this.friendsService.getFriends(this.user.id).subscribe(response => {
                                console.log('last', response);//this runs second
                                this.friends = response;
                            });
                        }
                    });
                    console.log('friends', this.friends); //friend is clear,
this runs first
                    this.listUsers = this.listUsers.filter(user => !this.friends.some(relationship => relationship[0].friend.id !== user.id));
                }
            );

The console messages are shown in reverse order, how can I change the order, once it's full I want to use the Filter function

Body:
That's because you're using RxJS streams in the wrong way. You setup your stream first, so any other console.log would run first. The Rx stream is async by itself, so you don't need async await. The other console.log will run when the stream actually is called and receives data.

The RxJS way would be to .pipe() your filter() inside the Rx stream.

It's not so much an Angular problem, it's more RxJS related. Here's an example of what it could look like:

   this.listUserService
  .getUsers()
  .pipe(
    tap(listUserData => {
      this.listUsers = listUserData;
    }),
    switchMap(data => {
      return this.friendsService.getFriends(data.id).pipe(
        tap(friends => {
          this.friends = friends;
        })
      );
    })
  )
  .subscribe();

The switchMap switches to another observable underwater, so you don't need two subscriptions. This is considered good practice!

I would highly recommend spending some time learning RxJS, it'll make your experiences in Angular much more enjoyable and productive!

I can help you out with that if you'd like!


问:
Getting last modification date of files in directory using PHP
I am trying to get the last modification date of all files in a directory using PHP.

I am using this:

```<code>foreach($dir as $file)
{
$mod_date=date("F d Y H:i:s.", filemtime($file));
}
</code>```

foreach($dir as $file) is returning the correct files, but all of the modification dates are coming back as 0000-00-00 00:00:00, instead of the actual modification date.

What changes do I need to make to get this working?

答:
Rather than use glob function, why not use scandir function.
Secondly, you could easily get the date format you want by using date("Y-m-d H:i:s", filemtime($file))

Body:
I am trying to get the last modification date of all files in a directory using PHP.

I am using this:

foreach($dir as $file)
{
$mod_date=date("F d Y H:i:s.", filemtime($file));
}

foreach($dir as $file) is returning the correct files, but all of the modification dates are coming back as 0000-00-00 00:00:00, instead of the actual modification date.

What changes do I need to make to get this working?


问:
Have fixed parameters in Java constructor - possible?
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

```<code>public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}
</code>```

and then call something along the lines of:

```<code>switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}
</code>```

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

答: Another solution if your constructors become hard to distinquish is to use static factory methods because these can have descriptive names. But as Bobby mentioned this seems to be more a case for refactoring to multiple types.</p>

Body:
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}

and then call something along the lines of:

switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.


问:
Vuejs typescript this.$refs.<refField>.value does not exist
While rewriting my VueJs project in typescript, I came across a TypeScript error.

This is a part of the component that has a custom v-model.

An input field in the html has a ref called 'plate' and I want to access the value of that. The @input on that field calls the update method written below.

Typescript is complaining that value does not exist on plate.

```<code>@Prop() value: any;

update() {
    this.$emit('input',
        plate: this.$refs.plate.value
    });
}
</code>```

template:

```<code><template>
<div>
    <div class="form-group">
        <label for="inputPlate" class="col-sm-2 control-label">Plate</label>

        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" @input="update">
        </div>
    </div>

</div>
</template>
</code>```

答:
Edit - 2021-03 (Composition API)

Updating this answer because Vue 3 (or the composition API plugin if you're using Vue 2) has some new functions.

```<code><template>
  <div ref="root">This is a root element</div>
</template>

<script lang="ts">
  import { ref, onMounted, defineComponent } from '@vue/composition-api'

  export default defineComponent({
    setup() {
      const root = ref(null)

      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value) // <div>This is a root element</div>
      })

      return {
        root
      }
    }
  })
</script>
</code>```

Edit - 2020-04:

The vue-property-decorator library provides @Ref which I recommend instead of my original answer.

import { Vue, Component, Ref } from 'vue-property-decorator'

import AnotherComponent from '@/path/to/another-component.vue'

@Component
export default class YourComponent extends Vue {
  @Ref() readonly anotherComponent!: AnotherComponent
  @Ref('aButton') readonly button!: HTMLButtonElement
}
```
<hr />
<h2>Original Answer</h2>
<p>None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.</p>
<pre class="lang-js prettyprint-override"><code>class YourComponent extends Vue {
  $refs!: {
    vue: Vue,
    element: HTMLInputElement,
    vues: Vue[],
    elements: HTMLInputElement[]
  }

  someMethod () {
    this.$refs.<element>.<attribute>
  }
}
</code>```

Body:
While rewriting my VueJs project in typescript, I came across a TypeScript error.

This is a part of the component that has a custom v-model.

An input field in the html has a ref called 'plate' and I want to access the value of that. The @input on that field calls the update method written below.

Typescript is complaining that value does not exist on plate.

@Prop() value: any;

update() {
    this.$emit('input',
        plate: this.$refs.plate.value
    });
}

template:

<template>

        Plate

            <input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" @input="update">

</template>

Body:
Edit - 2021-03 (Composition API)

Updating this answer because Vue 3 (or the composition API plugin if you're using Vue 2) has some new functions.

<template>
  <div ref="root">This is a root element</div>
</template>

<script lang="ts">
  import { ref, onMounted, defineComponent } from '@vue/composition-api'

  export default defineComponent({
    setup() {
      const root = ref(null)

      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value) // <div>This is a root element</div>
      })

      return {
        root
      }
    }
  })
</script>

Edit - 2020-04:

The vue-property-decorator library provides @Ref which I recommend instead of my original answer.

import { Vue, Component, Ref } from 'vue-property-decorator'

import AnotherComponent from '@/path/to/another-component.vue'

@Component
export default class YourComponent extends Vue {
  @Ref() readonly anotherComponent!: AnotherComponent
  @Ref('aButton') readonly button!: HTMLButtonElement
}

Original Answer

None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.

class YourComponent extends Vue {
  $refs!: {
    vue: Vue,
    element: HTMLInputElement,
    vues: Vue[],
    elements: HTMLInputElement[]
  }

  someMethod () {
    this.$refs.<element>.<attribute>
  }
}


问:
How to import xml data with XMLDOM using a comma as decimal separator
I am pretty new to VBA and importing data from a xml file.
At the moment I am working on a VBA script which imports the values of specific xml nodes in to an excel sheet. I was using the following guide which i changed to my needs:

https://excel-macro.tutorialhorizon.com/vba-excel-read-data-from-xml-file/

But I have some trouble to import decimal numbers. In the xml file the decimal seperator is a comma which the script will not recognize. Excel turns 75,13 into 7513.

When I change the decimal seperator in the xml file to a dot it works but is there a way to do this without touching the xml file for pre-processing?

I import the nodes as follows:

```<code>mainWorkBook.Sheets("Sheet1").Range("A" & intCounter).Value = G_JAHRE(i).ChildNodes(0).nodeTypedValue
</code>```

答:
It is a bit tricky to give you a perfect solution with the limited input, but here's a start:

```<code>mainWorkBook.Sheets("Sheet1").Range("A" & intCounter).Value = Replace(G_JAHRE(i).ChildNodes(0).nodeTypedValue, ".", ",")
</code>```

It makes a search for dot and replace with comma.

It is not an ideal solution and there are plenty of cases where it won't work, but if you have fairly clean input, it will most likely help.

Body:
I am pretty new to VBA and importing data from a xml file.
At the moment I am working on a VBA script which imports the values of specific xml nodes in to an excel sheet. I was using the following guide which i changed to my needs:

https://excel-macro.tutorialhorizon.com/vba-excel-read-data-from-xml-file/

But I have some trouble to import decimal numbers. In the xml file the decimal seperator is a comma which the script will not recognize. Excel turns 75,13 into 7513.

When I change the decimal seperator in the xml file to a dot it works but is there a way to do this without touching the xml file for pre-processing?

I import the nodes as follows:

mainWorkBook.Sheets("Sheet1").Range("A" & intCounter).Value = G_JAHRE(i).ChildNodes(0).nodeTypedValue

Body:
It is a bit tricky to give you a perfect solution with the limited input, but here's a start:

mainWorkBook.Sheets("Sheet1").Range("A" & intCounter).Value = Replace(G_JAHRE(i).ChildNodes(0).nodeTypedValue, ".", ",")

It makes a search for dot and replace with comma.

It is not an ideal solution and there are plenty of cases where it won't work, but if you have fairly clean input, it will most likely help.


问:
php eclipse debugging
I am runing a php script using eclipse. when a set breakpoint and run the script it throws me this error.

form the error it is apparent that i have change something the php.ini file. but i dont know what i have to change to make either zend or xdebug. even i dont know what the differnce b/w them.

following the error

The session could not be started.
In order to generate debug information, please make sure that the debugger is properly configured as a php.ini directive

答:
To solve this issue we need to go to the windows=>preferences and type PHP. There you can find PHP Executables and add

Name: php

Executable path: path you installed PHP (ex: C:\php\php.exe)

PHP ini file:  C:\php\php.ini

SAPI Type: CLI

PHP debugger: Zend Debugger to Xdebug

See the screenshot below:

Title: php eclipse debugging


问:
Pandas parse json column and and keep existing column into a new dataframe
I have the following dataframe:

```<code>name  stats
smith {"eye_color": "brown", "height": 160, "weight": 76}
jones {"eye_color": "blue", "height": 170, "weight": 85}
will  {"eye_color": "green", "height": 180, "weight": 94}
</code>```

I use the following code to parse the json field into a new dataframe:

```<code>new_df = df["stats"].apply(json.loads).apply(pd.Series)
</code>```

This gives me new_df:

```<code>eye_color height weight
brown     160    76
blue      170    85
green     180    94
</code>```

How can I update the code the above to add name to new_df, so that I have:

```<code>name  eye_color height weight
smith brown     160    76
jones blue      170    85
will  green     180    94
</code>```

答:
Use df.join():

```<code>new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series))
</code>```

Body:
I have the following dataframe:

name  stats
smith {"eye_color": "brown", "height": 160, "weight": 76}
jones {"eye_color": "blue", "height": 170, "weight": 85}
will  {"eye_color": "green", "height": 180, "weight": 94}

I use the following code to parse the json field into a new dataframe:

new_df = df["stats"].apply(json.loads).apply(pd.Series)

This gives me new_df:

eye_color height weight
brown     160    76
blue      170    85
green     180    94

How can I update the code the above to add name to new_df, so that I have:

name  eye_color height weight
smith brown     160    76
jones blue      170    85
will  green     180    94

Body:
Use df.join():

new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series))


问:
is there a way to create custom event and dispatch events on classes in cocos creator?
how do I create custom events in cocos creator? I tried creating a singleton class and using the instance to addEventListener, but that didn't work.
thanks!</p>

答:
You can do it in diferent ways, but on of the more effectives, how can goes over differents nodes are:

```<code>cc.game.emit("specialEvent", eventParamenters);
</code>```

and in your listener script:

```<code>cc.game.on("specialEvent", (eventData)=> { ...doSomething... } );
</code>```

Body:
You can do it in diferent ways, but on of the more effectives, how can goes over differents nodes are:

cc.game.emit("specialEvent", eventParamenters);

and in your listener script:

cc.game.on("specialEvent", (eventData)=> { ...doSomething... } );


问:
What is the quickest way from a concept to a site?
I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary.

I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site.  I was kinda wondering if there is such a thing, free or non-free

Looking forward to your suggestions...

UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint..

答: Something that other posters haven't mentioned so far is sketching out the interface first. Design what your main screen will look like, and where the links will take you. It's always a good idea to plan before diving into your problem. </p>

OwnerDisplayName: Cip

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: alamodey