答:
The correct SQL is</p>
```<code>SELECT
      CASE WHEN SUM(d.months) > 12 THEN SUM(d.years) + FLOOR(SUM(d.months/12)) ELSE SUM(d.years) END
      AS years
    , CASE WHEN SUM(d.days) > 30 THEN FLOOR(MOD((SUM(d.months) + FLOOR(SUM(d.days/30.4375))),12)) ELSE FLOOR(MOD(SUM(d.months), 12)) END
      AS months
    , CASE WHEN SUM(d.days) > 30 THEN FLOOR(MOD(SUM(d.days), 30)) ELSE FLOOR(MOD(SUM(d.days), 30)) END
      AS days

FROM (
      SELECT
              TIMESTAMPDIFF(YEAR , from_date, to_date )
              AS years
            , TIMESTAMPDIFF(MONTH, from_date + INTERVAL TIMESTAMPDIFF(YEAR , from_date, to_date) YEAR  , to_date )
              AS months
            , TIMESTAMPDIFF(DAY  , from_date + INTERVAL TIMESTAMPDIFF(MONTH, from_date, to_date) MONTH , to_date )
              AS days
        FROM (
            SELECT
                 from_date
                , COALESCE(to_date,CURRENT_DATE) to_date
            FROM experiences WHERE `user_id` ='1'
          ) d2
    ) d
</code>```

Title: How to sum durations in units of Year, Month and Day in MySQL?

Body:
I have a table duration:

-------------------------------
| id |    from    |     to    |
|----|------------|-----------|
|  1 | 2011-02-22 |    NULL   |
|  2 | 1999-08-03 |2005-03-30 |
|  3 | 1982-09-03 |1988-01-30 |
|  4 | 1965-12-01 |1980-05-02 |
-------------------------------

I want to calculate time differences (to-from) in a row and add them up. My query is:

SELECT CONCAT(SUM(TIMESTAMPDIFF( YEAR, from, IF(to IS NULL,'2017-10-
18', to))),' Years ',
SUM(TIMESTAMPDIFF( MONTH, from, IF(to IS NULL,'2017-10-18', to))
% 12),' Months ',
SUM(FLOOR( TIMESTAMPDIFF( DAY, from, IF(to IS NULL,'2017-10-18',
to)) % 30.4375 )),' Days ') AS Duration
FROM duration;

I am getting:

------------------------------
|         Duration           |
|----------------------------|
| 30 Years 23 Months 78 Days |
------------------------------

But I want to get:

-----------------------------
|         Duration          |
|---------------------------|
| 32 Years 1 Months 18 Days |
-----------------------------

Please help!

Body:
The correct SQL is

SELECT
      CASE WHEN SUM(d.months) > 12 THEN SUM(d.years) + FLOOR(SUM(d.months/12)) ELSE SUM(d.years) END
      AS years
    , CASE WHEN SUM(d.days) > 30 THEN FLOOR(MOD((SUM(d.months) + FLOOR(SUM(d.days/30.4375))),12)) ELSE FLOOR(MOD(SUM(d.months), 12)) END
      AS months
    , CASE WHEN SUM(d.days) > 30 THEN FLOOR(MOD(SUM(d.days), 30)) ELSE FLOOR(MOD(SUM(d.days), 30)) END
      AS days

FROM (
      SELECT
              TIMESTAMPDIFF(YEAR , from_date, to_date )
              AS years
            , TIMESTAMPDIFF(MONTH, from_date + INTERVAL TIMESTAMPDIFF(YEAR , from_date, to_date) YEAR  , to_date )
              AS months
            , TIMESTAMPDIFF(DAY  , from_date + INTERVAL TIMESTAMPDIFF(MONTH, from_date, to_date) MONTH , to_date )
              AS days
        FROM (
            SELECT
                 from_date
                , COALESCE(to_date,CURRENT_DATE) to_date
            FROM experiences WHERE `user_id` ='1'
          ) d2
    ) d


来源: stackexchange

问:
Flutter audioplayers apk release does not work
I am using Audioplayers Flutter Library for playing assets sound from assets/sounds/my_sound.mp3. I'm using AudioCache like this :

```<code>AudioCache.play(mysound)
</code>```

I am calling this inside a onpressed method from a Raised Button.
It's working find when I am playing my sound in the application from my emulator or my device when I was running

```<code>flutter run
</code>```

Working fine.

Now, I generate apk with

```<code>flutter build apk
</code>```

I'm getting the app_release.apk and download it inside my device.
Now, I am trying to launch the application. The app load assets images and other contents. But when I'm trying to play a sound, nothing happened...

I am trying to import apk without Google play store for now because I want test my app in production environments.

What's happened? Can I see a log inside my device for debugging the app?

答:
if you playing audio from assets using AudioCache,
try to set your AudioPlayer on mode: PlayerMode.LOW_LATENCY

```<code>AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Audioplayers Flutter Library for playing assets sound from assets/sounds/my_sound.mp3. I'm using AudioCache like this :

AudioCache.play(mysound)

I am calling this inside a onpressed method from a Raised Button.
It's working find when I am playing my sound in the application from my emulator or my device when I was running

flutter run

Working fine.

Now, I generate apk with

flutter build apk

I'm getting the app_release.apk and download it inside my device.
Now, I am trying to launch the application. The app load assets images and other contents. But when I'm trying to play a sound, nothing happened...

I am trying to import apk without Google play store for now because I want test my app in production environments.

What's happened? Can I see a log inside my device for debugging the app?

Body:
if you playing audio from assets using AudioCache,
try to set your AudioPlayer on mode: PlayerMode.LOW_LATENCY

AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);


问:
iPhone project - collect files into one place
Sorry if this has been answered before but all my searches do not return anything related to this.

Is there a way to collect all the files referenced in a project and save them in the procject folder automatically? Rather that having links to places where you may accidentally delete the files.

Thanks,

Eds

答: Xcode doesn't have a particular feature to support this, but when you add items to your Xcode project it does give you the option to copy those items to the project directory. Otherwise you need to manually copy the items to a common location.</p>

ContentLicense: CC BY-SA 3.0


问:
Accessing Facebook Messenger SendApi in python
Recently , exploring Facebook Messenger's Send Api and I got confused in accessing SendApi through Python requests.</p>

答:
So, the format which works for me is -

```<code>headers = {
    'Content-Type': 'application/json',
}
request_body = json.dumps({
        "recipient": {
        "id": sender_psid
        },
        "message": message
    })
params = {'access_token':PAGE_ACCESS_TOKEN}
url = "https://graph.facebook.com/v2.6/me/messages"
r = requests.post(url = url, data = request_body, headers = headers, params=params)
</code>```

or you can add access_token in request_body too. Declaring headers is important here

Body:
So, the format which works for me is -

headers = {
    'Content-Type': 'application/json',
}
request_body = json.dumps({
        "recipient": {
        "id": sender_psid
        },
        "message": message
    })
params = {'access_token':PAGE_ACCESS_TOKEN}
url = "https://graph.facebook.com/v2.6/me/messages"
r = requests.post(url = url, data = request_body, headers = headers, params=params)

or you can add access_token in request_body too. Declaring headers is important here


问:
Git Remote Tracking Branch and Upstream Branch are different
I am not sure how this happened, but if you look at these outputs, emote tracking branch and upstream branch is different. Can somebody explain how could this happen. I know that my pushes are working. What happens when I pull ?

```<code>PS C:\DigitalOffers\RegPrice> git branch
* dev
  master

PS C:\DigitalOffers\RegPrice> git branch -vv
* dev    b62f88b [origin/master: ahead 52] Price Zone resolution change.
  master 78d5fb6 [origin/master: behind 37] Merge branch 'master' of https://github.com/xxxxxxxxx

PS C:\DigitalOffers\RegPrice> git log
commit b62f88b137fa067f7d0f75ec35fb8b63fc885f50 (HEAD -> dev, origin/dev)

PS C:\DigitalOffers\RegPrice> cat .git/config
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/XXXXXX
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "origin/dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[http "https://github.com"]
    sslVerify = false
[gui]
    wmstate = zoomed
    geometry = 584x210+234+234 469 196

PS C:\DigitalOffers\RegPrice> git push
fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:master

To push to the branch of the same name on the remote, use

    git push origin HEAD

To choose either option permanently, see push.default in 'git help config'.
</code>```

One more point I want add is- these refs were done by EGit in eclipse.

答:
Fixed the configuration. Here is the new configuration and new push</p>

```<code>PS C:\DigitalOffers\RegPrice> git branch -vv
* dev    946f432 [origin/dev: ahead 1] Added app description in readme.md
master 78d5fb6 [origin/master: behind 37] Merge branch 'master' of
https://github.com/XXXXXX

PS C:\DigitalOffers\RegPrice> cat .git/config
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/XXXXXXX
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "dev"]
    remote = origin
    merge = refs/heads/dev
    rebase = false
[branch "origin/dev"]
    remote = origin
    merge = refs/heads/dev
    rebase = false
[http "https://github.com"]
    sslVerify = false
[gui]
    wmstate = zoomed
    geometry = 584x210+234+234 469 196

PS C:\DigitalOffers\RegPrice> git push
Username for 'https://github.com':
Password for 'https://@github.com':
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 349 bytes | 43.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To https://github.com/XXXXX
    b62f88b..946f432  dev -> dev
</code>```

Body:
I am not sure how this happened, but if you look at these outputs, emote tracking branch and upstream branch is different. Can somebody explain how could this happen. I know that my pushes are working. What happens when I pull ?

PS C:\DigitalOffers\RegPrice> git branch
* dev
  master

PS C:\DigitalOffers\RegPrice> git branch -vv
* dev    b62f88b [origin/master: ahead 52] Price Zone resolution change.
  master 78d5fb6 [origin/master: behind 37] Merge branch 'master' of https://github.com/xxxxxxxxx

PS C:\DigitalOffers\RegPrice> git log
commit b62f88b137fa067f7d0f75ec35fb8b63fc885f50 (HEAD -> dev, origin/dev)

PS C:\DigitalOffers\RegPrice> cat .git/config
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/XXXXXX
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "origin/dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[http "https://github.com"]
    sslVerify = false
[gui]
    wmstate = zoomed
    geometry = 584x210+234+234 469 196

PS C:\DigitalOffers\RegPrice> git push
fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:master

To push to the branch of the same name on the remote, use

    git push origin HEAD

To choose either option permanently, see push.default in 'git help config'.

One more point I want add is- these refs were done by EGit in eclipse.

Body:
Fixed the configuration. Here is the new configuration and new push

PS C:\DigitalOffers\RegPrice> git branch -vv
* dev    946f432 [origin/dev: ahead 1] Added app description in readme.md
master 78d5fb6 [origin/master: behind 37] Merge branch 'master' of
https://github.com/XXXXXX

PS C:\DigitalOffers\RegPrice> cat .git/config
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/XXXXXXX
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "dev"]
    remote = origin
    merge = refs/heads/dev
    rebase = false
[branch "origin/dev"]
    remote = origin
    merge = refs/heads/dev
    rebase = false
[http "https://github.com"]
    sslVerify = false
[gui]
    wmstate = zoomed
    geometry = 584x210+234+234 469 196

PS C:\DigitalOffers\RegPrice> git push
Username for 'https://github.com':
Password for 'https://@github.com':
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 349 bytes | 43.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To https://github.com/XXXXX
    b62f88b..946f432  dev -> dev


问:
error in reading html content from asp page
I am creating an HTML template as theme in ASP.NET. I want to read the content of the template on button click and store all the content in another template. I am reading the content as:

```<code> xmlDoc.Load(theme);
            XmlNodeList list = xmlDoc.SelectNodes("html/body/form/div/table/tbody/tr/td/textarea");
            headtext = list.Item(0).InnerText;
            totext = list.Item(1).InnerText;
            bodytext = list.Item(2).InnerText;
            footertext = list.Item(3).InnerText;
            string new_theme = edittheme(headtext, totext, bodytext, footertext);
            return new_theme ;
</code>```

but as my asp page contains:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="theme3.aspx.cs" Inherits="MailCham.theme3" %>
</code>```

It is giving an error while reading the content. How can i read the content of HTML page?

答: Use the HtmlAgilityPack library: here</p>

Body:
I am creating an HTML template as theme in ASP.NET. I want to read the content of the template on button click and store all the content in another template. I am reading the content as:

 xmlDoc.Load(theme);
            XmlNodeList list = xmlDoc.SelectNodes("html/body/form/div/table/tbody/tr/td/textarea");
            headtext = list.Item(0).InnerText;
            totext = list.Item(1).InnerText;
            bodytext = list.Item(2).InnerText;
            footertext = list.Item(3).InnerText;
            string new_theme = edittheme(headtext, totext, bodytext, footertext);
            return new_theme ;

but as my asp page contains:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="theme3.aspx.cs" Inherits="MailCham.theme3" %>

It is giving an error while reading the content. How can i read the content of HTML page?

Body: Use the HtmlAgilityPack library: here


问:
Get data fro firestore with React Native
I need to get data from Firestore but i can't, i need to know if my code is ok, because it doesn't work or something else is missing.

This is my firestore services

fireservices.js

```<code>    import React from 'react';
    import * as firebase from 'firebase';
    import { firebaseConfig } from '../firebase_const';
    import 'firebase/firestore';

        firebase.initializeApp(firebaseConfig)

class FireServices{

    static async getLocalization(idOfert) {
        firebase.firestore.collection('users').doc(idOfert)
    }

}

export default FireServices;
</code>```

And this is my class, this class use the method to get data

SecondClass.js

```<code>import React from 'react';
import FireServices from '../services/fireservices';

export default class SecondClass extends React.Component {

componentDidMount = async () => {

        this.onStart()
}

onStart = () => {
            FireServices.getLocalization('email@hotmail.com').get().then(doc => {
            console.log(doc)
        })
    }

render(){
 return (
  <View>
  </View>
 )
}
</code>```

答:
You are not returning from getLocalization.

It should be

```<code>static async getLocalization(idOfert) {
    return firebase.firestore.collection('users').doc(idOfert)
}
</code>```

Body:
I need to get data from Firestore but i can't, i need to know if my code is ok, because it doesn't work or something else is missing.

This is my firestore services

fireservices.js

    import React from 'react';
    import * as firebase from 'firebase';
    import { firebaseConfig } from '../firebase_const';
    import 'firebase/firestore';

        firebase.initializeApp(firebaseConfig)

class FireServices{

    static async getLocalization(idOfert) {
        firebase.firestore.collection('users').doc(idOfert)
    }

}

export default FireServices;

And this is my class, this class use the method to get data

SecondClass.js

import React from 'react';
import FireServices from '../services/fireservices';

export default class SecondClass extends React.Component {

componentDidMount = async () => {

        this.onStart()
}

onStart = () => {
            FireServices.getLocalization('email@hotmail.com').get().then(doc => {
            console.log(doc)
        })
    }

render(){
 return (
  <View>
  </View>
 )
}

Body:
You are not returning from getLocalization.

It should be

static async getLocalization(idOfert) {
    return firebase.firestore.collection('users').doc(idOfert)
}


问:
How to make a strings array by using dynamic memory allocation in C?
I tried to do this:

```<code>char** arr_from_num(int num)
{
    char** strings = (char**)malloc(num*sizeof(char*));
    if (strings == NULL)
        return 0;
    for (int i = 1; i <= num; i++) {
            strings[i-1] = (char*)malloc(9 * sizeof(char));
            strings[i-1] = "FizzBuzz";
    }
    return strings;
}
</code>```

But the function has a failure in doing this line:  char** strings = (char**)malloc(num*sizeof(char*));

How can I do it in other way?

答:
For starters the function produces numerous memory leaks. At first a memory is allocated and its address is assigned to a pointer

```<code>strings[i-1] = (char*)malloc(9 * sizeof(char));
</code>```

and then the pointer is reassigned by the address of a string literal

```<code>strings[i-1] = "FizzBuzz";
</code>```

The function can look for example the following way

```<code>char ** arr_from_num( size_t n )
{
    const char data[] = "FizzBuzz";

    char **strings = malloc( n * sizeof( char* ) );

    if ( strings != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            strings[i] = malloc( sizeof( data ) );
            if ( strings[i] != NULL ) strcpy( strings[i], data );
        }
    }

    return strings;
}
</code>```

Alternatively the function can be defined the following way

```<code>char ** arr_from_num( size_t n, size_t m, const char *dummy )
{
    char **strings = calloc( n, sizeof( char* ) );

    if ( strings != NULL && m != 0 )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            strings[i] = calloc( m, sizeof( char ) );

            if ( strings[i] != NULL && dummy != NULL )
            {
                strncpy( strings[i], dummy, m - 1 );
            }
        }
    }

    return strings;
}
</code>```

Here is a demonstrative program.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char ** arr_from_num( size_t n, size_t m, const char *dummy )
{
    char **strings = calloc( n, sizeof( char* ) );

    if ( strings != NULL && m != 0 )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            strings[i] = calloc( m, sizeof( char ) );

            if ( strings[i] != NULL && dummy != NULL )
            {
                strncpy( strings[i], dummy, m - 1 );
            }
        }
    }

    return strings;
}

int main(void)
{
    size_t n = 10;

    char **strings = arr_from_num( n, n, "FizzBuzz" );

    if ( strings != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            printf( "%zu: ", i );
            if ( strings[i] == NULL )
            {
                printf( "%p\n", ( void * )strings[i] );
            }
            else
            {
                puts( strings[i] );
            }
        }
    }

    if ( strings != NULL )
    {
        for ( size_t i = 0; i < n; i++ ) free( strings[i] );
    }

    free( strings );

    return 0;
}
</code>```

The program output is

```<code>0: FizzBuzz
1: FizzBuzz
2: FizzBuzz
3: FizzBuzz
4: FizzBuzz
5: FizzBuzz
6: FizzBuzz
7: FizzBuzz
8: FizzBuzz
9: FizzBuzz
</code>```

Body:
I tried to do this:

char** arr_from_num(int num)
{
    char** strings = (char**)malloc(num*sizeof(char*));
    if (strings == NULL)
        return 0;
    for (int i = 1; i <= num; i++) {
            strings[i-1] = (char*)malloc(9 * sizeof(char));
            strings[i-1] = "FizzBuzz";
    }
    return strings;
}

But the function has a failure in doing this line:  char** strings = (char**)malloc(num*sizeof(char*));

How can I do it in other way?

Body:
For starters the function produces numerous memory leaks. At first a memory is allocated and its address is assigned to a pointer

strings[i-1] = (char*)malloc(9 * sizeof(char));

and then the pointer is reassigned by the address of a string literal

strings[i-1] = "FizzBuzz";

The function can look for example the following way

char ** arr_from_num( size_t n )
{
    const char data[] = "FizzBuzz";

    char **strings = malloc( n * sizeof( char* ) );

    if ( strings != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            strings[i] = malloc( sizeof( data ) );
            if ( strings[i] != NULL ) strcpy( strings[i], data );
        }
    }

    return strings;
}

Alternatively the function can be defined the following way

char ** arr_from_num( size_t n, size_t m, const char *dummy )
{
    char **strings = calloc( n, sizeof( char* ) );

    if ( strings != NULL && m != 0 )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            strings[i] = calloc( m, sizeof( char ) );

            if ( strings[i] != NULL && dummy != NULL )
            {
                strncpy( strings[i], dummy, m - 1 );
            }
        }
    }

    return strings;
}

Here is a demonstrative program.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char ** arr_from_num( size_t n, size_t m, const char *dummy )
{
    char **strings = calloc( n, sizeof( char* ) );

    if ( strings != NULL && m != 0 )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            strings[i] = calloc( m, sizeof( char ) );

            if ( strings[i] != NULL && dummy != NULL )
            {
                strncpy( strings[i], dummy, m - 1 );
            }
        }
    }

    return strings;
}

int main(void)
{
    size_t n = 10;

    char **strings = arr_from_num( n, n, "FizzBuzz" );

    if ( strings != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            printf( "%zu: ", i );
            if ( strings[i] == NULL )
            {
                printf( "%p\n", ( void * )strings[i] );
            }
            else
            {
                puts( strings[i] );
            }
        }
    }

    if ( strings != NULL )
    {
        for ( size_t i = 0; i < n; i++ ) free( strings[i] );
    }

    free( strings );

    return 0;
}

The program output is

0: FizzBuzz
1: FizzBuzz
2: FizzBuzz
3: FizzBuzz
4: FizzBuzz
5: FizzBuzz
6: FizzBuzz
7: FizzBuzz
8: FizzBuzz
9: FizzBuzz


问:
How to append a string to a list or array in a for loop in scala?
```<code>  var RetainKeyList: mutable.Seq[String] = new scala.collection.mutable.ListBuffer[String]()

  for(element<-ts_rdd)
    {
      var elem1  = element._1
      var kpssSignificance: Double = 0.05
      var dOpt: Option[Int] = (0 to 2).find
          {
            diff =>
            var testTs = differencesOfOrderD(element._2, diff)
            var (stat, criticalValues) = kpsstest(testTs, "c")
            stat < criticalValues(kpssSignificance)
          }
      var d = dOpt match
          {
            case Some(v) => v
            case None => 300000
           }
      if(d.equals(300000))
           {
             println("Bad Key: " + elem1)
             RetainKeyList += elem1
           }

</code>```

Hi all,

I created a empty mutable list buffer var RetainKeyList: mutable.Seq[String] = new scala.collection.mutable.ListBuffer[String]() and I am trying to add a string elem1 to it in a for loop.

When I try to compile the code it hangs with no error message but if I remove the code RetainKeyList += elem1 I am able to print all of the elem1 string properly.

What am I doing wrong here? Is there a cleaner way to collect all the string elem1 generated in the for loop?

答:
Long story short, your code is running on a distributed environment, so the local collection is not modified. Every week someone asks this question, please if you do not understand what are the implications of distributed computing do not use a distributed framework like Spark.

Also, you are abusing of mutability in all parts. And mutability and a distributed environment don't play nicely.

Anyway, here is a better way to solve your problem.

```<code>val retainKeysRdd = ts_rdd.map {
  case (elem1, elem2) =>
    val kpssSignificance = 0.05d
    val dOpt = (0 to 2).find { diff =>
      val testTs = differencesOfOrderD(elem2, diff)
      val (stat, criticalValues) = kpsstest(testTs, "c")
      stat < criticalValues(kpssSignificance)
    }
    (elem1 -> dOpt)
} collect {
  case (key, None) => key
}
</code>```

This returns an RDD with the retain keys. If you are really sure you need this as a local collection and that they won't blow up your memory, you can do this:

```<code>val retainKeysList = retainKeysRdd.collect().toList
</code>```

Body:
  var RetainKeyList: mutable.Seq[String] = new scala.collection.mutable.ListBuffer[String]()

  for(element<-ts_rdd)
    {
      var elem1  = element._1
      var kpssSignificance: Double = 0.05
      var dOpt: Option[Int] = (0 to 2).find
          {
            diff =>
            var testTs = differencesOfOrderD(element._2, diff)
            var (stat, criticalValues) = kpsstest(testTs, "c")
            stat < criticalValues(kpssSignificance)
          }
      var d = dOpt match
          {
            case Some(v) => v
            case None => 300000
           }
      if(d.equals(300000))
           {
             println("Bad Key: " + elem1)
             RetainKeyList += elem1
           }

Hi all,

I created a empty mutable list buffer var RetainKeyList: mutable.Seq[String] = new scala.collection.mutable.ListBuffer[String]() and I am trying to add a string elem1 to it in a for loop.

When I try to compile the code it hangs with no error message but if I remove the code RetainKeyList += elem1 I am able to print all of the elem1 string properly.

What am I doing wrong here? Is there a cleaner way to collect all the string elem1 generated in the for loop?

Body:
Long story short, your code is running on a distributed environment, so the local collection is not modified. Every week someone asks this question, please if you do not understand what are the implications of distributed computing do not use a distributed framework like Spark.

Also, you are abusing of mutability in all parts. And mutability and a distributed environment don't play nicely.

Anyway, here is a better way to solve your problem.

val retainKeysRdd = ts_rdd.map {
  case (elem1, elem2) =>
    val kpssSignificance = 0.05d
    val dOpt = (0 to 2).find { diff =>
      val testTs = differencesOfOrderD(elem2, diff)
      val (stat, criticalValues) = kpsstest(testTs, "c")
      stat < criticalValues(kpssSignificance)
    }
    (elem1 -> dOpt)
} collect {
  case (key, None) => key
}

This returns an RDD with the retain keys. If you are really sure you need this as a local collection and that they won't blow up your memory, you can do this:

val retainKeysList = retainKeysRdd.collect().toList


问:
React state variable updates automatically without calling setState
I am facing the following issue and not able to figure it out.

I have two variables inside the state called userDetails & userDetailsCopy. In componentDidMount I am making an API call and saving the data in both userDetails & userDetailsCopy.

I am maintaining another copy called userDetailsCopy for comparison purposes.

I am updating only userDetails inside setState but even userDetailsCopy is also getting updated instead of have old API data.

Below is the code :

```<code>constructor(){
    super()
    this.state={
        userDetails:{},
        userDetailsCopy: {}
    }
}

componentDidMount(){
     // API will return the following data
       apiUserDetails : [
            {
                 'name':'Tom',
                 'age' : '28'
            },
            {
                 'name':'Jerry',
                 'age' : '20'

            }
        ]

       resp.data is nothing but apiUserDetails
    /////

     apiCall()
     .then((reps) => {
         this.setState({
             userDetails: resp.data,
             userDetailsCopy: resp.data
         })
     })
}

updateValue = (text,i) => {
     let userDetail = this.state.userDetails
     userDetail[i].name = text
     this.setState({
         userDetails: userDetail
     })
}

submit = () => {
     console.log(this.state.userDetials) // returns updated values
     console.log(this.state.userDetailsCopy) // also return updated values instead of returning old API data
}

Need a quick solution on this.
</code>```

答:
The problem with this is that you think you are making a copy of the object in state by doing this

```<code>     let userDetail = this.state.userDetails
     userDetail.name = text
</code>```

But, in Javascript, objects are not copied like this, they are passed by referrence. So userDetail at that point contains the referrence to the userDetails in your state, and when you mutate the userDetail it goes and mutates the one in the state.

ref: https://we-are.bookmyshow.com/understanding-deep-and-shallow-copy-in-javascript-13438bad941c

To properly clone the object from the state to your local variable, you need to instead do this:

```<code>let userDetail = {...this.state.userDetails}

OR

let userDetail = Object.assign({}, this.state.userDetails)
</code>```

Always remember, Objects are passed by referrence not value.

EDIT: I didn't read the question properly, but the above answer is still valid. The reason userDetailCopy is being updated too is because resp.data is passed by referrence to both of them, and editing any one of them will edit the other.

Body:
I am facing the following issue and not able to figure it out.

I have two variables inside the state called userDetails & userDetailsCopy. In componentDidMount I am making an API call and saving the data in both userDetails & userDetailsCopy.

I am maintaining another copy called userDetailsCopy for comparison purposes.

I am updating only userDetails inside setState but even userDetailsCopy is also getting updated instead of have old API data.

Below is the code :

constructor(){
    super()
    this.state={
        userDetails:{},
        userDetailsCopy: {}
    }
}

componentDidMount(){
     // API will return the following data
       apiUserDetails : [
            {
                 'name':'Tom',
                 'age' : '28'
            },
            {
                 'name':'Jerry',
                 'age' : '20'

            }
        ]

       resp.data is nothing but apiUserDetails
    /////

     apiCall()
     .then((reps) => {
         this.setState({
             userDetails: resp.data,
             userDetailsCopy: resp.data
         })
     })
}

updateValue = (text,i) => {
     let userDetail = this.state.userDetails
     userDetail[i].name = text
     this.setState({
         userDetails: userDetail
     })
}

submit = () => {
     console.log(this.state.userDetials) // returns updated values
     console.log(this.state.userDetailsCopy) // also return updated values instead of returning old API data
}

Need a quick solution on this.

Body:
The problem with this is that you think you are making a copy of the object in state by doing this

     let userDetail = this.state.userDetails
     userDetail.name = text

But, in Javascript, objects are not copied like this, they are passed by referrence. So userDetail at that point contains the referrence to the userDetails in your state, and when you mutate the userDetail it goes and mutates the one in the state.

ref: https://we-are.bookmyshow.com/understanding-deep-and-shallow-copy-in-javascript-13438bad941c

To properly clone the object from the state to your local variable, you need to instead do this:

let userDetail = {...this.state.userDetails}

OR

let userDetail = Object.assign({}, this.state.userDetails)

Always remember, Objects are passed by referrence not value.

EDIT: I didn't read the question properly, but the above answer is still valid. The reason userDetailCopy is being updated too is because resp.data is passed by referrence to both of them, and editing any one of them will edit the other.


问:
Using a regular expression to match filenames from a dictionary in python
I have a dictionary of filenames:

```<code>dic = {
    'this_file_name':'*this_file_name*.csv',
    'another': '*another*.csv'
    }
</code>```

I have a path:

file_path = glob.glob('path/to/files/*')

I'm trying to implement some logic that looks in the folder and sees if any files match the values in the dictionary.

```<code>for files in file_path:
    if re.match(dic.values(), files):
        # do stuff with the files
</code>```

I'm not sure how to implement this though.

答:
Your dictionary values are not valid regular expressions -- they are globs. Given that, you can just use glob.glob to match files (method1). Alternatively, you can use glob.glob to get a list of files in the directory and fnmatch to test each glob in your dictionary (method2). Finally, you can modify the values in dic to actually be regular expressions (method3).

```<code>search_dir = '.'

import glob

d1 = {
    'this_file_name': '*this_file_name*.csv',
    'another': '*another*.csv'
}

def method1():
    for k, v in d1.items():
        matches = glob.glob(search_dir + '/' + v)
        if matches:
            print(k, matches)

import fnmatch

def method2():
    names = glob.glob(search_dir + '/*')
    for k, v in d1.items():
        matches = fnmatch.filter(names, v)
        if matches:
            print(k, matches)

import re

d2 = {
    'this_file_name': 'this_file_name.*\.csv$',
    'another': 'another.*\.csv$'
}

def method3():
    names = glob.glob(search_dir + '/*')
    for k, v in d2.items():
        matches = [name for name in names if re.search(v, name)]
        if matches:
            print(k, matches)

if __name__ == '__main__':
    method1()
    method2()
    method3()
</code>```

Body:
I have a dictionary of filenames:

dic = {
    'this_file_name':'*this_file_name*.csv',
    'another': '*another*.csv'
    }

I have a path:

file_path = glob.glob('path/to/files/*')

I'm trying to implement some logic that looks in the folder and sees if any files match the values in the dictionary.

for files in file_path:
    if re.match(dic.values(), files):
        # do stuff with the files

I'm not sure how to implement this though.

Body:
Your dictionary values are not valid regular expressions -- they are globs. Given that, you can just use glob.glob to match files (method1). Alternatively, you can use glob.glob to get a list of files in the directory and fnmatch to test each glob in your dictionary (method2). Finally, you can modify the values in dic to actually be regular expressions (method3).

search_dir = '.'

import glob

d1 = {
    'this_file_name': '*this_file_name*.csv',
    'another': '*another*.csv'
}

def method1():
    for k, v in d1.items():
        matches = glob.glob(search_dir + '/' + v)
        if matches:
            print(k, matches)

import fnmatch

def method2():
    names = glob.glob(search_dir + '/*')
    for k, v in d1.items():
        matches = fnmatch.filter(names, v)
        if matches:
            print(k, matches)

import re

d2 = {
    'this_file_name': 'this_file_name.*\.csv$',
    'another': 'another.*\.csv$'
}

def method3():
    names = glob.glob(search_dir + '/*')
    for k, v in d2.items():
        matches = [name for name in names if re.search(v, name)]
        if matches:
            print(k, matches)

if __name__ == '__main__':
    method1()
    method2()
    method3()


问:
Binding dropdown list in a gridview edit item template
i can bind the dropdownlist in the edit item template. The drop down list is having null values.

```<code>protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)
  {
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
  }
}
</code>```

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

答:
I had problems with find control, in the end I used a little bit of recursion to find the control:

```<code>private Control FindControlRecursive(Control root, string id)
{
     if (root.ID == id)
    {
         return root;
    }

    foreach (Control c in root.Controls)
    {
         Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }

     return null;
}
</code>```

Then to find your control make this call:

```<code>drpBuildServers = (DropDownList) FindControlRecursive(e.Row.Cells[0], "ddlBuildServers");
</code>```

OwnerDisplayName: Renju

LastEditorDisplayName: ScarletGarden

ContentLicense: CC BY-SA 2.5

Body:
i can bind the dropdownlist in the edit item template. The drop down list is having null values.

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)
  {
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
  }
}

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

Body:
I had problems with find control, in the end I used a little bit of recursion to find the control:

private Control FindControlRecursive(Control root, string id)
{
     if (root.ID == id)
    {
         return root;
    }

    foreach (Control c in root.Controls)
    {
         Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }

     return null;
}

Then to find your control make this call:

drpBuildServers = (DropDownList) FindControlRecursive(e.Row.Cells[0], "ddlBuildServers");

OwnerDisplayName: ilivewithian


问:
Running npm command within Visual Studio Code
Is there anyway of executing the npm command within Visual Studio Code (using f1 into >) on Windows(10) to install packages to my folder I'm working in?

I have npm installed and I keep having to install npm packages from cmd

答:
You have to do the following 3 steps to fix your issues:

1.Download Node.js from here.

Install it and then add the path  C:\Program Files\nodejs to your System variables.

Then restart your visual studio code editor.

Happy code


问:
How to Commit/Rollback stored procedure based on return value in Snowflake?
I have a javascript stored procedure that return boolean. I want to be able to call this stored procedure inside a transaction and test the return value before committing the transaction.

BEGIN;
SET result = CALL my_stored_proc();

IF $result = true
COMMIT;
ELSE
ROLLBACK;```
</div>
</div>
</p>

<p>The stored procedure will return false if there is an exception or if there is some missing values based on business logic.</p>

<p>How do I achieve this in Snowflake?</p>

<hr>

<p>EDIT:
I tried the following and it did not work. The transaction remains open and the statements executed inside the stored proc are not rolled back until an explicit ROLLBACK statement is issued. </p>

```USE COMMON;

CREATE TABLE LOG
(
LOG_ID INT IDENTITY(1, 1) NOT NULL CONSTRAINT PK_LOG_ID PRIMARY KEY,
LOG_LEVEL VARCHAR (50) NOT NULL,
LOGGER VARCHAR (500) NOT NULL,
MESSAGE VARCHAR NOT NULL,
EXCEPTION VARCHAR NULL,
APPLICATION_NAME VARCHAR(500) NOT NULL,
LOGGED_ON DATETIME DEFAULT TO_TIMESTAMP_NTZ(CURRENT_TIMESTAMP()) NOT NULL,
LOGGED_BY VARCHAR(200) DEFAULT CURRENT_USER() NOT NULL
);

CREATE OR REPLACE PROCEDURE TEST_TRANSACTION()
RETURNS VARCHAR
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This is a test transaction.', '', 'DATA LOADER');
`});
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This message should not be in the logs.', '', 'DATA LOADER');
`});

throw 'Test error'
$$
;
-- Run the next 3 lines as a batch
BEGIN;
CALL COMMON.TEST_TRANSACTION(); -- This Fails
COMMIT; -- Commit is NOT executed

SELECT * FROM COMMON.LOG WHERE LOGGER = 'TEST_TRANSACTION'; -- The insert is successful & the transaction is still OPEN
```

How do I rollback the statements executed inside the stored procedure?

答:
So it turns out that you CAN issue transaction control commands (BEGIN, COMMIT, ROLLBACK) inside a stored procedure. I can being the transaction, check the return value inside the stored procedure and decide to COMMIT or ROLLBACK.

Someone should update the snowflake documentation.

```<code>CREATE OR REPLACE PROCEDURE TEST_TRANSACTION(result BOOLEAN)
RETURNS BOOLEAN NOT NULL
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
snowflake.execute({sqlText:`BEGIN;`});

snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This is a test transaction.', '', 'DATA LOADER');
`});
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This message should not be in the logs.', '', 'DATA LOADER');
`});

if ( RESULT ) { snowflake.execute( {sqlText: "COMMIT" }) }
    else {
        snowflake.execute( {sqlText: "ROLLBACK" }) };

return true;
$$
;
</code>```

Body:
I have a javascript stored procedure that return boolean. I want to be able to call this stored procedure inside a transaction and test the return value before committing the transaction.

BEGIN;
SET result = CALL my_stored_proc();

IF $result = true
COMMIT;
ELSE
ROLLBACK;

The stored procedure will return false if there is an exception or if there is some missing values based on business logic.

How do I achieve this in Snowflake?

EDIT:
I tried the following and it did not work. The transaction remains open and the statements executed inside the stored proc are not rolled back until an explicit ROLLBACK statement is issued.

USE COMMON;

CREATE TABLE LOG
(
LOG_ID INT IDENTITY(1, 1) NOT NULL CONSTRAINT PK_LOG_ID PRIMARY KEY,
LOG_LEVEL VARCHAR (50) NOT NULL,
LOGGER VARCHAR (500) NOT NULL,
MESSAGE VARCHAR NOT NULL,
EXCEPTION VARCHAR NULL,
APPLICATION_NAME VARCHAR(500) NOT NULL,
LOGGED_ON DATETIME DEFAULT TO_TIMESTAMP_NTZ(CURRENT_TIMESTAMP()) NOT NULL,
LOGGED_BY VARCHAR(200) DEFAULT CURRENT_USER() NOT NULL
);

CREATE OR REPLACE PROCEDURE TEST_TRANSACTION()
RETURNS VARCHAR
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This is a test transaction.', '', 'DATA LOADER');
`});
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This message should not be in the logs.', '', 'DATA LOADER');
`});

throw 'Test error'
$$
;
-- Run the next 3 lines as a batch
BEGIN;
CALL COMMON.TEST_TRANSACTION(); -- This Fails
COMMIT; -- Commit is NOT executed

SELECT * FROM COMMON.LOG WHERE LOGGER = 'TEST_TRANSACTION'; -- The insert is successful & the transaction is still OPEN

How do I rollback the statements executed inside the stored procedure?

Body:
So it turns out that you CAN issue transaction control commands (BEGIN, COMMIT, ROLLBACK) inside a stored procedure. I can being the transaction, check the return value inside the stored procedure and decide to COMMIT or ROLLBACK.

Someone should update the snowflake documentation.

CREATE OR REPLACE PROCEDURE TEST_TRANSACTION(result BOOLEAN)
RETURNS BOOLEAN NOT NULL
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
snowflake.execute({sqlText:`BEGIN;`});

snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This is a test transaction.', '', 'DATA LOADER');
`});
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This message should not be in the logs.', '', 'DATA LOADER');
`});

if ( RESULT ) { snowflake.execute( {sqlText: "COMMIT" }) }
    else {
        snowflake.execute( {sqlText: "ROLLBACK" }) };

return true;
$$
;


问:
Jest Error Unexpected token on react component

I am getting Unexpected token on the React Component Name while running npm test. Tried reading several other similar questions but none seems to be working for me. I have added content of babelrc , package.json and my test file content below

{ "presets": ["env"] }

  "dependencies": {
    "react": "^16.2.0",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.1.1",
    "redux": "^3.7.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-jest": "^23.0.0-alpha.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-to-json": "^3.3.3",
    "jest": "^22.4.2",
    "react-test-renderer": "^16.2.0"
  },
  "jest": {
    "notify": true,
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "setupTestFrameworkScriptFile": "./src/setupTests.js",
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    }
  }

import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../../src/components/App';

// describe what we are testing
describe('Render App Component', () => {

 // make our assertion and what we expect to happen
 it('should render without throwing an error', () => {
    wrapper = shallow(<App />);
    expect(wrapper.find('.app__wrapper').length).toEqual(1);
 })
})```

答:
If anybody comes here to figure out what is happening, I think the accepted answer is not related to the issue here.

When the file extension is .js and if you try to write JSX in that file, linter will complain if you have a correct ESlint configuration.

Instead, try to change the file extension to .jsx or .tsx (if Typescript involved).


问:
scala - count every line in which a word occurs
I want to find create a Map that has a word as a key and a List of integers as a value.
The Integers in the list should represent the line numbers as indices. Like so:

```<code>Map("test" -> List(0, 2), "test2"->List(1),"foo" -> List(0, 3), "bar" -> List(2))
</code>```

This would mean that the word test occurred in line 0&2, foo in line 0&3 and bar only in line 2.

I already managed to create a list of all words that occur in one line of text and read them to a list e.g.

```<code>val wordsWithLine= List((0,"test"), (0,"foo"), (1,"test2"), (2,"test"), (2,"bar"), (0,"test"), (3,"foo"))
</code>```

Now I'm stuck and have no Idea how I can create this map. I know that the function definition has to look like this, but I have no idea how to implement it:

```<code>def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] = {???}
</code>```

My idea was to use groupMapReduce() ? But I can't wrap my head around how this works.

I'm very new to Scala and functional programming in general so any tips would be highly appreciated

答:
You only need groupMap

```<code>def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] =
  listwithIndices.groupMap(_._2)(_._1)
</code>```

Body:
I want to find create a Map that has a word as a key and a List of integers as a value.
The Integers in the list should represent the line numbers as indices. Like so:

Map("test" -> List(0, 2), "test2"->List(1),"foo" -> List(0, 3), "bar" -> List(2))

This would mean that the word test occurred in line 0&2, foo in line 0&3 and bar only in line 2.

I already managed to create a list of all words that occur in one line of text and read them to a list e.g.

val wordsWithLine= List((0,"test"), (0,"foo"), (1,"test2"), (2,"test"), (2,"bar"), (0,"test"), (3,"foo"))

Now I'm stuck and have no Idea how I can create this map. I know that the function definition has to look like this, but I have no idea how to implement it:

def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] = {???}

My idea was to use groupMapReduce() ? But I can't wrap my head around how this works.

I'm very new to Scala and functional programming in general so any tips would be highly appreciated

Body:
You only need groupMap

def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] =
  listwithIndices.groupMap(_._2)(_._1)


问:
Jmeter - Using GET/POST with single call
For the purpose of my test, i need to test the same endpoint is capable of using both GET/POST http method. What is the easiest way, how i can do it without creating duplicates of the script?

答:
You can normally parameterize the HTTP request method by creating a simple CSV file with the following contents:

```<code>method
GET
POST
</code>```

once done you can add a CSV Data Set Config element and set it up like:

and in your HTTP Request sampler just use ${method} JMeter Variable

That's it, you can now run your request and it will hit the endpoint twice using different methods:

Body:
You can normally parameterize the HTTP request method by creating a simple CSV file with the following contents:

method
GET
POST

once done you can add a CSV Data Set Config element and set it up like:

and in your HTTP Request sampler just use ${method} JMeter Variable

That's it, you can now run your request and it will hit the endpoint twice using different methods:


问:
Remove Columns And Create Unique Row For Each Removed Column Pandas Dataframe
This is a really tricky issue I've run into which is slamming my memory management, here's the setup:

I have a dataframe with the following column setup:

```<code>Unique1 Unique2 Unique3 d_1 d_2 d_3..... d_2000
   A       B      C      1   4   0         100
</code>```

I want to remove the d_1...d_2000 columns and instead have a unique row for each entry:

```<code>Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   .
   .
   .
   A       B       C      d_2000  100
</code>```

The following code gives me a 2 dim series which can be zipped back up into a dataframe, but because I need to work with a few working variables it quickly runs out of 32gb of ram on linux (works on windows env but is very slow):

```<code>def convert_timeseries_to_rows(row):
    d_idx = 1
    rows_to_return = []
    for day_count in row[6:]: ### d columns start from 6
        new = list(row[:6]) ### keep first 6 columns
        day_string = "d_"+str(d_idx)
        new.append(day_string)
        new.append(day_count)
        rows_to_return.append(new)
        d_idx = d_idx + 1
    return rows_to_return ### return all rows generated

2_dim_series = df.apply(convert_timeseries_to_rows, axis=1)

data = []
columns = ['unique1', "unique2"..., 'date_index', 'units']
for each in 2_dim_series :
    for row in each:
        data.append(dict(zip(columns,row)))
data = pd.DataFrame(data)
data.to_csv('save_to_disk.csv')
</code>```

Can any of the pros think of a better way to do this (in python)?

Thanks!

Example Input:

```<code>Unique1 Unique2 Unique3 d_1 d_2 d_3
   A       B      C      1   4   0
   D       E      F      5   9   12
</code>```

Example Output:

```<code>Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   D       E       F      d_1     5
   D       E       F      d_2     9
   D       E       F      d_3     12

</code>```

答:
Pandas has a solution for this : melt</p>

```<code>df.melt(id_vars=['Unique1','Unique2','Unique3'],
        var_name='d_index',
        value_name='d_value')
 .sort_values('Unique1', ignore_index=True)

  Unique1   Unique2 Unique3 d_index d_value
0      A       B    C        d_1    1
1      A       B    C        d_2    4
2      A       B    C        d_3    0
3      D       E    F        d_1    5
4      D       E    F        d_2    9
5      D       E    F        d_3    12
</code>```

Body:
This is a really tricky issue I've run into which is slamming my memory management, here's the setup:

I have a dataframe with the following column setup:

Unique1 Unique2 Unique3 d_1 d_2 d_3..... d_2000
   A       B      C      1   4   0         100

I want to remove the d_1...d_2000 columns and instead have a unique row for each entry:

Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   .
   .
   .
   A       B       C      d_2000  100

The following code gives me a 2 dim series which can be zipped back up into a dataframe, but because I need to work with a few working variables it quickly runs out of 32gb of ram on linux (works on windows env but is very slow):

def convert_timeseries_to_rows(row):
    d_idx = 1
    rows_to_return = []
    for day_count in row[6:]: ### d columns start from 6
        new = list(row[:6]) ### keep first 6 columns
        day_string = "d_"+str(d_idx)
        new.append(day_string)
        new.append(day_count)
        rows_to_return.append(new)
        d_idx = d_idx + 1
    return rows_to_return ### return all rows generated

2_dim_series = df.apply(convert_timeseries_to_rows, axis=1)

data = []
columns = ['unique1', "unique2"..., 'date_index', 'units']
for each in 2_dim_series :
    for row in each:
        data.append(dict(zip(columns,row)))
data = pd.DataFrame(data)
data.to_csv('save_to_disk.csv')

Can any of the pros think of a better way to do this (in python)?

Thanks!

Example Input:

Unique1 Unique2 Unique3 d_1 d_2 d_3
   A       B      C      1   4   0
   D       E      F      5   9   12

Example Output:

Unique1 Unique2 Unique3 d_index d_value
   A       B       C      d_1     1
   A       B       C      d_2     4
   A       B       C      d_3     0
   D       E       F      d_1     5
   D       E       F      d_2     9
   D       E       F      d_3     12

Body:
Pandas has a solution for this : melt

df.melt(id_vars=['Unique1','Unique2','Unique3'],
        var_name='d_index',
        value_name='d_value')
 .sort_values('Unique1', ignore_index=True)

  Unique1   Unique2 Unique3 d_index d_value
0      A       B    C        d_1    1
1      A       B    C        d_2    4
2      A       B    C        d_3    0
3      D       E    F        d_1    5
4      D       E    F        d_2    9
5      D       E    F        d_3    12


问:
how do i get a list of all combinations for both words given?
i was trying to come up with a way to get a list of words like "yes" in all possible (but common) ways like lower cased and upper case and capitalized .
and then i found out you cant put two words in this function (the words "sup" & "hello") .
is there a way possible to be able to have all the words in one list with this function or should start over ?</p>

```<code>def case_insensetive(text) :
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    print (insensetive_string)

try :
   case_insensetive("sup","hello")
except :
   raise Exception ("you screwed something")
</code>```

答:
This is a typical job for the map() function.

Also, use return instead of print in your function.

```<code>def case_insensetive(text):
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    return insensetive_string

words = ['yes', 'hello']

r = list(map(case_insensetive, words))

print(r)
</code>```

Output:

```<code>[['yes', 'YES', 'Yes'], ['hello', 'HELLO', 'Hello']]
</code>```

If you want a single list, instead of a nested one:

```<code>flat_list = [item for sublist in r for item in sublist]
print(flat_list)

['yes', 'YES', 'Yes', 'hello', 'HELLO', 'Hello']
</code>```

Body:
i was trying to come up with a way to get a list of words like "yes" in all possible (but common) ways like lower cased and upper case and capitalized .
and then i found out you cant put two words in this function (the words "sup" & "hello") .
is there a way possible to be able to have all the words in one list with this function or should start over ?

def case_insensetive(text) :
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    print (insensetive_string)

try :
   case_insensetive("sup","hello")
except :
   raise Exception ("you screwed something")

Body:
This is a typical job for the map() function.

Also, use return instead of print in your function.

def case_insensetive(text):
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    return insensetive_string

words = ['yes', 'hello']

r = list(map(case_insensetive, words))

print(r)

Output:

[['yes', 'YES', 'Yes'], ['hello', 'HELLO', 'Hello']]

If you want a single list, instead of a nested one:

flat_list = [item for sublist in r for item in sublist]
print(flat_list)

['yes', 'YES', 'Yes', 'hello', 'HELLO', 'Hello']


问:
Flask subprocess cannot see changes in DB
Im using Flask app with long-running worker proccess and this process cannot see changes in DB.

main.py

In this file I create Flask app and start the process.

```<code>from paas.app_factory import create_app()

app = create_app()

from .controllers.resource_controller import *

from .worker import create_resource, delete_resource
from multiprocessing import Process
from flask import current_app

with app.app_context():
    create_proc = Process(target=create_resource, args=(current_app._get_current_object(),)).start()
</code>```

worker.py

Worker every 20 sec checks if new resources appeared in DB and if so, it will process them

```<code>def create_resources(app):
    with app.app_context():
        while True:
            resource = get_resource_to_create()
            if not resource:
                print("Wait for resource to create...")
                time.sleep(20)
                continue
            create_resource.....
</code>```

resource_controller.py

After application started I added some resource to db. Problem is, that through the second route I can get resource from db, but worker.py sees nothing in DB.

```<code>from .main import app

@app.route('resource/<resource>', method=POST)
create_resource():
    write_resource_to_db(resource)

@app.route('resources')
get_resources():
    select_all_resources_from_db()
</code>```

I believe there is some misunderstanding of application context from my side, but I cannot figure it out. Help would be really nice.

Thank you in advance.

P.S. Let's say get_resource_to_create() and select_all_resources_from_db() are the same function inside.

答:
Problem was in

```<code>def create_resources(app):
    with app.app_context():
        while True:
</code>```

Loop was in the app context == in one transaction, so it worked like that:

```<code>START TRANSACTION;
SELECT ...;
SELECT ...;
SELECT ...;
...
</code>```

So there was no chance to get fresh data.

If I switched the lines,

```<code>def create_resources(app):
    while True:
        with app.app_context():
</code>```

then after one cycle ends, there is a commit and new transaction with fresh data.

```<code>START TRANSACTION;
SELECT ... ;
COMMIT;
START TRANSACTION;
SELECT ... ;
COMMIT;
...
</code>```

Body:
Im using Flask app with long-running worker proccess and this process cannot see changes in DB.

main.py

In this file I create Flask app and start the process.

from paas.app_factory import create_app()

app = create_app()

from .controllers.resource_controller import *

from .worker import create_resource, delete_resource
from multiprocessing import Process
from flask import current_app

with app.app_context():
    create_proc = Process(target=create_resource, args=(current_app._get_current_object(),)).start()

worker.py

Worker every 20 sec checks if new resources appeared in DB and if so, it will process them

def create_resources(app):
    with app.app_context():
        while True:
            resource = get_resource_to_create()
            if not resource:
                print("Wait for resource to create...")
                time.sleep(20)
                continue
            create_resource.....

resource_controller.py

After application started I added some resource to db. Problem is, that through the second route I can get resource from db, but worker.py sees nothing in DB.

from .main import app

@app.route('resource/<resource>', method=POST)
create_resource():
    write_resource_to_db(resource)

@app.route('resources')
get_resources():
    select_all_resources_from_db()

I believe there is some misunderstanding of application context from my side, but I cannot figure it out. Help would be really nice.

Thank you in advance.

P.S. Let's say get_resource_to_create() and select_all_resources_from_db() are the same function inside.

Body:
Problem was in

def create_resources(app):
    with app.app_context():
        while True:

Loop was in the app context == in one transaction, so it worked like that:

START TRANSACTION;
SELECT ...;
SELECT ...;
SELECT ...;
...

So there was no chance to get fresh data.

If I switched the lines,

def create_resources(app):
    while True:
        with app.app_context():

then after one cycle ends, there is a commit and new transaction with fresh data.

START TRANSACTION;
SELECT ... ;
COMMIT;
START TRANSACTION;
SELECT ... ;
COMMIT;
...


问:
Calculation over each row from a CSV - file with Python
I want to do a calculation over each row from  csv-file in Python.

This is the loaddataa File:

```<code>import os
import pandas as pd

def loadData(relativPath):
    files = os.listdir(relativPath)
    path = os.path.abspath(relativPath)
    datas = list()
    for file in files:
        absPath = path + "/" + file
        print(absPath)
        data = pd.read_csv(absPath)
        datas.append(data)
    return datas
</code>```

These were my first steps:

```<code>import math as m
import loaddataa as ld

dataListStride = ld.loadData("../Data/Fabienne")
    indexStrideData = 1
    strideData = dataListStride[indexStrideData]

def horizontal(yAngle, yAcceleration, xAcceleration):
    a = (m.cos(yAngle)*yAcceleration)-(m.sin(yAngle)*xAcceleration)
    return a

resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    ......
    ......
</code>```

In the for - loop I don't know how to go on. The csv - file consists of 9 columns and 150 row. For the calculation I just need column 2, 4 and 5. The calculation with the formula in def horizontal shall be executed over each row, so that in the end I have 150 values. I hope it's clear what I want to do.

Thanks for helping me.

答:
Call the horizontal() function in each cycle and add the result to your list using resultsHorizontal.append().

Code:

```<code>resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    resultsHorizontal.append(horizontal(strideData_yAngle, strideData_yAcceleration, strideData_xAcceleration))
</code>```

Body:
I want to do a calculation over each row from  csv-file in Python.

This is the loaddataa File:

import os
import pandas as pd

def loadData(relativPath):
    files = os.listdir(relativPath)
    path = os.path.abspath(relativPath)
    datas = list()
    for file in files:
        absPath = path + "/" + file
        print(absPath)
        data = pd.read_csv(absPath)
        datas.append(data)
    return datas

These were my first steps:

import math as m
import loaddataa as ld

dataListStride = ld.loadData("../Data/Fabienne")
    indexStrideData = 1
    strideData = dataListStride[indexStrideData]

def horizontal(yAngle, yAcceleration, xAcceleration):
    a = (m.cos(yAngle)*yAcceleration)-(m.sin(yAngle)*xAcceleration)
    return a

resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    ......
    ......

In the for - loop I don't know how to go on. The csv - file consists of 9 columns and 150 row. For the calculation I just need column 2, 4 and 5. The calculation with the formula in def horizontal shall be executed over each row, so that in the end I have 150 values. I hope it's clear what I want to do.

Thanks for helping me.

Body:
Call the horizontal() function in each cycle and add the result to your list using resultsHorizontal.append().

Code:

resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    resultsHorizontal.append(horizontal(strideData_yAngle, strideData_yAcceleration, strideData_xAcceleration))


问:
When I am trying to run the code it gives error
I am trying to run the code in Jupyter notebook but it shows error SyntaxError: 'break' outside loop

```<code>import cv2
import sys
cpt=0
vidStream=cv2.VideoCapture(0)
while True:
    ret,frame=vidStream.read()
cv2.imshow("Test Frame", frame)
cv2.imwrite(r"E:\Face_Detection_Project\Test_images\0\image%04i.jpg" %cpt,frame)
cpt +=1
if cv2.waitKey(10)==ord('q'):
    break
</code>```

答:
Break should be inside the while loop. to be inside, you need to add indentation, like this:

```<code>import cv2
import sys
cpt=0
vidStream=cv2.VideoCapture(0)
while True:
    ret,frame=vidStream.read()
    cv2.imshow("Test Frame", frame)
    cv2.imwrite(r"E:\Face_Detection_Project\Test_images\0\image%04i.jpg" %cpt,frame)
    cpt +=1
    if cv2.waitKey(10)==ord('q'):
        break
</code>```

Body:
I am trying to run the code in Jupyter notebook but it shows error SyntaxError: 'break' outside loop

import cv2
import sys
cpt=0
vidStream=cv2.VideoCapture(0)
while True:
    ret,frame=vidStream.read()
cv2.imshow("Test Frame", frame)
cv2.imwrite(r"E:\Face_Detection_Project\Test_images\0\image%04i.jpg" %cpt,frame)
cpt +=1
if cv2.waitKey(10)==ord('q'):
    break

Body:
Break should be inside the while loop. to be inside, you need to add indentation, like this:

import cv2
import sys
cpt=0
vidStream=cv2.VideoCapture(0)
while True:
    ret,frame=vidStream.read()
    cv2.imshow("Test Frame", frame)
    cv2.imwrite(r"E:\Face_Detection_Project\Test_images\0\image%04i.jpg" %cpt,frame)
    cpt +=1
    if cv2.waitKey(10)==ord('q'):
        break


问:
Polymorphic variants and let%bind type error
I'm trying to use the technique in Composable Error Handling in OCaml (Result type with polymorphic variants for errors) for some code I've written. The types of the functions I'm trying to use look like this:

val parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t
```

<p>My attempt at composing them is this:</p>

<pre class="lang-ml prettyprint-override"><code>let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    let open Result.Let_syntax in
    let%bind tokens = lex lexer input in
    parse parser tokens
</code>```

Unfortunately the compiler (4.09.0) reports a type error:

```<code>File "src/Pratt.ml", line 147, characters 4-23:
147 |     parse parser tokens
          ^^^^^^^^^^^^^^^^^^^
Error: This expression has type
         (Nominal.term, [ `ParseError of string ]) result
       but an expression was expected of type
         (Nominal.term, [> `LexError of string ]) result
       The first variant type does not allow tag(s) `LexError
</code>```

Note that if I do the equivalent by hand, the code compiles:

let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    match lex lexer input with
      | Error (`LexError err) -> Error (`LexError err)
      | Ok tokens ->
        (match parse parser tokens with
        | Ok result -> Ok result
        | Error (`ParseError err) -> Error (`ParseError err))
```

<p>Actually, that's not quite true. The equivalent is this, which also fails to compile (in the same way):</p>

<pre class="lang-ml prettyprint-override"><code>    match lex lexer input with
      | Error err -> Error err
      | Ok tokens ->
        match parse parser tokens with
        | Ok result -> Ok result
        | Error err -> Error err
</code>```

```<code>File "src/Pratt.ml", line 155, characters 29-32:
155 |         | Error err -> Error err
                                   ^^^
Error: This expression has type [ `ParseError of string ]
       but an expression was expected of type
         [> `LexError of string | `ParseError of string ]
       The first variant type does not allow tag(s) `LexError
</code>```

So my question is this. Note that the error message says "This expression has type (Nominal.term, [ `ParseError of string ]) result". This is what I don't understand -- I never specify that type anywhere, in fact, both places ParseError is mentioned, it's with a > constraint. So where does this type come from? IE where does [>ParseError of string ]become[ ParseError of string ]?

Also:

What's the difference between my attempt and Vladimir's original (which I assume compiles)?

Is there a way to weaken a polymorphic variant from [ x ] to [> x ]? (other than mapping all the tags by hand from the first type to the second)

Edit:

I uploaded all of my code for context.

Edit 2 (sorry):

I did some exploration and came up with this implementation:

let parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks ->
    match expression parser toks with
    (* | [], result -> result *)
    (* | _, Error err -> Error err *)
    | _, Ok _ -> Error (`ParseError "leftover tokens")
    | _, _ -> Error (`ParseError "unimplemented")
```

If I remove either of the commented lines, the implementation of lex_and_parse starts to fail again. It's a bit disturbing to me that parse compiles and its type signature never changes, yet a caller can fail to typecheck. How is this possible? This kind of nonlocal effect seriously violates my expectation for how type checking / signatures (ought to) work. I'd really like to understand what's happening.

答:
The following functorized code:

```<code>module F(X: sig
    type parser type lexer type token
    module Nominal: sig type term end
    val parse :
      parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
    val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t
end) = struct
open X

let (let*) x f = match x with
  | Error _ as e -> e
  | Ok x -> f x

let lex_and_parse parser lexer input =
  let* tokens = lex lexer input in
  parse parser tokens
end
</code>```

compiles just fine with the expected type for lex_and_parse.

The issue is thus probably that your implementation of parse and lex have a closed error type.

Note that this issue could be fixed easily with a coercion since the closed error type is a subtype of the open one:

```<code>let fix parse =
(parse:
    parser -> token list -> (Nominal.term, [`ParseError of string ]) Result.t
 :> parser -> token list -> (Nominal.term, [>`ParseError of string ]) Result.t
 )
</code>```

but it is probably better to fix the implementation of the corresponding functions.

EDIT:

The initial error comes from this part of your code:

type parse_error = [ `ParseError of string ]
type parse_result = (Nominal.term, parse_error) Result.t
...
let rec expression
  : parser -> ?rbp:int -> token list -> token list * parse_result
...
let parse :
  parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> result
```

<p>Here your are constraining the error in the <code>parse_error</code> type to be exactly <code>`Parse_error</code>. Thus, when you return <code>result</code> in <code>parse</code>, its type its <code>(_,parse_error) result</code>. And since this result type can be unified with your annotation, no error is raised.</p>

<p>Maybe a first fix is to detail the type to make the typechecker aware that you intended the error type to be open:</p>

<pre class="lang-ml prettyprint-override"><code>let parse : 'error.
  parser -> token list ->
  (Nominal.term, [> `ParseError of string ] as 'error) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> result
</code>```

Here, the explicit universal annotation on the return type will prevent the type to be closed behind your back (the error message might be confusing before 4.10 ).

Then, one possible fix is to add a coercion to reopen the error type in parse:

let parse : 'error.
  parser -> token list ->
  (Nominal.term, [> `ParseError of string ] as 'error) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> (result:>(Nominal.term, [> parse_error]) result)
```

<p>or you could make the error type of expression open too:</p>

<pre class="lang-ml prettyprint-override"><code>type parse_error = [ `ParseError of string ]
type 'a parse_result = (Nominal.term, [> parse_error] as 'a) Result.t
...
let rec expression
  : parser -> ?rbp:int -> token list -> token list * 'a parse_result
  = ...

</code>```

Or an even easier fix: remove the type annotation, with

```<code>let rec expression parser ... =
</code>```

without the type annotation, the compiler inferq the right type. Indeed, this is a quite generic situation: the compiler is guaranteed to infer the best possible type without user interference.

Body:
I'm trying to use the technique in Composable Error Handling in OCaml (Result type with polymorphic variants for errors) for some code I've written. The types of the functions I'm trying to use look like this:

val parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t

My attempt at composing them is this:

let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    let open Result.Let_syntax in
    let%bind tokens = lex lexer input in
    parse parser tokens

Unfortunately the compiler (4.09.0) reports a type error:

File "src/Pratt.ml", line 147, characters 4-23:
147 |     parse parser tokens
          ^^^^^^^^^^^^^^^^^^^
Error: This expression has type
         (Nominal.term, [ `ParseError of string ]) result
       but an expression was expected of type
         (Nominal.term, [> `LexError of string ]) result
       The first variant type does not allow tag(s) `LexError

Note that if I do the equivalent by hand, the code compiles:

let lex_and_parse
  : parser -> lexer -> string -> (Nominal.term, [> `ParseError of string | `LexError of string ]) Result.t
  = fun parser lexer input ->
    match lex lexer input with
      | Error (`LexError err) -> Error (`LexError err)
      | Ok tokens ->
        (match parse parser tokens with
        | Ok result -> Ok result
        | Error (`ParseError err) -> Error (`ParseError err))

Actually, that's not quite true. The equivalent is this, which also fails to compile (in the same way):

    match lex lexer input with
      | Error err -> Error err
      | Ok tokens ->
        match parse parser tokens with
        | Ok result -> Ok result
        | Error err -> Error err

File "src/Pratt.ml", line 155, characters 29-32:
155 |         | Error err -> Error err
                                   ^^^
Error: This expression has type [ `ParseError of string ]
       but an expression was expected of type
         [> `LexError of string | `ParseError of string ]
       The first variant type does not allow tag(s) `LexError

So my question is this. Note that the error message says "This expression has type (Nominal.term, [ `ParseError of string ]) result". This is what I don't understand -- I never specify that type anywhere, in fact, both places ParseError is mentioned, it's with a > constraint. So where does this type come from? IE where does [>ParseError of string ]become[ ParseError of string ]?

Also:

What's the difference between my attempt and Vladimir's original (which I assume compiles)?

Is there a way to weaken a polymorphic variant from [ x ] to [> x ]? (other than mapping all the tags by hand from the first type to the second)

Edit:

I uploaded all of my code for context.

Edit 2 (sorry):

I did some exploration and came up with this implementation:

let parse : parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks ->
    match expression parser toks with
    (* | [], result -> result *)
    (* | _, Error err -> Error err *)
    | _, Ok _ -> Error (`ParseError "leftover tokens")
    | _, _ -> Error (`ParseError "unimplemented")

If I remove either of the commented lines, the implementation of lex_and_parse starts to fail again. It's a bit disturbing to me that parse compiles and its type signature never changes, yet a caller can fail to typecheck. How is this possible? This kind of nonlocal effect seriously violates my expectation for how type checking / signatures (ought to) work. I'd really like to understand what's happening.

Body:
The following functorized code:

module F(X: sig
    type parser type lexer type token
    module Nominal: sig type term end
    val parse :
      parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
    val lex : lexer -> string -> (token list, [> `LexError of string ]) Result.t
end) = struct
open X

let (let*) x f = match x with
  | Error _ as e -> e
  | Ok x -> f x

let lex_and_parse parser lexer input =
  let* tokens = lex lexer input in
  parse parser tokens
end

compiles just fine with the expected type for lex_and_parse.

The issue is thus probably that your implementation of parse and lex have a closed error type.

Note that this issue could be fixed easily with a coercion since the closed error type is a subtype of the open one:

let fix parse =
(parse:
    parser -> token list -> (Nominal.term, [`ParseError of string ]) Result.t
 :> parser -> token list -> (Nominal.term, [>`ParseError of string ]) Result.t
 )

but it is probably better to fix the implementation of the corresponding functions.

EDIT:

The initial error comes from this part of your code:

type parse_error = [ `ParseError of string ]
type parse_result = (Nominal.term, parse_error) Result.t
...
let rec expression
  : parser -> ?rbp:int -> token list -> token list * parse_result
...
let parse :
  parser -> token list -> (Nominal.term, [> `ParseError of string ]) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> result

Here your are constraining the error in the parse_error type to be exactly `Parse_error. Thus, when you return result in parse, its type its (_,parse_error) result. And since this result type can be unified with your annotation, no error is raised.

Maybe a first fix is to detail the type to make the typechecker aware that you intended the error type to be open:

let parse : 'error.
  parser -> token list ->
  (Nominal.term, [> `ParseError of string ] as 'error) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> result

Here, the explicit universal annotation on the return type will prevent the type to be closed behind your back (the error message might be confusing before 4.10 ).

Then, one possible fix is to add a coercion to reopen the error type in parse:

let parse : 'error.
  parser -> token list ->
  (Nominal.term, [> `ParseError of string ] as 'error) Result.t
  = fun parser toks -> match expression parser toks with
    | [], result -> (result:>(Nominal.term, [> parse_error]) result)

or you could make the error type of expression open too:

type parse_error = [ `ParseError of string ]
type 'a parse_result = (Nominal.term, [> parse_error] as 'a) Result.t
...
let rec expression
  : parser -> ?rbp:int -> token list -> token list * 'a parse_result
  = ...

Or an even easier fix: remove the type annotation, with

let rec expression parser ... =

without the type annotation, the compiler inferq the right type. Indeed, this is a quite generic situation: the compiler is guaranteed to infer the best possible type without user interference.


问:
iPhone project - collect files into one place
Sorry if this has been answered before but all my searches do not return anything related to this.

Is there a way to collect all the files referenced in a project and save them in the procject folder automatically? Rather that having links to places where you may accidentally delete the files.

Thanks,

Eds

答: What do you mean collect all the files? Do you mean your external files or class files. Your external files like images or audio/video files should be added into Resources directory, it does not matter where is the root directory of these files. Then, you can access with their name in the project.</p>


问:
Decode weight in data packets from wireshark with bluetooth low energy
I've been working doing some reverse engineering to different BLE based devices and I have a weight scale where I can't find a pattern to find/decode/interpret the weight value that I can get from the android app. I was also able to get the services and characteristics of this device but did not found a SIG standard match with the UUIDs from the bluetooth site.

I'm using an nRF51 dongle to sniffing data packets between the android app and the weight scale and I can look the ble traffic, but there are several events during the communication that I can't really understand what's the relation and I can't be able to convert those values to readable weight in kg or pounds.

My target value is: 71.3kg readed from the weight scale app.

Let me show you what I get from the ble sniffer.

first I see that the master is sending notification/indication requests to the handles 0x0009(notify), 0x000c(indication) and 0x000f(notify) in each characteristic of one service.

Then I start to read notification/indications values mixed with write commands. At the end of the communication, I see some packets that I feel that they are the ones with the weight scale data and BMI.
Packets number 574, 672 and 674 in the image.

So that give us the following candidates:

```<code>1st. packet_number_574 = '000002c9070002
2nd. packet_number_672 = '420001000000005ed12059007f02c9011d01f101'
3rd. packet_number_674 = '42018c016b00070237057d001a01bc001d007c'
</code>```

1st packet during the communication exchange looks more like a counter/RT/clock than a real measurement because of the data behavior, so I feel this one is not a real option.

2nd and 3rd looks more like real candidates, I have split them and convert them to decimal values and I have not found a relation, even combining bytes since this values are floating point data types. So my real question is, Am I missing something that you might see with this information? Do you know if there is a relation between this data packets and my target?

Thank you for taking your time reading me and any help could be good, thanks!

EDIT:

I have a python script that allows me to check the services and their characteristics hierarchy and some useful data like properties, their handles and descriptors.

```<code>Service 'fff0' (0000fff0-0000-1000-8000-00805f9b34fb):
    Characteristic 'fff1' (0000fff1-0000-1000-8000-00805f9b34fb):
              Handle: 8 (8)
            Readable: False
          Pro+perties: WRITE NOTIFY
          Descriptor: Descriptor <Client Characteristic Configuration> (handle 0x9; uuid 00002902-0000-1000-8000-00805f9b34fb)
    Characteristic 'fff2' (0000fff2-0000-1000-8000-00805f9b34fb):
              Handle: 11 (b)
            Readable: False
          Properties: WRITE NO RESPONSE INDICATE
          Descriptor: Descriptor <Client Characteristic Configuration> (handle 0xc; uuid 00002902-0000-1000-8000-00805f9b34fb)
    Characteristic 'fff3' (0000fff3-0000-1000-8000-00805f9b34fb):
              Handle: 14 (e)
            Readable: False
          Properties: NOTIFY
          Descriptor: Descriptor <Client Characteristic Configuration> (handle 0xf; uuid 00002902-0000-1000-8000-00805f9b34fb)
</code>```

This are the characteristics related to the notifications and indications that I see in wireshark. I think the packet number 574 (which characteristics has only a notifiy property) is more important than I think.

答:
I solve it by myself.

This post gives me the idea to take the values (2 bytes) and multiply them by 0.1, that way I could get the weight.

In bytes I could look for my target value without decimals 713, which is in hex = 0x02c9

If we look at the packet number 574:
000002c9070002 and split it 00:00:02:c9:07:00:02

I could see that 2nd and 3rd bytes match with this pattern!

The only thing required to do is to group this bytes and multiply the decimal value 713 x 0.1 = 71.3. I made different tests and found that this pattern is constant so I feel is accurate for my solution. Hope this could help someone in the future.

Body:
I've been working doing some reverse engineering to different BLE based devices and I have a weight scale where I can't find a pattern to find/decode/interpret the weight value that I can get from the android app. I was also able to get the services and characteristics of this device but did not found a SIG standard match with the UUIDs from the bluetooth site.

I'm using an nRF51 dongle to sniffing data packets between the android app and the weight scale and I can look the ble traffic, but there are several events during the communication that I can't really understand what's the relation and I can't be able to convert those values to readable weight in kg or pounds.

My target value is: 71.3kg readed from the weight scale app.

Let me show you what I get from the ble sniffer.

first I see that the master is sending notification/indication requests to the handles 0x0009(notify), 0x000c(indication) and 0x000f(notify) in each characteristic of one service.

Then I start to read notification/indications values mixed with write commands. At the end of the communication, I see some packets that I feel that they are the ones with the weight scale data and BMI.
Packets number 574, 672 and 674 in the image.

So that give us the following candidates:

1st. packet_number_574 = '000002c9070002
2nd. packet_number_672 = '420001000000005ed12059007f02c9011d01f101'
3rd. packet_number_674 = '42018c016b00070237057d001a01bc001d007c'

1st packet during the communication exchange looks more like a counter/RT/clock than a real measurement because of the data behavior, so I feel this one is not a real option.

2nd and 3rd looks more like real candidates, I have split them and convert them to decimal values and I have not found a relation, even combining bytes since this values are floating point data types. So my real question is, Am I missing something that you might see with this information? Do you know if there is a relation between this data packets and my target?

Thank you for taking your time reading me and any help could be good, thanks!

EDIT:

I have a python script that allows me to check the services and their characteristics hierarchy and some useful data like properties, their handles and descriptors.

Service 'fff0' (0000fff0-0000-1000-8000-00805f9b34fb):
    Characteristic 'fff1' (0000fff1-0000-1000-8000-00805f9b34fb):
              Handle: 8 (8)
            Readable: False
          Pro+perties: WRITE NOTIFY
          Descriptor: Descriptor <Client Characteristic Configuration> (handle 0x9; uuid 00002902-0000-1000-8000-00805f9b34fb)
    Characteristic 'fff2' (0000fff2-0000-1000-8000-00805f9b34fb):
              Handle: 11 (b)
            Readable: False
          Properties: WRITE NO RESPONSE INDICATE
          Descriptor: Descriptor <Client Characteristic Configuration> (handle 0xc; uuid 00002902-0000-1000-8000-00805f9b34fb)
    Characteristic 'fff3' (0000fff3-0000-1000-8000-00805f9b34fb):
              Handle: 14 (e)
            Readable: False
          Properties: NOTIFY
          Descriptor: Descriptor <Client Characteristic Configuration> (handle 0xf; uuid 00002902-0000-1000-8000-00805f9b34fb)

This are the characteristics related to the notifications and indications that I see in wireshark. I think the packet number 574 (which characteristics has only a notifiy property) is more important than I think.