问:
How to switch between terminals in Visual Studio Code?
I'm looking to switch between terminals open in visual studio code.

With this "Switch focus between editor and integrated terminal in Visual Studio Code" question I correctly setup the focus, but I would like to switch between terminals, not only from code to terminal.

Is there a way to do it?

答:
Go to File → Preferences → Keyboard Shortcuts or just press Ctrl + k + Ctrl + s.

Then click the icon in upper right corner, it opens keybindings.json file:

Try adding the following two entries to this file:

```<code>{
    "key": "ctrl+pagedown",
    "command": "workbench.action.terminal.focusNext",
    "when": "terminalFocus"
},
{
    "key": "ctrl+pageup",
    "command": "workbench.action.terminal.focusPrevious",
    "when": "terminalFocus"
}
</code>```

Note: On Mac change ctrl to cmd

Body:
Go to File → Preferences → Keyboard Shortcuts or just press Ctrl + k + Ctrl + s.

Then click the icon in upper right corner, it opens keybindings.json file:

Try adding the following two entries to this file:

{
    "key": "ctrl+pagedown",
    "command": "workbench.action.terminal.focusNext",
    "when": "terminalFocus"
},
{
    "key": "ctrl+pageup",
    "command": "workbench.action.terminal.focusPrevious",
    "when": "terminalFocus"
}

Note: On Mac change ctrl to cmd


来源: stackexchange

问:
How to Calculate change between rows in Pandas Data Frame
Suppose I have a daily sales record column. And from it I want to create two new columns. That keep track of the change from a month a go. For each day on the record. How would I go about doing this in Pandas Data frame. new to pandas and stuck here.
here is a sample data set

And what I am looking for is to create a new column "Change from a month ago",
which will tracks the difference between in daily sales between today and 30 days ago.

答:
Getting a sense of the data you're using would certainly make it a lot easier to answer this. However, a common way to do it is by creating a new column in pandas using the Series.shift operation in the following way:

```<code>import pandas as pd
df = pd.DataFrame({'Col1': [10, 20, 15, 30, 45],
                   'Col2': [13, 23, 18, 33, 48],
                   'Col3': [17, 27, 22, 37, 52]})

df['Col4'] = df.Col1.shift(periods=-3) # reference df.Col1 value from 3 rows back
</code>```

You can use this new column to do any arithmetic/algorithmic computation hereon.

ContentLicense: CC BY-SA 4.0

Body:
Getting a sense of the data you're using would certainly make it a lot easier to answer this. However, a common way to do it is by creating a new column in pandas using the Series.shift operation in the following way:

import pandas as pd
df = pd.DataFrame({'Col1': [10, 20, 15, 30, 45],
                   'Col2': [13, 23, 18, 33, 48],
                   'Col3': [17, 27, 22, 37, 52]})

df['Col4'] = df.Col1.shift(periods=-3) # reference df.Col1 value from 3 rows back

You can use this new column to do any arithmetic/algorithmic computation hereon.


问:
XmlWriter - disposable
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();
```

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

答:
Its good to have using block, where it ensures calling the Dispose on any object that implements IDisposable.

```<code>using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
     //do stuff
}
</code>```

The Dispose method for XmlWriter looks like-

```<code>protected virtual void Dispose(bool disposing)
{
    if (this.WriteState != WriteState.Closed)
    {
        try
        {
            this.Close();
        }
        catch
        {
        }
    }
}
</code>```

Title: XmlWriter - disposable

Body:
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

Body:
Its good to have using block, where it ensures calling the Dispose on any object that implements IDisposable.

using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
     //do stuff
}

The Dispose method for XmlWriter looks like-

protected virtual void Dispose(bool disposing)
{
    if (this.WriteState != WriteState.Closed)
    {
        try
        {
            this.Close();
        }
        catch
        {
        }
    }
}


问:
How to use Two Toggle buttons on same page having same function with different css?
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

```<code>onclick="themeToggle()" id="theme-switcher"
</code>```

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

```<code> var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

</code>```

This is the code for Two Toggle buttons

```<code>
    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label>

</code>```

```<code>
 <label class="switch" style="padding: 23px 0;">
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
<div>
    <span></span>
</div>

</code>```

Kindly help me in solving the issue with the code as well.

Thanks for the help.

答:
If you are using getElementById it will return the first occurrence of that id from dom, and as you are having same id on both button it is updating the first button every time.
Instead, you can except event object, in click function, and assign event.target to get the button element.</p>

Body:
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

onclick="themeToggle()" id="theme-switcher"

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

 var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

This is the code for Two Toggle buttons

    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

<input type="checkbox" onclick="themeToggle()" id="theme-switcher">

Kindly help me in solving the issue with the code as well.

Thanks for the help.


问:
Vertx : Running a block of code outside of the eventloop
I write a service by Vertx. My service run a function like this :

```<code>router.get("/report").handle(ServiceHandler::Count);
</code>```

My Count function takes a long time (about from 10 to 15 minutes) and that broke the golden rule of Vertx. I'm newbie and I've tried google it but I can not find the way out.

Please help me out!
Thanks very much.

答:
If the processing should take over 1 minute, generally you should NOT make it run via router from http-request.

Your ServiceHandler::Count function should rather return immediately with a "process started" message, and use some long-running mechanism like SockJS or good-ol email to notify the user about the completion.

Body:
I write a service by Vertx. My service run a function like this :

router.get("/report").handle(ServiceHandler::Count);

My Count function takes a long time (about from 10 to 15 minutes) and that broke the golden rule of Vertx. I'm newbie and I've tried google it but I can not find the way out.

Please help me out!
Thanks very much.


问:
Wildfly provisioning with galleon. Missing batch (jberet)
I tried to build a minimal Wildfly distribution with galleon with s2i which turned out pretty well so far.
But now my application has missing dependencies for batch.

So I tried to add batch to GALLEON_PROVISION_LAYERS but it seems there is no batch layer.

Here is my simplyfied s2i:

```<code>s2i build http://myrepository quay.io/wildfly/wildfly-centos7:latest wildflytest  --env GALLEON_PROVISION_LAYERS=datasources-web-server,jaxrs-server,cloud-server,keycloak,observability,h2-driver,h2-datasource,batch  --env ARTIFACT_DIR=subdir/target --env MODULE_DIR=subdir
</code>```

Am i just missing the right layer to user batch or do i need to use a full wildfly?

答: no layer for batch yet, you must use the default config.</p>

Body:
I tried to build a minimal Wildfly distribution with galleon with s2i which turned out pretty well so far.
But now my application has missing dependencies for batch.

So I tried to add batch to GALLEON_PROVISION_LAYERS but it seems there is no batch layer.

Here is my simplyfied s2i:

s2i build http://myrepository quay.io/wildfly/wildfly-centos7:latest wildflytest  --env GALLEON_PROVISION_LAYERS=datasources-web-server,jaxrs-server,cloud-server,keycloak,observability,h2-driver,h2-datasource,batch  --env ARTIFACT_DIR=subdir/target --env MODULE_DIR=subdir

Am i just missing the right layer to user batch or do i need to use a full wildfly?


问:
Trying to convert a string/char to an integer yielded an unexpected result
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?</p>

```<code>using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}
</code>```

答:
So actually in your code you are not printing that char in int but rather than you are printing ASCII value of '1' that is 49.

Whenever a char is converted to int it changes and assigns ASCII value of that char.

to solve your problem you can use folow:

```<code>#define conv_digit(ch) (ch-'0')
</code>```

Then just call this function passing binary[0] or whatever char you want.

Body:
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?

using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}

Body:
So actually in your code you are not printing that char in int but rather than you are printing ASCII value of '1' that is 49.

Whenever a char is converted to int it changes and assigns ASCII value of that char.

to solve your problem you can use folow:

#define conv_digit(ch) (ch-'0')

Then just call this function passing binary[0] or whatever char you want.


问:
Best place to check for property values
Assuming you have a class Photo:

```<code>class Photo
{
  public string Title {get; set;}
  public string FileExtension {get; set;}
  public void Save()
  {
    // Save to backing store here
  }
}
</code>```

Which would be the best place to check whether the values have been set correctly. In the propert setter or the Save method.

Edit: What if it is an Update method? If photos are added through a PhotoManager, using a method like PhotoManager.Add(Photo p), then which is the best place to do the validation.

Kind regards,

答:
It depends, when do you have enough data to check the correctness: If the correctness of FileExtension does not depend on the value of Title, and the correctness of Title does not depend on the value of FileExtension, you can check each of them inside the setters.

But if one of them depends on the other's value, and you don't know what is the order in which setters will be executed, you have to check Title and FileExtension only when you get them both. That can be in Save, or in some new Check method.

Also, maybe before doing Save you have to check, whether both Title and FileExtenstion were set.

So, to summarize, you may need the following checks:

Check Title's correctness: in Title.set

Check FileExtension's correctness: in FileExtension.set

Check that Title.set and FileExtension.set were executed: in Save

Check the "co-correcntess" of Title and FileExtesion: in Save

Regarding the Update method: I understand that you receive a Photo object with Title and FileExtenstion already set. In this case, you have to decide, whether you trust that Title and FileExtension were already checked in the Photo by whoever did set them. If you trust it, you don't have to change anything in my proposal above. But if you don't trust, then you also have to check Title's correctness and FileExtension's correctness in Save (or, again, in some new Check method).

ContentLicense: CC BY-SA 2.5

Title: Best place to check for property values

Body:
Assuming you have a class Photo:

class Photo
{
  public string Title {get; set;}
  public string FileExtension {get; set;}
  public void Save()
  {
    // Save to backing store here
  }
}

Which would be the best place to check whether the values have been set correctly. In the propert setter or the Save method.

Edit: What if it is an Update method? If photos are added through a PhotoManager, using a method like PhotoManager.Add(Photo p), then which is the best place to do the validation.

Kind regards,

OwnerDisplayName: Igor Oks

LastEditorDisplayName: Igor Oks


问:
Images (either PNGs or WebPs) suddenly have black backgrounds instead of transparent
I just changed my computer at work. Up until today, on my old PC that ran Windows 8, and when developing my Gatsby site on local, everything was fine. Since the switch (I'm now on W10) alkl my images with transparency have now lost their transparent layer and are black instead. Before-after Example

This happens only on local ; the site has two hosting instances, staging on AWS, prod on Netlify, and they're both okay. Also, the image appears fine when I open it in a new tab ; the black happens only when viewing the site in full. It happens on all browsers though.

I haven't changed the gatsby-configs so I really don't know if the problem is caused by Windows, or Gatsby, or the browsers, or... Although my guess is it's with gatsby-image or gatsby-transformer-remark, because other PNGs called with a simple import don't have this problem.

I've tried updating my libwebp library on Windows but couldn't find a version higher than 0.19

Here are my plugins from gatsby-config.js :

```<code>plugins: [{
            resolve: "gatsby-source-filesystem",
            options: {
                name: "src",
                path: `${__dirname}/src/`
            }
        }, {
            resolve: "gatsby-source-filesystem",
            options: {
                name: "dsp",
                path: `${__dirname}/src/pages/dsp/`
            }
        },
        {
            resolve: "gatsby-transformer-remark",
            options: {
                plugins: [{
                    resolve: "gatsby-remark-images",
                    options: {
                        maxWidth: 1200,
                        withWebp: true
                    },
                }, ],
            },
        },
        {
            resolve: "gatsby-plugin-catch-links"
        },
        {
            resolve: "gatsby-transformer-sharp"
        },
        {
            resolve: "gatsby-plugin-sharp"
        },
        {
            resolve: "gatsby-plugin-react-helmet"
        },
        {
            resolve: "gatsby-plugin-manifest",
            options: {
                name: "Mysite",
                short_name: "Mysite",
                start_url: "/",
                background_color: "#FFFFFF",
                theme_color: "#001464",
                display: "minimal-ui",
                icon: "static/icons/icon.png"
            }
        },
        {
            resolve: "gatsby-plugin-sitemap"
        },
        {
            resolve: "gatsby-plugin-google-tagmanager",
            options: {
                id: "GTM-MRM8KCP",

                // Include GTM in development.
                // Defaults to false meaning GTM will only be loaded in production.
                includeInDevelopment: true,

                // datalayer to be set before GTM is loaded
                // should be an object or a function that is executed in the browser
                // Defaults to null
                defaultDataLayer: {
                    platform: "gatsby"
                },

                // Specify optional GTM environment details.
                // gtmAuth: "YOUR_GOOGLE_TAGMANAGER_ENVIRONMENT_AUTH_STRING",
                gtmPreview: "Mysite React Preview",
                // dataLayerName: "YOUR_DATA_LAYER_NAME",
            },
        },
        {
            resolve: "gatsby-plugin-nprogress",
            options: {
                color: "#001464",
                showSpinner: false
            }
        },
        {
            resolve: "gatsby-source-wordpress",
            options: {
                baseUrl: "mysite.com",
                protocol: "https",
                hostingWPCOM: false,
                useACF: false,
                concurrentRequests: 10,
                verboseOutput: true,
                excludedRoutes: [
                    "/*/*/comments",
                ]
            }
        },
        {
            resolve: "gatsby-plugin-offline"
        },
        {
            resolve: "gatsby-plugin-sass"
        },
        {
            resolve: "gatsby-plugin-netlify-cms"
        },
        {
            resolve: "gatsby-plugin-svgr"
        }
    ]
</code>```

Here's the graphQL fragment I'm using for pretty much all the concerned images :

```<code>fragment basicFluid on File {
    childImageSharp {
        fluid(maxWidth: 1600) {
            ...GatsbyImageSharpFluid_withWebp
        }
    }
}
</code>```

On the page, I query the image as such :

```<code>query IndexImages {
    TimesSquare: file(relativePath: { eq: "assets/images/bg/home_time_square_bg.png" }) {
        ...basicFluid
    }
}
</code>```

And finally my package.json dependencies :

```<code>"dependencies": {
    "@babel/runtime": "7.0.0-beta.55",
    "@svgr/webpack": "^4.3.0",
    "gatsby": "^2.0.48",
    "gatsby-cli": "^2.4.6",
    "gatsby-image": "^2.0.20",
    "gatsby-paginate": "^1.0.16",
    "gatsby-plugin-catch-links": "^2.0.8",
    "gatsby-plugin-google-fonts": "^0.0.4",
    "gatsby-plugin-google-tagmanager": "^2.1.2",
    "gatsby-plugin-manifest": "^2.0.9",
    "gatsby-plugin-netlify": "^2.0.4",
    "gatsby-plugin-netlify-cms": "^3.0.8",
    "gatsby-plugin-nprogress": "^2.0.6",
    "gatsby-plugin-offline": "^2.0.14",
    "gatsby-plugin-page-transitions": "^1.0.7",
    "gatsby-plugin-react-helmet": "^3.0.2",
    "gatsby-plugin-sass": "^2.0.4",
    "gatsby-plugin-sharp": "^2.0.15",
    "gatsby-plugin-sitemap": "^2.0.2",
    "gatsby-plugin-svgr": "^2.0.2",
    "gatsby-remark-autolink-headers": "^2.0.11",
    "gatsby-remark-images": "^3.0.3",
    "gatsby-source-filesystem": "^2.0.7",
    "gatsby-source-stripe": "^1.2.1",
    "gatsby-source-wordpress": "^2.0.93",
    "gatsby-transformer-remark": "^2.1.12",
    "gatsby-transformer-sharp": "^2.1.8",
    "graphql": "^0.13.2",
    "hashmap": "^2.3.0",
    "i18n-react": "^0.7.0",
    "mobx": "^5.6.0",
    "netlify-cms": "^2.8.0",
    "netlify-identity-widget": "^1.4.14",
    "node-sass": "^4.9.3",
    "opentracing": "^0.14.3",
    "react": "^16.6.3",
    "react-countup": "^4.1.3",
    "react-dom": "^16.6.3",
    "react-helmet": "^5.2.0",
    "react-hubspot-form": "^1.3.7",
    "react-lazy-load": "^3.0.13",
    "react-lazyload": "^2.3.0",
    "react-md": "^1.5.0",
    "react-modal": "^3.8.1",
    "react-responsive-carousel": "^3.1.47",
    "react-scroll": "^1.7.11",
    "react-sticky": "^6.0.3",
    "react-swipeable-views": "^0.13.0",
    "react-swipeable-views-core": "^0.13.0",
    "typeface-roboto": "^0.0.54",
    "utf8": "^3.0.0",
    "yarn": "^1.9.4"
},
</code>```

Thanks for your help !

答:
I'm not sure but I have the similar problem.
My solution is remove srcSetWebp from query. I don't know why, but It just works.

Before:

```<code>query {
    allImageSharp {
      edges {
        node {
          fluid(maxWidth: 110) {
            aspectRatio
            originalName
            sizes
            src
            srcSet
            srcWebp
            srcSetWebp
            tracedSVG
          }
        }
      }
    }
  }
</code>```

After:

```<code>query {
    allImageSharp {
      edges {
        node {
          fluid(maxWidth: 110) {
            aspectRatio
            originalName
            sizes
            src
            srcSet
            srcWebp
            tracedSVG
          }
        }
      }
    }
  }
</code>```

Hope you can find someway for your solution.

Body:
I just changed my computer at work. Up until today, on my old PC that ran Windows 8, and when developing my Gatsby site on local, everything was fine. Since the switch (I'm now on W10) alkl my images with transparency have now lost their transparent layer and are black instead. Before-after Example

This happens only on local ; the site has two hosting instances, staging on AWS, prod on Netlify, and they're both okay. Also, the image appears fine when I open it in a new tab ; the black happens only when viewing the site in full. It happens on all browsers though.

I haven't changed the gatsby-configs so I really don't know if the problem is caused by Windows, or Gatsby, or the browsers, or... Although my guess is it's with gatsby-image or gatsby-transformer-remark, because other PNGs called with a simple import don't have this problem.

I've tried updating my libwebp library on Windows but couldn't find a version higher than 0.19

Here are my plugins from gatsby-config.js :

plugins: [{
            resolve: "gatsby-source-filesystem",
            options: {
                name: "src",
                path: `${__dirname}/src/`
            }
        }, {
            resolve: "gatsby-source-filesystem",
            options: {
                name: "dsp",
                path: `${__dirname}/src/pages/dsp/`
            }
        },
        {
            resolve: "gatsby-transformer-remark",
            options: {
                plugins: [{
                    resolve: "gatsby-remark-images",
                    options: {
                        maxWidth: 1200,
                        withWebp: true
                    },
                }, ],
            },
        },
        {
            resolve: "gatsby-plugin-catch-links"
        },
        {
            resolve: "gatsby-transformer-sharp"
        },
        {
            resolve: "gatsby-plugin-sharp"
        },
        {
            resolve: "gatsby-plugin-react-helmet"
        },
        {
            resolve: "gatsby-plugin-manifest",
            options: {
                name: "Mysite",
                short_name: "Mysite",
                start_url: "/",
                background_color: "#FFFFFF",
                theme_color: "#001464",
                display: "minimal-ui",
                icon: "static/icons/icon.png"
            }
        },
        {
            resolve: "gatsby-plugin-sitemap"
        },
        {
            resolve: "gatsby-plugin-google-tagmanager",
            options: {
                id: "GTM-MRM8KCP",

                // Include GTM in development.
                // Defaults to false meaning GTM will only be loaded in production.
                includeInDevelopment: true,

                // datalayer to be set before GTM is loaded
                // should be an object or a function that is executed in the browser
                // Defaults to null
                defaultDataLayer: {
                    platform: "gatsby"
                },

                // Specify optional GTM environment details.
                // gtmAuth: "YOUR_GOOGLE_TAGMANAGER_ENVIRONMENT_AUTH_STRING",
                gtmPreview: "Mysite React Preview",
                // dataLayerName: "YOUR_DATA_LAYER_NAME",
            },
        },
        {
            resolve: "gatsby-plugin-nprogress",
            options: {
                color: "#001464",
                showSpinner: false
            }
        },
        {
            resolve: "gatsby-source-wordpress",
            options: {
                baseUrl: "mysite.com",
                protocol: "https",
                hostingWPCOM: false,
                useACF: false,
                concurrentRequests: 10,
                verboseOutput: true,
                excludedRoutes: [
                    "/*/*/comments",
                ]
            }
        },
        {
            resolve: "gatsby-plugin-offline"
        },
        {
            resolve: "gatsby-plugin-sass"
        },
        {
            resolve: "gatsby-plugin-netlify-cms"
        },
        {
            resolve: "gatsby-plugin-svgr"
        }
    ]

Here's the graphQL fragment I'm using for pretty much all the concerned images :

fragment basicFluid on File {
    childImageSharp {
        fluid(maxWidth: 1600) {
            ...GatsbyImageSharpFluid_withWebp
        }
    }
}

On the page, I query the image as such :

query IndexImages {
    TimesSquare: file(relativePath: { eq: "assets/images/bg/home_time_square_bg.png" }) {
        ...basicFluid
    }
}

And finally my package.json dependencies :

"dependencies": {
    "@babel/runtime": "7.0.0-beta.55",
    "@svgr/webpack": "^4.3.0",
    "gatsby": "^2.0.48",
    "gatsby-cli": "^2.4.6",
    "gatsby-image": "^2.0.20",
    "gatsby-paginate": "^1.0.16",
    "gatsby-plugin-catch-links": "^2.0.8",
    "gatsby-plugin-google-fonts": "^0.0.4",
    "gatsby-plugin-google-tagmanager": "^2.1.2",
    "gatsby-plugin-manifest": "^2.0.9",
    "gatsby-plugin-netlify": "^2.0.4",
    "gatsby-plugin-netlify-cms": "^3.0.8",
    "gatsby-plugin-nprogress": "^2.0.6",
    "gatsby-plugin-offline": "^2.0.14",
    "gatsby-plugin-page-transitions": "^1.0.7",
    "gatsby-plugin-react-helmet": "^3.0.2",
    "gatsby-plugin-sass": "^2.0.4",
    "gatsby-plugin-sharp": "^2.0.15",
    "gatsby-plugin-sitemap": "^2.0.2",
    "gatsby-plugin-svgr": "^2.0.2",
    "gatsby-remark-autolink-headers": "^2.0.11",
    "gatsby-remark-images": "^3.0.3",
    "gatsby-source-filesystem": "^2.0.7",
    "gatsby-source-stripe": "^1.2.1",
    "gatsby-source-wordpress": "^2.0.93",
    "gatsby-transformer-remark": "^2.1.12",
    "gatsby-transformer-sharp": "^2.1.8",
    "graphql": "^0.13.2",
    "hashmap": "^2.3.0",
    "i18n-react": "^0.7.0",
    "mobx": "^5.6.0",
    "netlify-cms": "^2.8.0",
    "netlify-identity-widget": "^1.4.14",
    "node-sass": "^4.9.3",
    "opentracing": "^0.14.3",
    "react": "^16.6.3",
    "react-countup": "^4.1.3",
    "react-dom": "^16.6.3",
    "react-helmet": "^5.2.0",
    "react-hubspot-form": "^1.3.7",
    "react-lazy-load": "^3.0.13",
    "react-lazyload": "^2.3.0",
    "react-md": "^1.5.0",
    "react-modal": "^3.8.1",
    "react-responsive-carousel": "^3.1.47",
    "react-scroll": "^1.7.11",
    "react-sticky": "^6.0.3",
    "react-swipeable-views": "^0.13.0",
    "react-swipeable-views-core": "^0.13.0",
    "typeface-roboto": "^0.0.54",
    "utf8": "^3.0.0",
    "yarn": "^1.9.4"
},

Thanks for your help !

Body:
I'm not sure but I have the similar problem.
My solution is remove srcSetWebp from query. I don't know why, but It just works.

Before:

query {
    allImageSharp {
      edges {
        node {
          fluid(maxWidth: 110) {
            aspectRatio
            originalName
            sizes
            src
            srcSet
            srcWebp
            srcSetWebp
            tracedSVG
          }
        }
      }
    }
  }

After:

query {
    allImageSharp {
      edges {
        node {
          fluid(maxWidth: 110) {
            aspectRatio
            originalName
            sizes
            src
            srcSet
            srcWebp
            tracedSVG
          }
        }
      }
    }
  }

Hope you can find someway for your solution.


问:
what's the largest number float type can hold?
I'm new to programming and have recently come up with this simple question .
float type has 32 bits in which 8 bits are for the whole number part (the mantissa).
so my question is can float type hold numbers bigger than 255.9999 ?

and I would also appreciate if someone told me why this code is behaving unexpectedly. Is it a related issue?

```<code>int main(){
float a=123456789.1;
printf("%lf",a);
return 0;
}
</code>```

for which the output is :

```<code>123456792.000000
</code>```

答:
what's the largest number [the] float type can hold?

The C Standard defines:

```<code>FLT_MAX
</code>```

Include <float.h> to have it be #defined.

Body:
I'm new to programming and have recently come up with this simple question .
float type has 32 bits in which 8 bits are for the whole number part (the mantissa).
so my question is can float type hold numbers bigger than 255.9999 ?

and I would also appreciate if someone told me why this code is behaving unexpectedly. Is it a related issue?

int main(){
float a=123456789.1;
printf("%lf",a);
return 0;
}

for which the output is :

123456792.000000

Body:
what's the largest number [the] float type can hold?

The C Standard defines:

FLT_MAX

Include <float.h> to have it be #defined.


问:
Terraform AWS - The requested configuration is currently not supported (status code: 400)
I have just getting started with terraform using aws services.

I just created a new user IAM user and given it AdministrativeAccess

Copied down the Access Key and Secret and pasted it in terraform instance.tf file under provider "aws" {}

Ran the command: terraform init and it worked fine.

Ran the command: terraform apply but in the end it gives me following error:

aws_instance.example: Creating...

Error: Error launching source instance: Unsupported: The requested
  configuration is currently not supported. Please check the
  documentation for supported configurations.   status code: 400, request
  id: cf85fdcf-432e-23d3-1233-790cfb2aa33fs

on instance.tf line 7, in resource "aws_instance" "example":    7:
  resource "aws_instance" "example" {

Here is my terraform code:

```<code>provider "aws" {
  access_key = "ACCESS_KEY"
  secret_key = "SECRET_KEY"
  region     = "us-east-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0b9bd0b532ebcf4c9"
  instance_type = "t2.micro"
}
</code>```

Any help would be appreciatable,

Cheers :)

答: The best options are to check your AMI and the region. This is not a terraform issue. Its AWS AMI or REGION problem.</p>

Body:
I have just getting started with terraform using aws services.

I just created a new user IAM user and given it AdministrativeAccess

Copied down the Access Key and Secret and pasted it in terraform instance.tf file under provider "aws" {}

Ran the command: terraform init and it worked fine.

Ran the command: terraform apply but in the end it gives me following error:

aws_instance.example: Creating...

Error: Error launching source instance: Unsupported: The requested
  configuration is currently not supported. Please check the
  documentation for supported configurations.   status code: 400, request
  id: cf85fdcf-432e-23d3-1233-790cfb2aa33fs

on instance.tf line 7, in resource "aws_instance" "example":    7:
  resource "aws_instance" "example" {

Here is my terraform code:

provider "aws" {
  access_key = "ACCESS_KEY"
  secret_key = "SECRET_KEY"
  region     = "us-east-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0b9bd0b532ebcf4c9"
  instance_type = "t2.micro"
}

Any help would be appreciatable,

Cheers :)


问:
Prevent options popup closing without user sets an option
I have options.html and options.js, where user should set required option for an extension works properly, and click on save. Setted option is saved in storage and gotten later by background.js.

Further i have welcome.html, which loads immediately after successful installation. It has an iframe with options.html.

How can i prevent closing welcome.html without user sets any option?

答:
Use window.onbeforeunload.

welcome.html:

```<code><script src="welcome.js"></script>
<iframe src="options.html"></iframe>
</code>```

welcome.js:

```<code>window.onbeforeunload = () => '';
</code>```

Body:
Use window.onbeforeunload.

welcome.html:

<script src="welcome.js"></script>
<iframe src="options.html"></iframe>

welcome.js:

window.onbeforeunload = () => '';


问:
Mozmill UI automation and cookies
I recently used the Mozmill addon/tool do some UI automation. This has worked really well so far, except when I'm trying to set and then read some cookies. When I use Mozmill to set cookies, I don't seem to get the traditional javascript cookie behavior, i.e. I can set document.cookie as often as I want, but I always get the last value set when I read from the cookie object. Here is an example:

```<code>controller.window.document.cookie = "foo=bar";
controller.window.document.cookie = "me=too";
controller.window.alert("Cookie: " + controller.window.document.cookie); //"Cookie: me=too"
</code>```

Perhaps I don't understand how cookies work in javascript or perhaps they don't work the way I assume inside Mozmill. Mozmill documentation and google searches didn't yield any good answers. Thanks in advance for any help.

答:
I would try looking at Selenium.

Its designed for cross browser UI testing and is a more mature project. Mozmill is currently being used to make sure that firefox itself (and other applications based on mozilla) are working properly.

Title: Mozmill UI automation and cookies

Body:
I recently used the Mozmill addon/tool do some UI automation. This has worked really well so far, except when I'm trying to set and then read some cookies. When I use Mozmill to set cookies, I don't seem to get the traditional javascript cookie behavior, i.e. I can set document.cookie as often as I want, but I always get the last value set when I read from the cookie object. Here is an example:

controller.window.document.cookie = "foo=bar";
controller.window.document.cookie = "me=too";
controller.window.alert("Cookie: " + controller.window.document.cookie); //"Cookie: me=too"

Perhaps I don't understand how cookies work in javascript or perhaps they don't work the way I assume inside Mozmill. Mozmill documentation and google searches didn't yield any good answers. Thanks in advance for any help.

ContentLicense: CC BY-SA 3.0


问:
How to change the branching point in Git?
Suppose I have the following structure in my git repo:

```<code>          C'---D'---E'---F'    (dev)
        /
A---B---C---D---E---F       (master)
</code>```

I would like to pull C' into the master branch and change the branching point to C', i.e., I want to turn the above into

```<code>              D'---E'---F'     (dev)
             /
A---B---C---C'---D---E---F  (master)
</code>```

I believe I should use a combination of cherry-picking and rebasing, but I am confused about how to do so exactly.  Which sequence of operations should I perform?

Suggestion after comments for a clearer schema (since same-letter commits in the original were in fact unnecessary)

```<code>          G---H---I---J   (dev)
         /
A---B---C---D---E---F     (master)
</code>```

with the associated expected result :

```<code>              H---I---J    (dev)
             /
A---B---C---G---D---E---F  (master)
</code>```

答:
You just need to rebase master onto G:

```<code>git checkout master
git rebase <id-of-G>
</code>```

That will rewrite all the commits found in master which aren't found in G on top of G. There's no need for cherry-picking. Your dev branch will be unchanged.

Body:
Suppose I have the following structure in my git repo:

          C'---D'---E'---F'    (dev)
        /
A---B---C---D---E---F       (master)

I would like to pull C' into the master branch and change the branching point to C', i.e., I want to turn the above into

              D'---E'---F'     (dev)
             /
A---B---C---C'---D---E---F  (master)

I believe I should use a combination of cherry-picking and rebasing, but I am confused about how to do so exactly.  Which sequence of operations should I perform?

Suggestion after comments for a clearer schema (since same-letter commits in the original were in fact unnecessary)

          G---H---I---J   (dev)
         /
A---B---C---D---E---F     (master)

with the associated expected result :

              H---I---J    (dev)
             /
A---B---C---G---D---E---F  (master)

Body:
You just need to rebase master onto G:

git checkout master
git rebase <id-of-G>

That will rewrite all the commits found in master which aren't found in G on top of G. There's no need for cherry-picking. Your dev branch will be unchanged.


问:
Return the table_name and partition_name whose count have a value of 0
I'm trying to writing a query that return the table_name and partition_name whose count of that partition have a value of 0.

I've got the below query that return the SELECT COUNT() of the tables and its partition:

```<code>SELECT 'SELECT COUNT(*) FROM ' || TABLE_NAME || ' PARTITION (' || PARTITION_NAME || ');'
FROM user_tab_partitions
ORDER BY table_name;
</code>```

These are some of the SELECT that return:

```<code>SELECT COUNT(*) FROM A5109713 PARTITION (PT5109713_201210);
SELECT COUNT(*) FROM A5109713 PARTITION (PT5109713_201104);
SELECT COUNT(*) FROM A5109713 PARTITION (PT5109713_201301);
</code>```

The last one it's the only that return data:

```<code>COUNT(*) |
2430276  |
</code>```

What I need is a query that return the table_name and partition_name of those who has no data. Something like this:

```<code>TABLE_NAME | PARTITION_NAME
A5109713   | PT5109713_201210
A5109713   | PT5109713_201104
</code>```

答:
I would a procedure like this:

```<code>DECLARE
    r INTEGER;
    cur sys_refcursor;
BEGIN
    FOR aPart IN (SELECT TABLE_NAME, PARTITION_NAME FROM USER_TAB_PARTITIONS ORDER BY TABLE_NAME, PARTITION_POSITION) LOOP
        OPEN cur FOR 'SELECT ROWNUM FROM '||aPart.TABLE_NAME||' PARTITION ('||aPart.PARTITION_NAME||') WHERE ROWNUM <= 1';
        FETCH cur INTO r;
        IF cur%NOTFOUND THEN
            DBMS_OUTPUT.PUT_LINE(aPart.TABLE_NAME||CHR(9)||aPart.PARTITION_NAME);
        end if;
        close cur;
    END LOOP;
END;
</code>```

I would not rely on NUM_ROWS at view USER_TAB_PARTITIONS because the reliability of the information it contains depends on the freshness of your statistics.

I use SELECT ROWNUM FROM ... WHERE ROWNUM <= 1; instead of COUNT(*) for performance reason. Actually you are not interested in the total number of rows, you just like to know whether they are greater than 0.

In worst case COUNT(*) runs a FULL-TABLE Scan which is much slower than reading only the first record.

Body:
I'm trying to writing a query that return the table_name and partition_name whose count of that partition have a value of 0.

I've got the below query that return the SELECT COUNT() of the tables and its partition:

SELECT 'SELECT COUNT(*) FROM ' || TABLE_NAME || ' PARTITION (' || PARTITION_NAME || ');'
FROM user_tab_partitions
ORDER BY table_name;

These are some of the SELECT that return:

SELECT COUNT(*) FROM A5109713 PARTITION (PT5109713_201210);
SELECT COUNT(*) FROM A5109713 PARTITION (PT5109713_201104);
SELECT COUNT(*) FROM A5109713 PARTITION (PT5109713_201301);

The last one it's the only that return data:

COUNT(*) |
2430276  |

What I need is a query that return the table_name and partition_name of those who has no data. Something like this:

TABLE_NAME | PARTITION_NAME
A5109713   | PT5109713_201210
A5109713   | PT5109713_201104

Body:
I would a procedure like this:

DECLARE
    r INTEGER;
    cur sys_refcursor;
BEGIN
    FOR aPart IN (SELECT TABLE_NAME, PARTITION_NAME FROM USER_TAB_PARTITIONS ORDER BY TABLE_NAME, PARTITION_POSITION) LOOP
        OPEN cur FOR 'SELECT ROWNUM FROM '||aPart.TABLE_NAME||' PARTITION ('||aPart.PARTITION_NAME||') WHERE ROWNUM <= 1';
        FETCH cur INTO r;
        IF cur%NOTFOUND THEN
            DBMS_OUTPUT.PUT_LINE(aPart.TABLE_NAME||CHR(9)||aPart.PARTITION_NAME);
        end if;
        close cur;
    END LOOP;
END;

I would not rely on NUM_ROWS at view USER_TAB_PARTITIONS because the reliability of the information it contains depends on the freshness of your statistics.

I use SELECT ROWNUM FROM ... WHERE ROWNUM <= 1; instead of COUNT(*) for performance reason. Actually you are not interested in the total number of rows, you just like to know whether they are greater than 0.

In worst case COUNT(*) runs a FULL-TABLE Scan which is much slower than reading only the first record.


问:
Perl angle brackets in regex substitution
I have encountered the following code:

```<code>my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;
</code>```

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

```<code>$string =~ s/(\d+)/$1\./g;
</code>```

What do angle brackets mean?

答:
In Perl, you can use any delimiters you like, so the following are all equivalent:

```<code>s/PATTERN/REPLACEMENT/
s=PATTERN=REPLACEMENT=
s,PATTERN,REPLACEMENT,
</code>```

This is possible in sed, too.

But, in Perl, some of the delimiters are special because they come in pairs, e.g.

```<code>s{PATTERN}{REPLACEMENT}
s<PATTERN><REPLACEMENT>
s(PATTERN)[REPLACEMENT]
</code>```

etc.

Body:
I have encountered the following code:

my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

$string =~ s/(\d+)/$1\./g;

What do angle brackets mean?

Body:
In Perl, you can use any delimiters you like, so the following are all equivalent:

s/PATTERN/REPLACEMENT/
s=PATTERN=REPLACEMENT=
s,PATTERN,REPLACEMENT,

This is possible in sed, too.

But, in Perl, some of the delimiters are special because they come in pairs, e.g.

s{PATTERN}{REPLACEMENT}
s<PATTERN><REPLACEMENT>
s(PATTERN)[REPLACEMENT]

etc.


问:
What does AVG(x) - 1 give us?
I've been studying for the query that my colleague coded it. For each product, we counted the prices in a specific time period to see how the price has changed for each product. Let's say that this is "number_of_price".

And then, my colleague took the average of "number_of_price", and then he formulated it like this:

AVG(number_of_price) - 1 AS mean_price_updates

But to be frank, I have no clue why this equation gives us the mean_price_updates.

Any idea?

答:
If you have 3 different prices in a time period, you have 2 updates, i think it's as simple as that.

This and the fact that AVG(number_of_price - 1) = AVG(number_of_price) - 1

Title: What does AVG(x) - 1 give us?


问:
Fixed buttons between AppBar and SingleChildScrollView (Flutter)
I would like to include buttons between AppBar and ListView. In the example below, the buttons scroll along with the text. I tried to include the SingleChildScrollView within a Column, but was unsuccessful.

I read that the Column widget does not support scrolling. I already searched a lot, but I didn't find an example similar to what I need.

Can someone help me?

```<code>  @override
  Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text('A Idade do Lobo'),
          elevation: 0.0,
          backgroundColor: COLOR_MAIN,
        ),
        body: NotificationListener(
          onNotification: (notif) {
            if (_hasScroll) {
              if (notif is ScrollEndNotification && scrollOn) {
                Timer(Duration(seconds: 1), () {
                  _scroll();
                  setState(() {
                    _controlButton();
                  });
                });
              }
            }
            return true;
          },
          child: SingleChildScrollView(
            controller: _scrollController,
            child: new Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                new Center(
                  child: new Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      new RaisedButton(
                        onPressed: _showScrollPickerDialog,
                        child: Text('Rolagem ${_scrollSpeed}'),
                      ),
                      new RaisedButton(
                        onPressed: _showTomPickerDialog,
                        child: Text('TOM ${_tom}'),
                      ),
                    ],
                  ),
                ),
                new Flexible(
                  fit: FlexFit.loose,
                  child: new ListView.builder(
                    shrinkWrap: true,
                    itemCount: _songDetails.length,
                    itemBuilder: (context, index) {
                      return new Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Padding(
                            padding: new EdgeInsets.all(5.0),
                            child: new RichText(
                              text: TextSpan(children: [
                                new TextSpan(
                                  text: '${_songDetails[index].line}',
                                  style: _getStyle(
                                    _songDetails[index].type,
                                  ),
                                ),
                              ]),
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        floatingActionButton: _controlButton(),
      );
    }
  }

</code>```

答:
You can use bottom properly of AppBar to achieve desire UI.

Following example clear your idea.

```<code>import 'package:flutter/material.dart';

class DeleteWidget extends StatefulWidget {
  const DeleteWidget({Key key}) : super(key: key);

  @override
  _DeleteWidgetState createState() => _DeleteWidgetState();
}

class _DeleteWidgetState extends State<DeleteWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("your title"),
          bottom: PreferredSize(
            preferredSize: Size(MediaQuery.of(context).size.width, 40),
            child: Center(
              child: new Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new RaisedButton(
                    onPressed: () {},
                    child: Text('Rolagem '),
                  ),
                  new RaisedButton(
                    onPressed: () {},
                    child: Text('TOM '),
                  ),
                ],
              ),
            ),
          ),
        ),
        body: Container(
          child: ListView.builder(
            itemBuilder: (context, int index) {
              return Text(index.toString());
            },
            itemCount: 100,
          ),
        ));
  }
}
</code>```

Body:
I would like to include buttons between AppBar and ListView. In the example below, the buttons scroll along with the text. I tried to include the SingleChildScrollView within a Column, but was unsuccessful.

I read that the Column widget does not support scrolling. I already searched a lot, but I didn't find an example similar to what I need.

Can someone help me?

  @override
  Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text('A Idade do Lobo'),
          elevation: 0.0,
          backgroundColor: COLOR_MAIN,
        ),
        body: NotificationListener(
          onNotification: (notif) {
            if (_hasScroll) {
              if (notif is ScrollEndNotification && scrollOn) {
                Timer(Duration(seconds: 1), () {
                  _scroll();
                  setState(() {
                    _controlButton();
                  });
                });
              }
            }
            return true;
          },
          child: SingleChildScrollView(
            controller: _scrollController,
            child: new Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                new Center(
                  child: new Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      new RaisedButton(
                        onPressed: _showScrollPickerDialog,
                        child: Text('Rolagem ${_scrollSpeed}'),
                      ),
                      new RaisedButton(
                        onPressed: _showTomPickerDialog,
                        child: Text('TOM ${_tom}'),
                      ),
                    ],
                  ),
                ),
                new Flexible(
                  fit: FlexFit.loose,
                  child: new ListView.builder(
                    shrinkWrap: true,
                    itemCount: _songDetails.length,
                    itemBuilder: (context, index) {
                      return new Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Padding(
                            padding: new EdgeInsets.all(5.0),
                            child: new RichText(
                              text: TextSpan(children: [
                                new TextSpan(
                                  text: '${_songDetails[index].line}',
                                  style: _getStyle(
                                    _songDetails[index].type,
                                  ),
                                ),
                              ]),
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        floatingActionButton: _controlButton(),
      );
    }
  }

Body:
You can use bottom properly of AppBar to achieve desire UI.

Following example clear your idea.

import 'package:flutter/material.dart';

class DeleteWidget extends StatefulWidget {
  const DeleteWidget({Key key}) : super(key: key);

  @override
  _DeleteWidgetState createState() => _DeleteWidgetState();
}

class _DeleteWidgetState extends State<DeleteWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("your title"),
          bottom: PreferredSize(
            preferredSize: Size(MediaQuery.of(context).size.width, 40),
            child: Center(
              child: new Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new RaisedButton(
                    onPressed: () {},
                    child: Text('Rolagem '),
                  ),
                  new RaisedButton(
                    onPressed: () {},
                    child: Text('TOM '),
                  ),
                ],
              ),
            ),
          ),
        ),
        body: Container(
          child: ListView.builder(
            itemBuilder: (context, int index) {
              return Text(index.toString());
            },
            itemCount: 100,
          ),
        ));
  }
}


问:
Entity framework re-inserts the foreign key reference values
I have the below entity structure.

```<code>public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class University
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class Subject
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        //A student may have to go many universities for the courses in the curriculum
        public class UniversityStudentAssociation
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public Student Student { get; set; }
            public University University { get; set; }
            public IEnumerable<Subject> Subjects { get; set; }
        }
</code>```

My entity data is as below. The student should decide which course(s) he needs to opt for and from which university.

The student Roger needs to take two courses from MIT and 2 courses from Harvard

This data is obtained from the client side as view models and converted to entities.

```<code>
var universityStudentAssociations = new List<UniversityStudentAssociation>
            {
                //New association
                new UniversityStudentAssociation
                {
                    Id=0,
                    //Already existing student
                    Student=new Student
                    {
                        Id=1,
                        Name="Roger"
                    },
                    //Existing university
                    University= new University
                    {
                        Id=1,
                        Name="MIT"
                    },
                    Subjects=new List<Subject>
                    {
                        //Existing Subject
                        new Subject
                        {
                            Id=1,
                            Name="Psychology"
                        },
                        //Existing Subject
                        new Subject
                        {
                            Id=2,
                            Name="Sociology"
                        }
                    }
                },
                //New association
                new UniversityStudentAssociation
                {
                    Id=0,
                    //Already existing student
                    Student=new Student
                    {
                        Id=1,
                        Name="Roger"
                    },
                    //Existing university
                    University= new University
                    {
                        Id=2,
                        Name="Harvard"
                    },
                    Subjects=new List<Subject>
                    {
                        //Existing Subject
                        new Subject
                        {
                            Id=3,
                            Name="Physics"
                        },
                        //Existing Subject
                        new Subject
                        {
                            Id=4,
                            Name="Mathematics"
                        }
                    }
                }
            };
</code>```

Entity framework while inserting the data, assumes the student (Roger) object, the University (MIT and Harvard) and Subjects (Physics,Mathematics,Psychology and Sociology) needs to be re-inserted. But, it needs to just refer to Student, University and Subjects tables as foreign keys in UniversityStudentAssociation table.

Hence, every time I try to insert the above data, Entity framework inserts 2 new students, 2 new Universities and 4
Subjects into the respective tables.

Please help me on how I can tell Entity framework to refer to existing data and not insert new data.

I know the data seems bizzare. But, my business logic is analogous (I couldn't have used that here) to the entity class structure I have mentioned above.

Thanks in advance.

答:
It is important to understand that your DbSet<...> classes in your DbContext represent the tables in your database.

The class in DbSet<...> represents one row within the table, and the relations between this row and rows from other tables.

In entity framework, the non-virtual properties represent the columnts of the tables, the virtual properties represent the relations between the tables (one-to-many, many-to-many)

It seems to me that there is a one-to-many relation between Student and UniversityStudentAssociation: every Student has zero or more UniversityStudentAssociations and every UniversityStudentAssociation belongs to exactly one Student, namely the Student that property Student refers to.

Similarly there seems to be a one-to-many relation between University and UniversityStudentAssociation: every University has zero or more UniversityStudentAssociations and every UniversityStudentAssociation belongs to exactly one University, namely the University that property University refers to.

Because of these two one-to-many relations, there is in fact a many-to-many relation between Student and University: every Student attends zero or more Universities, and every University teaches zero or more Students. Table UniversityStudentAssociation serves as an (extended) junction table to implement this many-to-many relation (See many-to-many relations)

If you follow the entity framework conventions your classes will be as follows.

```<code>public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    // every Student has zero or more UniversityStudentAssociations (one-to-many)
    public virtual ICollection<UniversityStudentAssociation> UniversityStudentAssociations {get; set;}
}

public class University
{
    public int Id { get; set; }
    public string Name { get; set; }

    // every University has zero or more UniversityStudentAssociations (one-to-many)
    public virtual ICollection<UniversityStudentAssociation> UniversityStudentAssociations {get; set;}
}
</code>```

Class UniversityStudentAssociation:

```<code>public class UniversityStudentAssociation
{
    public int Id { get; set; }
    public string Name { get; set; }

    // Every UniversityStudentAssociation belongs to exactly one Student, using foreign key
    public int StudentId {get; set; }
    public virtual Student Student { get; set; }

    // Every UniversityStudentAssociation belongs to exactly one University, using foreign key
    public int UniversityId {get; set; }
    public virtual University University { get; set; }

    // Every UniversityStudentAssociation has zero or more Subjects (one-to-many)
    public IEnumerable<Subject> Subjects { get; set; }
}
</code>```

And finally the Subject class:

```<code>public class Subject
{
    public int Id { get; set; }
    public string Name { get; set; }

    // every Subject belongs to exactly one UniversityStudentAssociation using foreign key
    public int UniversityStudentAssociationId {get; set; }
    public virtual UniversityStudentAssociation UniversityStudentAssociation {get; set;}
}
</code>```

Note that I added virtual members to inform entity framework about the relations between the tables. Because one side has a virtual ICollection<...> and the other side a single virtual element, entity framework knows that this is a one-to-many relationship.

Another important change is the addition of the foreign keys. If you omit them, entity framework will add them anyway. I added them, because the non-virtual properties of the class represents the columns in your table. I want to make clear what columns the table has. Besides sometimes it enables you to do certain joins if you can't use the virtual collections.

Usually if you want to "get items with (some or all of) their subitems, you can use the Collections:

Give me (some properties of) all students that live in New York and (some properties of) all the universities they attend

```<code>var result = dbContext.Students
    .Where(student => student.City == "New York)
    .Select(student => new
    {
        // Select only the Student properties that you plan to use:
        Id = student.Id,
        Name = student.Name,
        ...

        Universities = student.UniversityStudentAssociations
            .Select(association => new
        {
            // I only want the university properties
            // again: only the properties that you plan to use:
            UniversityId = association.University.Id,
            UniversityName = association.University.Name,
    }
</code>```

Body:
I have the below entity structure.

public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class University
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class Subject
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        //A student may have to go many universities for the courses in the curriculum
        public class UniversityStudentAssociation
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public Student Student { get; set; }
            public University University { get; set; }
            public IEnumerable<Subject> Subjects { get; set; }
        }

My entity data is as below. The student should decide which course(s) he needs to opt for and from which university.

The student Roger needs to take two courses from MIT and 2 courses from Harvard

This data is obtained from the client side as view models and converted to entities.

var universityStudentAssociations = new List<UniversityStudentAssociation>
            {
                //New association
                new UniversityStudentAssociation
                {
                    Id=0,
                    //Already existing student
                    Student=new Student
                    {
                        Id=1,
                        Name="Roger"
                    },
                    //Existing university
                    University= new University
                    {
                        Id=1,
                        Name="MIT"
                    },
                    Subjects=new List<Subject>
                    {
                        //Existing Subject
                        new Subject
                        {
                            Id=1,
                            Name="Psychology"
                        },
                        //Existing Subject
                        new Subject
                        {
                            Id=2,
                            Name="Sociology"
                        }
                    }
                },
                //New association
                new UniversityStudentAssociation
                {
                    Id=0,
                    //Already existing student
                    Student=new Student
                    {
                        Id=1,
                        Name="Roger"
                    },
                    //Existing university
                    University= new University
                    {
                        Id=2,
                        Name="Harvard"
                    },
                    Subjects=new List<Subject>
                    {
                        //Existing Subject
                        new Subject
                        {
                            Id=3,
                            Name="Physics"
                        },
                        //Existing Subject
                        new Subject
                        {
                            Id=4,
                            Name="Mathematics"
                        }
                    }
                }
            };

Entity framework while inserting the data, assumes the student (Roger) object, the University (MIT and Harvard) and Subjects (Physics,Mathematics,Psychology and Sociology) needs to be re-inserted. But, it needs to just refer to Student, University and Subjects tables as foreign keys in UniversityStudentAssociation table.

Hence, every time I try to insert the above data, Entity framework inserts 2 new students, 2 new Universities and 4
Subjects into the respective tables.

Please help me on how I can tell Entity framework to refer to existing data and not insert new data.

I know the data seems bizzare. But, my business logic is analogous (I couldn't have used that here) to the entity class structure I have mentioned above.

Thanks in advance.

Body:
It is important to understand that your DbSet<...> classes in your DbContext represent the tables in your database.

The class in DbSet<...> represents one row within the table, and the relations between this row and rows from other tables.

In entity framework, the non-virtual properties represent the columnts of the tables, the virtual properties represent the relations between the tables (one-to-many, many-to-many)

It seems to me that there is a one-to-many relation between Student and UniversityStudentAssociation: every Student has zero or more UniversityStudentAssociations and every UniversityStudentAssociation belongs to exactly one Student, namely the Student that property Student refers to.

Similarly there seems to be a one-to-many relation between University and UniversityStudentAssociation: every University has zero or more UniversityStudentAssociations and every UniversityStudentAssociation belongs to exactly one University, namely the University that property University refers to.

Because of these two one-to-many relations, there is in fact a many-to-many relation between Student and University: every Student attends zero or more Universities, and every University teaches zero or more Students. Table UniversityStudentAssociation serves as an (extended) junction table to implement this many-to-many relation (See many-to-many relations)

If you follow the entity framework conventions your classes will be as follows.

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    // every Student has zero or more UniversityStudentAssociations (one-to-many)
    public virtual ICollection<UniversityStudentAssociation> UniversityStudentAssociations {get; set;}
}

public class University
{
    public int Id { get; set; }
    public string Name { get; set; }

    // every University has zero or more UniversityStudentAssociations (one-to-many)
    public virtual ICollection<UniversityStudentAssociation> UniversityStudentAssociations {get; set;}
}

Class UniversityStudentAssociation:

public class UniversityStudentAssociation
{
    public int Id { get; set; }
    public string Name { get; set; }

    // Every UniversityStudentAssociation belongs to exactly one Student, using foreign key
    public int StudentId {get; set; }
    public virtual Student Student { get; set; }

    // Every UniversityStudentAssociation belongs to exactly one University, using foreign key
    public int UniversityId {get; set; }
    public virtual University University { get; set; }

    // Every UniversityStudentAssociation has zero or more Subjects (one-to-many)
    public IEnumerable<Subject> Subjects { get; set; }
}

And finally the Subject class:

public class Subject
{
    public int Id { get; set; }
    public string Name { get; set; }

    // every Subject belongs to exactly one UniversityStudentAssociation using foreign key
    public int UniversityStudentAssociationId {get; set; }
    public virtual UniversityStudentAssociation UniversityStudentAssociation {get; set;}
}

Note that I added virtual members to inform entity framework about the relations between the tables. Because one side has a virtual ICollection<...> and the other side a single virtual element, entity framework knows that this is a one-to-many relationship.

Another important change is the addition of the foreign keys. If you omit them, entity framework will add them anyway. I added them, because the non-virtual properties of the class represents the columns in your table. I want to make clear what columns the table has. Besides sometimes it enables you to do certain joins if you can't use the virtual collections.

Usually if you want to "get items with (some or all of) their subitems, you can use the Collections:

Give me (some properties of) all students that live in New York and (some properties of) all the universities they attend

var result = dbContext.Students
    .Where(student => student.City == "New York)
    .Select(student => new
    {
        // Select only the Student properties that you plan to use:
        Id = student.Id,
        Name = student.Name,
        ...

        Universities = student.UniversityStudentAssociations
            .Select(association => new
        {
            // I only want the university properties
            // again: only the properties that you plan to use:
            UniversityId = association.University.Id,
            UniversityName = association.University.Name,
    }


问:
Passing data from router to server file node.js express
I am trying to build a web app using node.js and I would like to pass data from my router, file which processes a form, to my server file that will actually emit events to the other user connected.

router.js

```<code>module.exports=function(app) {
    const express = require('express');
    const User = require("./public/classes/User");
    const router = express.Router();
    const {check, validationResult} = require('express-validator');
    const {matchedData} = require('express-validator/filter');

    var userlist = new Array();

    router.get('/', (req, res) => {
        res.render('index', {
            data: {},
            errors: {}
        })
    });

    router.post('/enter', [
        check('username')
            .isLength({min: 1})
            .withMessage('Username is required').trim()   //implement personalized check
    ], (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.render('index', {
                data: req.body,
                errors: errors.mapped()
            })
        }
        const data = matchedData(req)

    });
    return router;

    //MOVE TO SUPPORT
    function find(name) {
        return 1;
    }

}
</code>```

server.js

```<code>const express = require('express');
const layout = require('express-layout');
const app = express();
var server = require('http').createServer(app);
var io=require('socket.io')(server);
const routes = require('./router')(app);
const bodyParser = require('body-parser');
var fs = require("fs");

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

const middleware = [
    layout(),
    express.static(path.join(__dirname, 'public')),
    bodyParser.urlencoded(),

];

app.use(middleware);

app.use('/', routes);

app.use((req, res, next) => {
    res.status(404).send("Sorry can't find that!");
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

io.on('connect', onConnect);

function onConnect(socket) {
    var contents = fs.readFileSync("./public/rooms.json");
    let rooms = JSON.parse(contents);
    socket.emit('parse',rooms);
    socket.on('join',function (name, room) {
        console.log(name+" "+ room);
        socket.join(room);
        socket.user=name;
        socket.room=room;
    })
}

server.listen(3000, () => {
    console.log(`App running at http://localhost:3000`);
});
</code>```

I would like to pass the processed data of my post request to the server, how do I do that?

答:
If all you want to do is send the data processed in the route handler to the client(s), you don't need to send it to the server file first, you can emit from the route handler. To do that, you would have to store a reference to the socket object so you can use it in other places apart from the socket connection call-back function.

Update your onConnect function in server.js to store a reference to socket in app locals:

```<code>function onConnect(socket) {
  // Store the socket object in app locals
  app.locals.socket = socket;
  var contents = fs.readFileSync("./public/rooms.json");
  let rooms = JSON.parse(contents);
  socket.emit('parse',rooms);
  socket.on('join',function (name, room) {
      console.log(name+" "+ room);
      socket.join(room);
      socket.user=name;
      socket.room=room;
  })
}
</code>```

And in the route handler, you can emit the data whenever you want:

```<code>router.post('/enter', [
  check('username')
    .isLength({ min: 1 })
    .withMessage('Username is required').trim()   //implement personalized check
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.render('index', {
      data: req.body,
      errors: errors.mapped()
    })
  }
  const data = matchedData(req)
  // Emit your data here:
  app.locals.socket.emit("data", data);
});
</code>```

Body:
I am trying to build a web app using node.js and I would like to pass data from my router, file which processes a form, to my server file that will actually emit events to the other user connected.

router.js

module.exports=function(app) {
    const express = require('express');
    const User = require("./public/classes/User");
    const router = express.Router();
    const {check, validationResult} = require('express-validator');
    const {matchedData} = require('express-validator/filter');

    var userlist = new Array();

    router.get('/', (req, res) => {
        res.render('index', {
            data: {},
            errors: {}
        })
    });

    router.post('/enter', [
        check('username')
            .isLength({min: 1})
            .withMessage('Username is required').trim()   //implement personalized check
    ], (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.render('index', {
                data: req.body,
                errors: errors.mapped()
            })
        }
        const data = matchedData(req)

    });
    return router;

    //MOVE TO SUPPORT
    function find(name) {
        return 1;
    }

}

server.js

const express = require('express');
const layout = require('express-layout');
const app = express();
var server = require('http').createServer(app);
var io=require('socket.io')(server);
const routes = require('./router')(app);
const bodyParser = require('body-parser');
var fs = require("fs");

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

const middleware = [
    layout(),
    express.static(path.join(__dirname, 'public')),
    bodyParser.urlencoded(),

];

app.use(middleware);

app.use('/', routes);

app.use((req, res, next) => {
    res.status(404).send("Sorry can't find that!");
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

io.on('connect', onConnect);

function onConnect(socket) {
    var contents = fs.readFileSync("./public/rooms.json");
    let rooms = JSON.parse(contents);
    socket.emit('parse',rooms);
    socket.on('join',function (name, room) {
        console.log(name+" "+ room);
        socket.join(room);
        socket.user=name;
        socket.room=room;
    })
}

server.listen(3000, () => {
    console.log(`App running at http://localhost:3000`);
});

I would like to pass the processed data of my post request to the server, how do I do that?

Body:
If all you want to do is send the data processed in the route handler to the client(s), you don't need to send it to the server file first, you can emit from the route handler. To do that, you would have to store a reference to the socket object so you can use it in other places apart from the socket connection call-back function.

Update your onConnect function in server.js to store a reference to socket in app locals:

function onConnect(socket) {
  // Store the socket object in app locals
  app.locals.socket = socket;
  var contents = fs.readFileSync("./public/rooms.json");
  let rooms = JSON.parse(contents);
  socket.emit('parse',rooms);
  socket.on('join',function (name, room) {
      console.log(name+" "+ room);
      socket.join(room);
      socket.user=name;
      socket.room=room;
  })
}

And in the route handler, you can emit the data whenever you want:

router.post('/enter', [
  check('username')
    .isLength({ min: 1 })
    .withMessage('Username is required').trim()   //implement personalized check
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.render('index', {
      data: req.body,
      errors: errors.mapped()
    })
  }
  const data = matchedData(req)
  // Emit your data here:
  app.locals.socket.emit("data", data);
});


问:
Python "list order"
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]
</code>```

get this

```<code>1,7,U1
1.5,8,U1
2,5.5,U1
</code>```

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

```<code>l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)
</code>```

get

```<code>4.24231542,U1
3.41424819,U1
2.17214734,U1
</code>```

Thanks

Title: Python "list order"

Body:
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

get this

1,7,U1
1.5,8,U1
2,5.5,U1

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)

get

4.24231542,U1
3.41424819,U1
2.17214734,U1

Thanks

Body:
>>> print k
[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1']]
>>> for a, b, c in k:
...     print '%s,%s,%s' % (a, b, c)
...
1,7,U1
1.5,8,U1
2,5.5,U1

Now, you try! (for the second one)


问:
Set Global variable from Controller function
i am working on CI project where i am stuck somewhere. I try to set a global variable value from function and access this value from other function. Here is my code..

```<code>class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
        echo $this->gData;
    }

}
</code>```

userinfo is my actual page which opens in browser, and fetch data of user from user table. On my view i have button on click of button i am calling ajax which call the getuserinfo method of controller, it suppose to return the username which i set in userinfo method but unfortunetly it not working. Any will plz guide me where i am making mistake. (I am not allowed to use session)

答:
try this: You have to set user name first in global variable:

```<code>class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
       $this->userinfo();
        echo $this->gData;
    }

}
</code>```

OR you can use constructor: I am not familiar with CI

```<code>class Example extends CI_Controller {

        public $gData = "";

         Public function __construct() {
         parent::__construct();
         $this->userinfo();
      }

        public function userinfo() {
            //Here i fetch user infomration from database table
            $userName = "userName";
            $this->gData = $userName;
        }

        public function getuserinfo() {

            echo $this->gData;
        }

    }
</code>```

Edited Answer:
Based on comment the solution can be like this if you don't want to use session :

1. Create a view using the Query of userinfo.

2. Create a model using that view and write your logic.
I think this may help you . It will not slow down your result.

Body:
i am working on CI project where i am stuck somewhere. I try to set a global variable value from function and access this value from other function. Here is my code..

class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
        echo $this->gData;
    }

}

userinfo is my actual page which opens in browser, and fetch data of user from user table. On my view i have button on click of button i am calling ajax which call the getuserinfo method of controller, it suppose to return the username which i set in userinfo method but unfortunetly it not working. Any will plz guide me where i am making mistake. (I am not allowed to use session)

Body:
try this: You have to set user name first in global variable:

class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
       $this->userinfo();
        echo $this->gData;
    }

}

OR you can use constructor: I am not familiar with CI

class Example extends CI_Controller {

        public $gData = "";

         Public function __construct() {
         parent::__construct();
         $this->userinfo();
      }

        public function userinfo() {
            //Here i fetch user infomration from database table
            $userName = "userName";
            $this->gData = $userName;
        }

        public function getuserinfo() {

            echo $this->gData;
        }

    }

Edited Answer:
Based on comment the solution can be like this if you don't want to use session :

1. Create a view using the Query of userinfo.

2. Create a model using that view and write your logic.
I think this may help you . It will not slow down your result.


问:
SQL - How to join query results in same line
I have an application that save the working time based on machine, operation, operator and reference.

My query returns the data like this:

u_reference | u_user | u_operation | u_machine | price | u_action | Start             | Work time
P-2000-9429 | John   | F3X         | 144       | 60    | PLAY     |2019-11-08 09:40:53| 00:00:00
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-08 18:00:45| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-09 07:13:23| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-09 12:19:21| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-11 07:09:50| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | STOP     |2019-11-11 11:03:26| 17:19:21
```

```select  u_daily_work_alb.u_reference, u_daily_work_alb.u_user, u_daily_work_alb.u_operation, u_machines_alb.u_design as u_machine, u_machines_alb.epcusto as price, u_daily_work_alb.u_action, u_daily_work_alb.u_created_at as Start, u_daily_work_alb.u_work_time as Work_time
from u_daily_work_alb
  inner join u_machines_alb on u_machines_alb.id = u_daily_work_alb.u_machineId
where u_daily_work_alb.bostamp = 'ALB472248D84210CFA9FE30'
  and u_daily_work_alb.u_reference = 'p-2000-9429'
order by u_daily_work_alb.id asc
```

<p>bostamp column is like an id.</p>

<p>Now what I need is a result like this:</p>

<pre class="lang-none prettyprint-override"><code>u_reference | u_user | u_operation | u_machine | price | Start             |END                | Work time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-08 09:40:53|2019-11-08 18:00:45| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-09 07:13:23|2019-11-09 12:19:21| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-11 07:09:50|2019-11-11 11:03:26| calculate time
</code>```

I think the column u_action is important because we know that after a play we have a pause or stop. After a pause we have a replay or stop and after a replay we have a pause or stop.

How can I do that?

答:
I have (possibly incorrectly) assumed T-sql. However I think a similar approach could be used in most databases.

I have set up an example below using the tables you provided - you would need to change this to match your underlying query.

basically I get all the start events and assign them a row number based on their event time - i then left join them to all the end events based on that row number.

if it is possible to skip an end event (a start with no pause or stop) - this will cause you problems.

```<code>CREATE TABLE dbo.SampleData (
u_reference varchar(100),
u_user varchar(100),
u_operation varchar(100),
u_machine varchar(100),
price varchar(100),
u_action varchar(100),
[Start] datetime,
[Work time] datetime
)

INSERT INTO dbo.SampleData (u_reference, u_user, u_operation, u_machine, price, u_action, [Start], [Work time])
VALUES  ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'PLAY'     ,'2019-11-08 09:40:53', '00:00:00'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'PAUSE'    ,'2019-11-08 18:00:45', '08:19:52'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'REPLAY'   ,'2019-11-09 07:13:23', '08:19:52'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'PAUSE'    ,'2019-11-09 12:19:21', '13:25:49'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'REPLAY'   ,'2019-11-11 07:09:50', '13:25:49'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'STOP'     ,'2019-11-11 11:03:26', '17:19:21')

SELECT  A.u_reference,
        A.u_user,
        A.u_operation,
        A.u_machine,
        A.price,
        A.[Start],
        B.[Start] AS EndTime,
         CONVERT(varchar, DATEADD(second, (DATEDIFF(SECOND,A.[Start],B.[Start])), 0), 108) AS WorkingTime

FROM (
        -- All Start/Restart Events
        SELECT *,
               ROW_NUMBER() OVER (ORDER BY [Start]) as Rownum
        FROM dbo.SampleData
        WHERE u_action  IN ('PLAY','REPLAY')

) A
LEFT JOIN (
        -- All End Events
        SELECT *,
               ROW_NUMBER() OVER (ORDER BY [Start]) as Rownum
        FROM dbo.SampleData
        WHERE u_action  IN ('PAUSE','STOP')

) B
ON A.Rownum = B.Rownum
ORDER BY A.[Start]
</code>```

The Output is;

Body:
I have an application that save the working time based on machine, operation, operator and reference.

My query returns the data like this:

u_reference | u_user | u_operation | u_machine | price | u_action | Start             | Work time
P-2000-9429 | John   | F3X         | 144       | 60    | PLAY     |2019-11-08 09:40:53| 00:00:00
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-08 18:00:45| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-09 07:13:23| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-09 12:19:21| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-11 07:09:50| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | STOP     |2019-11-11 11:03:26| 17:19:21

select  u_daily_work_alb.u_reference, u_daily_work_alb.u_user, u_daily_work_alb.u_operation, u_machines_alb.u_design as u_machine, u_machines_alb.epcusto as price, u_daily_work_alb.u_action, u_daily_work_alb.u_created_at as Start, u_daily_work_alb.u_work_time as Work_time
from u_daily_work_alb
  inner join u_machines_alb on u_machines_alb.id = u_daily_work_alb.u_machineId
where u_daily_work_alb.bostamp = 'ALB472248D84210CFA9FE30'
  and u_daily_work_alb.u_reference = 'p-2000-9429'
order by u_daily_work_alb.id asc

bostamp column is like an id.

Now what I need is a result like this:

u_reference | u_user | u_operation | u_machine | price | Start             |END                | Work time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-08 09:40:53|2019-11-08 18:00:45| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-09 07:13:23|2019-11-09 12:19:21| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-11 07:09:50|2019-11-11 11:03:26| calculate time

I think the column u_action is important because we know that after a play we have a pause or stop. After a pause we have a replay or stop and after a replay we have a pause or stop.

How can I do that?

Body:
I have (possibly incorrectly) assumed T-sql. However I think a similar approach could be used in most databases.

I have set up an example below using the tables you provided - you would need to change this to match your underlying query.

basically I get all the start events and assign them a row number based on their event time - i then left join them to all the end events based on that row number.

if it is possible to skip an end event (a start with no pause or stop) - this will cause you problems.

CREATE TABLE dbo.SampleData (
u_reference varchar(100),
u_user varchar(100),
u_operation varchar(100),
u_machine varchar(100),
price varchar(100),
u_action varchar(100),
[Start] datetime,
[Work time] datetime
)

INSERT INTO dbo.SampleData (u_reference, u_user, u_operation, u_machine, price, u_action, [Start], [Work time])
VALUES  ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'PLAY'     ,'2019-11-08 09:40:53', '00:00:00'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'PAUSE'    ,'2019-11-08 18:00:45', '08:19:52'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'REPLAY'   ,'2019-11-09 07:13:23', '08:19:52'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'PAUSE'    ,'2019-11-09 12:19:21', '13:25:49'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'REPLAY'   ,'2019-11-11 07:09:50', '13:25:49'),
        ('P-2000-9429' , 'John'   , 'F3X'         , '144'       , '60'    , 'STOP'     ,'2019-11-11 11:03:26', '17:19:21')

SELECT  A.u_reference,
        A.u_user,
        A.u_operation,
        A.u_machine,
        A.price,
        A.[Start],
        B.[Start] AS EndTime,
         CONVERT(varchar, DATEADD(second, (DATEDIFF(SECOND,A.[Start],B.[Start])), 0), 108) AS WorkingTime

FROM (
        -- All Start/Restart Events
        SELECT *,
               ROW_NUMBER() OVER (ORDER BY [Start]) as Rownum
        FROM dbo.SampleData
        WHERE u_action  IN ('PLAY','REPLAY')

) A
LEFT JOIN (
        -- All End Events
        SELECT *,
               ROW_NUMBER() OVER (ORDER BY [Start]) as Rownum
        FROM dbo.SampleData
        WHERE u_action  IN ('PAUSE','STOP')

) B
ON A.Rownum = B.Rownum
ORDER BY A.[Start]

The Output is;


问:
multiple file uploader in reactjs form
I have a list of items in database and I want to render it in table and will add input type=file for each to upload file for each item
on handle click i want to send item name to handle function but i couldn't,
to make it clearer i want send value item.documentname to file1MadChangedHandler function, every time i click</p>

```<code>   {this.props.Organizations.listDocs
    ?
    <div>
       { this.props.Organizations.listDocs.map(function (item, index) {
          return(
                <tr key={item.documentName}>
                    {item.documentName}
                        <td>
                        <td>
                            <input component="input"
                                type="file"
                                id="{item.documentName}"
                                onChange={(event,item)=> {
                                    this.file1MadChangedHandler(event,item) }}
                                // onChange={this.file1MadChangedHandler}
                                ref={fileInput => ref.fileInput = fileInput}
                                style={{ display: "None" }}
                            />
                            <button onClick={(item) => this.fileInput.click(item.documentName)}>Pick File</button>
                        </td>
                </tr>
            )

        })
                }
    </div>
    :
    ""
}
</code>```

答:
fileHandler = (event) => {
  if(event.target.value !== ""){
    event.preventDefault();
    this.form.validateFields(event.target.name);

    const fileObject = event.target.id;
    const name = event.target.files[0].name;
    const size = ((event.target.files[0].size)/1000000).toFixed(2);
    let img = [...this.state.img];

    img.push({inptid: fileObject,
      name: name,
      size: size});

    const fetchImage = img.map(e => e['inptid'])
    .map((e, i, final) => final.lastIndexOf(e) === i && i)
    .filter(e => img[e]).map(e => img[e]);

    this.setState({ img: fetchImage});

  }else{
    return false;
  }
}```
</div>
</div>
</p>

<p><strong>NOTE our render section and forms are comming dynamically via loop for your cases it might be different</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><input
  type="file"
  className="form-control none"
  ref={formfields.title}
  name={formfields.title}
  id={formfields._id}
  key={formfields._id}
  index={formindex}
  onChange={this.fileHandler}
  required
/>

{
  img.filter(data => data.inptid === formfields._id)
  .map((data,index) =>{
    return(
      (data.inptid === formfields._id)
      ?
      <p>{data.name}   - <i><b>{data.size} MB </b></i></p>
      :
      ''
    )
  })
}</code>```

Title: multiple file uploader in reactjs form

Body:
I have a list of items in database and I want to render it in table and will add input type=file for each to upload file for each item
on handle click i want to send item name to handle function but i couldn't,
to make it clearer i want send value item.documentname to file1MadChangedHandler function, every time i click

   {this.props.Organizations.listDocs
    ?

       { this.props.Organizations.listDocs.map(function (item, index) {
          return(

                    {item.documentName}

                            <input component="input"
                                type="file"
                                id="{item.documentName}"
                                onChange={(event,item)=> {
                                    this.file1MadChangedHandler(event,item) }}
                                // onChange={this.file1MadChangedHandler}
                                ref={fileInput => ref.fileInput = fileInput}
                                style={{ display: "None" }}
                            />
                            <button onClick={(item) => this.fileInput.click(item.documentName)}>Pick File</button>

            )

        })
                }

    :
    ""
}

Body:
fileHandler = (event) => {
  if(event.target.value !== ""){
    event.preventDefault();
    this.form.validateFields(event.target.name);

    const fileObject = event.target.id;
    const name = event.target.files[0].name;
    const size = ((event.target.files[0].size)/1000000).toFixed(2);
    let img = [...this.state.img];

    img.push({inptid: fileObject,
      name: name,
      size: size});

    const fetchImage = img.map(e => e['inptid'])
    .map((e, i, final) => final.lastIndexOf(e) === i && i)
    .filter(e => img[e]).map(e => img[e]);

    this.setState({ img: fetchImage});

  }else{
    return false;
  }
}

NOTE our render section and forms are comming dynamically via loop for your cases it might be different

<input
  type="file"
  className="form-control none"
  ref={formfields.title}
  name={formfields.title}
  id={formfields._id}
  key={formfields._id}
  index={formindex}
  onChange={this.fileHandler}
  required
/>

{
  img.filter(data => data.inptid === formfields._id)
  .map((data,index) =>{
    return(
      (data.inptid === formfields._id)
      ?
      <p>{data.name}   - <i><b>{data.size} MB </b></i></p>
      :
      ''
    )
  })
}


Title: What does AVG(x) - 1 give us?

Body:
I've been studying for the query that my colleague coded it. For each product, we counted the prices in a specific time period to see how the price has changed for each product. Let's say that this is "number_of_price".

And then, my colleague took the average of "number_of_price", and then he formulated it like this:

AVG(number_of_price) - 1 AS mean_price_updates

But to be frank, I have no clue why this equation gives us the mean_price_updates.

Any idea?

Body:
I suppose that the price change counts include the original price. E.g.:

+------+------------+-------+
| item | date       | price |
+------+------------+-------+
|    1 | 2020-01-01 | 10.00 |
|    1 | 2020-01-05 | 12.00 |
|    1 | 2020-01-16 | 13.00 |
|    2 | 2020-01-01 | 20.00 |
|    2 | 2020-01-27 | 23.00 |
+------+------------+-------+

That is three prices for product #1 and two prices for product #2. The avarage is 2.5 prices per product. Minus 1 is 1.5 price changes per product (two for #1 and 1 for #2).