问:
Spark 2.0 with spark.read.text Expected scheme-specific part at index 3: s3: error
I am running into a weird issue with spark 2.0, using the sparksession to load a text file. Currently my spark config looks like:

```<code>val sparkConf = new SparkConf().setAppName("name-here")
sparkConf.registerKryoClasses(Array(Class.forName("org.apache.hadoop.io.LongWritable"), Class.forName("org.apache.hadoop.io.Text")))
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
val spark = SparkSession.builder()
    .config(sparkConf)
    .getOrCreate()
spark.sparkContext.hadoopConfiguration.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
spark.sparkContext.hadoopConfiguration.set("fs.s3a.enableServerSideEncryption", "true")
spark.sparkContext.hadoopConfiguration.set("mapreduce.fileoutputcommitter.algorithm.version", "2")
</code>```

If I load an s3a file through an rdd, it works fine. However, if I try to use something like:

```<code>    val blah = SparkConfig.spark.read.text("s3a://bucket-name/*/*.txt")
        .select(input_file_name, col("value"))
        .drop("value")
        .distinct()
    val x = blah.collect()
    println(blah.head().get(0))
    println(x.size)
</code>```

I get an exception that says: java.net.URISyntaxException: Expected scheme-specific part at index 3: s3:

Do I need to add some addition s3a configuration for the sqlcontext or sparksession? I haven't found any question or online resource that specifies this. What is weird is that it seems like the job runs for 10 minutes, but then fails with this exception. Again, using the same bucket and everything, a regular load of an rdd has no issues.

The other weird thing is that it is complaining about s3 and not s3a. I have triple checked my prefix, and it always says s3a.

Edit: Checked both s3a and s3, both throw the same exception.

```<code>17/04/06 21:29:14 ERROR ApplicationMaster: User class threw exception:
java.lang.IllegalArgumentException: java.net.URISyntaxException:
Expected scheme-specific part at index 3: s3:
java.lang.IllegalArgumentException: java.net.URISyntaxException:
Expected scheme-specific part at index 3: s3:
at org.apache.hadoop.fs.Path.initialize(Path.java:205)
at org.apache.hadoop.fs.Path.<init>(Path.java:171)
at org.apache.hadoop.fs.Path.<init>(Path.java:93)
at org.apache.hadoop.fs.Globber.glob(Globber.java:240)
at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1732)
at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1713)
at org.apache.spark.deploy.SparkHadoopUtil.globPath(SparkHadoopUtil.scala:237)
at org.apache.spark.deploy.SparkHadoopUtil.globPathIfNecessary(SparkHadoopUtil.scala:243)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:374)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:370)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
at scala.collection.immutable.List.flatMap(List.scala:344)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:370)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
at org.apache.spark.sql.DataFrameReader.text(DataFrameReader.scala:506)
at org.apache.spark.sql.DataFrameReader.text(DataFrameReader.scala:486)
at com.omitted.omitted.jobs.Omitted$.doThings(Omitted.scala:18)
at com.omitted.omitted.jobs.Omitted$.main(Omitted.scala:93)
at com.omitted.omitted.jobs.Omitted.main(Omitted.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:637)
Caused by: java.net.URISyntaxException: Expected scheme-specific part
at index 3: s3:
at java.net.URI$Parser.fail(URI.java:2848)
at java.net.URI$Parser.failExpecting(URI.java:2854)
at java.net.URI$Parser.parse(URI.java:3057)
at java.net.URI.<init>(URI.java:746)
at org.apache.hadoop.fs.Path.initialize(Path.java:202)
... 26 more
17/04/06 21:29:14 INFO ApplicationMaster: Final app status: FAILED,
exitCode: 15, (reason: User class threw exception:
java.lang.IllegalArgumentException: java.net.URISyntaxException:
Expected scheme-specific part at index 3: s3:)
</code>```

答:
This should work.

get the right JARs on your CP (Spark with Hadoop 2.7, matching hadoop-aws JAR, aws-java-sdk-1.7.4.jar (exactly this version) and joda-time-2.9.3.jar (or a later vesion)

you shouldn't need to set the fs.s3a.impl value, as that's done in the hadoop default settings. If you do find yourself doing that, it's a sign of a problem.

What's the full stack trace?

Body:
I am running into a weird issue with spark 2.0, using the sparksession to load a text file. Currently my spark config looks like:

val sparkConf = new SparkConf().setAppName("name-here")
sparkConf.registerKryoClasses(Array(Class.forName("org.apache.hadoop.io.LongWritable"), Class.forName("org.apache.hadoop.io.Text")))
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
val spark = SparkSession.builder()
    .config(sparkConf)
    .getOrCreate()
spark.sparkContext.hadoopConfiguration.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
spark.sparkContext.hadoopConfiguration.set("fs.s3a.enableServerSideEncryption", "true")
spark.sparkContext.hadoopConfiguration.set("mapreduce.fileoutputcommitter.algorithm.version", "2")

If I load an s3a file through an rdd, it works fine. However, if I try to use something like:

    val blah = SparkConfig.spark.read.text("s3a://bucket-name/*/*.txt")
        .select(input_file_name, col("value"))
        .drop("value")
        .distinct()
    val x = blah.collect()
    println(blah.head().get(0))
    println(x.size)

I get an exception that says: java.net.URISyntaxException: Expected scheme-specific part at index 3: s3:

Do I need to add some addition s3a configuration for the sqlcontext or sparksession? I haven't found any question or online resource that specifies this. What is weird is that it seems like the job runs for 10 minutes, but then fails with this exception. Again, using the same bucket and everything, a regular load of an rdd has no issues.

The other weird thing is that it is complaining about s3 and not s3a. I have triple checked my prefix, and it always says s3a.

Edit: Checked both s3a and s3, both throw the same exception.

17/04/06 21:29:14 ERROR ApplicationMaster: User class threw exception:
java.lang.IllegalArgumentException: java.net.URISyntaxException:
Expected scheme-specific part at index 3: s3:
java.lang.IllegalArgumentException: java.net.URISyntaxException:
Expected scheme-specific part at index 3: s3:
at org.apache.hadoop.fs.Path.initialize(Path.java:205)
at org.apache.hadoop.fs.Path.<init>(Path.java:171)
at org.apache.hadoop.fs.Path.<init>(Path.java:93)
at org.apache.hadoop.fs.Globber.glob(Globber.java:240)
at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1732)
at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1713)
at org.apache.spark.deploy.SparkHadoopUtil.globPath(SparkHadoopUtil.scala:237)
at org.apache.spark.deploy.SparkHadoopUtil.globPathIfNecessary(SparkHadoopUtil.scala:243)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:374)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:370)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
at scala.collection.immutable.List.flatMap(List.scala:344)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:370)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
at org.apache.spark.sql.DataFrameReader.text(DataFrameReader.scala:506)
at org.apache.spark.sql.DataFrameReader.text(DataFrameReader.scala:486)
at com.omitted.omitted.jobs.Omitted$.doThings(Omitted.scala:18)
at com.omitted.omitted.jobs.Omitted$.main(Omitted.scala:93)
at com.omitted.omitted.jobs.Omitted.main(Omitted.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:637)
Caused by: java.net.URISyntaxException: Expected scheme-specific part
at index 3: s3:
at java.net.URI$Parser.fail(URI.java:2848)
at java.net.URI$Parser.failExpecting(URI.java:2854)
at java.net.URI$Parser.parse(URI.java:3057)
at java.net.URI.<init>(URI.java:746)
at org.apache.hadoop.fs.Path.initialize(Path.java:202)
... 26 more
17/04/06 21:29:14 INFO ApplicationMaster: Final app status: FAILED,
exitCode: 15, (reason: User class threw exception:
java.lang.IllegalArgumentException: java.net.URISyntaxException:
Expected scheme-specific part at index 3: s3:)


来源: stackexchange

问:
How to perform inner join in mysql
I have to write a query such that ,I need to get events whose start date  is of 30 min from now.
My conditions are:

1) get the event from events table

2)Join created by of events with id in users table.

3)Comments from comment table with user ser id

But the problem here is if there is no comment for event then the event it self is not coming.If any comment is present it is coming.I dont want this.If comment is not there just fetch it as empty but not hide the total event .Can anyone please help me,.Thanks.

```<code> select u.email ,group_members.user_id,users.first_name,u.first_name
                as host_name,events.name,events.start_date,comments.comments,c.first_name as
                comment_user,comments.id from events
                inner join users as u on u.id = events.created_by
                inner join comments on events.id = comments.event_id
                inner join group_members on events.group_id = group_members.group_id
                inner join users as c on comments.from_user = c.id
                inner join users on group_members.user_id = users.id
                where events.start_date  between date_add(now(),interval 1 minute) and date_add(
                now(),interval 30 minute)
                and group_members.user_status = 2
                and events.status = 2
</code>```

答:
You need a left join to the comments table.  I would put that table last in the from clause.

```<code>select u.email, gm.user_id, gu.first_name, u.first_name as host_name,
       e.name, e.start_date, c.comments, uc.first_name as comment_user,
       c.id
from events e inner join
     users u
     on u.id = e.created_by inner join
     group_members gm
     on e.events.group_id = gm.group_id inner join
     users gu
     on gm.user_id = gu.id left join
     comments c
     on e.id = c.event_id left join
     users uc
     on c.from_user = uc.id
where e.start_date between date_add(now(),interval 1 minute) and date_add(now(),interval 30 minute) and
       gm.user_status = 2 and
       e.status = 2;
</code>```

Once you use a left join on comments, you also need a left join for the from user.  I replaced all table names with aliases -- this makes it easier to track which table is used for which purpose.

ContentLicense: CC BY-SA 3.0

Title: How to perform inner join in mysql

Body:
I have to write a query such that ,I need to get events whose start date  is of 30 min from now.
My conditions are:

1) get the event from events table

2)Join created by of events with id in users table.

3)Comments from comment table with user ser id

But the problem here is if there is no comment for event then the event it self is not coming.If any comment is present it is coming.I dont want this.If comment is not there just fetch it as empty but not hide the total event .Can anyone please help me,.Thanks.

 select u.email ,group_members.user_id,users.first_name,u.first_name
                as host_name,events.name,events.start_date,comments.comments,c.first_name as
                comment_user,comments.id from events
                inner join users as u on u.id = events.created_by
                inner join comments on events.id = comments.event_id
                inner join group_members on events.group_id = group_members.group_id
                inner join users as c on comments.from_user = c.id
                inner join users on group_members.user_id = users.id
                where events.start_date  between date_add(now(),interval 1 minute) and date_add(
                now(),interval 30 minute)
                and group_members.user_status = 2
                and events.status = 2

Body:
You need a left join to the comments table.  I would put that table last in the from clause.

select u.email, gm.user_id, gu.first_name, u.first_name as host_name,
       e.name, e.start_date, c.comments, uc.first_name as comment_user,
       c.id
from events e inner join
     users u
     on u.id = e.created_by inner join
     group_members gm
     on e.events.group_id = gm.group_id inner join
     users gu
     on gm.user_id = gu.id left join
     comments c
     on e.id = c.event_id left join
     users uc
     on c.from_user = uc.id
where e.start_date between date_add(now(),interval 1 minute) and date_add(now(),interval 30 minute) and
       gm.user_status = 2 and
       e.status = 2;

Once you use a left join on comments, you also need a left join for the from user.  I replaced all table names with aliases -- this makes it easier to track which table is used for which purpose.


问:
All other browser like chrome and Firefox but not show on safari
```<code>https://testing007.s3-api.us-geo.objectstorage.softlayer.net/1A23CDC6F75811E6BFD706E21CB7534C---prof__6.jpg
</code>```

<p>all other browser like chrome and Firefox but not show on safari  </p>

答: Trying opening it in private mode check if it works that way</p>

Body:
https://testing007.s3-api.us-geo.objectstorage.softlayer.net/1A23CDC6F75811E6BFD706E21CB7534C---prof__6.jpg

all other browser like chrome and Firefox but not show on safari


问:
How to play audio file of URL link using AVAudioPlayer in iphone objective-c
I am creating a voice communication feature in my application that sends voice notes between users via a web server, however during
 testing I am experiencing an error with playing back message I created
 with AVAudioPlayer. The AVAudioplayer just returns a null value.

How do I play an audio file from the URL link with AVAudioPlayer?

```<code>if (!self.audioRecorder.recording) {

        NSURL *url = [NSURL URLWithString:[@"http://.../sound.mp4"]];
        NSLog(@"%@", url);
        NSLog(@"PlayBack");

        NSData *audioData = [NSData dataWithContentsOfURL:url];
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) objectAtIndex:0]
                              stringByAppendingPathComponent:@"sound1.caf"];
        [audioData writeToFile:filePath atomically:YES];

        NSError *error;
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
        if (self.audioPlayer == nil) {
            NSLog(@"%@", [error description]);
            NSLog(@"%@", [self.audioPlayer description]);
        }else
            [self.audioPlayer play];
    }else [self.audioRecorder stop];
</code>```

答:
please try out this code:

```<code>- (void) playMessageSound : (NSString *) filename{

self.soundFilename = filename;
//[[RBDMuteSwitch sharedInstance] detectMuteSwitch];
NSString *name = [filename stringByDeletingPathExtension];
NSString *extension = [filename pathExtension];
NSString *filePath = [[NSBundle mainBundle]pathForResource:name ofType:extension];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0;
[self.audioPlayer play];
</code>```

}

Body:
I am creating a voice communication feature in my application that sends voice notes between users via a web server, however during
 testing I am experiencing an error with playing back message I created
 with AVAudioPlayer. The AVAudioplayer just returns a null value.

How do I play an audio file from the URL link with AVAudioPlayer?

if (!self.audioRecorder.recording) {

        NSURL *url = [NSURL URLWithString:[@"http://.../sound.mp4"]];
        NSLog(@"%@", url);
        NSLog(@"PlayBack");

        NSData *audioData = [NSData dataWithContentsOfURL:url];
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) objectAtIndex:0]
                              stringByAppendingPathComponent:@"sound1.caf"];
        [audioData writeToFile:filePath atomically:YES];

        NSError *error;
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
        if (self.audioPlayer == nil) {
            NSLog(@"%@", [error description]);
            NSLog(@"%@", [self.audioPlayer description]);
        }else
            [self.audioPlayer play];
    }else [self.audioRecorder stop];

Body:
please try out this code:

- (void) playMessageSound : (NSString *) filename{

self.soundFilename = filename;
//[[RBDMuteSwitch sharedInstance] detectMuteSwitch];
NSString *name = [filename stringByDeletingPathExtension];
NSString *extension = [filename pathExtension];
NSString *filePath = [[NSBundle mainBundle]pathForResource:name ofType:extension];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0;
[self.audioPlayer play];

}


问:
How to establish a description for each file in git?
In most SCM systems (e.g. PTC Integrity, ClearCase) it is possible to have a description for each managed file as a kind of metadata.

The description can hold information like project, customer variant etc. and is necessary to fullfill normative standards.

Sure, this information can be put in the header of a source file - but how can I get this with binary files? Is there a way to get this in git?

答:
There is nothing exactly like this. So you probably would have to use additional file(s) as suggested in comments. Also there is semi-official way to add medatada to git commits in form of:

```<code><tag>: <info>
</code>```

For example, "Signed-off-by: User <user@example.com>". You could use that in a form of, for example, "X-FileDescription (<path>): <description>", and use command:

```<code>git log --fixed-strings --grep="X-FileDescription (<path>)" --max-count=1
</code>```

to find the last version of the description for a specific file.

Body:
There is nothing exactly like this. So you probably would have to use additional file(s) as suggested in comments. Also there is semi-official way to add medatada to git commits in form of:

<tag>: <info>

For example, "Signed-off-by: User <user@example.com>". You could use that in a form of, for example, "X-FileDescription (<path>): <description>", and use command:

git log --fixed-strings --grep="X-FileDescription (<path>)" --max-count=1

to find the last version of the description for a specific file.


问:
setup multiple azure web app for the same url?
Say we have one azure web app and pointing to url http://www.example.com

The web app is in UK.

Now we have lots of customers from Australia, can we create another web app and hosted in Australia and still responding to url http://www.example.com?

Then base on the location of the user (i.e. where the traffic is from), the dns entry will be resolved to point to either the web app hosted in uk or in Australia?

答:
What you are looking for is a service called Traffic Manager it can do just that. It has an internal integration with WebApps (if you use Standard or higher tier for WebApps).

Reference: https://learn.microsoft.com/en-us/azure/traffic-manager/traffic-manager-overview


问:
Dplyr replace value based on function of previous column and row
I'm trying to replace NA values with the mean of the previous row and previous column same row using dplyr. See example below:

```<code>df <- data.frame(A=c(1,1,2),
                    B=c(2,4,NA))
</code>```

So in this case the NA would be replaced by 3. How do I do this?

Below is what I was the lines I was thinking on but it doesn't work.

```<code>dfb <- df %>%
        mutate(B = if_else(is.na(B), mean(lag(B),A), B))
</code>```

Thanks!

答:
Instead of using mean we can mention them separately and then divide it by 2.

```<code>df %>% mutate(B = ifelse(is.na(B),(lag(B) + A)/2, B))

#  A B
#1 1 2
#2 1 4
#3 2 3
</code>```

Body:
I'm trying to replace NA values with the mean of the previous row and previous column same row using dplyr. See example below:

df <- data.frame(A=c(1,1,2),
                    B=c(2,4,NA))

So in this case the NA would be replaced by 3. How do I do this?

Below is what I was the lines I was thinking on but it doesn't work.

dfb <- df %>%
        mutate(B = if_else(is.na(B), mean(lag(B),A), B))

Thanks!

Body:
Instead of using mean we can mention them separately and then divide it by 2.

df %>% mutate(B = ifelse(is.na(B),(lag(B) + A)/2, B))

#  A B
#1 1 2
#2 1 4
#3 2 3


问:
Timer in Windows batch file
Can someone point me to a way of adding a timer to a Windows batch file? I need to track the time my batch runs from start.</p>

答:
As far as I know there is no explicit 'timer' command you can use in batch files - however there is a fairly simple solution.  At the top of your batch file record the current time (start time) at the end of the batch file record the current time (end time) and then compare the two.  Something like this should do it (it does seem overly complicated but it handles most quirks of time):

```<code>:: Store start time
set StartTIME=%TIME%
set H=%StartTIME:~0,2%
if "%H:~0,1%"==" " set H=%H:~1,1%
if "%H:~0,1%"=="0" set H=%H:~1,1%
set M=%StartTIME:~3,2%
if "%M:~0,1%"=="0" set M=%M:~1,1%
set S=%StartTIME:~6,2%
if "%S:~0,1%"=="0" set S=%S:~1,1%
set U=%StartTIME:~9,2%
if "%U:~0,1%"=="0" set U=%U:~1,1%
)
set /a Start100S=%H%*360000+%M%*6000+%S%*100+%U%

::
:: Add your script functionality here
::

:: Get the end time
set StopTIME=%TIME%
set H=%StopTIME:~0,2%
if "%H:~0,1%"==" " set H=%H:~1,1%
if "%H:~0,1%"=="0" set H=%H:~1,1%
set M=%StopTIME:~3,2%
if "%M:~0,1%"=="0" set M=%M:~1,1%
set S=%StopTIME:~6,2%
if "%S:~0,1%"=="0" set S=%S:~1,1%
set U=%StopTIME:~9,2%
if "%U:~0,1%"=="0" set U=%U:~1,1%
)

set /a Stop100S=%H%*360000+%M%*6000+%S%*100+%U%

:: Test midnight rollover. If so, add 1 day=8640000 1/100ths secs
if %Stop100S% LSS %Start100S% set /a Stop100S+=8640000
set /a TookTime=%Stop100S%-%Start100S%

echo Started: %StartTime%
echo Stopped: %StopTime%
echo Elapsed: %TookTime:~0,-2%.%TookTime:~-2% seconds
</code>```

Alternatively #1 : The Windows Server 2k3 resource kit includes timeit.exe.  You can use this to display various performance stats for your script.

Alternatively #2 : You could go much simpler than the script posted above and do this:

```<code>echo %time%
::
:: Your script functionality
::
echo %time%
</code>```

However, this won't give you execution time in seconds.

Title: Timer in Windows batch file

Body:
As far as I know there is no explicit 'timer' command you can use in batch files - however there is a fairly simple solution.  At the top of your batch file record the current time (start time) at the end of the batch file record the current time (end time) and then compare the two.  Something like this should do it (it does seem overly complicated but it handles most quirks of time):

:: Store start time
set StartTIME=%TIME%
set H=%StartTIME:~0,2%
if "%H:~0,1%"==" " set H=%H:~1,1%
if "%H:~0,1%"=="0" set H=%H:~1,1%
set M=%StartTIME:~3,2%
if "%M:~0,1%"=="0" set M=%M:~1,1%
set S=%StartTIME:~6,2%
if "%S:~0,1%"=="0" set S=%S:~1,1%
set U=%StartTIME:~9,2%
if "%U:~0,1%"=="0" set U=%U:~1,1%
)
set /a Start100S=%H%*360000+%M%*6000+%S%*100+%U%

::
:: Add your script functionality here
::

:: Get the end time
set StopTIME=%TIME%
set H=%StopTIME:~0,2%
if "%H:~0,1%"==" " set H=%H:~1,1%
if "%H:~0,1%"=="0" set H=%H:~1,1%
set M=%StopTIME:~3,2%
if "%M:~0,1%"=="0" set M=%M:~1,1%
set S=%StopTIME:~6,2%
if "%S:~0,1%"=="0" set S=%S:~1,1%
set U=%StopTIME:~9,2%
if "%U:~0,1%"=="0" set U=%U:~1,1%
)

set /a Stop100S=%H%*360000+%M%*6000+%S%*100+%U%

:: Test midnight rollover. If so, add 1 day=8640000 1/100ths secs
if %Stop100S% LSS %Start100S% set /a Stop100S+=8640000
set /a TookTime=%Stop100S%-%Start100S%

echo Started: %StartTime%
echo Stopped: %StopTime%
echo Elapsed: %TookTime:~0,-2%.%TookTime:~-2% seconds

Alternatively #1 : The Windows Server 2k3 resource kit includes timeit.exe.  You can use this to display various performance stats for your script.

Alternatively #2 : You could go much simpler than the script posted above and do this:

echo %time%
::
:: Your script functionality
::
echo %time%

However, this won't give you execution time in seconds.

ContentLicense: CC BY-SA 2.5


问:
I want to get Data from ajax call
I have made this ajax call to get data from view. Now I want to make a new ajax call to get data from this call in a new Ajax call. In short words want to make a new Ajax call on next button which will take data from this Ajax. But I dont know what will its url and how It will get data . Any idea ?</p>

```<code>function loadMaps(id) {
             var field = { id : id };
            var field1 = { id : id };
            jQuery.ajax('{% url "mapport.maps.product" %}', {
                data : field,
                nextpage : field1,

                success: function(response, status, xhr) {
                    showMaps(response.data)
                     pagination(response.nextpage, response.previouspage,                response.currentpage , response.totalpages,response.previousNum, response.nextNum)

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

答:
just create another function below run it the way you want as follows. I think your english is letting you down here.</p>

```<code>function loadMaps(id) {
        var field = { id : id };
        var field1 = { id : id };
        jQuery.ajax('{% url "mapport.maps.product" %}', {
            data : field,
            nextpage : field1,

            success: function(response, status, xhr) {
                showMaps(response.data)
                pagination(response.nextpage, response.previouspage,
            response.currentpage , response.totalpages,response.previousNum, response.nextNum)

newAjaxCall(response.data)

            }
        });
    }

function newAjaxCall(dataFromAbove) {

}
</code>```

Title: I want to get Data from ajax call

Body:
I have made this ajax call to get data from view. Now I want to make a new ajax call to get data from this call in a new Ajax call. In short words want to make a new Ajax call on next button which will take data from this Ajax. But I dont know what will its url and how It will get data . Any idea ?

function loadMaps(id) {
             var field = { id : id };
            var field1 = { id : id };
            jQuery.ajax('{% url "mapport.maps.product" %}', {
                data : field,
                nextpage : field1,

                success: function(response, status, xhr) {
                    showMaps(response.data)
                     pagination(response.nextpage, response.previouspage,                response.currentpage , response.totalpages,response.previousNum, response.nextNum)

                }
            });
        }

Body:
just create another function below run it the way you want as follows. I think your english is letting you down here.

function loadMaps(id) {
        var field = { id : id };
        var field1 = { id : id };
        jQuery.ajax('{% url "mapport.maps.product" %}', {
            data : field,
            nextpage : field1,

            success: function(response, status, xhr) {
                showMaps(response.data)
                pagination(response.nextpage, response.previouspage,
            response.currentpage , response.totalpages,response.previousNum, response.nextNum)

newAjaxCall(response.data)

            }
        });
    }

function newAjaxCall(dataFromAbove) {

}


问:
How to add triangle to input[type='text']
I want to add a small triangle to the upper-right corner of an input type='text' HTML element, like Excel uses to indicate a comment.

The accepted answer to this question:

How to add triangle in table cell

shows how to do it for a table cell.  I naively applied the "note" css class to my input element but it didn't work.  Any suggestions for how to achieve this?

答:
Given a simple input field

```<code> <input type="text" />
</code>```

and assuming we can't use or rely on a parent element for styling, you may use multiple box-shadow to create a triangle, e.g.

Codepen demo

Result (triangle outside)

Code

```<code>input {
  padding: 10px;
  border: 1px #ccc solid;
  margin: 15px;
  box-shadow: 0 -12px 0 #fff, 12px 0px 0 #fff,
              1px -12px 0 #fff, 2px -11px 0 #fff,
              3px -10px 0 #fff, 4px -9px 0 #fff,
              5px -8px 0 #fff, 6px -7px 0 #fff,
              7px -6px 0 #fff, 8px -5px 0 #fff,
              9px -3px 0 #fff, 10px -2px 0 #fff,
              11px -1px 0 #fff, 12px 0 0 #fff,
              8px -12px 0 #9bc;
}
</code>```

Of course you can change the size of the triangle playing with the offset(y/x) of the box-shadow.

If you need to place the triangle inside the input you could just add a couple of properties to the code above and use outline and outline-offset instead of the border property to create the illusion of an outer border. All the shadows don't move from their position, just give enough space to the offset in order to wrap them.

Codepen demo

Result (triangle inside)

Code

```<code>input {
   padding: 0;
   border: 0;
   outline: 1px #ccc solid;
   outline-offset: 15px;
   ...
}
</code>```

Body:
Given a simple input field

 <input type="text" />

and assuming we can't use or rely on a parent element for styling, you may use multiple box-shadow to create a triangle, e.g.

Codepen demo

Result (triangle outside)

Code

input {
  padding: 10px;
  border: 1px #ccc solid;
  margin: 15px;
  box-shadow: 0 -12px 0 #fff, 12px 0px 0 #fff,
              1px -12px 0 #fff, 2px -11px 0 #fff,
              3px -10px 0 #fff, 4px -9px 0 #fff,
              5px -8px 0 #fff, 6px -7px 0 #fff,
              7px -6px 0 #fff, 8px -5px 0 #fff,
              9px -3px 0 #fff, 10px -2px 0 #fff,
              11px -1px 0 #fff, 12px 0 0 #fff,
              8px -12px 0 #9bc;
}

Of course you can change the size of the triangle playing with the offset(y/x) of the box-shadow.

If you need to place the triangle inside the input you could just add a couple of properties to the code above and use outline and outline-offset instead of the border property to create the illusion of an outer border. All the shadows don't move from their position, just give enough space to the offset in order to wrap them.

Codepen demo

Result (triangle inside)

Code

input {
   padding: 0;
   border: 0;
   outline: 1px #ccc solid;
   outline-offset: 15px;
   ...
}


问:
.htaccess url rewrite remove id
Is it possible with .htaccess to remove the parameter ID of the url & just show the text. Currently i have url like

Current URL

```<code>http://localhost/profile.php?profileid=4554
</code>```

Rewrited with .htaccess

```<code>http://localhost/profileid-4554/My UserName
</code>```

Needed URL

```<code>http://localhost/profileid/My UserName
</code>```

In the above url, i want to remove the id 4554. My .htaccess

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^profileid-([0-9]+) profile?profileid=$1
</code>```

Is it possible to do that?

答:
```<code>index.php
<a href="directory/1">click</a>

detail.php
<?php
echo $_GET['id'];
echo $_GET['page'];
 ?>

.htaccess
RewriteEngine on
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$  detail.php?page=$1&id=$2    [NC,L]
</code>```

Title: .htaccess url rewrite remove id

Body:
Is it possible with .htaccess to remove the parameter ID of the url & just show the text. Currently i have url like

Current URL

http://localhost/profile.php?profileid=4554

Rewrited with .htaccess

http://localhost/profileid-4554/My UserName

Needed URL

http://localhost/profileid/My UserName

In the above url, i want to remove the id 4554. My .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^profileid-([0-9]+) profile?profileid=$1

Is it possible to do that?


问:
.NET Random Class picking always 0 when range is 0 or 1
I am writing a random question generator. I would like to pick one question from each section.

Random class with DateTime.Now.Milliseconds as seed value generates random numbers, if the range is greater than 2(0,2/2+). But, If I give a min of 0 and a max of 1 in the range, it always returns me 0.

Am I using it wrongly.

Please suggest if there are any other alternatives.

Thanks,
Mahesh

答:
Reading on MSDN (Random.Next(int), Random.Next(int, int)) you will see that the upper bound is always exclusive. That is, to get a number between 0 and 1 (both inclusive) you can do:</p>

```<code>Random prng = new Random();
Console.WriteLine(prng.Next(0, 2)); //2 because it is exclusive
</code>```

Body:
Reading on MSDN (Random.Next(int), Random.Next(int, int)) you will see that the upper bound is always exclusive. That is, to get a number between 0 and 1 (both inclusive) you can do:

Random prng = new Random();
Console.WriteLine(prng.Next(0, 2)); //2 because it is exclusive


问:
STS JPA Tools not generating all Entities from Tables
I have created a few tables in my DB and a demo project in STS which I have converted to a JPA project. I then right click on it and select JPA Tools -> Generate Entities from Tables.

It works perfectly, except that it does not generate all Entities from the Tables. I have added two new tables and can see the in the Data Source Explorer, but when doing the generation, entities for those two does not get generated.

I have had this problem before, it's almost as if STS is keeping cache or something from a previous generation and now doing only that, but I am not sure where to look or how to clean it.

Any help please.

答:
Got it working,

For those of you interested, I had to select each table one by one and generate the Entity. STS does not like it when you select all tables. Just select one and generate the entity, then repeat the process for the next one, etc, etc.


问:
GET Web API Method returns method not allowed
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

```<code>public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}
</code>```

and this is how I enabled CORS:

```<code>config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
</code>```

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

```<code>GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6
</code>```

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

```<code>public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
</code>```

答: From what I can see, you need to define the "api/Reserve" prefix. You can do so by adding a Route attribute to the controller class with this string, or modify the Route attribute in the method to "api/reserve/CommitReserve".</p>

Body:
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}

and this is how I enabled CORS:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}


问:
Is PHP used for quick and easy website where other languages are used in more complex websites?
I just put this question in serverfault.com and I know that this question may be rejected in Stackoverflow.

But I thought programmers know better.

This stat shows that PHP is used by 75.2% of all the websites whose server-side programming language.

http://w3techs.com/technologies/overview/programming_language/all

And this page shows that PHP is the least used server-side language in ranked by usage on top websites

http://w3techs.com/technologies/topsite/programming_language

Q1. Does this mean PHP is used for quick and easy website where other languages are used in more complex websites?

Q2. Why PHP is ranked at the bottom? Or why big company tend to use other language than PHP?

Update: I know that facebook and other biggies uses PHP. But it does not tell why there are more other languages are used in top websites.

答:
Q1

First of all this means, that "top sites" dont use, what everybody else use. Small sites tends to use a ready-to-use software, like wordpress, drupal, ..., which runs on nearly every hoster. "top sites" on the other hand can manage theire own server, write theire own software and therefore doesnt depend on existing software.

I would not assume, that these sites are all really more complex.

Q2
Dont know, what you want to know. Its located at the bottom of the list, because 3.2 is smaller than 3.5 ^^


答:
A simple base R method using subsetting is

```<code>df$B[is.na(df$B)] <- (df$B[which(is.na(df$B))-1] + df$A[is.na(df$B)]) / 2
df
  A B
1 1 2
2 1 4
3 2 3
</code>```

is.na returns a logical vector indicating whether each element is NA. which returns the position of logical TRUE elements. which is necessary for the first component of the average, since we have to find the lagged value.

This can be extended a bit to reduce computation (responding to docendo-discimus's comment) by computing the missing values once, and storing it, then re-using this vector.

```<code>missers <- is.na(df$B)
df$B[missers] <- (df$B[which(missers)-1] + df$A[missers]) / 2
#clean up, maybe
rm(missers)
</code>```

Title: Dplyr replace value based on function of previous column and row

Body:
A simple base R method using subsetting is

df$B[is.na(df$B)] <- (df$B[which(is.na(df$B))-1] + df$A[is.na(df$B)]) / 2
df
  A B
1 1 2
2 1 4
3 2 3

is.na returns a logical vector indicating whether each element is NA. which returns the position of logical TRUE elements. which is necessary for the first component of the average, since we have to find the lagged value.

This can be extended a bit to reduce computation (responding to docendo-discimus's comment) by computing the missing values once, and storing it, then re-using this vector.

missers <- is.na(df$B)
df$B[missers] <- (df$B[which(missers)-1] + df$A[missers]) / 2
#clean up, maybe
rm(missers)


问:
How to disable tableView scrolling?
When I add a tableView in a viewController by default the tableView scrolls, but I want it static. Is it possible?

Here is my code:

```<code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
   return names.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableview.dequeueReusableCellWithIdentifier("cell") as! TableViewCell
    cell.username.text = names[indexPath.row]
    return cell
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    return 50.0
}
</code>```

答:
Swift 3, 4 and 5:

```<code>tableView.isScrollEnabled = false
</code>```

Title: How to disable tableView scrolling?

Body:
When I add a tableView in a viewController by default the tableView scrolls, but I want it static. Is it possible?

Here is my code:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
   return names.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableview.dequeueReusableCellWithIdentifier("cell") as! TableViewCell
    cell.username.text = names[indexPath.row]
    return cell
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    return 50.0
}

Body:
Swift 3, 4 and 5:

tableView.isScrollEnabled = false

ContentLicense: CC BY-SA 4.0


问:
Keep fullscreen mode when navigating through webApp in iOS
I do have a web app which opens in fullscreen mode when launched from iOS homescreen via icon using the meta tag

```<code><meta name="apple-mobile-web-app-capable" content="yes">
</code>```

I also want to keep fullscreen mode when navigating through my app using normal

```<code><a href="category/pageA.html">Page A</a>
</code>```

links. I found several solution approaches setting the location.href manually to prevent iOS open the new page in Safari browser but this does not seems to work.

My current (non working) approach is as follows:

```<code>var openLink = function (event) {
  event.preventDefault();
  let target = event.target;
  while (target.tagName.toUpperCase() !== 'A') {
    target = target.parentNode;
  }
  let href = target.href;
  window.location.href = href;
  return false;
};
</code>```

And then on each (internal) link use

```<code><a href="category/pageA.html" onclick="openLink()">Page A</a>
</code>```

But this does not work and when clicked still opens Safari showing the linked page in normal mode (no fullscreen and with addressbar).

The only thing I currently did not try is to refactor my Web App to be a Single Page Application and thus don't have "real" links inside it. But if possible I would like to avoid this.

答:
Untested, but try replacing

```<code>window.location.href = href;
</code>```

with

```<code>window.location.assign( href );
</code>```

or

```<code>window.location.replace( href );
</code>```

The former allows navigation via window.history.back(), the latter doesn't.

Body:
I do have a web app which opens in fullscreen mode when launched from iOS homescreen via icon using the meta tag

<meta name="apple-mobile-web-app-capable" content="yes">

I also want to keep fullscreen mode when navigating through my app using normal

Page A

links. I found several solution approaches setting the location.href manually to prevent iOS open the new page in Safari browser but this does not seems to work.

My current (non working) approach is as follows:

var openLink = function (event) {
  event.preventDefault();
  let target = event.target;
  while (target.tagName.toUpperCase() !== 'A') {
    target = target.parentNode;
  }
  let href = target.href;
  window.location.href = href;
  return false;
};

And then on each (internal) link use

Page A

But this does not work and when clicked still opens Safari showing the linked page in normal mode (no fullscreen and with addressbar).

The only thing I currently did not try is to refactor my Web App to be a Single Page Application and thus don't have "real" links inside it. But if possible I would like to avoid this.

Body:
Untested, but try replacing

window.location.href = href;

with

window.location.assign( href );

or

window.location.replace( href );

The former allows navigation via window.history.back(), the latter doesn't.


问:
how can i remove some namespaces from output
I have and XML with more namespaces. in output XML i need some of them and some of required.

XML INPUT:

```<code>    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ali="http://www.niso.org/schemas/ali/1.0"
    xmlns:mml="http://www.w3.org/1998/Math/MathML"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <child1>child1</child1>
    <child2>child2</child2>
    <child3>child3</child3>
    <child4>child4</child4>
</root>
</code>```

XSLT :

```<code>    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ali="http://www.niso.org/schemas/ali/1.0"
    xmlns:mml="http://www.w3.org/1998/Math/MathML"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    extension-element-prefixes="ali"
    exclude-result-prefixes="xs ali xsi mml xlink"
    version="2.0">

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

MY OUTPUT:

```<code>    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ali="http://www.niso.org/schemas/ali/1.0" xmlns:mml="http://www.w3.org/1998/Math/MathML"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <child1>child1</child1>
    <child2>child2</child2>
    <child3>child3</child3>
    <child4>child4</child4>
</root>
</code>```

MY REQUIRED OUTPUT:

Need removed these only two namespaces ali

答:
You can try this:</p>

```<code> <xsl:template match="@* | node()">
        <xsl:copy copy-namespaces="no">
            <xsl:copy-of select="namespace::* except namespace::ali"/>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
</code>```

Body:
I have and XML with more namespaces. in output XML i need some of them and some of required.

XML INPUT:

    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ali="http://www.niso.org/schemas/ali/1.0"
    xmlns:mml="http://www.w3.org/1998/Math/MathML"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <child1>child1</child1>
    <child2>child2</child2>
    <child3>child3</child3>
    <child4>child4</child4>
</root>

XSLT :

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ali="http://www.niso.org/schemas/ali/1.0"
    xmlns:mml="http://www.w3.org/1998/Math/MathML"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    extension-element-prefixes="ali"
    exclude-result-prefixes="xs ali xsi mml xlink"
    version="2.0">

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

MY OUTPUT:

    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ali="http://www.niso.org/schemas/ali/1.0" xmlns:mml="http://www.w3.org/1998/Math/MathML"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <child1>child1</child1>
    <child2>child2</child2>
    <child3>child3</child3>
    <child4>child4</child4>
</root>

MY REQUIRED OUTPUT:

Need removed these only two namespaces ali

Body:
You can try this:

 <xsl:template match="@* | node()">
        <xsl:copy copy-namespaces="no">
            <xsl:copy-of select="namespace::* except namespace::ali"/>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>


问:
Why do I have to "git rm" when deleting files?
I started learning git and I found it strange how you have to use git command git rm file to delete file from repository. I aware that there is another way to do this which is to delete the file straight from repository then use git add file. Why do you have to do this, I thought git is smarter then that? What happen if I just move the file I want to delete to trashcan and process with normal flow git add . then git commit -m "message". I currently working on a school project and that is how I always deleting my files up to this point (move it to trash can and not declare git rm file). I didn't run into any problem or maybe they were problems but other team members may had cleaned it up.

答:
git-rm - Remove files from the working tree and from the index

Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory. (There is no option to remove a file only from the working tree and yet keep it in the index; use /bin/rm if you want to do that.) The files being removed have to be identical to the tip of the branch, and no updates to their contents can be staged in the index, though that default behavior can be overridden with the -f option. When --cached is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index.

https://git-scm.com/docs/git-rm


问:
ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke
I'm getting ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke when executing:

```<code>REVOKE REFERENCES ON dbo.ABC FROM XYZ;
</code>```

How do I address the issue?

答:
REFERENCES is the privilege which allows us to create foreign keys across schemas. If the privilege is revoked any foreign keys we created on the referenced object must be dropped. The documentation says

"When a REFERENCES privilege for a table is revoked from a user, any foreign key integrity constraints that are defined by the user and require the dropped REFERENCES privilege are automatically dropped. "

Hence the need for cascade constraints.

```<code>revoke references on dbo.abc from xyz cascade constraints;
</code>```

Body:
I'm getting ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke when executing:

REVOKE REFERENCES ON dbo.ABC FROM XYZ;

How do I address the issue?

Body:
REFERENCES is the privilege which allows us to create foreign keys across schemas. If the privilege is revoked any foreign keys we created on the referenced object must be dropped. The documentation says

"When a REFERENCES privilege for a table is revoked from a user, any foreign key integrity constraints that are defined by the user and require the dropped REFERENCES privilege are automatically dropped. "

Hence the need for cascade constraints.

revoke references on dbo.abc from xyz cascade constraints;


问:
Google Cloud - Adding additional Internal IP to VM
I'm trying to build a webserver in Google Cloud Platform that hosts multiple websites (GBP, IE, FR, DK etc.)

Generally, we assign a range of IPs to the server statically, set the bindings in IIS, then loadbalance using a virtual IP.

It seems near enough impossible to assign another internal IP in GCP. Lots of guides about additional external IPs, but we don't want a public facing webserver like this.

Anybody have any idea on how to add additional internal IPs to a VM / Instance?

Also, I have tried changing the internal address I have assigned to the Instance to static in network adapter settings, next thing I know I can't access my VM for love nor money, had to delete and re-create. If I go into advanced settings to add additional static IPs, w'ere set to DHCP apparently, so can't add additional IPs.

Thanks all.

答:
Answer that I recieved from GCE discussion group, in Google Groups:

"You can add additional internal IP addresses to a VM instance. This is possible by enabling IP forwarding for the VM, creating a static network route, adding appropriate firewall rules, and setting additional internal IP addresses to network adapter of Windows. These steps are described in this article for Linux machines (https://cloud.google.com/compute/docs/networking#set_a_static_target_ip_address). The same steps are valid for Windows VMs. You will need to keep the initial internal IP address, subnet mask, gateway address and DNS settings of the adapter and manually enter them in properties of IPv4 of the network adapter. The below is a screenshot of my configuration on a VM instance (Windows 2008 R2) that perfectly works."


问:
Position div under another div
I have 2 divs: div with submit and order-content div

        <form>

submit

        </form>

                  <form>
                  </form>

```

Also when I add new product, im appending new table row, so css position attribute doesn't work as I want cause it has static values. I thought about making jquery which gets height of new row and increments submit input position, but is there better solution?

答:
$(".input").click(function(){
 $("#table").append('
Data
')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="order">
 <div  class="col-xs-12 form-group">

 </div>
        <div class="col-xs-12 form-group">
        <button class="btn input">
        submit
        </button></div>

        <div class="col-xs-12 order-content">
        <table id="table" class="form-group"><tr><td>Data</td></tr></table>
          <div class="new-product">
              <div class="product-add">
                  <form>
                  <input type="text" class="form-control" />
                  </form>
              </div>
          </div>
       </div>
    </div></code>```

Title: Position div under another div

Body:
I have 2 divs: div with submit and order-content div

        <form>

submit

        </form>

                  <form>
                  </form>

Also when I add new product, im appending new table row, so css position attribute doesn't work as I want cause it has static values. I thought about making jquery which gets height of new row and increments submit input position, but is there better solution?

Body:
$(".input").click(function(){
 $("#table").append('<tr><td>Data</td></tr>')
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="order">
 <div  class="col-xs-12 form-group">

 </div>
        <div class="col-xs-12 form-group">
        <button class="btn input">
        submit
        </button></div>

        <div class="col-xs-12 order-content">
        <table id="table" class="form-group"><tr><td>Data</td></tr></table>
          <div class="new-product">
              <div class="product-add">
                  <form>
                  <input type="text" class="form-control" />
                  </form>
              </div>
          </div>
       </div>
    </div>


问:
CTE to get dates between two dates using SQL Server
I want to fetch missing dates between two dates

say @maxDate = '2013-01-28'

say @curDate = GetDate()

I have written CTE to do this. Here is my CTE:

```<code>create procedure EmpDate
as  begin
declare @curDate Date
set @curDate = GETDATE()
declare @maxDate Date
select @maxDate = MAX(EmpAttendance.Sdate)
from EmpAttendance

;with GetDates As
(
select 1 as counter, @maxDate as Date
UNION ALL
select counter + 1, DATEADD(day,counter,@maxDate)
from GetDates
where DATEADD(day, counter, @maxDate) < @curDate
)
select Date from GetDates
end
go
</code>```

The result of this is

```<code>Date
2013-01-28
2013-01-29
2013-01-30
</code>```

but I want

```<code>2013-01-29
2013-01-30
</code>```

Please help me out.

答:
```<code>DECLARE @STARTDATE      DATETIME;
DECLARE @ENDDATE        DATETIME;
DECLARE @YEARS          INTEGER;

SET @YEARS = 10;
SET @STARTDATE = '20170101';

SELECT  @ENDDATE = DATEADD(DAY,-1,DATEADD(YEAR,@YEARS,@STARTDATE));
DECLARE @FirstDayOfWeek INTEGER;

SET @FirstDayOfWeek = 6;

;WITH CTE_DATES
AS
(
    SELECT @STARTDATE AS [DATE],
    1 AS [Level]
    UNION ALL
    SELECT
        DATEADD(DAY,1, [DATE] )  , [Level] + 1
    FROM CTE_DATES
    WHERE [DATE] < @ENDDATE
)
SELECT
    [DATE],
    DATENAME(dw,[Date]) AS Daynamelong,
    LEFT(DATENAME(dw,[Date]),3) AS DaynameShort,
    DATEPART(dw,[Date]) AS NaturalDayNumber,
    CASE WHEN DATEPART(dw,[Date]) >= @FirstDayOfWeek THEN  (DATEPART(dw,[Date]) - (@FirstDayOfWeek)) +1
    ELSE
        ((DATEPART(dw,[Date]) - (@FirstDayOfWeek)) +1) + 7
    END AS SpecialDayNumber,
    [Level]
FROM
    CTE_DATES
ORDER BY
    [DATE] ASC
OPTION (MAXRECURSION 5000);
</code>```

Body:
I want to fetch missing dates between two dates

say @maxDate = '2013-01-28'

say @curDate = GetDate()

I have written CTE to do this. Here is my CTE:

create procedure EmpDate
as  begin
declare @curDate Date
set @curDate = GETDATE()
declare @maxDate Date
select @maxDate = MAX(EmpAttendance.Sdate)
from EmpAttendance

;with GetDates As
(
select 1 as counter, @maxDate as Date
UNION ALL
select counter + 1, DATEADD(day,counter,@maxDate)
from GetDates
where DATEADD(day, counter, @maxDate) < @curDate
)
select Date from GetDates
end
go

The result of this is

Date
2013-01-28
2013-01-29
2013-01-30

but I want

2013-01-29
2013-01-30

Please help me out.


问:
Error in data binding in Xaml
```<code>I have tried data binding in WPF.
But it is showing few errors.Please help me.
</code>```

I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.

```<code>Xaml code
<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Window.DataContext>
        <l:DataBinding />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

**Code behind**

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            Setupviewmodel();
        }
        private void Setupviewmodel
        {
            TextString="this worked";
        }
        public string TextString{get;set;}
    }
}
</code>```

答:
Okay so first of all read the error messages ... It clearly says that l is not defined in XAML but still you're trying to use it : <l:DataBinding />...

Fix this by declaring l in your XAML :

```<code><Window x:Class="Shweta.DataBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:l="<your l declaration"/>
</code>```

Another thing is that you haven't implemented INotifyPropertyChanged so you'r value wont get updated anyway.

Implement this like such :

```<code>public partial class DataBinding : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
    {
        if ( PropertyChanged != null )
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    string text;
    public string TextString
    {
        get { return text; }
        set { text = value; NotifyPropertyChanged(); }
    }

    public DataBinding()
        : base()
    {
        InitializeComponent();
        Setupviewmodel();
        // as @Nahuel Ianni stated, he has to set DataContext to CodeBehind
        // in order to be able to get bindings work
        DataContext = this; // <-- only if not binded before
    }

    public void Setupviewmodel() // forgot to to place ()
    // produced error : `A get or set accessor expected`
    {
        TextString = "this worked";
    }
}
</code>```

Yet another thing is that you have to specify DataContext only when it's not the same as your code behind so you do not need this part :

```<code><Window.DataContext>
    <l:DataBinding />
</Window.DataContext>
</code>```

Title: Error in data binding in Xaml

Body:
I have tried data binding in WPF.
But it is showing few errors.Please help me.

I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.

Xaml code
<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Window.DataContext>
        <l:DataBinding />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

**Code behind**

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            Setupviewmodel();
        }
        private void Setupviewmodel
        {
            TextString="this worked";
        }
        public string TextString{get;set;}
    }
}

Body:
Okay so first of all read the error messages ... It clearly says that l is not defined in XAML but still you're trying to use it : <l:DataBinding />...

Fix this by declaring l in your XAML :

<Window x:Class="Shweta.DataBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:l="<your l declaration"/>

Another thing is that you haven't implemented INotifyPropertyChanged so you'r value wont get updated anyway.

Implement this like such :

public partial class DataBinding : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
    {
        if ( PropertyChanged != null )
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    string text;
    public string TextString
    {
        get { return text; }
        set { text = value; NotifyPropertyChanged(); }
    }

    public DataBinding()
        : base()
    {
        InitializeComponent();
        Setupviewmodel();
        // as @Nahuel Ianni stated, he has to set DataContext to CodeBehind
        // in order to be able to get bindings work
        DataContext = this; // <-- only if not binded before
    }

    public void Setupviewmodel() // forgot to to place ()
    // produced error : `A get or set accessor expected`
    {
        TextString = "this worked";
    }
}

Yet another thing is that you have to specify DataContext only when it's not the same as your code behind so you do not need this part :

<Window.DataContext>
    <l:DataBinding />
</Window.DataContext>


问:
Can Google Cloud Compute connect to Mandrill for SMTP relay?
I'm using Mandrill service, now I want to use this service to replay instance email, you know that instance blocked 25 port, so will use 2525 port for this replay, is Google Cloud Compute support Mandrill ?

Thanks

答: I have personally used mandrill and found no issues working with Google cloud as long as the port is 2525. </p>


问:
Using Bamboo CLI from Command Prompt
I am trying to fetch the plan details of a Bamboo Project using Bamboo CLI. I downloaded the Bobswift CLIand a jar file was downloaded. i opened command prompt in the folder that had this jar file and i ran the command bamboo --action getProjectList. But i am getting an error as 'bamboo' not recognized as an internal command.

答:
If you using Windows you need to run the following command in the command prompt : "bamboo.bat --action getProjectList"

If you are using linux or OSx run the following in the terminal "./bamboo.sh --action getProjectList"

Title: Using Bamboo CLI from Command Prompt


问:
includes() not working in IE
I am using the following code. It works perfectly in browsers such as Chrome, Firefox or Edge. However when I check in IE11 it does not work and breaks all the functionality.

```<code>var href = jQuery(this).attr('href');
if (href.includes('#')) {
  // action
}
</code>```

I think includes() does not work in IE11. Is there a solution for this?

答:
includes is not supported in Internet Explorer (or Opera)

Instead you can use indexOf. #indexOf returns the index of the first character of the substring if it is in the string, otherwise it returns -1. (Much like the Array equivalent)

Try the following:

```<code>var href = jQuery(this).attr('href');

if(href.indexOf('#') > -1) //this will true if the string contains #
{
   // action
}
</code>```

This is supported by all browsers. This is a good read for your issue :)

Title: includes() not working in IE

Body:
I am using the following code. It works perfectly in browsers such as Chrome, Firefox or Edge. However when I check in IE11 it does not work and breaks all the functionality.

var href = jQuery(this).attr('href');
if (href.includes('#')) {
  // action
}

I think includes() does not work in IE11. Is there a solution for this?

Body:
includes is not supported in Internet Explorer (or Opera)

Instead you can use indexOf. #indexOf returns the index of the first character of the substring if it is in the string, otherwise it returns -1. (Much like the Array equivalent)

Try the following:

var href = jQuery(this).attr('href');

if(href.indexOf('#') > -1) //this will true if the string contains #
{
   // action
}

This is supported by all browsers. This is a good read for your issue :)


问:
What does the performSelector method do?
What does performSelector do? What is the difference between creating a new NSThread and the performSelector method?

How it works and where should we use it?

答:
performSelector executes a selector. In other words, it calls a method.

It is very different from running a new thread.

I think it would be best for you to read up on selectors.


问:
Session doesn't save value with redirect-> "with" method laravel 5.2
When I put data like this:

```<code>$request->session()->put('123', '12345')
</code>```

, session contains this value, but when I try to put data into session this way

```<code>$result = ['status' => 'Product has been updated']
return redirect('/admin/products/')->with($result);
</code>```

Session doesn't contains it.

```<code>kernel:

    class Kernel extends HttpKernel
{

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
         \Illuminate\Session\Middleware\StartSession::class,
         \Illuminate\View\Middleware\ShareErrorsFromSession::class
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

routes:

    Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
        Route::get('/', ['uses' => 'Admin\IndexController@index', 'as' => 'adminIndex']);
        Route::resource('/products', 'Admin\ProductController');
    });
</code>```

I have red about changes in laravel 5.2 and that this problem may cause web middleware but i haven't it in my routes. Why session doesn't contain given status then?

答:
You can use the Session::flash(key,value) function to store data for retrieval once before performing a redirect.

```<code>Session::flash('123', '12345');
</code>```

OR

```<code>session()->flash('123','12345');
return redirect('/admin/products/');
</code>```

You can read these values later but only once, it will resolve your issue.

Body:
When I put data like this:

$request->session()->put('123', '12345')

, session contains this value, but when I try to put data into session this way

$result = ['status' => 'Product has been updated']
return redirect('/admin/products/')->with($result);

Session doesn't contains it.

kernel:

    class Kernel extends HttpKernel
{

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
         \Illuminate\Session\Middleware\StartSession::class,
         \Illuminate\View\Middleware\ShareErrorsFromSession::class
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

routes:

    Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
        Route::get('/', ['uses' => 'Admin\IndexController@index', 'as' => 'adminIndex']);
        Route::resource('/products', 'Admin\ProductController');
    });

I have red about changes in laravel 5.2 and that this problem may cause web middleware but i haven't it in my routes. Why session doesn't contain given status then?

Body:
You can use the Session::flash(key,value) function to store data for retrieval once before performing a redirect.

Session::flash('123', '12345');

OR

session()->flash('123','12345');
return redirect('/admin/products/');

You can read these values later but only once, it will resolve your issue.


问:
Why Quality of service set to background runs in main thread?
Why is the below code running in main thread although i have specified qos to background thread?

```<code>func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background)
    queue.sync {

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
        for i in 100..<110 {
            print("Ⓜ", i)
        }
    }
}

testQueue()
</code>```

Whenever i try to run the method i get msg in console as is in main threadwhich should not be the case..I am reading in this article.

http://www.appcoda.com/grand-central-dispatch/

See the Getting Started with dispatch queues section.

答:
You have specified a background queue, not a background thread. When you dispatch a task on a queue, GCD looks for a thread to run the task on.

Since you are using a synchronous dispatch, the main queue is blocked, leaving the main thread free to perform work, so your task executes on the main thread.

tasks dispatched on the main queue will run on the main thread

tasks dispatched on another queue may run on the main thread or another thread

Body:
Why is the below code running in main thread although i have specified qos to background thread?

func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background)
    queue.sync {

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
        for i in 100..<110 {
            print("Ⓜ", i)
        }
    }
}

testQueue()

Whenever i try to run the method i get msg in console as is in main threadwhich should not be the case..I am reading in this article.

http://www.appcoda.com/grand-central-dispatch/

See the Getting Started with dispatch queues section.


答:
The issue is because includes() is unsupported in all versions of IE: MDN Reference

Instead you can use the much more widely supported indexOf():

```<code>var href = $(this).attr('href');
if (href.indexOf('#') != -1) {
  // action
}
</code>```

You could also prototype this to add the includes() method to IE:

```<code>String.prototype.includes = function(match) {
  return this.indexOf(match) !== -1;
}
</code>```

Title: includes() not working in IE

Body:
The issue is because includes() is unsupported in all versions of IE: MDN Reference

Instead you can use the much more widely supported indexOf():

var href = $(this).attr('href');
if (href.indexOf('#') != -1) {
  // action
}

You could also prototype this to add the includes() method to IE:

String.prototype.includes = function(match) {
  return this.indexOf(match) !== -1;
}


问:
Python Decimals format
What is a good way to format a python decimal like this way?

1.00 --> '1'

1.20 --> '1.2'

1.23 --> '1.23'

1.234 --> '1.23'

1.2345 --> '1.23'

答:
Only first part of Justin's answer is correct.
Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

```<code>>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'
</code>```

Title: Python Decimals format

Body:
Only first part of Justin's answer is correct.
Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'


问:
Eloquent join table with two conditions
I have two tables:

A: id | user_id | phonenumber | status | ...

B: id | user_id | phonenumber | name | ...

I would like to list all elements in table A but I have to left join the elements to table B.

I can do it with DB:

```<code>DB::table('A')
  ->leftJoin('B', function ($join) {
    $join->on('A.phonenumber', '=', 'B.phonenumber')
         ->on('A.user_id', '=', 'B.user_id');
  })
  ->select(...)
  ->where('A.user_id', '=', $userId)
  ->get();
</code>```

Is it possible to solve it with eloquent somehow?

答:
```<code>modelname::where(condition)->leftjoin(tablename,fieldname,othertable.fieldname)->get()
</code>```

This is format how we write join in laravel

```<code>$postdata = post::select('categories.id', 'posts.id', 'categories.categoryname', 'posts.title', 'posts.body', 'posts.image', 'posts.created_at', 'users.name')
            ->where('post_type', 'publish')
            ->where('status', 'active')
            ->where('categories.id', $id)
            ->leftJoin('users', 'users.id', '=', 'posts.user_id')
            ->leftJoin('categories', 'categories.id', '=', 'posts.category')
            ->orderBy('created_at', 'desc')
            ->paginate(5);
</code>```

This query display blog with username and with category using join it's my proect convenient query you can also create for you in this manner

Title: Eloquent join table with two conditions

Body:
I have two tables:

A: id | user_id | phonenumber | status | ...

B: id | user_id | phonenumber | name | ...

I would like to list all elements in table A but I have to left join the elements to table B.

I can do it with DB:

DB::table('A')
  ->leftJoin('B', function ($join) {
    $join->on('A.phonenumber', '=', 'B.phonenumber')
         ->on('A.user_id', '=', 'B.user_id');
  })
  ->select(...)
  ->where('A.user_id', '=', $userId)
  ->get();

Is it possible to solve it with eloquent somehow?

Body:
modelname::where(condition)->leftjoin(tablename,fieldname,othertable.fieldname)->get()

This is format how we write join in laravel

$postdata = post::select('categories.id', 'posts.id', 'categories.categoryname', 'posts.title', 'posts.body', 'posts.image', 'posts.created_at', 'users.name')
            ->where('post_type', 'publish')
            ->where('status', 'active')
            ->where('categories.id', $id)
            ->leftJoin('users', 'users.id', '=', 'posts.user_id')
            ->leftJoin('categories', 'categories.id', '=', 'posts.category')
            ->orderBy('created_at', 'desc')
            ->paginate(5);

This query display blog with username and with category using join it's my proect convenient query you can also create for you in this manner


问:
PHP convert Array to Object
var_dump($response);

outputs:

```<code> array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }
</code>```

how can I convert $response to an object to operate it like in the following code:

```<code>echo $response->metafields[0]->id;
</code>```

I've tried the code below, but without any result :/

```<code>$object = json_decode(json_encode($response));
</code>```

答:
If you make an object with (object) $response, the child elements will still be arrays. Then you could do

```<code>$response->metafields[13][id]
</code>```

If you want the object notation through the whole chain you need something like the function sandip has provided.

But why not just make this call:

```<code>$response[metafields][13][id]
</code>```

Title: PHP convert Array to Object

Body:
var_dump($response);

outputs:

 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }

how can I convert $response to an object to operate it like in the following code:

echo $response->metafields[0]->id;

I've tried the code below, but without any result :/

$object = json_decode(json_encode($response));

Body:
If you make an object with (object) $response, the child elements will still be arrays. Then you could do

$response->metafields[13][id]

If you want the object notation through the whole chain you need something like the function sandip has provided.

But why not just make this call:

$response[metafields][13][id]


问:
How to find a list of nodes by two conditions in cypher?
I have 3 kinds of nodes: tag, city and place.

I want to write a query which takes 2 lists

```<code> [tag1,tag2,....]
</code>```

and

```<code> [city1,city2,....].
</code>```

I want to find a list of places located in one of these cities and order them from the one has as much tags as possible to the ones with fewer tags.

```<code> MATCH (spot:Spot)-[:located_at]->(city:City )
 where city.id IN ["22","23"]
 with spot as sp,city as cy
 MATCH (sp:Spot)-[rels:tagged_by]->(tag:Tag)
 where tag.id IN ["16", "10151", "21"]
 with sp as fsp, tag
 RETURN fsp, tag,    count(distinct fsp.id) AS cnt
 order by cnt desc
</code>```

I tried that query and somehow could not list the nodes and their tags.

Please help!
Thanks in advance!

答:
How I would approach this problem is.

```<code>MATCH (spot:Spot)-[:located_at]->(city:City)
RETURN city,spot,size(spot-[:tagged_by]->()) as tags order by tags desc
</code>```

so now you get all the spots with the most tags. Obviously you can add filters how you want

```<code>MATCH (spot:Spot)-[:located_at]->(city:City) where city.name = "London"
RETURN city,spot,size(spot-[:tagged_by]->())  as tags order by tags desc
</code>```

Body:
I have 3 kinds of nodes: tag, city and place.

I want to write a query which takes 2 lists

 [tag1,tag2,....]

and

 [city1,city2,....].

I want to find a list of places located in one of these cities and order them from the one has as much tags as possible to the ones with fewer tags.

 MATCH (spot:Spot)-[:located_at]->(city:City )
 where city.id IN ["22","23"]
 with spot as sp,city as cy
 MATCH (sp:Spot)-[rels:tagged_by]->(tag:Tag)
 where tag.id IN ["16", "10151", "21"]
 with sp as fsp, tag
 RETURN fsp, tag,    count(distinct fsp.id) AS cnt
 order by cnt desc

I tried that query and somehow could not list the nodes and their tags.

Please help!
Thanks in advance!

Body:
How I would approach this problem is.

MATCH (spot:Spot)-[:located_at]->(city:City)
RETURN city,spot,size(spot-[:tagged_by]->()) as tags order by tags desc

so now you get all the spots with the most tags. Obviously you can add filters how you want

MATCH (spot:Spot)-[:located_at]->(city:City) where city.name = "London"
RETURN city,spot,size(spot-[:tagged_by]->())  as tags order by tags desc


问:
How to format numbers by prepending 0 to single-digit numbers?
I want to format a number to have two digits. The problem is caused when 0–9 is passed, so I need it to be formatted to 00–09.

Is there a number formatter in JavaScript?

答:
my example would be:

```<code><div id="showTime"></div>

    function x() {
    var showTime = document.getElementById("showTime");
    var myTime = new Date();
    var hour = myTime.getHours();
    var minu = myTime.getMinutes();
    var secs = myTime.getSeconds();
    if (hour < 10) {
        hour = "0" + hour
    };
    if (minu < 10) {
        minu = "0" + minu
    };
    if (secs < 10) {
        secs = "0" + secs
    };

    showTime.innerHTML = hour + ":" + minu + ":" + secs;
}

setInterval("x()", 1000)
</code>```

Body:
my example would be:

<div id="showTime"></div>

    function x() {
    var showTime = document.getElementById("showTime");
    var myTime = new Date();
    var hour = myTime.getHours();
    var minu = myTime.getMinutes();
    var secs = myTime.getSeconds();
    if (hour < 10) {
        hour = "0" + hour
    };
    if (minu < 10) {
        minu = "0" + minu
    };
    if (secs < 10) {
        secs = "0" + secs
    };

    showTime.innerHTML = hour + ":" + minu + ":" + secs;
}

setInterval("x()", 1000)


问:
ROracle dbWriteTable affirms insertion that didnt happen
My goal is to create a table in the database and fill it with data afterwards. This is my code:

```<code>library(ROracle)

# ... "con" is the connection string, created in an earlier stage!

# 1 create example
testdata <- data.frame(A = c(1,2,3), B = c(4,5,6))
# 2 create-statement
createTable <- paste0("CREATE TABLE TestTable(", paste(paste(colnames(testdata), c("integer", "integer")), collapse = ","), ")")
# 3 send and execute query
dbGetQuery(con, createTable)
# 4 write example data
dbWriteTable(con, "TestTable", testdata, row.names = TRUE, append = TRUE)
</code>```

I already suceeded a few times. The table was created and filled.

Now step 4 doesn't work anymore, R returns TRUE after execution of dbWriteTable though. But the table is still empty.

I know this is a vague question, but does anyone have an idea what could be wrong here?

答:
I found the solution for my problem. After creating the table in step 3, you have to commit! After that, the data is written into the table.</p>

```<code>library(ROracle)

# ... "con" is the connection string, created in an earlier stage!
# 1 create example
testdata <- data.frame(A = c(1,2,3), B = c(4,5,6))
# 2 create-statement
createTable <- paste0("CREATE TABLE TestTable(", paste(paste(colnames(testdata), c("integer", "integer")), collapse = ","), ")")
# 3 send and execute query
dbGetQuery(con, createTable)
# NEW LINE: COMMIT!
dbCommit(con)
# 4 write example data
dbWriteTable(con, "TestTable", testdata, row.names = TRUE, append = TRUE)
</code>```

Body:
My goal is to create a table in the database and fill it with data afterwards. This is my code:

library(ROracle)

# ... "con" is the connection string, created in an earlier stage!

# 1 create example
testdata <- data.frame(A = c(1,2,3), B = c(4,5,6))
# 2 create-statement
createTable <- paste0("CREATE TABLE TestTable(", paste(paste(colnames(testdata), c("integer", "integer")), collapse = ","), ")")
# 3 send and execute query
dbGetQuery(con, createTable)
# 4 write example data
dbWriteTable(con, "TestTable", testdata, row.names = TRUE, append = TRUE)

I already suceeded a few times. The table was created and filled.

Now step 4 doesn't work anymore, R returns TRUE after execution of dbWriteTable though. But the table is still empty.

I know this is a vague question, but does anyone have an idea what could be wrong here?

Body:
I found the solution for my problem. After creating the table in step 3, you have to commit! After that, the data is written into the table.

library(ROracle)

# ... "con" is the connection string, created in an earlier stage!
# 1 create example
testdata <- data.frame(A = c(1,2,3), B = c(4,5,6))
# 2 create-statement
createTable <- paste0("CREATE TABLE TestTable(", paste(paste(colnames(testdata), c("integer", "integer")), collapse = ","), ")")
# 3 send and execute query
dbGetQuery(con, createTable)
# NEW LINE: COMMIT!
dbCommit(con)
# 4 write example data
dbWriteTable(con, "TestTable", testdata, row.names = TRUE, append = TRUE)


问:
check if .click() function is available in browser
I am building an application that uses .click() method in couple of places. It was reported that it causes errors in safari (windows version) because its not available in the browser.

I made some research and i found good alternative, i created a polyfill solution for it, but i am struggling to find how can i check if browser supports .click() method.

I tried following:

Element.prototype.click returns undefined in all browsers

Element.click returns undefined in all browsers

document.prototype.click returns undefined in all browsers

document.click returns undefined in all browsers

This is the polyfill i made:

```<code>Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
};
</code>```

Now i just need to check it and apply only if .click() is unavailable.

答:
Just check if the event exist for a new created dom element:</p>

```<code>if (!document.createElement('div').click) {
  Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
  };
}
</code>```

Body:
I am building an application that uses .click() method in couple of places. It was reported that it causes errors in safari (windows version) because its not available in the browser.

I made some research and i found good alternative, i created a polyfill solution for it, but i am struggling to find how can i check if browser supports .click() method.

I tried following:

Element.prototype.click returns undefined in all browsers

Element.click returns undefined in all browsers

document.prototype.click returns undefined in all browsers

document.click returns undefined in all browsers

This is the polyfill i made:

Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
};

Now i just need to check it and apply only if .click() is unavailable.

Body:
Just check if the event exist for a new created dom element:

if (!document.createElement('div').click) {
  Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
  };
}


问:
Replacing words in text file using a dictionary
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line
</code>```

答:
If You are more familiar with Python, You can use tips from Official documentation:

7.1. string — Common string operations

And subclass, the Template class, in which you define somehow that every single world will be a new placeholder, and then with safe_substitute() You could get a nice and reliable solution.

Body:
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line