问:
Importing custom module into jupyter notebook
Yes, I know this is a recurrent question but I still couldn't find a convincing answer. I even read at https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html but could not find out how to solve the problem:

I'm running python 3.6 project that includes jupyter (ipython) notebooks. I want the notebook to import a custom local helpers.py package that I will probably use also later in other sources.

The project structure is similar to:

```<code>my_project/
│
├── my_project/
│   ├── notebooks/
│       └── a_notebook.ipynb
│   ├── __init__.py     # suppose to make package `my_project` importable
│   └── helpers.py
│
├── tests/
│   └── helpers_tests.py
│
├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
└── setup.py
</code>```

When importing helpers in the notebook I get the error:

```<code>----> 4 import helpers

ModuleNotFoundError: No module named 'helpers'
</code>```

I also tried from my_project import helpers and I get the same error ModuleNotFoundError: No module named 'my_project'

I finally (and temporarily) used the usual trick:

```<code>import sys
sys.path.append('..')
import helpers
</code>```

But it looks awful and I'm still looking for a better solution

答:
Try the following line:

from my_project.helpers import what_you_need

This line should also work:

import my_project.helpers

Body:
Yes, I know this is a recurrent question but I still couldn't find a convincing answer. I even read at https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html but could not find out how to solve the problem:

I'm running python 3.6 project that includes jupyter (ipython) notebooks. I want the notebook to import a custom local helpers.py package that I will probably use also later in other sources.

The project structure is similar to:

my_project/
│
├── my_project/
│   ├── notebooks/
│       └── a_notebook.ipynb
│   ├── __init__.py     # suppose to make package `my_project` importable
│   └── helpers.py
│
├── tests/
│   └── helpers_tests.py
│
├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
└── setup.py

When importing helpers in the notebook I get the error:

----> 4 import helpers

ModuleNotFoundError: No module named 'helpers'

I also tried from my_project import helpers and I get the same error ModuleNotFoundError: No module named 'my_project'

I finally (and temporarily) used the usual trick:

import sys
sys.path.append('..')
import helpers

But it looks awful and I'm still looking for a better solution


来源: stackexchange

问:
.createElement() with HTML
My aim is to add HTML using .createElement() of wp.element but it outputs as text, example:

```<code>wp.element.createElement(
        Meta,
        {
            className: 'TEST',
            title: 'TEST',
            initialOpen: true,
        },
        'Here is html: <input type="text">'
);
</code>```

What am I missing here?

答:
You should use wp.element.render with the created element if you want that in the DOM correctly.

Please see the example in the documentation:

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

<script>
function Greeting( props ) {
    return wp.element.createElement( 'span', null,
        'Hello ' + props.toWhom + '!'
    );
}

wp.element.render(
    wp.element.createElement( Greeting, { toWhom: 'World' } ),
    document.getElementById( 'greeting' )
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: .createElement() with HTML

Body:
My aim is to add HTML using .createElement() of wp.element but it outputs as text, example:

wp.element.createElement(
        Meta,
        {
            className: 'TEST',
            title: 'TEST',
            initialOpen: true,
        },
        'Here is html: <input type="text">'
);

What am I missing here?

Body:
You should use wp.element.render with the created element if you want that in the DOM correctly.

Please see the example in the documentation:

<div id="greeting"></div>

<script>
function Greeting( props ) {
    return wp.element.createElement( 'span', null,
        'Hello ' + props.toWhom + '!'
    );
}

wp.element.render(
    wp.element.createElement( Greeting, { toWhom: 'World' } ),
    document.getElementById( 'greeting' )
</script>


问:
Create table variable with exact same structure of another table
In T-SQL, I can create a table variable using syntax like

```<code>DECLARE @table AS TABLE (id INT, col VARCHAR(20))
</code>```

For now, if I want to create an exact copy of a real table in the database, I do something like this

```<code>SELECT *
FROM INFOMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MY_TABLE_NAME'
</code>```

to check the column datatype and also max length, and start to create the @table variable, naming the variable, datatype and max_length one by one which is not very effective. May I know if there is any simpler way to do it like

```<code>DECLARE @table AS TABLE = SOME_REAL_TABLE_IN_DATABASE
</code>```

Furthermore, is there any way to retrieve the column name, data type and max length of the column and use it directly in the declaration like

```<code>DECLARE @table AS TABLE (@col1_specs)
</code>```

Thank you in advance.

EDIT:
Thanks for the answers and comments, we can do that for @table_variable but only in dynamic SQL and it is not good for maintainability. However, we can do that using #temp_table.

Based on the answer by Ezlo, we can do something like this :

```<code>SELECT TABLE.* INTO #TEMP_TABLE FROM TABLE
</code>```

For more information, please refer to this answer.

Difference between temp table and table variable (stackoverflow)

Difference between temp table and table variable (dba.stackexchange)

答:
The answer for both questions is simple NO.

Although, I agree with you that T-SQL should change in this way.

In the first case, it means having a command to clone a table structure.

Of course, there is a possibility to make your own T-SQL extension by using SQLCLR.

Body:
In T-SQL, I can create a table variable using syntax like

DECLARE @table AS TABLE (id INT, col VARCHAR(20))

For now, if I want to create an exact copy of a real table in the database, I do something like this

SELECT *
FROM INFOMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MY_TABLE_NAME'

to check the column datatype and also max length, and start to create the @table variable, naming the variable, datatype and max_length one by one which is not very effective. May I know if there is any simpler way to do it like

DECLARE @table AS TABLE = SOME_REAL_TABLE_IN_DATABASE

Furthermore, is there any way to retrieve the column name, data type and max length of the column and use it directly in the declaration like

DECLARE @table AS TABLE (@col1_specs)

Thank you in advance.

EDIT:
Thanks for the answers and comments, we can do that for @table_variable but only in dynamic SQL and it is not good for maintainability. However, we can do that using #temp_table.

Based on the answer by Ezlo, we can do something like this :

SELECT TABLE.* INTO #TEMP_TABLE FROM TABLE

For more information, please refer to this answer.

Difference between temp table and table variable (stackoverflow)

Difference between temp table and table variable (dba.stackexchange)


问:
How do I loop the function callback with a random delay in phaser 3?
So my Phaser 3 game requires to call a function spawn with random delay each time between 3s to 6s.
Here is what I tried :

```<code>Enemies = this.time.addEvent({
delay:  Phaser.Math.Between(3000,6000),
loop: true,
callback: spawn,
callbackScope: this });
</code>```

But this code does not works. The delay is chosen at random only once and then that value is used throughout.

答:
You can see in your own link that there is a oneShot timer. You can use that inside the spawn function.

Now a new one-shot timer with a random delay will be created when spawn() is called. The timer then calls spawn() again...

```<code>function spawn() {
     let delay = Phaser.Math.Between(3000,6000)
     var timer = scene.time.delayedCall(delay, spawn, args, scope);
}

spawn()
</code>```

Body:
So my Phaser 3 game requires to call a function spawn with random delay each time between 3s to 6s.
Here is what I tried :

Enemies = this.time.addEvent({
delay:  Phaser.Math.Between(3000,6000),
loop: true,
callback: spawn,
callbackScope: this });

But this code does not works. The delay is chosen at random only once and then that value is used throughout.

Body:
You can see in your own link that there is a oneShot timer. You can use that inside the spawn function.

Now a new one-shot timer with a random delay will be created when spawn() is called. The timer then calls spawn() again...

function spawn() {
     let delay = Phaser.Math.Between(3000,6000)
     var timer = scene.time.delayedCall(delay, spawn, args, scope);
}

spawn()


问:
Fill vue-multiselect with router-links
I am trying to fill the vue-multiselect dropdown with <router-link> options. The usual way to specify router links to different components is declaratively in <template>, while vue-multiselect uses bind with options array. Any ideas how to go through with this?

I want to reuse vue-multiselect for navigation between components.

答:
OK, after contacting Damian, developer of vue-multiselect, I've got the answer. The idea is to use the vue-multiselect as action dispatcher: https://vue-multiselect.js.org/#sub-action-dispatcher

You add

```<code>:reset-after="true"
@select=“navigateTo"
</code>```

And in navigateTo you do this.$router.push({ path: 'xyz' }).

Title: Fill vue-multiselect with router-links

Body:
OK, after contacting Damian, developer of vue-multiselect, I've got the answer. The idea is to use the vue-multiselect as action dispatcher: https://vue-multiselect.js.org/#sub-action-dispatcher

You add

:reset-after="true"
@select=“navigateTo"

And in navigateTo you do this.$router.push({ path: 'xyz' }).


问:
Creating 2 numbers from a one #C
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

```<code>int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }
</code>```

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

答:
This works for me:</p>

```<code>int number = 12345;

string result1 = "";
string result2 = "";

string numberString = number.ToString();

for (int i = 0; i < numberString.Length; i++ )
{
    if (numberString[i] % 2 == 0)
    {
        result1 = result1 + numberString[i];
    }
    else
    {
        result2 = result2 + numberString[i];
    }
}

int evenNumbers = int.Parse(result1);
int oddNumbers = int.Parse(result2);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Creating 2 numbers from a one #C

Body:
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

Body:
This works for me:

int number = 12345;

string result1 = "";
string result2 = "";

string numberString = number.ToString();

for (int i = 0; i < numberString.Length; i++ )
{
    if (numberString[i] % 2 == 0)
    {
        result1 = result1 + numberString[i];
    }
    else
    {
        result2 = result2 + numberString[i];
    }
}

int evenNumbers = int.Parse(result1);
int oddNumbers = int.Parse(result2);


问:
TypeError cannot read property undefined - Gatsby
I'm stuck with this problem and I'm not sure what's wrong. I am new to Gatsby.

I am trying to create pages from a JSON file. I keep getting this error

TypeError: Cannot read property 'Layout' of undefined

Here's the JSON data and code:

JSON file

```<code>{
    "Header" : {
        "TopMenu" : [
            {
                "url" : "/log-in",
                "name" : "Log in",
                "target" : "_self"
            },
            {
                "url" : "/about",
                "name" : "About",
                "target" : "_self"
            }
        ],
        "MainMenu" : [
            {
                "url" : "/",
                "name" : "Home",
                "target" : "_self"
            },
            {
                "url" : "/service",
                "name" : "Service",
                "target" : "_self"
            }
        ]
    },
    "Footer" : {
        "Links" : [
            {
                "url" : "/",
                "name" : "Home",
                "target" : "_self"
            },
            {
                "url" : "/service",
                "name" : "Service",
                "target" : "_self"
            },
            {
                "url" : "/blog",
                "name" : "Blog",
                "target" : "_self"
            }
        ]
    },
    "pages" : [
        {
            "name" : "Home",
            "content" : "This is the home page.",
            "url" : "/"
        },
        {
            "name" : "About",
            "content" : "This is the about page.",
            "url" : "/about"
        },
        {
            "name" : "Service",
            "content" : "This is the service page.",
            "url" : "/service"
        },
        {
            "name" : "Blog",
            "content" : "This is the blog page.",
            "url" : "/blog"
        }
    ]
}
</code>```

gatsby-node.js

```<code>exports.createPages = ({actions}) => {
    const {createPage} = actions
    const pageData = JSON.parse(fs.readFileSync('./content/data.json', { encoding: 'utf-8' }));
    const pageTemplate = path.resolve('src/templates/page.js');

    pageData.pages.forEach(page => {
        createPage({
          path: page.url,
          component: pageTemplate,
          context: {
            Layout : {
                Header : pageData.Header,
                Footer : pageData.Footer
            },
            ...page,
          }
        });
      });
}
</code>```

src/template/page.js

```<code>import React from "react"
 const Page = props => {
    const { Layout = null, name = null, content = null, url = null } = props.PageContext;

    return (
      <React.Fragment>
        <MainLayout headerLayout={Layout.Header} footerLayout={Layout.Footer}>
            {content}
        </MainLayout>
      </React.Fragment>
    );
  };

export default Page;
</code>```

gatsby-config.js

```<code>module.exports = {
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        //icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    }
  ]
}
</code>```

EDIT:
Added the gatsby-config.js

Any help is much appreciated.

答:
You got a typo there. In src/template/page.js, it should be props.pageContext instead of props.PageContext. PageContext is undefined, hence the type error.

```<code>    const {
      Layout = null,
      name = null
      content = null,
      url = null
-   } = props.PageContext;
+   } = props.pageContext;

</code>```

Body:
I'm stuck with this problem and I'm not sure what's wrong. I am new to Gatsby.

I am trying to create pages from a JSON file. I keep getting this error

TypeError: Cannot read property 'Layout' of undefined

Here's the JSON data and code:

JSON file

{
    "Header" : {
        "TopMenu" : [
            {
                "url" : "/log-in",
                "name" : "Log in",
                "target" : "_self"
            },
            {
                "url" : "/about",
                "name" : "About",
                "target" : "_self"
            }
        ],
        "MainMenu" : [
            {
                "url" : "/",
                "name" : "Home",
                "target" : "_self"
            },
            {
                "url" : "/service",
                "name" : "Service",
                "target" : "_self"
            }
        ]
    },
    "Footer" : {
        "Links" : [
            {
                "url" : "/",
                "name" : "Home",
                "target" : "_self"
            },
            {
                "url" : "/service",
                "name" : "Service",
                "target" : "_self"
            },
            {
                "url" : "/blog",
                "name" : "Blog",
                "target" : "_self"
            }
        ]
    },
    "pages" : [
        {
            "name" : "Home",
            "content" : "This is the home page.",
            "url" : "/"
        },
        {
            "name" : "About",
            "content" : "This is the about page.",
            "url" : "/about"
        },
        {
            "name" : "Service",
            "content" : "This is the service page.",
            "url" : "/service"
        },
        {
            "name" : "Blog",
            "content" : "This is the blog page.",
            "url" : "/blog"
        }
    ]
}

gatsby-node.js

exports.createPages = ({actions}) => {
    const {createPage} = actions
    const pageData = JSON.parse(fs.readFileSync('./content/data.json', { encoding: 'utf-8' }));
    const pageTemplate = path.resolve('src/templates/page.js');

    pageData.pages.forEach(page => {
        createPage({
          path: page.url,
          component: pageTemplate,
          context: {
            Layout : {
                Header : pageData.Header,
                Footer : pageData.Footer
            },
            ...page,
          }
        });
      });
}

src/template/page.js

import React from "react"
 const Page = props => {
    const { Layout = null, name = null, content = null, url = null } = props.PageContext;

    return (
      <React.Fragment>
        <MainLayout headerLayout={Layout.Header} footerLayout={Layout.Footer}>
            {content}
        </MainLayout>
      </React.Fragment>
    );
  };

export default Page;

gatsby-config.js

module.exports = {
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        //icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    }
  ]
}

EDIT:
Added the gatsby-config.js

Any help is much appreciated.

Body:
You got a typo there. In src/template/page.js, it should be props.pageContext instead of props.PageContext. PageContext is undefined, hence the type error.

    const {
      Layout = null,
      name = null
      content = null,
      url = null
-   } = props.PageContext;
+   } = props.pageContext;


问:
How to catch the error page in a website which throw System Error /Server Error In Selenium Webdriver c# and fail in my test case Nunit
I have been trying to find ways to catch this error in my selenium webdriver c#.Is any method which will catch this error in my test case ? There is system error or Server Error but I am unable to retrieve my error and fail my test cases. All my test cases which have these error (System/Server) end with the result = "Test Passed" instead of showing of the Error.

Eg: Click to View ServerError

Eg: Click to View System Error

```<code>[Test]

    public void TestYamaha()
    {
        driver = new ChromeDriver();
        driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Login/Login.aspx");
        driver.Manage().Window.Maximize();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();

        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("manteng");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("Nic15742368");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
        Thread.Sleep(2000);
        driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Announcement_News/Announcement_News_Search.aspx");
        Thread.Sleep(2000);
        driver.FindElement(By.CssSelector(".ui-datepicker-trigger:nth-child(2)")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.CssSelector(".ui-icon-circle-triangle-w")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.LinkText("1")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
             Thread.Sleep(2000);
        driver.FindElement(By.CssSelector(".clsDataGridAltData a:nth-child(2) > img")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
        Thread.Sleep(2000);
    }
</code>```

This code shows System Error (As shown in the picture) but how I show in my test case.

答:
Use try-catch block to handle any exception and if required then you can log it in catch block. You should use any assertion library for making it pass/fail.

Note: Don't write everything into Test class.

Body:
I have been trying to find ways to catch this error in my selenium webdriver c#.Is any method which will catch this error in my test case ? There is system error or Server Error but I am unable to retrieve my error and fail my test cases. All my test cases which have these error (System/Server) end with the result = "Test Passed" instead of showing of the Error.

Eg: Click to View ServerError

Eg: Click to View System Error

[Test]

    public void TestYamaha()
    {
        driver = new ChromeDriver();
        driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Login/Login.aspx");
        driver.Manage().Window.Maximize();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();

        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("manteng");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("Nic15742368");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
        Thread.Sleep(2000);
        driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Announcement_News/Announcement_News_Search.aspx");
        Thread.Sleep(2000);
        driver.FindElement(By.CssSelector(".ui-datepicker-trigger:nth-child(2)")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.CssSelector(".ui-icon-circle-triangle-w")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.LinkText("1")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
             Thread.Sleep(2000);
        driver.FindElement(By.CssSelector(".clsDataGridAltData a:nth-child(2) > img")).Click();
        Thread.Sleep(2000);
        driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
        Thread.Sleep(2000);
    }

This code shows System Error (As shown in the picture) but how I show in my test case.


答:
Wordpress use react as you see here from your links

Element is, quite simply, an abstraction layer atop React.

That's mean you use top level of React api

https://reactjs.org/docs/react-api.html#createelement

And react can't pass you add js code like a innerHtml because it's dangerous (any script can run from text).

For example some bad guy can use this vulnerabilitys for XSS attack.

But if you need add some HTML inside of element you can use method  dangerouslySetInnerHTML

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

```<code>function createMarkup() {
  return {__html: 'First · Second'};
}

React.createElement('h1', { dangerouslySetInnerHTML: createMarkup() }, `Welcome to react world`)
</code>```

https://github.com/purescript-contrib/purescript-react/issues/53#issuecomment-164175324

Title: .createElement() with HTML

Body:
Wordpress use react as you see here from your links

Element is, quite simply, an abstraction layer atop React.

That's mean you use top level of React api

https://reactjs.org/docs/react-api.html#createelement

And react can't pass you add js code like a innerHtml because it's dangerous (any script can run from text).

For example some bad guy can use this vulnerabilitys for XSS attack.

But if you need add some HTML inside of element you can use method  dangerouslySetInnerHTML

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

React.createElement('h1', { dangerouslySetInnerHTML: createMarkup() }, `Welcome to react world`)

https://github.com/purescript-contrib/purescript-react/issues/53#issuecomment-164175324


问:
Deleting a part of a cell
Does anyone know how to delete certain values in a cell and leave the rest in the cell.

For example I have these values in one cell:

Trash

Recycle

Delete

Erase

Store

Keep

Save

I want the values from Trash to Erase gone while the three other values stay. so we have:

Store

Keep

Save

Is this even possible to achieve?

答:
You could try =Mid and =Find

Formula: =MID(A1,FIND("Erase",A1)+6,LEN(A1)-FIND("Erase",A1)+6+1)

Title: Deleting a part of a cell


问:
UserDefaults not working on didload in my project
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

```<code>class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}
</code>```

When the  user clicks login Button, the code is as below

```<code>ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}
</code>```

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

答:
I think you're probably trying to achieve this:

```<code>class User {
    static var isLoggedIn: Bool {
        get {
            return UserDefaults.standard.bool(forKey: "islogged")
        }
        set(aIsLoggedIn) {
            UserDefaults.standard.set(aIsLoggedIn, forKey: "islogged")
        }
    }
}
</code>```

The problem with your code is that you don't save the state of isLoggedIn, so at every startup the value is always false

Body:
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

When the  user clicks login Button, the code is as below

ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

Body:
I think you're probably trying to achieve this:

class User {
    static var isLoggedIn: Bool {
        get {
            return UserDefaults.standard.bool(forKey: "islogged")
        }
        set(aIsLoggedIn) {
            UserDefaults.standard.set(aIsLoggedIn, forKey: "islogged")
        }
    }
}

The problem with your code is that you don't save the state of isLoggedIn, so at every startup the value is always false


问:
How to send the element object as parameter to javascript function without ID
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

```<code><td ...... >
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXX">

<td ......
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXXX">
</code>```

Based on clicked ....> I would like to hide/show it (or to show/hide next class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

```<code>function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}
</code>```

答:
so copied Your sample and came up with this. ;)  try this out.. and
  make sure You understand what's happening here.

```<code>$(() => {
            $("body").on("click",".GridLinkRenderer", (e) => {
                e.preventDefault();
                //works on the first link.. stil misses a few check..
                //for example do we have the next td.. at all..
                console.log($(e.currentTarget).closest('td').next('td').find('.GridLinkRenderer'));
            })
        });
</code>```

Body:
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

<td ......

Based on clicked  I would like to hide/show it (or to show/hide next <a class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}

Body:
so copied Your sample and came up with this. ;)  try this out.. and
  make sure You understand what's happening here.

$(() => {
            $("body").on("click",".GridLinkRenderer", (e) => {
                e.preventDefault();
                //works on the first link.. stil misses a few check..
                //for example do we have the next td.. at all..
                console.log($(e.currentTarget).closest('td').next('td').find('.GridLinkRenderer'));
            })
        });


问:
regular expression to parse html title tag
I need to parse a lot of html files in order to know which ones contain specific text within title tag.

Let's suppose that titles are

```<code>file1.htm
<title>100 text other text</title>
file2.htm
<title>text 100 text other text</title>
file3.htm
<title>text 1000 text other text</title>
file4.htm
<title>text one hundred text other text</title>
</code>```

Following my example I need to find files name that contain 100 or one hundred, that is files 1,2 and 4.

My problem is that I don't know how to write regular expression

```<code>gci "c:\my_folder" | ? {$_.extension -eq ".htm"} |
select-string -pattern '<title>*100*</title>' |
Select-Object -Unique Path
</code>```

Please note, if this may be important for regexp, that title tag is not at the beginning of a row but in the middle.
Thanks in advance.

答:
try

```<code><title>(.*[^[:alnum:]])?(100|one hundred)([^[:alnum:]].*)?</title>
</code>```

for the pattern to match. pattern syntax is PCRE (like in perl), it can be reformulated if necessary.

best regards,

carsten

ps:
beware of the pitfalls - all the recommendations and warnings from the comments do hold; still, in your case, the regex approach seems viable (mainly because you're investigating the 'title' tag's content, there should only be a single one per file and spreading it across multiple lines would be plain silly imho).

Body:
I need to parse a lot of html files in order to know which ones contain specific text within title tag.

Let's suppose that titles are

file1.htm
<title>100 text other text</title>
file2.htm
<title>text 100 text other text</title>
file3.htm
<title>text 1000 text other text</title>
file4.htm
<title>text one hundred text other text</title>

Following my example I need to find files name that contain 100 or one hundred, that is files 1,2 and 4.

My problem is that I don't know how to write regular expression

gci "c:\my_folder" | ? {$_.extension -eq ".htm"} |
select-string -pattern '<title>*100*</title>' |
Select-Object -Unique Path

Please note, if this may be important for regexp, that title tag is not at the beginning of a row but in the middle.
Thanks in advance.

Body:
try

<title>(.*[^[:alnum:]])?(100|one hundred)([^[:alnum:]].*)?</title>

for the pattern to match. pattern syntax is PCRE (like in perl), it can be reformulated if necessary.

best regards,

carsten

ps:
beware of the pitfalls - all the recommendations and warnings from the comments do hold; still, in your case, the regex approach seems viable (mainly because you're investigating the 'title' tag's content, there should only be a single one per file and spreading it across multiple lines would be plain silly imho).


问:
Insert multiple records in Sqflite
How to insert quickly multiple records in sqflite? The standard quickly method is:

```<code>await database.insert(table, object.toMap())
</code>```

But I don't think that insert record one to one with a cycle is a good idea.
Or I can insert all list with a transaction?

答:
You can use batch in such case.

```<code>batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();
</code>```

big batches,you can use await batch.commit(noResult: true);

Title: Insert multiple records in Sqflite

Body:
How to insert quickly multiple records in sqflite? The standard quickly method is:

await database.insert(table, object.toMap())

But I don't think that insert record one to one with a cycle is a good idea.
Or I can insert all list with a transaction?

Body:
You can use batch in such case.

batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();

big batches,you can use await batch.commit(noResult: true);


问:
Compute sum of values in array using PHP
I'm trying to combine the scores of employee for my program. My sample is one employee is evaluated more than one. So basically, if employee 1 have scored of 87 and 90 the total should be 177. After computation, I need to return the result with the highest score.
Here so far my sample code (I simplified my code for this question because it is too long to post the original code):

```<code>$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

print_r($scores);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}
</code>```

The result does not return the employee with highest score and not sure which in my code is incorrect. thanks for help

do this:- https://3v4l.org/WhVaN

答:
```<code>$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    $highest_score = 0;
    $highest_employee = '';

    foreach($scores as $key => $value) {
        if ( ! isset($combined_score[$value[1]])) {
            $combined_score[$value[1]] = $value[2];
        }
        else {
            $combined_score[$value[1]] += $value[2];
        }

        if ($highest_score < $combined_score[$value[1]]) {
            $highest_score = $combined_score[$value[1]];
            $highest_employee = $value[1];  //the highest value employee
        }
    }

    return $highest_employee;
}
</code>```

Body:
I'm trying to combine the scores of employee for my program. My sample is one employee is evaluated more than one. So basically, if employee 1 have scored of 87 and 90 the total should be 177. After computation, I need to return the result with the highest score.
Here so far my sample code (I simplified my code for this question because it is too long to post the original code):

$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

print_r($scores);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}

The result does not return the employee with highest score and not sure which in my code is incorrect. thanks for help

do this:- https://3v4l.org/WhVaN


问:
How do I redirect a www url to a no-www url using nginx-ingress-controller?
I am trying to get the url www.example.com to redirect itself to example.com while preserving everything about the original request in k8s 1.11.1

I am attempting to do this using a simple Ingress, and am then using annotations to redirect it.

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/tls-acme: "true"
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/permanent-redirect: https://example.com
    nginx.ingress.kubernetes.io/ssl-redirect: "True"
  name: example-redirect
spec:
  tls:
  - hosts:
    - www.example.com
    secretName: example-tls
  rules:
  - host: www.example.com
    http:
      paths:
      - backend:
          serviceName: example
          servicePort: http
</code>```

The issue here is that I don't want to have any rules/backend. I simply want to redirect www.example.com to example.com using an Ingress, but k8s Ingresses require me to have rules. Are there any workarounds here?

答:
Actually, Ingress resource has strongly defined prerequisites for the relevant API specification. You may exclude rules: field from the general configuration, however backend: should be definitely specified, in the way that Nginx Ingress controller could route network traffic to the target endpoint in case no rules declared or matched.

Whenever you create any specific settings for Nginx Ingress controller either via Annotations or ConfigMaps, both of the options doing the same job of applying some specific configuration to the underlying nginx.conf file which resides on nginx-ingress-controller Pod. It means that Ingress controller applies server {} and location {} blocks into the corresponded Nginx web server Pod for particular host:

```<code>server {
        server_name www.example.com ;

        listen 80;

        listen [::]:80;

        set $proxy_upstream_name "-";

        listen 443  ssl http2;

        listen [::]:443  ssl http2;

        .............

        location / {

            set $namespace      "default";
            set $ingress_name   "example-redirect";
            set $service_name   "example";
            set $service_port   "http";
            set $location_path  "/";
            ......................
                   }
       }
</code>```

Therefore, I suppose that you can capture nginx.conf file, based on Ingress resource configuration and then apply it independently inside Ingress controller Pod.

I assume that you may consider also to use nginx.ingress.kubernetes.io/from-to-www-redirect: "true" annotation in order to achieve the goal in current scenario.

Body:
I am trying to get the url www.example.com to redirect itself to example.com while preserving everything about the original request in k8s 1.11.1

I am attempting to do this using a simple Ingress, and am then using annotations to redirect it.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/tls-acme: "true"
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/permanent-redirect: https://example.com
    nginx.ingress.kubernetes.io/ssl-redirect: "True"
  name: example-redirect
spec:
  tls:
  - hosts:
    - www.example.com
    secretName: example-tls
  rules:
  - host: www.example.com
    http:
      paths:
      - backend:
          serviceName: example
          servicePort: http

The issue here is that I don't want to have any rules/backend. I simply want to redirect www.example.com to example.com using an Ingress, but k8s Ingresses require me to have rules. Are there any workarounds here?

Body:
Actually, Ingress resource has strongly defined prerequisites for the relevant API specification. You may exclude rules: field from the general configuration, however backend: should be definitely specified, in the way that Nginx Ingress controller could route network traffic to the target endpoint in case no rules declared or matched.

Whenever you create any specific settings for Nginx Ingress controller either via Annotations or ConfigMaps, both of the options doing the same job of applying some specific configuration to the underlying nginx.conf file which resides on nginx-ingress-controller Pod. It means that Ingress controller applies server {} and location {} blocks into the corresponded Nginx web server Pod for particular host:

server {
        server_name www.example.com ;

        listen 80;

        listen [::]:80;

        set $proxy_upstream_name "-";

        listen 443  ssl http2;

        listen [::]:443  ssl http2;

        .............

        location / {

            set $namespace      "default";
            set $ingress_name   "example-redirect";
            set $service_name   "example";
            set $service_port   "http";
            set $location_path  "/";
            ......................
                   }
       }

Therefore, I suppose that you can capture nginx.conf file, based on Ingress resource configuration and then apply it independently inside Ingress controller Pod.

I assume that you may consider also to use nginx.ingress.kubernetes.io/from-to-www-redirect: "true" annotation in order to achieve the goal in current scenario.


问:
How can I use gzip for my angular project?
I read some article about decreasing angular project size, in those articles I founded some solution but one of them was Obscure for me and that was gzipped compression, my question is how I can use gzip for my application?

If it helps you, I'm using asp.net core as my back-end technology.

答:
You can use gzip-all

I'm currently using this version

```<code>"gzip-all": "^1.0.0"
</code>```

So my build command will be

```<code>ng build --prod && gzip-all \"dist/*.*\"
</code>```

So gzip-all will gzip every file in dist folder

Body:
You can use gzip-all

I'm currently using this version

"gzip-all": "^1.0.0"

So my build command will be

ng build --prod && gzip-all \"dist/*.*\"

So gzip-all will gzip every file in dist folder


问:
How to use historical dataset for enriching Flink DataStream
I am working on a real-time project with Flink and I need to enrich the state of each card with prior transactions for computing transactions features as below:

For each card I have a feature that counts the number of transactions in the past 24 hours. On the other hand I have 2 data sources:

First, a database table which stores the transactions of cards until the end of yesterday.

Second, the stream of today's transactions.

So the first step is to fetch the yesterday transactions of each card from database and store them in card state. Then the second step is to update this state with today’s transactions which come on stream and compute the number of transactions in the past 24 hours for them.
I tried to read the database data as a stream and connect it to the today transactions. So, to reach above goal, I used RichFlatMap function. However, because the database data was not stream inherently, the output was not correct. RichFlatMap function is in following:

```<code>transactionsHistory.connect(transactionsStream).flatMap(new
RichCoFlatMapFunction<History, Tuple2<String, Transaction>,
ExtractedFeatures>() {
    private ValueState<History> history;
    @Override
    public void open(Configuration config) throws Exception {
        this.history = getRuntimeContext().getState(new
    ValueStateDescriptor<>("card history", History.class));
    }
    //historical data
    @Override
    public void flatMap1(History history,
    Collector<ExtractedFeatures> collector) throws Exception {
        this.history.update(history);
    }
    //new transactions from stream
    @Override
    public void flatMap2(Tuple2<String, Transaction>
    transactionTuple, Collector<ExtractedFeatures> collector) throws
    Exception {
        History history = this.history.value();
        Transaction transaction = transactionTuple.f1;
        ArrayList<History> prevDayHistoryList =
        history.prevDayTransactions;

        // This function returns transactions which are in 24 hours
        //window of the current transaction and their count.
        Tuple2<ArrayList<History>, Integer> prevDayHistoryTuple =
        findHistoricalDate(prevDayHistoryList,
                transaction.transactionLocalDate);
        prevDayHistoryList = prevDayHistoryTuple.f0;
        history.prevDayTransactions = prevDayHistoryList;
        this.history.update(history);
        ExtractedFeatures ef = new ExtractedFeatures();
        ef.updateFeatures(transaction, prevDayHistoryTuple.f1);
        collector.collect(ef);
    }
});
</code>```

What is the right design pattern to achieve the above enriching requirement in a Flink streaming program?
I found the blow question on stack overflow which is similar to my question but I couldn’t solve my problem so I decided to ask for help :)

Enriching DataStream using static DataSet in Flink streaming

Any help would be really appreciated.

答:
However, because the database data was not stream inherently, the output was not correct.

It certainly is possible to enrich streaming data with information coming from a relational database. What can be tricky, though, is to somehow guarantee that the enrichment data is ingested before it is needed. In general you may need to buffer the stream to be enriched until the enrichment data has been bootstrapped/ingested. One approach that is sometimes taken, for example, is to

run the app with the stream-to-be-enriched disabled

take a savepoint once the enrichment data has been fully ingested and stored in flink state

restart the app from the savepoint with the stream-to-be-enriched enabled

In the case you describe, however, it seems like a simpler approach would work. If you only need 24 hours of historic data, then why not ignore the database of historic transactions? Just run your application until it has seen 24 hours of streaming data, after which the historic database becomes irrelevant anyway.

But if you must ingest the historic data, and you don't like the savepoint-based approach outlined above, here are a couple of other possibilities:

buffer the un-enriched events in flink state (e.g. ListState or MapState) until the historic stream has been ingested

write a custom SourceFunction that blocks the primary stream until the historic data has been ingested

For a more thorough exploration of this topic, see Bootstrapping State In Apache Flink.

Better support for this use case is planned for a future release, btw.

Body:
I am working on a real-time project with Flink and I need to enrich the state of each card with prior transactions for computing transactions features as below:

For each card I have a feature that counts the number of transactions in the past 24 hours. On the other hand I have 2 data sources:

First, a database table which stores the transactions of cards until the end of yesterday.

Second, the stream of today's transactions.

So the first step is to fetch the yesterday transactions of each card from database and store them in card state. Then the second step is to update this state with today’s transactions which come on stream and compute the number of transactions in the past 24 hours for them.
I tried to read the database data as a stream and connect it to the today transactions. So, to reach above goal, I used RichFlatMap function. However, because the database data was not stream inherently, the output was not correct. RichFlatMap function is in following:

transactionsHistory.connect(transactionsStream).flatMap(new
RichCoFlatMapFunction<History, Tuple2<String, Transaction>,
ExtractedFeatures>() {
    private ValueState<History> history;
    @Override
    public void open(Configuration config) throws Exception {
        this.history = getRuntimeContext().getState(new
    ValueStateDescriptor<>("card history", History.class));
    }
    //historical data
    @Override
    public void flatMap1(History history,
    Collector<ExtractedFeatures> collector) throws Exception {
        this.history.update(history);
    }
    //new transactions from stream
    @Override
    public void flatMap2(Tuple2<String, Transaction>
    transactionTuple, Collector<ExtractedFeatures> collector) throws
    Exception {
        History history = this.history.value();
        Transaction transaction = transactionTuple.f1;
        ArrayList<History> prevDayHistoryList =
        history.prevDayTransactions;

        // This function returns transactions which are in 24 hours
        //window of the current transaction and their count.
        Tuple2<ArrayList<History>, Integer> prevDayHistoryTuple =
        findHistoricalDate(prevDayHistoryList,
                transaction.transactionLocalDate);
        prevDayHistoryList = prevDayHistoryTuple.f0;
        history.prevDayTransactions = prevDayHistoryList;
        this.history.update(history);
        ExtractedFeatures ef = new ExtractedFeatures();
        ef.updateFeatures(transaction, prevDayHistoryTuple.f1);
        collector.collect(ef);
    }
});

What is the right design pattern to achieve the above enriching requirement in a Flink streaming program?
I found the blow question on stack overflow which is similar to my question but I couldn’t solve my problem so I decided to ask for help :)

Enriching DataStream using static DataSet in Flink streaming

Any help would be really appreciated.


答:
Object names and data types (tables, columns, etc.) can't be parameterized (can't come from variables). This means you can't do the following (which would be required to copy a table structure, for example):

```<code>DECLARE @TableName VARCHAR(50) = 'Employees'

SELECT
    T.*
FROM
    @TableName AS T
</code>```

The only workaround is to use dynamic SQL:

```<code>DECLARE @TableName VARCHAR(50) = 'Employees'

DECLARE @DynamicSQL VARCHAR(MAX) = '
    SELECT
        T.*
    FROM
        ' + QUOTENAME(@TableName) + ' AS T '

EXEC (@DynamicSQL)
</code>```

However, variables (scalar and table variables) declared outside the dynamic SQL won't be accessible inside as they lose scope:

```<code>DECLARE @VariableOutside INT = 10

DECLARE @DynamicSQL VARCHAR(MAX) = 'SELECT @VariableOutside AS ValueOfVariable'

EXEC (@DynamicSQL)
</code>```

Msg 137, Level 15, State 2, Line 1

  Must declare the scalar variable "@VariableOutside".

This means that you will have to declare your variable inside the dynamic SQL:

```<code>DECLARE @DynamicSQL VARCHAR(MAX) = 'DECLARE @VariableOutside INT = 10
                                    SELECT @VariableOutside AS ValueOfVariable'

EXEC (@DynamicSQL)
</code>```

Result:

```<code>ValueOfVariable
10
</code>```

Which brings me to my conclusion: if you want to dynamically create a copy of an existing table as a table variable, all the access of your table variable will have to be inside a dynamic SQL script, which is a huge pain and has some cons (harder to maintain and read, more prone to error, etc.).

A common approach is to work with temporary tables instead. Doing a SELECT * INTO to create them will inherit the table's data types. You can add an always false WHERE condition (like WHERE 1 = 0) if you don't want the actual rows to be inserted.

```<code>IF OBJECT_ID('tempdb..#Copy') IS NOT NULL
    DROP TABLE #Copy

SELECT
    T.*
INTO
    #Copy
FROM
    YourTable AS T
WHERE
    1 = 0
</code>```

Title: Create table variable with exact same structure of another table

Body:
In T-SQL, I can create a table variable using syntax like

DECLARE @table AS TABLE (id INT, col VARCHAR(20))

For now, if I want to create an exact copy of a real table in the database, I do something like this

SELECT *
FROM INFOMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MY_TABLE_NAME'

to check the column datatype and also max length, and start to create the @table variable, naming the variable, datatype and max_length one by one which is not very effective. May I know if there is any simpler way to do it like

DECLARE @table AS TABLE = SOME_REAL_TABLE_IN_DATABASE

Furthermore, is there any way to retrieve the column name, data type and max length of the column and use it directly in the declaration like

DECLARE @table AS TABLE (@col1_specs)

Thank you in advance.

EDIT:
Thanks for the answers and comments, we can do that for @table_variable but only in dynamic SQL and it is not good for maintainability. However, we can do that using #temp_table.

Based on the answer by Ezlo, we can do something like this :

SELECT TABLE.* INTO #TEMP_TABLE FROM TABLE

For more information, please refer to this answer.

Difference between temp table and table variable (stackoverflow)

Difference between temp table and table variable (dba.stackexchange)

Body:
Object names and data types (tables, columns, etc.) can't be parameterized (can't come from variables). This means you can't do the following (which would be required to copy a table structure, for example):

DECLARE @TableName VARCHAR(50) = 'Employees'

SELECT
    T.*
FROM
    @TableName AS T

The only workaround is to use dynamic SQL:

DECLARE @TableName VARCHAR(50) = 'Employees'

DECLARE @DynamicSQL VARCHAR(MAX) = '
    SELECT
        T.*
    FROM
        ' + QUOTENAME(@TableName) + ' AS T '

EXEC (@DynamicSQL)

However, variables (scalar and table variables) declared outside the dynamic SQL won't be accessible inside as they lose scope:

DECLARE @VariableOutside INT = 10

DECLARE @DynamicSQL VARCHAR(MAX) = 'SELECT @VariableOutside AS ValueOfVariable'

EXEC (@DynamicSQL)

Msg 137, Level 15, State 2, Line 1

  Must declare the scalar variable "@VariableOutside".

This means that you will have to declare your variable inside the dynamic SQL:

DECLARE @DynamicSQL VARCHAR(MAX) = 'DECLARE @VariableOutside INT = 10
                                    SELECT @VariableOutside AS ValueOfVariable'

EXEC (@DynamicSQL)

Result:

ValueOfVariable
10

Which brings me to my conclusion: if you want to dynamically create a copy of an existing table as a table variable, all the access of your table variable will have to be inside a dynamic SQL script, which is a huge pain and has some cons (harder to maintain and read, more prone to error, etc.).

A common approach is to work with temporary tables instead. Doing a SELECT * INTO to create them will inherit the table's data types. You can add an always false WHERE condition (like WHERE 1 = 0) if you don't want the actual rows to be inserted.

IF OBJECT_ID('tempdb..#Copy') IS NOT NULL
    DROP TABLE #Copy

SELECT
    T.*
INTO
    #Copy
FROM
    YourTable AS T
WHERE
    1 = 0


问:
Is there a way to reset counter incremented using atomic.AddUint64?
I am implementing global counters for a concurrent go application.

My use case is that the counter should be reset after x seconds and written to DB.

I have tried using mutex (I am able to reset counter using this)

Also when I increment the counter I also log something.
I have found that after the application runs for about 8-9 hours the number of lines logged and the counter value do not match (mutex version) Counter values is always less.
I have still not found the cause for this.

I am using mutex in the following manner

func (s *Metrics) AddQps() {
    s.qpsMu.Lock()
    s.qps++
    s.qpsMu.Unlock()
}

And the flushing of metrics is done as follows.

for {
    ticker := time.NewTicker(time.Duration(interval) * time.Second)
    select {
    case <-ticker.C:
       logger.Println("flushing metrics...")
    }
}
```

I had implemented the mutex part referencing
[How to create global counter in golang in highly concurrent system

Due to the above mentioned problem I am now trying counters using sync.atomic.
As I want the metric to be flushed after x seconds I wanted to reset the counter.

答:
So what is the problem to use something like this?</p>

```<code>func TestNameAtomic(t *testing.T) {
    var i int64

    atomic.AddInt64(&i, 1)
    atomic.AddInt64(&i, 1)
    atomic.AddInt64(&i, 1)
    fmt.Println(i)

    atomic.CompareAndSwapInt64(&i, i, 0)
    fmt.Println(i)
}
</code>```

Body:
I am implementing global counters for a concurrent go application.

My use case is that the counter should be reset after x seconds and written to DB.

I have tried using mutex (I am able to reset counter using this)

Also when I increment the counter I also log something.
I have found that after the application runs for about 8-9 hours the number of lines logged and the counter value do not match (mutex version) Counter values is always less.
I have still not found the cause for this.

I am using mutex in the following manner

func (s *Metrics) AddQps() {
    s.qpsMu.Lock()
    s.qps++
    s.qpsMu.Unlock()
}

And the flushing of metrics is done as follows.

for {
    ticker := time.NewTicker(time.Duration(interval) * time.Second)
    select {
    case <-ticker.C:
       logger.Println("flushing metrics...")
    }
}

I had implemented the mutex part referencing
[How to create global counter in golang in highly concurrent system

Due to the above mentioned problem I am now trying counters using sync.atomic.
As I want the metric to be flushed after x seconds I wanted to reset the counter.

Body:
So what is the problem to use something like this?

func TestNameAtomic(t *testing.T) {
    var i int64

    atomic.AddInt64(&i, 1)
    atomic.AddInt64(&i, 1)
    atomic.AddInt64(&i, 1)
    fmt.Println(i)

    atomic.CompareAndSwapInt64(&i, i, 0)
    fmt.Println(i)
}


问:
Sorting strings in reverse order with backbone.js
I'm trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

```<code>var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("title");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));
</code>```

The above code sorts the chapters from A -> Z, but how do I write a comparator that sorts it from Z -> A?

答:
If you're working with non-numerical values, there is no obvious way to do a reverse sort. Backbone makes use of the _.sortBy() and _.sortedIndex() methods from Underscore to order the models based on the comparator, and these methods automatically sort in ascending order. The naive way to do this would be to use chapters.pluck('title').reverse(), as the result of pluck will be an array. But calling reverse on some Collection methods will reverse the Collection models in place, so next time you call it, the models will be back in ascending order. You could always do something like:

```<code>var results = [],
    titles  = chapters.pluck('title');

for(var i=0, len=titles.length; i<len; i++) {
  results.push(titles[i]);
}

results.reverse();
</code>```

This would not affect the models array in your Backbone collection, as it would create a completely new results array in memory, but retain references to the original models, so calling things like save would still update the Collection state.

But that's not very elegant, and creates a lot of extra coding throughout your project any time you want to reverse the results. I think we can do better.

In order to make this work, you'll need to perform a bit of unwieldy JavaScript ninjary in your comparator method to make this work - note this is untested:

```<code>chapters.comparator = function(chapter) {
  var alphabet = '0123456789abcdefghijklmnopqrstuvwxyz',
      title = chapter.get('title').toLowerCase(),
      inverse_title = '',
      index;

  for(var i=0, len=title.length; i<len; i++) {
    index = alphabet.indexOf(title.charAt(i));

    if(index === -1) {
      inverse_title += title.charAt(i);
      continue;
    }

    inverse_title += alphabet.charAt(alphabet.length - index - 1);
  }

  return inverse_title;
};
</code>```

This concept probably needs improving to take into account symbols, etc., but essentially it inverts the comparator string in such a way that "Z" becomes "0", "Y" becomes "1", etc., which should produce the reverse sort you're after.

Body:
I'm trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("title");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));

The above code sorts the chapters from A -> Z, but how do I write a comparator that sorts it from Z -> A?

Body:
If you're working with non-numerical values, there is no obvious way to do a reverse sort. Backbone makes use of the _.sortBy() and _.sortedIndex() methods from Underscore to order the models based on the comparator, and these methods automatically sort in ascending order. The naive way to do this would be to use chapters.pluck('title').reverse(), as the result of pluck will be an array. But calling reverse on some Collection methods will reverse the Collection models in place, so next time you call it, the models will be back in ascending order. You could always do something like:

var results = [],
    titles  = chapters.pluck('title');

for(var i=0, len=titles.length; i<len; i++) {
  results.push(titles[i]);
}

results.reverse();

This would not affect the models array in your Backbone collection, as it would create a completely new results array in memory, but retain references to the original models, so calling things like save would still update the Collection state.

But that's not very elegant, and creates a lot of extra coding throughout your project any time you want to reverse the results. I think we can do better.

In order to make this work, you'll need to perform a bit of unwieldy JavaScript ninjary in your comparator method to make this work - note this is untested:

chapters.comparator = function(chapter) {
  var alphabet = '0123456789abcdefghijklmnopqrstuvwxyz',
      title = chapter.get('title').toLowerCase(),
      inverse_title = '',
      index;

  for(var i=0, len=title.length; i<len; i++) {
    index = alphabet.indexOf(title.charAt(i));

    if(index === -1) {
      inverse_title += title.charAt(i);
      continue;
    }

    inverse_title += alphabet.charAt(alphabet.length - index - 1);
  }

  return inverse_title;
};

This concept probably needs improving to take into account symbols, etc., but essentially it inverts the comparator string in such a way that "Z" becomes "0", "Y" becomes "1", etc., which should produce the reverse sort you're after.


问:
Statistical significance on matplotlib / seaborn graph?
I finished analyzing my data and want to show that they are statistically significant using the t-test_ind. However, I haven't found anything functional to show this other than what was referenced in (How does one insert statistical annotations (stars or p-values) into matplotlib / seaborn plots?):

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from statannot import add_stat_annotation

ax = sns.barplot(x=x, y=y, order=order)
add_stat_annotation(ax, data=df, x=x, y=y,
                    boxPairList=[(order[0], order[1]), (order[0], order[2])],
                    test='t-test_ind',
                    textFormat='star',
                    loc='outside')
```

Using this approach however, whenever I try to save the plot using plt.savefig() the added significancies using the add_stat_annotation are discared (matplotlib does not seem to recognize the added annotations). Using the loc='inside' option messes up my plot so it isn't really an option.

I am therefore asking if there is some simpler way to add the sigificancies directly in matplotlib / seaborn or if you can plt.savefig() with enough border / padding to include everything.

答:
It was mainly a xlabel cut off problem. So in future applications I would use the add_stat_annotation from webermarcolivier/statannot. To save your files use one of the following possibilities:

import matplotlib.pyplot as plt

plt.tight_layout() # Option 1
plt.autoscale()    # Option 2
plt.savefig('filename.png', bbox_inches = "tight") # Option 3
```

Hope this will help someone for future use.

Body:
I finished analyzing my data and want to show that they are statistically significant using the t-test_ind. However, I haven't found anything functional to show this other than what was referenced in (How does one insert statistical annotations (stars or p-values) into matplotlib / seaborn plots?):

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from statannot import add_stat_annotation

ax = sns.barplot(x=x, y=y, order=order)
add_stat_annotation(ax, data=df, x=x, y=y,
                    boxPairList=[(order[0], order[1]), (order[0], order[2])],
                    test='t-test_ind',
                    textFormat='star',
                    loc='outside')

Using this approach however, whenever I try to save the plot using plt.savefig() the added significancies using the add_stat_annotation are discared (matplotlib does not seem to recognize the added annotations). Using the loc='inside' option messes up my plot so it isn't really an option.

I am therefore asking if there is some simpler way to add the sigificancies directly in matplotlib / seaborn or if you can plt.savefig() with enough border / padding to include everything.

Body:
It was mainly a xlabel cut off problem. So in future applications I would use the add_stat_annotation from webermarcolivier/statannot. To save your files use one of the following possibilities:

import matplotlib.pyplot as plt

plt.tight_layout() # Option 1
plt.autoscale()    # Option 2
plt.savefig('filename.png', bbox_inches = "tight") # Option 3

Hope this will help someone for future use.


问:
How to get in-between attribute value of a d3 element while a transition is going on?
I am trying to build a simple svg game to catch a moving circle. There is a catchCircle, a moving preyCircle and a Catch Me button. catchCircle starts moving vertically from bottom of the screen, crosses preyCircle and gets disappeared at the top. The idea is to click the button when the preyCircle overlaps the catchCircle. In that case I just need to check if the distance of cy attributes of both the circle is less than sum of their radius.

Problem I am facing here is to get the cy attribute of catchCircle while the transition is going on. If I try to get preyCircle.attr('cy') from inside onclick event method, error is shown:
"Uncaught Error: too late; already running"

<button id="catchMe"> Catch Me </button>

```

My code is running on https://jsfiddle.net/avi5102005/uh627zt5/62/.

Can somebody guide me the way I should have approached? Thanks in advance.

答:
First add Id to your circles

```<code>const catchCircle = svg.append('circle')
    .attr('r', radius)
  .attr('cx', width / 2)
  .attr('cy', 100)
  .attr("id", "catch") //add ID
  .attr('stroke', 'red')
  .attr('stroke-width', 3)
  .attr('fill', 'none');

const preyCircle = svg.append('circle')
    .attr('r', radius)
  .attr('cx', width / 2)
  .attr('cy', height - radius)
  .attr('fill', 'red')
  .attr("id", "prey") //add ID
  .transition()
    .duration(5000)
    .delay(1000)
    .attr('cy', radius)
    .remove();
</code>```

next, on your button press do:

```<code>d3.select('#catchMe')
    .on('click', () => {
    catched = false;
     let py = d3.select("#prey").attr("cy"); // get prey's y
     let px = d3.select("#prey").attr("cx"); // get prey's x
     let pr = +d3.select("#prey").attr("r"); // get prey's radius

     let cy = d3.select("#catch").attr("cy");
     let cx = d3.select("#catch").attr("cx");
     let cr = +d3.select("#catch").attr("r");

     //Pythagoras distance formula
     let distance = Math.pow(px-cx, 2) + Math.pow(py-cy, 2);
     catched = Math.sqrt(distance) < cr + pr; //check if overlap

    const msgSpan = d3.select('#msg');
    msgSpan.node().textContent = catched? "Perfect! :)" : "Oh no! :(";
  });
</code>```

working code here

Body:
I am trying to build a simple svg game to catch a moving circle. There is a catchCircle, a moving preyCircle and a Catch Me button. catchCircle starts moving vertically from bottom of the screen, crosses preyCircle and gets disappeared at the top. The idea is to click the button when the preyCircle overlaps the catchCircle. In that case I just need to check if the distance of cy attributes of both the circle is less than sum of their radius.

Problem I am facing here is to get the cy attribute of catchCircle while the transition is going on. If I try to get preyCircle.attr('cy') from inside onclick event method, error is shown:
"Uncaught Error: too late; already running"

<button id="catchMe"> Catch Me </button>

My code is running on https://jsfiddle.net/avi5102005/uh627zt5/62/.

Can somebody guide me the way I should have approached? Thanks in advance.

Body:
First add Id to your circles

const catchCircle = svg.append('circle')
    .attr('r', radius)
  .attr('cx', width / 2)
  .attr('cy', 100)
  .attr("id", "catch") //add ID
  .attr('stroke', 'red')
  .attr('stroke-width', 3)
  .attr('fill', 'none');

const preyCircle = svg.append('circle')
    .attr('r', radius)
  .attr('cx', width / 2)
  .attr('cy', height - radius)
  .attr('fill', 'red')
  .attr("id", "prey") //add ID
  .transition()
    .duration(5000)
    .delay(1000)
    .attr('cy', radius)
    .remove();

next, on your button press do:

d3.select('#catchMe')
    .on('click', () => {
    catched = false;
     let py = d3.select("#prey").attr("cy"); // get prey's y
     let px = d3.select("#prey").attr("cx"); // get prey's x
     let pr = +d3.select("#prey").attr("r"); // get prey's radius

     let cy = d3.select("#catch").attr("cy");
     let cx = d3.select("#catch").attr("cx");
     let cr = +d3.select("#catch").attr("r");

     //Pythagoras distance formula
     let distance = Math.pow(px-cx, 2) + Math.pow(py-cy, 2);
     catched = Math.sqrt(distance) < cr + pr; //check if overlap

    const msgSpan = d3.select('#msg');
    msgSpan.node().textContent = catched? "Perfect! :)" : "Oh no! :(";
  });

working code here


问:
How to Deal with empty or blank cell in excel file using apache poi
I am currently working on the concept of copying the data from one excel sheet to another workbook with if blank cells exist then the same should be copied to the output file. below is the screenshot for input file:

here is my code to perform copy function

```<code>import org.apache.poi.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.examples.CreateCell;

import java.io.*;
import java.util.*;
public class openwb_test {

    public static void main(String[] args) throws Exception {

        File inputFile=new File("input.xlsx");
        FileInputStream fis=new FileInputStream(inputFile);
        XSSFWorkbook inputWorkbook=new XSSFWorkbook(fis);
        int inputSheetCount=inputWorkbook.getNumberOfSheets();
        System.out.println("Input sheetCount: "+inputSheetCount);

        File outputFile=new File("output.xlsx");
        FileOutputStream fos=new FileOutputStream(outputFile);

        XSSFWorkbook outputWorkbook=new XSSFWorkbook();

        for(int i=0;i<inputSheetCount;i++)
        {
            XSSFSheet inputSheet=inputWorkbook.getSheetAt(i);
            String inputSheetName=inputWorkbook.getSheetName(i);
            XSSFSheet outputSheet=outputWorkbook.createSheet(inputSheetName);

            copySheet(inputSheet,outputSheet);
        }

        outputWorkbook.write(fos);

        fos.close();

        outputWorkbook.close();
    }

    public static void copySheet(XSSFSheet inputSheet,XSSFSheet outputSheet)
    {
        int rowCount=inputSheet.getLastRowNum();
        System.out.println(rowCount+" rows in inputsheet "+inputSheet.getSheetName());

        int currentRowIndex=0; if(rowCount>0)
        {
            Iterator<Row> rowIterator=inputSheet.iterator();
            //XSSFRow row=(XSSFRow) rowIterator.next();
            while(rowIterator.hasNext())
            {
                int currentCellIndex=0;
                Iterator<Cell> cellIterator=((XSSFRow) rowIterator.next()).cellIterator();
                while(cellIterator.hasNext())
                {

                    String cellData=cellIterator.next().toString();

                    if(currentCellIndex==0 )
                        outputSheet.createRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
                    else
                        outputSheet.getRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);

                    currentCellIndex++;
                }

                currentRowIndex++;
                System.out.println(currentRowIndex);
            }
            System.out.println((currentRowIndex-1)+" rows added to outputsheet "+outputSheet.getSheetName());
            System.out.println();
        }
    }

}
</code>```

But if I run the above code, the results will be copied but wherever the blank cells exists, code will trim off.
for example below is the output snip:

Could anyone suggest me how we can handle the blank cell in this scenario as my expectation is input file data should be copied as it is including blank cells to the output file

答:
The getCell method has a second argument that specifies a policy for handling empty cells.

Use it in a good ol' for loop:

```<code>    for (int i=0; i<row.getLastCellNum(); i++) {
        Cell cell = row.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
        if (cell == null) {
            // ...
        } else {
            // ...
        }
    }
</code>```

Body:
I am currently working on the concept of copying the data from one excel sheet to another workbook with if blank cells exist then the same should be copied to the output file. below is the screenshot for input file:

here is my code to perform copy function

import org.apache.poi.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.examples.CreateCell;

import java.io.*;
import java.util.*;
public class openwb_test {

    public static void main(String[] args) throws Exception {

        File inputFile=new File("input.xlsx");
        FileInputStream fis=new FileInputStream(inputFile);
        XSSFWorkbook inputWorkbook=new XSSFWorkbook(fis);
        int inputSheetCount=inputWorkbook.getNumberOfSheets();
        System.out.println("Input sheetCount: "+inputSheetCount);

        File outputFile=new File("output.xlsx");
        FileOutputStream fos=new FileOutputStream(outputFile);

        XSSFWorkbook outputWorkbook=new XSSFWorkbook();

        for(int i=0;i<inputSheetCount;i++)
        {
            XSSFSheet inputSheet=inputWorkbook.getSheetAt(i);
            String inputSheetName=inputWorkbook.getSheetName(i);
            XSSFSheet outputSheet=outputWorkbook.createSheet(inputSheetName);

            copySheet(inputSheet,outputSheet);
        }

        outputWorkbook.write(fos);

        fos.close();

        outputWorkbook.close();
    }

    public static void copySheet(XSSFSheet inputSheet,XSSFSheet outputSheet)
    {
        int rowCount=inputSheet.getLastRowNum();
        System.out.println(rowCount+" rows in inputsheet "+inputSheet.getSheetName());

        int currentRowIndex=0; if(rowCount>0)
        {
            Iterator<Row> rowIterator=inputSheet.iterator();
            //XSSFRow row=(XSSFRow) rowIterator.next();
            while(rowIterator.hasNext())
            {
                int currentCellIndex=0;
                Iterator<Cell> cellIterator=((XSSFRow) rowIterator.next()).cellIterator();
                while(cellIterator.hasNext())
                {

                    String cellData=cellIterator.next().toString();

                    if(currentCellIndex==0 )
                        outputSheet.createRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
                    else
                        outputSheet.getRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);

                    currentCellIndex++;
                }

                currentRowIndex++;
                System.out.println(currentRowIndex);
            }
            System.out.println((currentRowIndex-1)+" rows added to outputsheet "+outputSheet.getSheetName());
            System.out.println();
        }
    }

}

But if I run the above code, the results will be copied but wherever the blank cells exists, code will trim off.
for example below is the output snip:

Could anyone suggest me how we can handle the blank cell in this scenario as my expectation is input file data should be copied as it is including blank cells to the output file

Body:
The getCell method has a second argument that specifies a policy for handling empty cells.

Use it in a good ol' for loop:

    for (int i=0; i<row.getLastCellNum(); i++) {
        Cell cell = row.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
        if (cell == null) {
            // ...
        } else {
            // ...
        }
    }


答:
Using a class with a static variable for a UserDefaults value is bad practice. Apart from that setting the static variable doesn't update the value in UserDefaults.

In the button action set the value in UserDefaults and perform the segue

```<code>@IBAction func login(_ sender : Any)  {
    UserDefaults.standard.set(true, forKey:"islogged")
    performSegue(...
}
</code>```

In viewDidLoad get the value directly from UserDefaults

```<code>func viewDidLoad() {
    super.viewDidLoad()
    if UserDefaults.standard.bool(forKey:"islogged") {
        performSegue(...
    } else {
        // present error
    }

}
</code>```

Title: UserDefaults not working on didload in my project

Body:
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

When the  user clicks login Button, the code is as below

ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

Body:
Using a class with a static variable for a UserDefaults value is bad practice. Apart from that setting the static variable doesn't update the value in UserDefaults.

In the button action set the value in UserDefaults and perform the segue

@IBAction func login(_ sender : Any)  {
    UserDefaults.standard.set(true, forKey:"islogged")
    performSegue(...
}

In viewDidLoad get the value directly from UserDefaults

func viewDidLoad() {
    super.viewDidLoad()
    if UserDefaults.standard.bool(forKey:"islogged") {
        performSegue(...
    } else {
        // present error
    }

}


问:
Selenium and SVG
I have a web application that uses an SVG gauge in it. this gauge displays the health status of my grid (several machines).

The gauge has 3 colors: green, yellow, and red.

I want to be able to write a test that ensures that this gauge represents data correctly. That is, my test will calculate the expected grid health value and make sure the gauge points to the appropriate area.

Is this possible using Selenium 2.0?

答:
Selenium will allow you to, using JavaScript, get at the properties of any element in the DOM, so something like

```<code>var gaugeFill = document.getElementById('mygauge').getAttribute('fill');
</code>```

will get you the fill color, but it may come back like: "rgb(255,0,0)" for Red. You'll have to inspect that, and set up your compare logic accordingly.

Also, you didn't say how you're rendering the SVG. There are so many ways... What I described works for modern browsers where the SCV elements are straight up part of the DOM, but that's not the case for older browsers or if you're using something Raphael.

Title: Selenium and SVG

Body:
Selenium will allow you to, using JavaScript, get at the properties of any element in the DOM, so something like

var gaugeFill = document.getElementById('mygauge').getAttribute('fill');

will get you the fill color, but it may come back like: "rgb(255,0,0)" for Red. You'll have to inspect that, and set up your compare logic accordingly.

Also, you didn't say how you're rendering the SVG. There are so many ways... What I described works for modern browsers where the SCV elements are straight up part of the DOM, but that's not the case for older browsers or if you're using something Raphael.


问:
How to update text element after property change in Polymer 3?
So I'm using a data table which has an active element. When that active elment changes I store the name of the active element in a property of my polymer element. Then I display this String property in a div.
Now I know for certain that the property change works, because I console.log it after a change, the div displaying the property doesn't update and continually displays the default value I have set.

```<code>export class ProjectsOverview extends PolymerElement {
  static get template() {
      return html`
         ...
         <div>{{currentProject}}</div>
         ...
      `
  }

  static get properties() {
      return {
        currentProject: {
          type: String,
          value: "placeholder",
          notify: true,
          reflectToAttribute: true
        }
      };
  }

  connectedCallback() {
      super.connectedCallback();

      const grid = this.shadowRoot.querySelector('vaadin-grid');

      grid.addEventListener('active-item-changed', function(event) {
        const item = event.detail.value;

        grid.selectedItems = [item];
        if (item) {
          this.set('currentProject', item.name);
        } else {
          this.set('currentProject', '');
        }
        console.log(this.currentProject);
      });
  }
}
</code>```

My expected result would be that every time the currentProject property is updated, the div displaying the property updates as well.

答:
The active-item-changed callback does not have its context bound to the Polymer instance (i.e., this is the grid and not the Polymer component). Instead of the function expression, use an arrow function to automatically bind this to the correct context.

// grid.addEventListener('active-item-changed', function(event) { // DON'T DO THIS
grid.addEventListener('active-item-changed', (event) => {
  /* this is the Polymer instance here */
  this.set('currentProject', ...);
})
```

Body:
So I'm using a data table which has an active element. When that active elment changes I store the name of the active element in a property of my polymer element. Then I display this String property in a div.
Now I know for certain that the property change works, because I console.log it after a change, the div displaying the property doesn't update and continually displays the default value I have set.

export class ProjectsOverview extends PolymerElement {
  static get template() {
      return html`
         ...

{{currentProject}}

         ...
      `
  }

  static get properties() {
      return {
        currentProject: {
          type: String,
          value: "placeholder",
          notify: true,
          reflectToAttribute: true
        }
      };
  }

  connectedCallback() {
      super.connectedCallback();

      const grid = this.shadowRoot.querySelector('vaadin-grid');

      grid.addEventListener('active-item-changed', function(event) {
        const item = event.detail.value;

        grid.selectedItems = [item];
        if (item) {
          this.set('currentProject', item.name);
        } else {
          this.set('currentProject', '');
        }
        console.log(this.currentProject);
      });
  }
}

My expected result would be that every time the currentProject property is updated, the div displaying the property updates as well.


问:
How to read the mask of an image using opencv in python
I am working on this challenge called Carvana Segmentation in kaggle. The dataset consists of 5088 images, for each image there is a mask. For eg, the below is a single image (.jpg file) and its corresponding mask (.gif file).

I was able to read .jpg files using cv2, but not the .gif files. The syntax i used to read .gif file is

```<code> >>> image = cv2.imread('filename.gif',cv2.IMREAD_GRAYSCALE)
</code>```

When I try to print the image, returns None

```<code> >>> print(image) -> None
</code>```

Can someone suggest any other method, please

答:
You can't use imread(), there's no codec for that builtin (still a license problem)[https://answers.opencv.org/question/185929/how-to-read-gif-in-python/]

Since you are interested in python, you may use PIL library as mentioned here.

```<code>from PIL import Image
im = Image.open("animation.gif")

# To iterate through the entire gif
try:
    while 1:
        im.seek(im.tell()+1)
        # do something to im
except EOFError:
    pass # end of sequence
</code>```

Body:
I am working on this challenge called Carvana Segmentation in kaggle. The dataset consists of 5088 images, for each image there is a mask. For eg, the below is a single image (.jpg file) and its corresponding mask (.gif file).

I was able to read .jpg files using cv2, but not the .gif files. The syntax i used to read .gif file is

 >>> image = cv2.imread('filename.gif',cv2.IMREAD_GRAYSCALE)

When I try to print the image, returns None

 >>> print(image) -> None

Can someone suggest any other method, please

Body:
You can't use imread(), there's no codec for that builtin (still a license problem)[https://answers.opencv.org/question/185929/how-to-read-gif-in-python/]

Since you are interested in python, you may use PIL library as mentioned here.

from PIL import Image
im = Image.open("animation.gif")

# To iterate through the entire gif
try:
    while 1:
        im.seek(im.tell()+1)
        # do something to im
except EOFError:
    pass # end of sequence