问:
Ionic 4 hardware backbutton close on double tap not working
I am working on my application but stuck in one problem which is hardware backbutton. I need when user click on backbutton so it will not back the app or close just show some toast.

And on double tap close the app. But its not working no toast is showing and hardware back button is working .

This is my code in app.component.ts

```<code>  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
              // this does work
        this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
          if (outlet && outlet.canGoBack()) {
              outlet.pop();

          } else if (this.router.url === '/wallet') {
              if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                  // this.platform.exitApp(); // Exit from app
                  navigator['app'].exitApp(); // work for ionic 4

              } else {
                this.toast = this.toastCtrl.create({
                  message: 'double tap to exit.',
                  duration: 2000,
                  position: 'bottom'
                }).then((toastData)=>{
                  console.log(toastData);
                  toastData.present();
                });

              this.lastTimeBackPress = new Date().getTime();
              }
          }
      });

    });
  }
</code>```

Its working fine in some ionic version but my version is ionic 6.0.1

I have try with dfferent answers this is working but how can i enable double tap close int it ? now its not closing or back on hardware button but i need to clsoe app on double tap

```<code>  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
              // this does work
      this.platform.backButton.subscribeWithPriority(9999, () => {
        document.addEventListener('backbutton', function (event) {
          event.preventDefault();
          event.stopPropagation();
          console.log('hello');
        }, false);
      });
    });
  }
</code>```

答:
Refer to this code and make changes if required as per your requirement.

Under initializeApp() call a function backbuttonSubscribeMethod()

```<code>initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.backbuttonSubscribeMethod();
    });
  }
</code>```

Define your method

```<code>backbuttonSubscribeMethod() {
    let a = 0;
    this.platform.backButton.subscribe(() => {
        a++;
        if (a == 2) { // logic for double tap
          navigator['app'].exitApp();
        }
    });
  }
</code>```

Unsubscribe it under this

```<code>  ngOnDestroy() {
    this.platform.backButton.unsubscribe();
  }
</code>```

Body:
I am working on my application but stuck in one problem which is hardware backbutton. I need when user click on backbutton so it will not back the app or close just show some toast.

And on double tap close the app. But its not working no toast is showing and hardware back button is working .

This is my code in app.component.ts

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
              // this does work
        this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
          if (outlet && outlet.canGoBack()) {
              outlet.pop();

          } else if (this.router.url === '/wallet') {
              if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                  // this.platform.exitApp(); // Exit from app
                  navigator['app'].exitApp(); // work for ionic 4

              } else {
                this.toast = this.toastCtrl.create({
                  message: 'double tap to exit.',
                  duration: 2000,
                  position: 'bottom'
                }).then((toastData)=>{
                  console.log(toastData);
                  toastData.present();
                });

              this.lastTimeBackPress = new Date().getTime();
              }
          }
      });

    });
  }

Its working fine in some ionic version but my version is ionic 6.0.1

I have try with dfferent answers this is working but how can i enable double tap close int it ? now its not closing or back on hardware button but i need to clsoe app on double tap

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
              // this does work
      this.platform.backButton.subscribeWithPriority(9999, () => {
        document.addEventListener('backbutton', function (event) {
          event.preventDefault();
          event.stopPropagation();
          console.log('hello');
        }, false);
      });
    });
  }

Body:
Refer to this code and make changes if required as per your requirement.

Under initializeApp() call a function backbuttonSubscribeMethod()

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.backbuttonSubscribeMethod();
    });
  }

Define your method

backbuttonSubscribeMethod() {
    let a = 0;
    this.platform.backButton.subscribe(() => {
        a++;
        if (a == 2) { // logic for double tap
          navigator['app'].exitApp();
        }
    });
  }

Unsubscribe it under this

  ngOnDestroy() {
    this.platform.backButton.unsubscribe();
  }


来源: stackexchange

问:
Refresh Visual Studio Code list of files
Visual Studio Code (Version 0.10.11, on OSX) does not refresh the files in a folder.  Is there any way to force it to refresh.  Currently I have to close and reopen the whole program.</p>

答: When search.maintainFileSearchCache option is enabled I started to find the files with I'm using Ctrl-P shortcut

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How do I update a single value in a json document using jq?
Appologies if I've overlooked something very obvious; I've just found jq and am trying to use it to update one JSON value without affecting the surrounding data.

I'd like to pipe a curl result into jq, update a value, and pipe the updated JSON to a curl -X PUT.  Something like

```<code>curl http://example.com/shipping.json | jq '.' field: value | curl -X PUT http://example.com/shipping.json
</code>```

So far I've hacked it together using sed, but after looking at a few examples of the |= operator in jq I'm sure that I don't need these.

Here's a JSON sample--how would I use jq to set "local": false, while preserving the rest of the JSON?

```<code>{
  "shipping": {
    "local": true,
    "us": true,
    "us_rate": {
      "amount": "0.00",
      "currency": "USD",
      "symbol": "$"
    }
  }
}
</code>```

答:
Update a value (sets .foo.bar to "new value"):

```<code>jq '.foo.bar = "new value"' file.json
</code>```

Update a value using a variable (sets .foo.bar to "hello"):

```<code>variable="hello"; jq --arg variable "$variable" '.foo.bar = $variable' file.json
</code>```

Body:
Appologies if I've overlooked something very obvious; I've just found jq and am trying to use it to update one JSON value without affecting the surrounding data.

I'd like to pipe a curl result into jq, update a value, and pipe the updated JSON to a curl -X PUT.  Something like

curl http://example.com/shipping.json | jq '.' field: value | curl -X PUT http://example.com/shipping.json

So far I've hacked it together using sed, but after looking at a few examples of the |= operator in jq I'm sure that I don't need these.

Here's a JSON sample--how would I use jq to set "local": false, while preserving the rest of the JSON?

{
  "shipping": {
    "local": true,
    "us": true,
    "us_rate": {
      "amount": "0.00",
      "currency": "USD",
      "symbol": "$"
    }
  }
}

Body:
Update a value (sets .foo.bar to "new value"):

jq '.foo.bar = "new value"' file.json

Update a value using a variable (sets .foo.bar to "hello"):

variable="hello"; jq --arg variable "$variable" '.foo.bar = $variable' file.json


问:
GCC ARM Performance drop
I stumbled upon very strange issue with GCC. The issue is 25% drop in performance. Here is the story.

I have a pice of software which is fp32 compute intensive (neural networks compiled with TVM). I compile it for ARM (rk3399 device), here is info:

gcc -v

```<code>Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/arm-linux-gnueabihf/5/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 5.4.0-6ubuntu1~16.04.12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-libitm --disable-libquadmath --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-armhf/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-armhf --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-armhf --with-arch-directory=arm --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --enable-multilib --disable-sjlj-exceptions --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --disable-werror --enable-multilib --enable-checking=release --build=arm-linux-gnueabihf --host=arm-linux-gnueabihf --target=arm-linux-gnueabihf
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu/Linaro 5.4.0-6ubuntu1~16.04.12)
</code>```

uname -a

```<code>Linux FriendlyELEC 4.4.143 #1 SMP Tue Nov 20 11:10:11 CST 2018 aarch64 aarch64 aarch64 GNU/Linux
</code>```

lscpu

```<code>Architecture:          aarch64
Byte Order:            Little Endian
CPU(s):                6
On-line CPU(s) list:   0-5
Thread(s) per core:    1
Core(s) per socket:    3
Socket(s):             2
Model name:            ARMv8 Processor rev 2 (v8l)
CPU max MHz:           1800.0000
CPU min MHz:           408.0000
Hypervisor vendor:     horizontal
Virtualization type:   full
</code>```

The code was initially "slow" and cpp11, I decided to try cpp17 and cpp14. cpp17 was not supported, but cpp14 was. I switched to cpp14 and voila I got boost around 25% in performance. I really tested it to make sure the boost is in fact real and not a measuring mistake. I had this boost for a week then my device rebooted and the boost in performance was gone!

It may sound crazy, but I'm very sure in my code and measurements I had. I didn't have explicit compile flags prior to this gimmick. Now I'm trying to figure out compile flags for GCC to reclaim what was lost, but I don't have much experience with GCC. What could be the issue here? What flags can affect performance that much?

the code uses .so files, compiled with use of llvm and gcc

```<code>llvm -device=arm_cpu -target=armv8l-linux-gnueabihf -mattr=+neon,fp-armv8
</code>```

答: It's not GCC fault. It's CPU frequency scaling problem. I had device with ARM with Linux (ubuntu) on board, strange behavior and different benchmarking results are due to strange cpu frequency governing by OS. </p>

Title: GCC ARM Performance drop

Body:
I stumbled upon very strange issue with GCC. The issue is 25% drop in performance. Here is the story.

I have a pice of software which is fp32 compute intensive (neural networks compiled with TVM). I compile it for ARM (rk3399 device), here is info:

gcc -v

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/arm-linux-gnueabihf/5/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 5.4.0-6ubuntu1~16.04.12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-libitm --disable-libquadmath --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-armhf/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-armhf --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-armhf --with-arch-directory=arm --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --enable-multilib --disable-sjlj-exceptions --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --disable-werror --enable-multilib --enable-checking=release --build=arm-linux-gnueabihf --host=arm-linux-gnueabihf --target=arm-linux-gnueabihf
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu/Linaro 5.4.0-6ubuntu1~16.04.12)

uname -a

Linux FriendlyELEC 4.4.143 #1 SMP Tue Nov 20 11:10:11 CST 2018 aarch64 aarch64 aarch64 GNU/Linux

lscpu

Architecture:          aarch64
Byte Order:            Little Endian
CPU(s):                6
On-line CPU(s) list:   0-5
Thread(s) per core:    1
Core(s) per socket:    3
Socket(s):             2
Model name:            ARMv8 Processor rev 2 (v8l)
CPU max MHz:           1800.0000
CPU min MHz:           408.0000
Hypervisor vendor:     horizontal
Virtualization type:   full

The code was initially "slow" and cpp11, I decided to try cpp17 and cpp14. cpp17 was not supported, but cpp14 was. I switched to cpp14 and voila I got boost around 25% in performance. I really tested it to make sure the boost is in fact real and not a measuring mistake. I had this boost for a week then my device rebooted and the boost in performance was gone!

It may sound crazy, but I'm very sure in my code and measurements I had. I didn't have explicit compile flags prior to this gimmick. Now I'm trying to figure out compile flags for GCC to reclaim what was lost, but I don't have much experience with GCC. What could be the issue here? What flags can affect performance that much?

the code uses .so files, compiled with use of llvm and gcc

llvm -device=arm_cpu -target=armv8l-linux-gnueabihf -mattr=+neon,fp-armv8


问:
Kafka cluster configuration issue
I am facing an issue with the Kafka clustering setup that I have. I have a Kafka cluster with two broker that are connected to two zookeepers. I am posting data to a topic that have replication factor and partition two each with a spring boot Kafka producer and consuming the same with another spring boot app.

I found one strange behavior when testing the cluster in the following manner -

```<code> Turned off node1 and node 2
 Turned on node 1
 Turned off node 1
 Turned on node 2
</code>```

After turning on node 2 Kafka cluster got failed and I am not able to produce data to Kafka. My consumer started throwing the message continuously as given below.

[Producer clientId=producer-1] Connection to node 1 (/server1-ip:9092) could not be established. Broker may not be available.

Issue is visible in both nodes. But if I kept both system up for a while issue will get resolved and I can turn off any of the node without breaking the cluster.

My broker configuration is as below.

 broker.id=0

 listeners=PLAINTEXT://server1-ip:9092

advertised.listeners=PLAINTEXT://serever1-ip:9092

num.network.threads=3

num.io.threads=8

socket.send.buffer.bytes=102400

socket.receive.buffer.bytes=102400

socket.request.max.bytes=104857600

log.dirs=/home/user/kafka/data/kafka-logs

num.partitions=1

num.recovery.threads.per.data.dir=2

offsets.topic.replication.factor=2

transaction.state.log.replication.factor=2

transaction.state.log.min.isr=2

log.retention.hours=168

log.segment.bytes=1073741824

log.retention.check.interval.ms=300000

zookeeper.connect=serever1-ip:2181,serever2-ip:2181

zookeeper.connection.timeout.ms=6000

group.initial.rebalance.delay.ms=3000

auto.leader.rebalance.enable=true

leader.imbalance.check.interval.seconds=5

Zookeeper configuration

dataDir=/home/user/kafka/data

clientPort=2181

maxClientCnxns=0

initLimit=10

syncLimit=5

tickTime=2000

server.1=server1-ip:2888:3888

server.2=server2-ip:2888:3888

Is this is an expected behavior of Kafka or am I doing something wrong with this configuration ?

Can somebody help me with this issue ..

答:
Add all the bootstrap server IPs in your properties file. If anyone of the server is down the Kafka consumer will try to connect to Kafka with an]]]other bootstrap servers. Add server 2 url in the below line:

EDIT:

```<code>spring.kafka.bootstrap-servers={SERVER1_HOST},{SERVER2_HOST}
</code>```

Title: Kafka cluster configuration issue

Body:
I am facing an issue with the Kafka clustering setup that I have. I have a Kafka cluster with two broker that are connected to two zookeepers. I am posting data to a topic that have replication factor and partition two each with a spring boot Kafka producer and consuming the same with another spring boot app.

I found one strange behavior when testing the cluster in the following manner -

 Turned off node1 and node 2
 Turned on node 1
 Turned off node 1
 Turned on node 2

After turning on node 2 Kafka cluster got failed and I am not able to produce data to Kafka. My consumer started throwing the message continuously as given below.

[Producer clientId=producer-1] Connection to node 1 (/server1-ip:9092) could not be established. Broker may not be available.

Issue is visible in both nodes. But if I kept both system up for a while issue will get resolved and I can turn off any of the node without breaking the cluster.

My broker configuration is as below.

 broker.id=0

 listeners=PLAINTEXT://server1-ip:9092

advertised.listeners=PLAINTEXT://serever1-ip:9092

num.network.threads=3

num.io.threads=8

socket.send.buffer.bytes=102400

socket.receive.buffer.bytes=102400

socket.request.max.bytes=104857600

log.dirs=/home/user/kafka/data/kafka-logs

num.partitions=1

num.recovery.threads.per.data.dir=2

offsets.topic.replication.factor=2

transaction.state.log.replication.factor=2

transaction.state.log.min.isr=2

log.retention.hours=168

log.segment.bytes=1073741824

log.retention.check.interval.ms=300000

zookeeper.connect=serever1-ip:2181,serever2-ip:2181

zookeeper.connection.timeout.ms=6000

group.initial.rebalance.delay.ms=3000

auto.leader.rebalance.enable=true

leader.imbalance.check.interval.seconds=5

Zookeeper configuration

dataDir=/home/user/kafka/data

clientPort=2181

maxClientCnxns=0

initLimit=10

syncLimit=5

tickTime=2000

server.1=server1-ip:2888:3888

server.2=server2-ip:2888:3888

Is this is an expected behavior of Kafka or am I doing something wrong with this configuration ?

Can somebody help me with this issue ..

Body:
Add all the bootstrap server IPs in your properties file. If anyone of the server is down the Kafka consumer will try to connect to Kafka with an]]]other bootstrap servers. Add server 2 url in the below line:

EDIT:

spring.kafka.bootstrap-servers={SERVER1_HOST},{SERVER2_HOST}


问:
How to calculate percentages of poker hands when the program knows all hands?
I am looking to calculate the percentages that you see on tv when watching poker in my java program. The difference between this question and many others, if unclear, is that the program DOES know all players hands and can therefore determine an accurate percentage. There are many websites such as this one: https://www.pokerlistings.com/online-poker-odds-calculator
where you can input the players cards and it will give you the percentages. I was wondering if there were any all ready set algorithms for this or any java API that i could use in my program. I understand that my question may be a bit unrealistic. So if there is no algorithms or APIs, perhaps someone knows how it is calculated, so that i can try to construct my own algorithm?

In case there is still confusion:
If there are 3 players and their hands are

player 1: As kh

player 2: 2d 3c

player 3: AH AD

I would like to know the percentage that each player has to win preflop, pre-turn and pre-river
Thanks in advance.

答:
The numbers are much smaller than you might expect, so brute-forcing is quite possible. The trick is to disregard the order the cards come out as much as possible. For example, if you're considering preflop probabilities, you only care about the entire board by the river, and not the specific flop, turn and river.

Given 3 hands (6 cards), there's 46 cards remaining in the deck. That means there's choose(46, 5) = 1,370,754 different boards by the river. Enumerate all boards, and count how many times each hand wins on the river. (Or more accurately, compute the equity for each hand, since sometimes 2 or 3 hands will tie on the river). This gives you preflop probabilities, and this is the most expensive thing to compute.

Given the flop, there's only choose(43, 2) = 903 boards possible by the end, so the flop probabilities (which you call the pre-turn), it's very cheap to enumerate all the runouts and compute the average equity for the three hands.

Given the flop and turn, there's only 42 possible river cards. So on the turn (pre-river), it's even cheaper to compute the hand equities.

You'll ideally need a fast hand evaluator, but that should be easy to find online if you don't want to write it yourself.


问:
Understanding how javascript code is download in a google home device, for local home execution (action on google smart home)
I try to understand how my javascript code that handle local execution bahavior is download in my google home mini. I know I give an url towards a server or a web page here :

Action google interface

And this code is used in my google home to handle local execution but I just put my web page url here, in the test tab. So if I want to deploy my app in a production environnement, how will i do that ? I did not see any other place to put the url toward my code.

I red this page: https://developers.google.com/assistant/smarthome/concepts/local

And followed this tuto: https://github.com/actions-on-google/smart-home-local

Thanks for your answers.

答: Finally, i found my response. For now, local execution is just in preview. So no production management is implemented yet.</p>


问:
How to handle expired access token in asp.net core using refresh token with OpenId Connect
I have configured an ASOS OpenIdConnect Server using and an asp.net core mvc app that uses the "Microsoft.AspNetCore.Authentication.OpenIdConnect": "1.0.0 and "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0". I have tested the "Authorization Code" workflow and everything works.

The client web app processes the authentication as expected and creates a cookie storing the id_token, access_token, and refresh_token.

How do I force Microsoft.AspNetCore.Authentication.OpenIdConnect to request a new access_token when it expires?

The asp.net core mvc app ignores the expired access_token.

I would like to have openidconnect see the expired access_token then make a call using the refresh token to get a new access_token. It should also update the cookie values. If the refresh token request fails I would expect openidconnect to "sign out" the cookie (remove it or something).

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            AuthenticationScheme = "Cookies"
        });

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            ClientId = "myClient",
            ClientSecret = "secret_secret_secret",
            PostLogoutRedirectUri = "http://localhost:27933/",
            RequireHttpsMetadata = false,
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,
            ResponseType = OpenIdConnectResponseType.Code,
            AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet,
            Authority = http://localhost:27933,
            MetadataAddress = "http://localhost:27933/connect/config",
            Scope = { "email", "roles", "offline_access" },
        });
</code>```

答:
Following on from @longday's answer, I have had success in using this code to force a client refresh without having to manually query an open id endpoint:</p>

```<code>OnValidatePrincipal = context =>
{
    if (context.Properties.Items.ContainsKey(".Token.expires_at"))
    {
        var expire = DateTime.Parse(context.Properties.Items[".Token.expires_at"]);
        if (expire > DateTime.Now) //TODO:change to check expires in next 5 mintues.
        {
            context.ShouldRenew = true;
            context.RejectPrincipal();
        }
    }

    return Task.FromResult(0);
}
</code>```

Body:
I have configured an ASOS OpenIdConnect Server using and an asp.net core mvc app that uses the "Microsoft.AspNetCore.Authentication.OpenIdConnect": "1.0.0 and "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0". I have tested the "Authorization Code" workflow and everything works.

The client web app processes the authentication as expected and creates a cookie storing the id_token, access_token, and refresh_token.

How do I force Microsoft.AspNetCore.Authentication.OpenIdConnect to request a new access_token when it expires?

The asp.net core mvc app ignores the expired access_token.

I would like to have openidconnect see the expired access_token then make a call using the refresh token to get a new access_token. It should also update the cookie values. If the refresh token request fails I would expect openidconnect to "sign out" the cookie (remove it or something).

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            AuthenticationScheme = "Cookies"
        });

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            ClientId = "myClient",
            ClientSecret = "secret_secret_secret",
            PostLogoutRedirectUri = "http://localhost:27933/",
            RequireHttpsMetadata = false,
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,
            ResponseType = OpenIdConnectResponseType.Code,
            AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet,
            Authority = http://localhost:27933,
            MetadataAddress = "http://localhost:27933/connect/config",
            Scope = { "email", "roles", "offline_access" },
        });

Body:
Following on from @longday's answer, I have had success in using this code to force a client refresh without having to manually query an open id endpoint:

OnValidatePrincipal = context =>
{
    if (context.Properties.Items.ContainsKey(".Token.expires_at"))
    {
        var expire = DateTime.Parse(context.Properties.Items[".Token.expires_at"]);
        if (expire > DateTime.Now) //TODO:change to check expires in next 5 mintues.
        {
            context.ShouldRenew = true;
            context.RejectPrincipal();
        }
    }

    return Task.FromResult(0);
}


问:
How to create the migrations for database views using php artisan in Laravel?
Actually, I have managed to create a sql views for Laravel using PHP Artisan using below step.

Step 1. Run below command:

```<code>php artisan make:migration create_overall_report_views
</code>```

Step 2.

Open the migration file and add the below code:

```<code>class CreateOverallReportView extends Migration
{
  /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    //
    DB::statement("
      CREATE VIEW views_overall_report AS
      (
        SELECT er.user_id as user_id, e.id AS entities_id,
            c.status_id AS status_id, s.name AS status_name

        FROM `user_roles` er
          LEFT JOIN elists e ON e.id=er.entities_id
          LEFT JOIN `clists` c ON c.id=e.checklists_id
          LEFT JOIN `status` s ON s.id = c.overall_status_id

        WHERE s.slug = 'completed'
          AND c.deleted_at IS NULL
      )
    ");
  }

  /**
  * Reverse the migrations.
  *
  * @return void
  */
  public function down()
  {
    DB::statement('DROP VIEW IF EXISTS views_overall_report');
  }

}
</code>```

Step 3. To call and run the SQL Views via Laravel query

```<code>$items = $DB::table('views_overall_report')
            ->select('status_id', 'status_name',
                $DB::raw('count(entities_id) as counts')
            )
            ->groupBy('status_id')
            ->orderBy('counts' , 'desc')
            ->whereIn('user_id', Auth::user()->id())
            ->get();
print_r($items);
</code>```

Hope that helps. Please let me know if anyone has better solution!!

答:
Write your migration like this, with 'CREATE OR REPLACE' in up function:</p>

```<code>public function up()
   {

    DB::statement('CREATE OR REPLACE VIEW my_view AS SELECT name FROM users');
   }

public function down()
    {
        DB::statement('DROP VIEW my_view');
    }
</code>```

Body:
Actually, I have managed to create a sql views for Laravel using PHP Artisan using below step.

Step 1. Run below command:

php artisan make:migration create_overall_report_views

Step 2.

Open the migration file and add the below code:

class CreateOverallReportView extends Migration
{
  /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    //
    DB::statement("
      CREATE VIEW views_overall_report AS
      (
        SELECT er.user_id as user_id, e.id AS entities_id,
            c.status_id AS status_id, s.name AS status_name

        FROM `user_roles` er
          LEFT JOIN elists e ON e.id=er.entities_id
          LEFT JOIN `clists` c ON c.id=e.checklists_id
          LEFT JOIN `status` s ON s.id = c.overall_status_id

        WHERE s.slug = 'completed'
          AND c.deleted_at IS NULL
      )
    ");
  }

  /**
  * Reverse the migrations.
  *
  * @return void
  */
  public function down()
  {
    DB::statement('DROP VIEW IF EXISTS views_overall_report');
  }

}

Step 3. To call and run the SQL Views via Laravel query

$items = $DB::table('views_overall_report')
            ->select('status_id', 'status_name',
                $DB::raw('count(entities_id) as counts')
            )
            ->groupBy('status_id')
            ->orderBy('counts' , 'desc')
            ->whereIn('user_id', Auth::user()->id())
            ->get();
print_r($items);

Hope that helps. Please let me know if anyone has better solution!!

Body:
Write your migration like this, with 'CREATE OR REPLACE' in up function:

public function up()
   {

    DB::statement('CREATE OR REPLACE VIEW my_view AS SELECT name FROM users');
   }

public function down()
    {
        DB::statement('DROP VIEW my_view');
    }


问:
How to change tooltip content in c3js
I'm working on a timeline display and I have data that I want to show on the tooltip. currently it only shows the value at each time. and I cannot find a way to change it. the example below shows how to change the value's format but not what values are displayed

```<code>var chart = c3.generate({
data: {
    columns: [
        ['data1', 30000, 20000, 10000, 40000, 15000, 250000],
        ['data2', 100, 200, 100, 40, 150, 250]
    ],
    axes: {
        data2: 'y2'
    }
},
axis : {
    y : {
        tick: {
            format: d3.format("s")
        }
    },
    y2: {
        show: true,
        tick: {
            format: d3.format("$")
        }
    }
},
tooltip: {
    format: {
        title: function (d) { return 'Data ' + d; },
        value: function (value, ratio, id) {
            var format = id === 'data1' ? d3.format(',') : d3.format('$');
            return format(value);
        }
           //value: d3.format(',') // apply this format to both y and y2
    }
}
});
</code>```

it's taken from http://c3js.org/samples/tooltip_format.html
they do admit that there isn't an example for content editing but I couldn't find anything in the reference or forums, but a suggestion to change the code (it's here: https://github.com/masayuki0812/c3/blob/master/c3.js in line 300) and below:

```<code>__tooltip_contents = getConfig(['tooltip', 'contents'], function (d, defaultTitleFormat, defaultValueFormat, color) {
        var titleFormat = __tooltip_format_title ? __tooltip_format_title : defaultTitleFormat,
            nameFormat = __tooltip_format_name ? __tooltip_format_name : function (name) { return name; },
            valueFormat = __tooltip_format_value ? __tooltip_format_value : defaultValueFormat,
            text, i, title, value, name, bgcolor;
        for (i = 0; i < d.length; i++) {
            if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }

            if (! text) {
                title = titleFormat ? titleFormat(d[i].x) : d[i].x;
                text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
            }

            name = nameFormat(d[i].name);
            value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
            bgcolor = levelColor ? levelColor(d[i].value) : color(d[i].id);

            text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>";
            text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
            text += "<td class='value'>" + value + "</td>";
            text += "</tr>";
        }
        return text + "</table>";
    })
</code>```

did anyone attempted to do so? developed some function to facilitate the process? have any tips on how to do so correctly? I do not know how to change their code in a way I could use more data or data different than the d value the function gets.

答:
I faced a problem which is related tooltip position and style for c3 before. in order to arrange tooltip in c3 freely, my suggestion is manipulating tooltip with d3.

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>// internal = chart.internal()

const mousePos = d3.mouse(internal.svg.node()); // find mouse position
const clientX = mousePos[0]; //for x
const clientY = mousePos[1]; //for y
const tooltip = d3.select("#tooltip"); //select tooltip div (apply your style)
tooltip.style("display", "initial");  //show tooltip
tooltip.style("left", clientX - mouseOffSet.X + "px"); // set position
tooltip.style("top", clientY - mouseOffSet.Y + "px");  // set position
tooltip.html("<span>" + content + "</span>");

// you can arrange all content and style whatever you want</code>```

```
</div>
</div>

Good luck!!
</code>```

Title: How to change tooltip content in c3js

Body:
I'm working on a timeline display and I have data that I want to show on the tooltip. currently it only shows the value at each time. and I cannot find a way to change it. the example below shows how to change the value's format but not what values are displayed

var chart = c3.generate({
data: {
    columns: [
        ['data1', 30000, 20000, 10000, 40000, 15000, 250000],
        ['data2', 100, 200, 100, 40, 150, 250]
    ],
    axes: {
        data2: 'y2'
    }
},
axis : {
    y : {
        tick: {
            format: d3.format("s")
        }
    },
    y2: {
        show: true,
        tick: {
            format: d3.format("$")
        }
    }
},
tooltip: {
    format: {
        title: function (d) { return 'Data ' + d; },
        value: function (value, ratio, id) {
            var format = id === 'data1' ? d3.format(',') : d3.format('$');
            return format(value);
        }
           //value: d3.format(',') // apply this format to both y and y2
    }
}
});

it's taken from http://c3js.org/samples/tooltip_format.html
they do admit that there isn't an example for content editing but I couldn't find anything in the reference or forums, but a suggestion to change the code (it's here: https://github.com/masayuki0812/c3/blob/master/c3.js in line 300) and below:

__tooltip_contents = getConfig(['tooltip', 'contents'], function (d, defaultTitleFormat, defaultValueFormat, color) {
        var titleFormat = __tooltip_format_title ? __tooltip_format_title : defaultTitleFormat,
            nameFormat = __tooltip_format_name ? __tooltip_format_name : function (name) { return name; },
            valueFormat = __tooltip_format_value ? __tooltip_format_value : defaultValueFormat,
            text, i, title, value, name, bgcolor;
        for (i = 0; i < d.length; i++) {
            if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }

            if (! text) {
                title = titleFormat ? titleFormat(d[i].x) : d[i].x;
                text = "
" + (title || title === 0 ? "
" + title + "
" : "");
            }

            name = nameFormat(d[i].name);
            value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
            bgcolor = levelColor ? levelColor(d[i].value) : color(d[i].id);

            text += "
";
            text += "" + name + "	";
            text += "" + value + "	";
            text += "
";
        }
        return text + "
";
    })

did anyone attempted to do so? developed some function to facilitate the process? have any tips on how to do so correctly? I do not know how to change their code in a way I could use more data or data different than the d value the function gets.

Body:
I faced a problem which is related tooltip position and style for c3 before. in order to arrange tooltip in c3 freely, my suggestion is manipulating tooltip with d3.

// internal = chart.internal()

const mousePos = d3.mouse(internal.svg.node()); // find mouse position
const clientX = mousePos[0]; //for x
const clientY = mousePos[1]; //for y
const tooltip = d3.select("#tooltip"); //select tooltip div (apply your style)
tooltip.style("display", "initial");  //show tooltip
tooltip.style("left", clientX - mouseOffSet.X + "px"); // set position
tooltip.style("top", clientY - mouseOffSet.Y + "px");  // set position
tooltip.html("<span>" + content + "</span>");

// you can arrange all content and style whatever you want

 <div
      id="tooltip"
      className="your-style"
      style={{ display: "none", position: "absolute" }}
    />

Good luck!!


问:
Using tweetsharp to pull data for a specific user
Using tweetsharp to pull data for a specific user: I would like to get the numbers of retweet (RT or Retweet) and the numbers of mentioning (@).

Could you help me? Thanks.

答:
The current version of TweetSharp, version 2.0, has methods that map directly to the Twitter API.

Assuming you have the oAuth tokens for a user you can use methods like

```<code>.ListRetweetsOfMyTweets(...)
.ListTweetsMentioningMe(...)
</code>```

If you don't have access to a user's profile, you can still do a search for that user using the standard search query syntax.

```<code>.Search("to:JohnDoe" ... )
.Search("from:JohnDoe" ... )
</code>```

Both should get you the details you're looking for.

ContentLicense: CC BY-SA 2.5

Body:
The current version of TweetSharp, version 2.0, has methods that map directly to the Twitter API.

Assuming you have the oAuth tokens for a user you can use methods like

.ListRetweetsOfMyTweets(...)
.ListTweetsMentioningMe(...)

If you don't have access to a user's profile, you can still do a search for that user using the standard search query syntax.

.Search("to:JohnDoe" ... )
.Search("from:JohnDoe" ... )

Both should get you the details you're looking for.


问:
Matching string from one file to another file and append the values
I have two text files with 350 m+ rows. Content of two text files are as follows:

```<code>file1:
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT

</code>```

```<code>file2:
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58

</code>```

I would like to match the value of column 1 of file 2 and the string in file1 and append the value after > of file1 with file2 whenever there is a match.

The desired output is:

```<code>15_48499991_ENSG00000074803_C_G_G    CCAATCGCTTTCAAGTTAGTGTG    -14.48
15_48499991_ENSG00000074803_C_G_G    CAATCGCTTTCAAGTTAGTGTGA    -29.94
15_48499991_ENSG00000074803_C_G_G    AATCGCTTTCAAGTTAGTGTGAT    -20.58
</code>```

Any suggestions would be helpful here.

Thanks

答:
You can create a dictionary from file1 and use it to process file2.</p>

```<code>from io import StringIO

file1 = '''\
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT
'''

file2 = '''\
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58
'''

# Create a look-up table from first file.
map = {}
with StringIO(file1) as file:  # Open file1.
    for line in file:
        first = line.rstrip()[1:]  # Remove leading '>'.
        second = next(file).rstrip()
        map[second] = first

# Output matches in desired format.
with StringIO(file2) as file:  # Open file2.
    for line in file:
        first, second = line.split()
        print(f'{map[first]}    {first}    {second}')
</code>```

Body:
I have two text files with 350 m+ rows. Content of two text files are as follows:

file1:
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT

file2:
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58

I would like to match the value of column 1 of file 2 and the string in file1 and append the value after > of file1 with file2 whenever there is a match.

The desired output is:

15_48499991_ENSG00000074803_C_G_G    CCAATCGCTTTCAAGTTAGTGTG    -14.48
15_48499991_ENSG00000074803_C_G_G    CAATCGCTTTCAAGTTAGTGTGA    -29.94
15_48499991_ENSG00000074803_C_G_G    AATCGCTTTCAAGTTAGTGTGAT    -20.58

Any suggestions would be helpful here.

Thanks

Body:
You can create a dictionary from file1 and use it to process file2.

from io import StringIO

file1 = '''\
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT
'''

file2 = '''\
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58
'''

# Create a look-up table from first file.
map = {}
with StringIO(file1) as file:  # Open file1.
    for line in file:
        first = line.rstrip()[1:]  # Remove leading '>'.
        second = next(file).rstrip()
        map[second] = first

# Output matches in desired format.
with StringIO(file2) as file:  # Open file2.
    for line in file:
        first, second = line.split()
        print(f'{map[first]}    {first}    {second}')


答:
I tried to summarize your requirement as below:

Example input,in a minute window there can be multiple VAL changes for each batch ID:

Make:batch1,Val:01, Make:batch1,val:01, Make:batch1,val:02,
  Make:batch1,val:02 ×××××××××××× Make:batch2,val:01,
  Make:batch2,val:01, Xxxxxxxxxx

Desired output,only val for every batch changes and no duplicates:

Make:batch1,val:01 Make:batch1,val:02 Make:batch2,val:01

Answer is divided into 2 parts:

1.Collect data in a static period, you could use built-in Tumbling Window function as below:

2.No built-in ASA function like distinct to filter the duplicate.I'd suggest you using GROUP BY, MAX,ASA UDF(link) to approaching your result.

SQL:

```<code> SELECT g.Payload.Make,g.Payload.VAL,max(udf.convertdate(g.Payload.TS)) as TS
    FROM geoinput g TIMESTAMP BY g.Payload.TS
    GROUP BY g.Payload.Make,g.Payload.VAL, TumblingWindow(Duration(minute, 1))
</code>```

Test output:

BTW,i just use below code inside UDF

```<code>var date = new Date(datetime);
    return date.getTime();
</code>```

Another workaround,you could collect all the data during 1 minute then use Azure Function as Output. In the Azure Function, you could process data as you want. Such as use JSON object to store the data.Key-Value structure could filter duplicate rows.

Title: azure Stream analytics isfirst and last query

Body:
I have the payload something like below. I need to get the first distinct  batch values for every 1 minute period. Please let me know how to achieve this in stream analytics using isfirst and lag or last

Output like:

BATCH=01,"2015-01-01T00:00:01.0000000Z"
   BATCH=02,"2015-01-01T00:00:03.0000000Z"
   BATCH=03,"2015-01-01T00:00:06.0000000Z"
   BATCH=01,"2015-01-01T00:00:14.0000000Z"
   BATCH=02,"2015-01-01T00:00:18.0000000Z"
   BATCH=03,"2015-01-01T00:00:22.0000000Z"
   BATCH=01,"2015-01-01T00:00:27.0000000Z"
   BATCH=01,"2015-01-01T00:00:31.0000000Z"

Pay Load:
    [{
            "Payload": {
                "Make": "BATCH1",
                "VAL": "01",
                "TS": "2015-01-01T00:00:01.0000000Z"
            }
    },
    {
    "Payload": {
            "Make": "BATCH1",
            "VAL": "01",
            "TS": "2015-01-01T00:00:02.0000000Z"
        }
    },
    {
        "Payload": {
            "Make": "BATCH1",
            "VAL": "02",
            "TS": "2015-01-01T00:00:03.0000000Z"
        }
    },
    {
        "Payload": {
            "Make": "BATCH1",
            "VAL": "02",
            "TS": "2015-01-01T00:00:04.0000000Z"
        }
    },
    {
        "Payload": {
            "Make": "BATCH1",
            "VAL": "02",
            "TS": "2015-01-01T00:00:05.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH1",
            "VAL": "03",
            "TS": "2015-01-01T00:00:06.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH1",
            "VAL": "03",
            "TS": "2015-01-01T00:00:07.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH1",
            "VAL": "03",
            "TS": "2015-01-01T00:00:10.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH1",
            "VAL": "03",
            "TS": "2015-01-01T00:00:11.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH1",
            "VAL": "03",
            "TS": "2015-01-01T00:00:12.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "01",
            "TS": "2015-01-01T00:00:13.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "01",
            "TS": "2015-01-01T00:00:14.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "01",
            "TS": "2015-01-01T00:00:15.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "01",
            "TS": "2015-01-01T00:00:16.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "01",
            "TS": "2015-01-01T00:00:17.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "02",
            "TS": "2015-01-01T00:00:18.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "02",
            "TS": "2015-01-01T00:00:20.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH2",
            "VAL": "02",
            "TS": "2015-01-01T00:00:21.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH3",
            "VAL": "02",
            "TS": "2015-01-01T00:00:22.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH3",
            "VAL": "02",
            "TS": "2015-01-01T00:00:23.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH3",
            "VAL": "02",
            "TS": "2015-01-01T00:00:24.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH3",
            "VAL": "02",
            "TS": "2015-01-01T00:00:25.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH3",
            "VAL": "02",
            "TS": "2015-01-01T00:00:26.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH4",
            "VAL": "01",
            "TS": "2015-01-01T00:00:27.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH4",
            "VAL": "01",
            "TS": "2015-01-01T00:00:28.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH4",
            "VAL": "01",
            "TS": "2015-01-01T00:00:29.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH4",
            "VAL": "01",
            "TS": "2015-01-01T00:00:30.0000000Z"
        }

    },
    {"Payload": {
            "Make": "BATCH5",
            "VAL": "01",
            "TS": "2015-01-01T00:00:31.0000000Z"
        }

    }
    ]

Body:
I tried to summarize your requirement as below:

Example input,in a minute window there can be multiple VAL changes for each batch ID:

Make:batch1,Val:01, Make:batch1,val:01, Make:batch1,val:02,
  Make:batch1,val:02 ×××××××××××× Make:batch2,val:01,
  Make:batch2,val:01, Xxxxxxxxxx

Desired output,only val for every batch changes and no duplicates:

Make:batch1,val:01 Make:batch1,val:02 Make:batch2,val:01

Answer is divided into 2 parts:

1.Collect data in a static period, you could use built-in Tumbling Window function as below:

2.No built-in ASA function like distinct to filter the duplicate.I'd suggest you using GROUP BY, MAX,ASA UDF(link) to approaching your result.

SQL:

 SELECT g.Payload.Make,g.Payload.VAL,max(udf.convertdate(g.Payload.TS)) as TS
    FROM geoinput g TIMESTAMP BY g.Payload.TS
    GROUP BY g.Payload.Make,g.Payload.VAL, TumblingWindow(Duration(minute, 1))

Test output:

BTW,i just use below code inside UDF

var date = new Date(datetime);
    return date.getTime();

Another workaround,you could collect all the data during 1 minute then use Azure Function as Output. In the Azure Function, you could process data as you want. Such as use JSON object to store the data.Key-Value structure could filter duplicate rows.


问:
Editing templates in ui in Azure Devops Services
I like the concept of templates in Azure DevOps. However, one limitation I run into is that it does not allow visualizing the steps of the template in the pipeline editor for a YAML based pipeline. This seems like a big restriction for it's adoption for me personally. Is there something that I am missing here?</p>

答:
Editing templates in ui in Azure Devops Services

For this issue , agree with 4c74356b41 , visualizing template step in YAML editor is currently not supported in azure devops.

Currently, only specific tasks can be visualized in the yaml file, by clicking the settings above the task. The editor page appears on the right side of the web ui. As for template steps, visualization is not supported for the time being.

Apart from the negative answer, I think what you want is a good idea! So I post a feature request here in DC forum. you could vote that suggestion ticket and share your comment there,The product team would provide the updates if they view it.


问:
How do you handle checks to see if a user changed something in a dialog
Talking .NET WinForms here:

If you have an application where someone can change items using some properties dialog for example, how do you determine if a user has changed something when he clicks on cancel (to decide whether to display a cancel confirmation message box, or not).

I can think of 2 methods:

Defining a dirty bit and handling all "changed" events to set this bit to true.

Clone the original object and write some comparison code to determine if the modified object really was modified compared with the original

Is there any more elegant and/or more generic way to do that?

答:
Rethink the design where you want to display a confirmation dialog box. Confirmation boxes are largely useless because users become conditioned to always press "yes, that's what I meant". Instead, if a user cancels after having made a change, provide a mechanism for the user to recover that data. This is particularly important if the dialog in the data is difficult or time consuming for the user to reproduce, not so important if the user could redo their work in a matter of seconds.

To answer your specific question though, I recommend choice (2) where you have a clone of the object. Comparing the original to the new is the surest way to know "has the data changed?". If you use the dirty bit concept, make sure you handle the case where the user changed a value then changed it back. Usually to do that though, you have to keep a copy of the original version anyway so you're back to keeping a copy of the original object. With a copy of the original object in hand it's probably easier to just compare the two objects than to manage tracking a dirty bit.

OwnerDisplayName: Stefan Koell

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: Bryan Oakley


问:
polymorphic .find_or_create_by with mongoid 2.0.1, on embedded document collections?
in previous released of Mongoid (2.0.beta.20), I could pass a class type as the
2nd parameter of the .find_or_create_by block on embedded document collections.
this doesn't appear to be the case any more, with v2.0.1, yet I still
need to do polymorphic find_or_create_by. any suggestions / pointers
on how to do this?

I used to do this:

SomeClass.childclass.find_or_create_by({:key => "value"},
InheritingChildClass)

now I get an exception saying too many arguments (2 for 1)
on .find_or_create_by.

how can I tell the collection to create an object of the correct type, when using find_or_create_by? Or, how can i create my own method that will be functionaly equivalent to what I want, and be re-usable across my embedded document collections?

any help is appreciated.

thanks.

答:
I ended up rolling my own solution for this</p>

```<code>module Mongoid::Relations
  class Many
    def find_or_new(attrs, type, &block)
      inst = self.where(attrs).first

      unless inst
        inst = type.new
        inst.write_attributes attrs
        self << inst
      end

      inst
    end
  end
end
</code>```

Body:
I ended up rolling my own solution for this

module Mongoid::Relations
  class Many
    def find_or_new(attrs, type, &block)
      inst = self.where(attrs).first

      unless inst
        inst = type.new
        inst.write_attributes attrs
        self << inst
      end

      inst
    end
  end
end


答:
You need to subset your lables (Dates in your case) too:</p>

```<code>ggplot(Final, aes(x = Step, y = Value)) +
geom_line(size = 1) +
geom_point() +
scale_x_continuous(labels=Date[seq(1, 50,by=10)],
                   breaks = seq(1, 50,by=10))
</code>```

Title: Using date in scale_x_continuous with breaks

Body:
I am trying to replace the x-axis values created using step, which are values 1:50.
I can replace these easily using scale_x_continuous but when I use breaks I get the error below. I cannot use date and time in the plot function I am using so looking for a work around to get date on my axis

 Date =      c( "2018-10-18 00:00:00 BST", "2018-10-18 00:10:00 BST", "2018-10-18 00:20:00 BST", "2018-10-18 00:30:00 BST", "2018-10-18 00:40:00 BST", "2018-10-18 00:50:00 BST",
                 "2018-10-18 01:00:00 BST", "2018-10-18 01:10:00 BST", "2018-10-18 01:20:00 BST", "2018-10-18 01:30:00 BST", "2018-10-18 01:40:00 BST", "2018-10-18 01:50:00 BST",
                 "2018-10-18 02:00:00 BST", "2018-10-18 02:10:00 BST", "2018-10-18 02:20:00 BST", "2018-10-18 02:30:00 BST", "2018-10-18 02:40:00 BST", "2018-10-18 02:50:00 BST",
                 "2018-10-18 03:00:00 BST", "2018-10-18 03:10:00 BST", "2018-10-18 03:20:00 BST", "2018-10-18 03:30:00 BST", "2018-10-18 03:40:00 BST", "2018-10-18 03:50:00 BST",
                 "2018-10-18 04:00:00 BST", "2018-10-18 04:10:00 BST", "2018-10-18 04:20:00 BST", "2018-10-18 04:30:00 BST", "2018-10-18 04:40:00 BST", "2018-10-18 04:50:00 BST",
                 "2018-10-18 05:00:00 BST", "2018-10-18 05:10:00 BST", "2018-10-18 05:20:00 BST", "2018-10-18 05:30:00 BST", "2018-10-18 05:40:00 BST", "2018-10-18 05:50:00 BST",
                 "2018-10-18 06:00:00 BST", "2018-10-18 06:10:00 BST", "2018-10-18 06:20:00 BST", "2018-10-18 06:30:00 BST", "2018-10-18 06:40:00 BST", "2018-10-18 06:50:00 BST",
                 "2018-10-18 07:00:00 BST", "2018-10-18 07:10:00 BST", "2018-10-18 07:20:00 BST", "2018-10-18 07:30:00 BST", "2018-10-18 07:40:00 BST", "2018-10-18 07:50:00 BST",
                 "2018-10-18 08:00:00 BST", "2018-10-18 08:10:00 BST")

  Step  <- c(1:50)
  Value <- runif(50,0,10)
  Final <- data.frame(Step, Value)

                      ggplot(Final, aes(x = Step, y = Value)) +
                        geom_line(size = 1) +
                        geom_point() +
                        scale_x_continuous(labels=Date,breaks = seq(1, 50))       #works
                        scale_x_continuous(labels=Date,breaks = seq(1, 50,by=10)) #doesntwork

Error: `breaks` and `labels` must have the same length

Body:
You need to subset your lables (Dates in your case) too:

ggplot(Final, aes(x = Step, y = Value)) +
geom_line(size = 1) +
geom_point() +
scale_x_continuous(labels=Date[seq(1, 50,by=10)],
                   breaks = seq(1, 50,by=10))


问:
How to fix Cannot find name 'Set'
I have simple ts file with a simple sum function that just simple add two numbers no Rocket Science here below

```<code>function sum(a,b){
    return a+b;
}
</code>```

But when I run

```<code>tsc TypeScript.ts
</code>```

I get this error below?

```<code>   ts
    ../../../../node_modules/@types/react/index.d.ts:388:23 - error TS2583: Cannot find name
    'Set'. Do you need to change your target library? Try changing the `lib` compiler option
    to es2015 or later.

    388         interactions: Set<SchedulerInteraction>,
                              ~~~

    Found 1 error.

</code>```

How can i fix this error?

答:
I searched through StackOverflow and i found the answer.
Just type this following command in the terminal

```<code>npm install @types/node --save-dev
</code>```

Then the error will dissapear!

Title: How to fix Cannot find name 'Set'

Body:
I have simple ts file with a simple sum function that just simple add two numbers no Rocket Science here below

function sum(a,b){
    return a+b;
}

But when I run

tsc TypeScript.ts

I get this error below?

   ts
    ../../../../node_modules/@types/react/index.d.ts:388:23 - error TS2583: Cannot find name
    'Set'. Do you need to change your target library? Try changing the `lib` compiler option
    to es2015 or later.

    388         interactions: Set<SchedulerInteraction>,
                              ~~~

    Found 1 error.

How can i fix this error?

Body:
I searched through StackOverflow and i found the answer.
Just type this following command in the terminal

npm install @types/node --save-dev

Then the error will dissapear!


问:
Skip the filenames whch do not have contents while doing a for loop
I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

```<code>for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done
</code>```

Output

```<code>-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)
</code>```

Desired output..

```<code>-- file6 --
some output
-- file9 --
some output
</code>```

答:
The proper way to simply get the names of the files containing "string_something" is:

```<code>grep -l -d skip -F 'string_something' *
</code>```

If you insist on wrapping the filename in "-- name --", then you can loop over the results of grep and format the output as desired, e.g.

```<code>for i in $(grep -l -d skip -F 'string_something' *); do
    printf -- "-- %s --\n%s\n" "$i" 'string_something'
done
</code>```

Look things over and let me know if you have further questions.

Body:
I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done

Output

-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)

Desired output..

-- file6 --
some output
-- file9 --
some output

Body:
The proper way to simply get the names of the files containing "string_something" is:

grep -l -d skip -F 'string_something' *

If you insist on wrapping the filename in "-- name --", then you can loop over the results of grep and format the output as desired, e.g.

for i in $(grep -l -d skip -F 'string_something' *); do
    printf -- "-- %s --\n%s\n" "$i" 'string_something'
done

Look things over and let me know if you have further questions.


问:
Why does my Snowflake Table load keep failing?
Just created a trial Snowflake account, created a simple (17 column) table.

Tried to import csv into it.

Every time I try I get a 'Staging error': "There was an error while trying to stage "[filename]".
Reason: Maximum file size exceeded."

True, the main file I want is 4GB, but I keep cutting it down to smaller sizes (last one is 72mb) and still get the same error.

Yes, of course I could make the file even smaller, but already missing the point of using the system! If I can't load my data, what's the point of the db..?

I'm sure there is something simple and obvious I'm missing, but I don't know what that is.

Thanks in advance for any help.

答:
You forgot to mention which loading method you're trying to use. Looking at what you're saying I suspect you're trying to import the file via the web interface, and that's only intended for small files (up to 50mb). If you want to import a bigger file (or multiple files) you should go with bulk load using COPY (this can have different scenarios depending on the cloud you use):

https://docs.snowflake.net/manuals/user-guide/data-load-bulk.html


问:
need to open home activity on back pressed android
I have a activity stack in normal case is  A -> B -> C and when i received a push notification and have implemented click_action it opens Activity C which is correct.

Now, what is need is when activity C opens from push notification after pressing back button it gets closed and whole application goes in background, but i need to navigate to Home screen (Activity A)

```<code><activity
    android:name="Activity_A"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_B"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_C"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="adjustPan">
    <intent-filter>
        <action android:name="Activity_C" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
</code>```

答:
you can add below line in you AndroidManifest.xml file in Activity C.

```<code>android:launchMode="singleTop"
</code>```

It will redirect you to home activity when opened from Notification and is back pressed. Hope this helps you.

Body:
I have a activity stack in normal case is  A -> B -> C and when i received a push notification and have implemented click_action it opens Activity C which is correct.

Now, what is need is when activity C opens from push notification after pressing back button it gets closed and whole application goes in background, but i need to navigate to Home screen (Activity A)

<activity
    android:name="Activity_A"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_B"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_C"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="adjustPan">
    <intent-filter>
        <action android:name="Activity_C" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Body:
you can add below line in you AndroidManifest.xml file in Activity C.

android:launchMode="singleTop"

It will redirect you to home activity when opened from Notification and is back pressed. Hope this helps you.


问:
How can I print or put to some HashMap or anything else my result of query?
I have an SQL query in the following Java Code:

```<code>try {
    Statement st = conn.createStatement();
    try {
        st.execute("SELECT * FROM students WHERE course_id =1");
    } finally {
        // st.close();
    }
} catch (SQLException ex) {
    throw new RuntimeException(ex);
}
</code>```

When I execute this code, I don't see anything in the console.

I want to put the results to a Hashmap or print them to see the values, at least.

How can I implement printing to the console or storing the results in a Map?

答:
It would really help to know the column information (labels, amount, types), but maybe, you can do what you want having the following code as a hint or template and reading the comments carefully:</p>

```<code>public static void main(String[] args) {
    // provide the query as String with a question mark for the parameter
    String query = "SELECT * FROM students WHERE course_id = ?";
    // and provide the parameter value
    int id = 1;

    // use a try with resources in order to automatically close the resources
    try (PreparedStatement ps = conn.prepareStatement(query)) { // WON'T COMPILE due to conn
        // set the position and the parameter to the query
        ps.setInt(1, id);
        // execute the query and receive the results
        ResultSet rs = ps.executeQuery();

        /*
         *  since we neither know how many columns "* FROM students" returns,
         *  nor what types their values have, we have to determine them programmatically
         */

        // that means we need to receive them from the meta data of the result set
        ResultSetMetaData rsmd = rs.getMetaData();

        // provide a StringBuilder for the output of the header information
        StringBuilder headerInfoBuilder = new StringBuilder();

        // extract the column information
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            headerInfoBuilder.append(rsmd.getColumnLabel(i))
                            .append(" [")
                            .append(rsmd.getColumnType(i))
                            .append("]")
                            .append(";");
        }

        // remove the last semicolon
        String headerInfo = headerInfoBuilder.toString()
                                            .substring(0, headerInfoBuilder.length() - 1);
        // and print the header information
        System.out.println(headerInfo);

        // provide a variable that counts the rows
        int rowCount;

        // then iterate the results
        while (rs.next()) {
            /*
             * print the results here or store them in a data structure,
             * depends on the types and amount of columns
             */

            rowCount++;
        }

        // output the row count
        System.out.println(rowCount + " rows received");

    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}
</code>```

Body:
I have an SQL query in the following Java Code:

try {
    Statement st = conn.createStatement();
    try {
        st.execute("SELECT * FROM students WHERE course_id =1");
    } finally {
        // st.close();
    }
} catch (SQLException ex) {
    throw new RuntimeException(ex);
}

When I execute this code, I don't see anything in the console.

I want to put the results to a Hashmap or print them to see the values, at least.

How can I implement printing to the console or storing the results in a Map?

Body:
It would really help to know the column information (labels, amount, types), but maybe, you can do what you want having the following code as a hint or template and reading the comments carefully:

public static void main(String[] args) {
    // provide the query as String with a question mark for the parameter
    String query = "SELECT * FROM students WHERE course_id = ?";
    // and provide the parameter value
    int id = 1;

    // use a try with resources in order to automatically close the resources
    try (PreparedStatement ps = conn.prepareStatement(query)) { // WON'T COMPILE due to conn
        // set the position and the parameter to the query
        ps.setInt(1, id);
        // execute the query and receive the results
        ResultSet rs = ps.executeQuery();

        /*
         *  since we neither know how many columns "* FROM students" returns,
         *  nor what types their values have, we have to determine them programmatically
         */

        // that means we need to receive them from the meta data of the result set
        ResultSetMetaData rsmd = rs.getMetaData();

        // provide a StringBuilder for the output of the header information
        StringBuilder headerInfoBuilder = new StringBuilder();

        // extract the column information
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            headerInfoBuilder.append(rsmd.getColumnLabel(i))
                            .append(" [")
                            .append(rsmd.getColumnType(i))
                            .append("]")
                            .append(";");
        }

        // remove the last semicolon
        String headerInfo = headerInfoBuilder.toString()
                                            .substring(0, headerInfoBuilder.length() - 1);
        // and print the header information
        System.out.println(headerInfo);

        // provide a variable that counts the rows
        int rowCount;

        // then iterate the results
        while (rs.next()) {
            /*
             * print the results here or store them in a data structure,
             * depends on the types and amount of columns
             */

            rowCount++;
        }

        // output the row count
        System.out.println(rowCount + " rows received");

    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}


问:
How to get all value from ACE Editor using PHP
I used ACE Editor. I want to get all value from ACE Editor using PHP. How can i get?

I wrote JQuery Ajax code

```<code> $('#save').click(function(){
            var editor = ace.edit("editor");
            var code = editor.getSession().getDocument().getValue();
                  $.ajax({
                       type: "POST",
                       url: "data.php",
                       data: {'code':code},
                       success: function (data) {
                           console.log(data);
                       }
                     });
        });
</code>```

When this code work, not all the code comes, what can i do? without getlValue() or getSession()

thanks regards

答:
I solved.

That's like

```<code>$('#save').click(function(){
            var editor = ace.edit("codeArea");
            var code = editor.getSession().getValue();
                  $.ajax({
                       type: "POST",
                       url: "data.php",
                       data: {'code':code},
                       success: function (data) {
                           console.log(data);
                       }
                     });
        });
</code>```

all you have to do ace.edit('codeArea'); not 'editor'

Body:
I used ACE Editor. I want to get all value from ACE Editor using PHP. How can i get?

I wrote JQuery Ajax code

 $('#save').click(function(){
            var editor = ace.edit("editor");
            var code = editor.getSession().getDocument().getValue();
                  $.ajax({
                       type: "POST",
                       url: "data.php",
                       data: {'code':code},
                       success: function (data) {
                           console.log(data);
                       }
                     });
        });

When this code work, not all the code comes, what can i do? without getlValue() or getSession()

thanks regards

Body:
I solved.

That's like

$('#save').click(function(){
            var editor = ace.edit("codeArea");
            var code = editor.getSession().getValue();
                  $.ajax({
                       type: "POST",
                       url: "data.php",
                       data: {'code':code},
                       success: function (data) {
                           console.log(data);
                       }
                     });
        });

all you have to do ace.edit('codeArea'); not 'editor'


问:
Magento has a redirect loop
My Magento web site home page has a redirect loop error. When I try to open it it goes to my old server url and gives the error:

The webpage resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.

When I try to go into admin it takes to me old server admin url without any error.

I down loaded the fresh data base and connected my store to that it works fine but when i connect it my old data base it give same error.

Please advise me.

答: I had the same issue and after reloading and reloading my page I noticed that the error message responded to www.mydomain.tld and sometimes to mydomain.tld. I'm using Plesk on the server and I remembered that I set the Domain to always be called without www. I just changed that to none in the hosting settings of the domain. Lucky me, that solved that issue. Hope that helps someone else.</p>

Title: Magento has a redirect loop


问:
Uncaught Exception: DateTime::__construct(): Failed to parse time string
I'm using the function below to calculate the age (in years) of people from birthdays dates (in european format DD/MM/YYYY) that are stored as text in Wordpress Advanced Custom Fields

```<code>function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}
</code>```

In the majority of cases it works fine but in some cases I got the error below :

```<code> Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99
</code>```

Example of data that works fine :
       $age = get_age($birthday);

For $birthday value = 05/04/1946 it works fine but for $birthday value = 26/01/1958 I get the error above.
I don't undertand why as the data seems to me the same format in the 2 cases.

Do you have any clue why ?

Thanks.
Regards.

答:
According to this:

https://www.php.net/manual/en/datetime.formats.php

```<code>// THIS IS INVALID, WOULD IMPLY MONTH == 19
$external = "19/10/2016 14:48:21";

// HOWEVER WE CAN INJECT THE FORMATTING WHEN WE DECODE THE DATE
$format = "d/m/Y H:i:s";
$dateobj = DateTime::createFromFormat($format, $external);

$iso_datetime = $dateobj->format(Datetime::ATOM);
echo "SUCCESS: $external EQUALS ISO-8601 $iso_datetime";
</code>```

26 is treated as month. So, add $format = "d/m/Y"; to your date like above.

Body:
I'm using the function below to calculate the age (in years) of people from birthdays dates (in european format DD/MM/YYYY) that are stored as text in Wordpress Advanced Custom Fields

function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}

In the majority of cases it works fine but in some cases I got the error below :

 Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99

Example of data that works fine :
       $age = get_age($birthday);

For $birthday value = 05/04/1946 it works fine but for $birthday value = 26/01/1958 I get the error above.
I don't undertand why as the data seems to me the same format in the 2 cases.

Do you have any clue why ?

Thanks.
Regards.

Body:
According to this:

https://www.php.net/manual/en/datetime.formats.php

// THIS IS INVALID, WOULD IMPLY MONTH == 19
$external = "19/10/2016 14:48:21";

// HOWEVER WE CAN INJECT THE FORMATTING WHEN WE DECODE THE DATE
$format = "d/m/Y H:i:s";
$dateobj = DateTime::createFromFormat($format, $external);

$iso_datetime = $dateobj->format(Datetime::ATOM);
echo "SUCCESS: $external EQUALS ISO-8601 $iso_datetime";

26 is treated as month. So, add $format = "d/m/Y"; to your date like above.


问:
Get value from property that's value is xml
I have a property that's contain :   <date xmlns="http://test.com/ds">20200222</date>.

And i want to get the value '20200222' how can i do it ?   knowing that if it's empty i get <date xmlns="http://test.com/ds"/>
please advise .

答:
If <date xmlns="http://test.com/ds">20200222</date> is a string, you can use slice.

```<code>var str = '<date xmlns="http://test.com/ds">20200222</date>';
var value = str.slice(str.indexOf('>')+1, str.indexOf('</date>');
console.log(value); //prints "20200222"
</code>```

When there is no date, same method returns blank string:

```<code>var str = '<date xmlns="http://test.com/ds"/>';
var value = str.slice(str.indexOf('>')+1, str.indexOf('</date>');
console.log(value); //prints ""
</code>```

Body:
If <date xmlns="http://test.com/ds">20200222</date> is a string, you can use slice.

var str = '<date xmlns="http://test.com/ds">20200222</date>';
var value = str.slice(str.indexOf('>')+1, str.indexOf('</date>');
console.log(value); //prints "20200222"

When there is no date, same method returns blank string:

var str = '<date xmlns="http://test.com/ds"/>';
var value = str.slice(str.indexOf('>')+1, str.indexOf('</date>');
console.log(value); //prints ""


答:
It happens because usually previous activities are saved in a stack and when user press back button the stack is called so from what i understood from your question if You want to open Home Activity through Activity C just call intent from Activity C to Home Activity by overriding the onbackpressed() method in Activity C.
Here is an Example..

```<code>Intent homeIntent = new Intent(this,HomeActivity);
startActivity(homeIntent);
finish();
</code>```

finish() is used for removing the stacked activities.

Title: need to open home activity on back pressed android

Body:
It happens because usually previous activities are saved in a stack and when user press back button the stack is called so from what i understood from your question if You want to open Home Activity through Activity C just call intent from Activity C to Home Activity by overriding the onbackpressed() method in Activity C.
Here is an Example..

Intent homeIntent = new Intent(this,HomeActivity);
startActivity(homeIntent);
finish();

finish() is used for removing the stacked activities.


问:
Access Number of Users in a chrome extension HTML
I have a chrome extension, and I am creating a website for it, that has info, and a way to test it. I would like to show the number of users currently, but have found no way to do this. It doesn't have to update every day, but if it updated weekly that would be great!
Also- I don't care if it is by a outside company rather than chrome itself. all that matters is that it works.</p>

答: I am planning to show something similar on my extension's site so I have googled around a bit recently. I found a repo (https://github.com/petasittek/chrome-web-store-stats) that parses information about extensions in the Chrome Web Store. It could be useful for you. I think I will end up just parsing the Webstore page for the user numbers everyday in save it to a database. My extension is also available for Firefox and I will do the same there then aggregate the results.</p>


问:
Using a sub query in column list
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days.  My result would return something like:

```<code>7Days  14Days  28Days
21     35      56
</code>```

I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?

```<code>select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())
</code>```

答:
It isn't the prettiest code in the world, but it does the trick. Try selecting from three subqueries, one for each range. </p>

```<code>select * from
(select COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -7, getdate())) as Seven
inner join (select  COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -14, getdate())) as fourteen on 1 = 1
inner join (select  COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -28, getdate())) as twentyeight on 1 = 1
</code>```

Title: Using a sub query in column list

Body:
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days.  My result would return something like:

7Days  14Days  28Days
21     35      56

I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?

select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())

Body:
It isn't the prettiest code in the world, but it does the trick. Try selecting from three subqueries, one for each range.

select * from
(select COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -7, getdate())) as Seven
inner join (select  COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -14, getdate())) as fourteen on 1 = 1
inner join (select  COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -28, getdate())) as twentyeight on 1 = 1


问:
Unknown character in HTML scraping
Here is the code I used to scrape the data

<?php
$html = file_get_contents('https://websitename.com/videoname.html');
preg_match_all( '|<source.*?src=[\'"](.*?)[\'"].*?>|i',$html, $matches );
echo $matches[ 1 ][ 0 ];
?>
```
<p>It takes data from the following HTML line</p>
<pre class="lang-html prettyprint-override"><code><video id="f-player"><source src="https://websitename.com/video/143.mp4?secl=1bYfG7HEZeTr2KOAMwp6QA&sect=1581943226"></video>
</div>
</code>```

The "secl=1bYfG7HEZeTr2KOAMwp6QA&sect=1581943226" frequently changes, that is why I want to use this script.

It is able to collect data but the out put is like this

https://websitename.com/video/143.mp4?secl=1bYfG7HEZeTr2KOAMwp6QA§=1581943226

The &sect was replaced by §!
What should I do ?

答:
You can use PHP DOMDocument

```<code><?php

/**
* get_links()
*
* @param string $url
* @return array
*/
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <source> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('source') as $link) {
        $links[] = array('url' => $link->getAttribute('src'));
    }

    //Return the links
    return $links;
}
?>
</code>```

try to use above function like

```<code>$links = get_links('https://websitename.com/videoname.html');
</code>```

Title: Unknown character in HTML scraping

Body:
Here is the code I used to scrape the data

<?php
$html = file_get_contents('https://websitename.com/videoname.html');
preg_match_all( '|<source.*?src=[\'"](.*?)[\'"].*?>|i',$html, $matches );
echo $matches[ 1 ][ 0 ];
?>

It takes data from the following HTML line

<video id="f-player"><source src="https://websitename.com/video/143.mp4?secl=1bYfG7HEZeTr2KOAMwp6QA&sect=1581943226"></video>

The "secl=1bYfG7HEZeTr2KOAMwp6QA&sect=1581943226" frequently changes, that is why I want to use this script.

It is able to collect data but the out put is like this

https://websitename.com/video/143.mp4?secl=1bYfG7HEZeTr2KOAMwp6QA§=1581943226

The &sect was replaced by §!
What should I do ?

Body:
You can use PHP DOMDocument

<?php

/**
* get_links()
*
* @param string $url
* @return array
*/
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <source> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('source') as $link) {
        $links[] = array('url' => $link->getAttribute('src'));
    }

    //Return the links
    return $links;
}
?>

try to use above function like

$links = get_links('https://websitename.com/videoname.html');


问:
accessing the key of a dictionary using only one element from its value
I have two dictionaries, one, a class to function dictionary:

```<code>{'A': ['__init__', 'message'],
 'Head': ['__init__', 'talk'],
 'Human': ['__init__', 'createHead']}
</code>```

another, a class to subclass dictionary:

```<code>{'Human': ['A', 'Head']}
</code>```

Here, classes 'A' and 'Head' are inside class 'Human'.

I derive this class from the first library using the functions,(assume i know all the functions in a particular class).

Is it possible to get Human' just with 'A'? (i.e., I just know one element in the value list of second dictionary)

答:
Well, you can traverse the dictionary, and return any keys that contain the value you're searching for using list comprehension:</p>

```<code>class_to_func = {'A': ['__init__', 'message'],
    'Head': ['__init__', 'talk'],
    'Human': ['__init__', 'createHead']}
class_to_subclass = {'Human': ['A', 'Head']}
matching_classes = [key for key,value in class_to_subclass.items() if 'A' in value]
print(matching_classes)
</code>```

Body:
I have two dictionaries, one, a class to function dictionary:

{'A': ['__init__', 'message'],
 'Head': ['__init__', 'talk'],
 'Human': ['__init__', 'createHead']}

another, a class to subclass dictionary:

{'Human': ['A', 'Head']}

Here, classes 'A' and 'Head' are inside class 'Human'.

I derive this class from the first library using the functions,(assume i know all the functions in a particular class).

Is it possible to get Human' just with 'A'? (i.e., I just know one element in the value list of second dictionary)

Body:
Well, you can traverse the dictionary, and return any keys that contain the value you're searching for using list comprehension:

class_to_func = {'A': ['__init__', 'message'],
    'Head': ['__init__', 'talk'],
    'Human': ['__init__', 'createHead']}
class_to_subclass = {'Human': ['A', 'Head']}
matching_classes = [key for key,value in class_to_subclass.items() if 'A' in value]
print(matching_classes)


问:
Xcode make files open in current window?
In Xcode 4, whenever I double click on a file, it opens in a new window. I'd rather it open in the existing editor pane instead. Is there an option or something that will let this happen?</p>

答: It seems like if i single click on a file then that opens it.</p>


答:
I fix your function like this :

```<code>function get_age($birthDate_old) {
    return date_diff(
        DateTime::createFromFormat('d/m/Y', $birthDate_old),
        new DateTime('today')
    )->y;
}
</code>```

In your case your date is malformated since DateTime constructor doesn't know if you pass a month or a day.

05/04/1946 is ok.

26/01/1958 is not ok because 26 represent month by default.

Title: Uncaught Exception: DateTime::__construct(): Failed to parse time string

Body:
I fix your function like this :

function get_age($birthDate_old) {
    return date_diff(
        DateTime::createFromFormat('d/m/Y', $birthDate_old),
        new DateTime('today')
    )->y;
}

In your case your date is malformated since DateTime constructor doesn't know if you pass a month or a day.

05/04/1946 is ok.

26/01/1958 is not ok because 26 represent month by default.


问:
Where is the "Sync Project With Gradle Files" option in Android Studio 3.5.3?
I'm new to Android Studio and I'm having trouble in finding the "Sync Project With Gradle Files"

option in Android Studio version 3.5.3. I'm currently developing applications with Flutter.

I did find out that in the previous version of Android Studio (I'm not sure which, sorry!), it seems that the "Sync Project With Gradle Files" option can be found by clicking
File > Sync Project With Gradle Files OR at the toolbar.

(Attached are images regarding previous "Sync Project With Gradle Files" locations)

File

toolbar

However, I could not find it in my Android Studio version 3.5.3's  File nor at the toolbar. There is no such option.

I am sorry if this question has already been answered else where or
  the question is a duplicated one. (This is also my first time posting
  a question in Stack Overflow) I would be very grateful if someone can
  help me with this...thank you in advance

答: If you right click on the build.gradle there's a Synchronize option nearer to the bottom of the popup. HTH


问:
Make custom validations in EXTJS as components
I have written custom validations like below

```<code>Ext.apply(Ext.form.field.VTypes, {
    valInt: function(v) {
        return /^(\d+(,\d+)*)?$/.test(v);
    },
    valIntText: 'Must be in the form #,#',
    valIntMask: /[\d\,]/i
});
</code>```

It works. But i want to make all such custom validation in a single file and then load it or auto load it. How do i do it?

I can do like below in app.js

```<code> Ext.onReady(function() {
  Ext.apply(Ext.form.field.VTypes, {
        valInt: function(v) {
            return /^(\d+(,\d+)*)?$/.test(v);
        },
        valIntText: 'Must be in the form #,#',
        valIntMask: /[\d\,]/i
    });
});
</code>```

But then the app.js file will become big after all validations.

答:
According to @CD..

1) I've found the overrides folder in my app

2) put this VTypes.js file in the root of overrides folder:

```<code>Ext.override(Ext.form.field.VTypes, {
    digitsOnly: function (value) {
        return this.digitsOnlyRe.test(value);
    },
    digitsOnlyRe: /\\d*$/,
    digitsOnlyText: 'Use digits only!'
});
</code>```

Now all works, thnx all

Body:
I have written custom validations like below

Ext.apply(Ext.form.field.VTypes, {
    valInt: function(v) {
        return /^(\d+(,\d+)*)?$/.test(v);
    },
    valIntText: 'Must be in the form #,#',
    valIntMask: /[\d\,]/i
});

It works. But i want to make all such custom validation in a single file and then load it or auto load it. How do i do it?

I can do like below in app.js

 Ext.onReady(function() {
  Ext.apply(Ext.form.field.VTypes, {
        valInt: function(v) {
            return /^(\d+(,\d+)*)?$/.test(v);
        },
        valIntText: 'Must be in the form #,#',
        valIntMask: /[\d\,]/i
    });
});

But then the app.js file will become big after all validations.

Body:
According to @CD..

1) I've found the overrides folder in my app

2) put this VTypes.js file in the root of overrides folder:

Ext.override(Ext.form.field.VTypes, {
    digitsOnly: function (value) {
        return this.digitsOnlyRe.test(value);
    },
    digitsOnlyRe: /\\d*$/,
    digitsOnlyText: 'Use digits only!'
});

Now all works, thnx all


问:
Unix shell - Find unique columns by comparing two files
I have two files where I want to compare the first column to find the unique ones using unix shell.

File 1:

```<code>yellow
green
red
white
</code>```

File 2:

```<code>yellow,not_started
red,in_progress
</code>```

I want the output to be

```<code>green
white
</code>```

答:
Easy to do with join:

```<code>$ join -t, -v1 <(sort file1.txt) <(sort file2.txt)
green
white
</code>```

-v1 tells it to print out records in the first file that don't match up to a record in the second file. The sorts are because join requires its input files to be sorted based on the (default first) join column.

Alternative using awk:

```<code>$ awk -F, 'NR == FNR { seen[$1] = 1; next } !($0 in seen)' file2.txt file1.txt
green
white
</code>```

Note the second file comes first in the arguments to awk.

Body:
I have two files where I want to compare the first column to find the unique ones using unix shell.

File 1:

yellow
green
red
white

File 2:

yellow,not_started
red,in_progress

I want the output to be

green
white

Body:
Easy to do with join:

$ join -t, -v1 <(sort file1.txt) <(sort file2.txt)
green
white

-v1 tells it to print out records in the first file that don't match up to a record in the second file. The sorts are because join requires its input files to be sorted based on the (default first) join column.

Alternative using awk:

$ awk -F, 'NR == FNR { seen[$1] = 1; next } !($0 in seen)' file2.txt file1.txt
green
white

Note the second file comes first in the arguments to awk.


问:
HOw to convert jquery to react js
I have jquery code how we can convert it to React js
I want to achieve onfocus and onblur on input to add and remove class on specific div.

Anyone have any idea how we can achieve this.

```<code>$("input#password").focus(function() {
  $("#overlay").addClass("newoverlay");
}).blur(function() {
  $("#overlay").removeClass("newoverlay");
});
</code>```

HTML

```<code><div id="overlay" class="">Focus/Blur</div>
<input type="txt" id="password"/>
</code>```

答:
```<code>import React from 'react';

const foo: React.FC = () => {
  const [isFocused, setFocus] = React.useState(false);

  const handleFocus = () => {
    setFocus(true);
  };

  const handleBlur = () => {
    setFocus(false);
  };

  return (
    <div
      className={`someClass ${isFocused && 'focus'}`}
      onFocus={handleFocus}
      onBlur={handleBlur}
    >
      hello
    </div>
  );
}

export default foo;
</code>```

here is the code what you looking for.

you can check react event in following link
https://reactjs.org/docs/events.html

and also using classnames or clsx is good idea.

Title: HOw to convert jquery to react js

Body:
I have jquery code how we can convert it to React js
I want to achieve onfocus and onblur on input to add and remove class on specific div.

Anyone have any idea how we can achieve this.

$("input#password").focus(function() {
  $("#overlay").addClass("newoverlay");
}).blur(function() {
  $("#overlay").removeClass("newoverlay");
});

HTML

Focus/Blur

<input type="txt" id="password"/>

Body:
import React from 'react';

const foo: React.FC = () => {
  const [isFocused, setFocus] = React.useState(false);

  const handleFocus = () => {
    setFocus(true);
  };

  const handleBlur = () => {
    setFocus(false);
  };

  return (
    <div
      className={`someClass ${isFocused && 'focus'}`}
      onFocus={handleFocus}
      onBlur={handleBlur}
    >
      hello
    </div>
  );
}

export default foo;

here is the code what you looking for.

you can check react event in following link
https://reactjs.org/docs/events.html

and also using classnames or clsx is good idea.