问:
Optimize the performance of SQL query
I need to fetch all the ID's from certain tables in between two timestamps

```<code>select Distinct PK1 from(
SELECT A.PK1
FROM  T1 A , T2 B, T3 C, T4 D
WHERE TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' ) <= '2016-06-02 00:00:00' and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
union

SELECT A.PK1
FROM  T1 a, T2 B , T3 C, T4 D
WHERE TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )  <='2016-06-02 00:00:00'  and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
UNION
select A.PK1
from  T11 A, T1 B , T2 C, T3 D, T4 E  WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')<='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS
NOT NULL AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL
UNION

select A.PK1
from  T15 A , T1 B, T2 C, T3 D, T4 E WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS NOT NULL
AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL

UNION

select A.PK1
from  T12 a, T6 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK6=b.PK6 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION
select A.PK1
from  T14 a, T8 b, T1 C, T2 D, T3 E,
 T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK8=b.PK8 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL
  AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

 )
</code>```

My question is how can I optimize the query for better performance.

答:
Using to_char here converts date in every row to characterset, then compares it to value on right side. At the top of your code, convert value on right hand side to datetime and compare that to column of date type directly. That will make it faster.

Also, you can check out estimated query execution path, and minimize cost of individual steps.

Title: Optimize the performance of SQL query

Body:
I need to fetch all the ID's from certain tables in between two timestamps

select Distinct PK1 from(
SELECT A.PK1
FROM  T1 A , T2 B, T3 C, T4 D
WHERE TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS' ) <= '2016-06-02 00:00:00' and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
union

SELECT A.PK1
FROM  T1 a, T2 B , T3 C, T4 D
WHERE TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )>= '2016-06-01 00:00:00'
AND TO_CHAR(A.DATE2,'YYYY-MM-DD HH24:MI:SS' )  <='2016-06-02 00:00:00'  and a.PK2 is not null
AND A.PK2=B.PK2 AND B.PK3 IS NOT NULL AND B.PK3=C.PK3 AND C.PK4 IS NOT NULL
AND C.PK4=D.PK4 AND D.PK5 IS NOT NULL
UNION
select A.PK1
from  T11 A, T1 B , T2 C, T3 D, T4 E  WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')<='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS
NOT NULL AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL
UNION

select A.PK1
from  T15 A , T1 B, T2 C, T3 D, T4 E WHERE
TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(A.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'
AND A.PK1=B.PK1 AND B.PK2 IS NOT NULL
AND B.PK2=C.PK2 AND C.PK3 IS NOT NULL AND C.PK3=D.PK3 AND D.PK4 IS NOT NULL
AND D.PK4=E.PK4 AND E.PK5 IS NOT NULL

UNION

select A.PK1
from  T12 a, T6 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK6=b.PK6 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE2,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION

select A.PK1
from  T13 A, T7 b, T1 C, T2 D, T3 E, T4 F WHERE
TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE3,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00'

and A.PK7=b.PK7 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

UNION
select A.PK1
from  T14 a, T8 b, T1 C, T2 D, T3 E,
 T4 F WHERE
TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')>='2016-06-01 00:00:00'
AND TO_CHAR(b.DATE1,'YYYY-MM-DD HH24:MI:SS')  <='2016-06-02 00:00:00' and A.PK8=b.PK8 AND A.PK1=C.PK1 AND
  C.PK2 IS NOT NULL AND C.PK2=D.PK2 AND D.PK3 IS NOT NULL
  AND D.PK3=E.PK3
  AND E.PK4 IS NOT NULL AND E.PK4=F.PK4 AND F.PK5 IS NOT NULL

 )

My question is how can I optimize the query for better performance.


来源: stackexchange

问:
Enum.Parse returning unexpected members
Consider the following piece of code:

```<code>namespace ConsoleApplication1 {
class Program {
    public static void Main (string[] args) {
        var en = (TestEnum)Enum.Parse(typeof(TestEnum), "AA");
        Console.WriteLine(en.ToString());
        Console.ReadKey();
    }
}

public enum TestEnum {
    AA = 0x01,
    AB = 0x02,
    AC = 0x03,
    BA = 0x01,
    BB = 0x02,
    BC = 0x03
}
}
</code>```

If you execute this, the variable en will get the value of TestEnum.BA. Now I have learned from this that enum flags should be unique, or you get these kind of unexpected things, but I do fail to understand what is happening here.

The even weirder part is that when I add the [Flags] attribute to the TestEnum, it solves the problem and returns TestEnum.AA instead of TestEnum.BA, but for the original enum (which is much larger, around ~200 members) for which I have discovered this problem this does not make a difference.

My understanding is that enums are a value type, so when you define your own flags it will store the value in memory as 0x01 in the case of for TestEnum.AA, and when you cast it from object to TestEnum it will do the lookup for that flag value and find TestEnum.BA.

This is also confirmed by running the following line:

```<code>var en = (TestEnum)(object)TestEnum.AA;
Console.WriteLine(en.ToString());
</code>```

Which will output: BA

So my question is: what exactly is happening here? And more importantly why does adding the Flags attribute make a difference?

答:
Firstly, this is nothing to do with Enum.Parse(). The underlying type of an enum by default is int, so in your example TestEnum.AA and TestEnum.BA are both stored as 1 and there is no way to distinguish them.

Witness the following code:

```<code>Console.WriteLine(TestEnum.AA); // Prints BA
Console.WriteLine(TestEnum.BA); // Prints BA
</code>```

Secondly, the reason that setting the [Flags] attribute changes the output is because a different code path is taken when determining the string.

Here's the code from ReferenceSource:

```<code>private static String InternalFormat(RuntimeType eT, Object value)
{
    if (!eT.IsDefined(typeof(System.FlagsAttribute), false)) // Not marked with Flags attribute
    {
        // Try to see if its one of the enum values, then we return a String back else the value
        String retval = GetName(eT, value);
        if (retval == null)
            return value.ToString();
        else
            return retval;
    }
    else // These are flags OR'ed together (We treat everything as unsigned types)
    {
        return InternalFlagsFormat(eT, value);

    }
}
</code>```

Note how GetName() is called if [Flags] is not set, otherwise InternalFlagsFormat() is called.

The implementation of GetName() ends up doing a binary search to find the value, whereas InternalFlagsFormat() winds up doing a linear search to find the value.

InternalFlagsFormat() must do a linear search because it may need to set multiple values (e.g. "X|Y|Z") so Microsoft implemented an O(N) solution for it. However for GetName() they went for a more efficient O(Log2(N)) solution.

A binary search can (and does) find a different duplicate value than the linear search does, hence the difference.

ContentLicense: CC BY-SA 3.0

Title: Enum.Parse returning unexpected members

Body:
Consider the following piece of code:

namespace ConsoleApplication1 {
class Program {
    public static void Main (string[] args) {
        var en = (TestEnum)Enum.Parse(typeof(TestEnum), "AA");
        Console.WriteLine(en.ToString());
        Console.ReadKey();
    }
}

public enum TestEnum {
    AA = 0x01,
    AB = 0x02,
    AC = 0x03,
    BA = 0x01,
    BB = 0x02,
    BC = 0x03
}
}

If you execute this, the variable en will get the value of TestEnum.BA. Now I have learned from this that enum flags should be unique, or you get these kind of unexpected things, but I do fail to understand what is happening here.

The even weirder part is that when I add the [Flags] attribute to the TestEnum, it solves the problem and returns TestEnum.AA instead of TestEnum.BA, but for the original enum (which is much larger, around ~200 members) for which I have discovered this problem this does not make a difference.

My understanding is that enums are a value type, so when you define your own flags it will store the value in memory as 0x01 in the case of for TestEnum.AA, and when you cast it from object to TestEnum it will do the lookup for that flag value and find TestEnum.BA.

This is also confirmed by running the following line:

var en = (TestEnum)(object)TestEnum.AA;
Console.WriteLine(en.ToString());

Which will output: BA

So my question is: what exactly is happening here? And more importantly why does adding the Flags attribute make a difference?

Body:
Firstly, this is nothing to do with Enum.Parse(). The underlying type of an enum by default is int, so in your example TestEnum.AA and TestEnum.BA are both stored as 1 and there is no way to distinguish them.

Witness the following code:

Console.WriteLine(TestEnum.AA); // Prints BA
Console.WriteLine(TestEnum.BA); // Prints BA

Secondly, the reason that setting the [Flags] attribute changes the output is because a different code path is taken when determining the string.

Here's the code from ReferenceSource:

private static String InternalFormat(RuntimeType eT, Object value)
{
    if (!eT.IsDefined(typeof(System.FlagsAttribute), false)) // Not marked with Flags attribute
    {
        // Try to see if its one of the enum values, then we return a String back else the value
        String retval = GetName(eT, value);
        if (retval == null)
            return value.ToString();
        else
            return retval;
    }
    else // These are flags OR'ed together (We treat everything as unsigned types)
    {
        return InternalFlagsFormat(eT, value);

    }
}

Note how GetName() is called if [Flags] is not set, otherwise InternalFlagsFormat() is called.

The implementation of GetName() ends up doing a binary search to find the value, whereas InternalFlagsFormat() winds up doing a linear search to find the value.

InternalFlagsFormat() must do a linear search because it may need to set multiple values (e.g. "X|Y|Z") so Microsoft implemented an O(N) solution for it. However for GetName() they went for a more efficient O(Log2(N)) solution.

A binary search can (and does) find a different duplicate value than the linear search does, hence the difference.


问:
webpack splitting code by module
since my react app bundle.js is too big, so I want to splitting it by module(via react router)

(react, react-router 4)

app is only endpoint and I import every sub-app router in app

what our module system like:

app

--> subApp1

--> subApp2

--> subApp3

how I import sub-app now:

```<code>// app.js
import { Route, Switch } from 'react-router-dom';
import SubApp1 from '../SubApp1'
import SubApp2 from '../SubApp2'
import SubApp3 from '../SubApp3'

const App = () => (
  <Switch>
    <Route path="sub-app1" component={SubApp1} />
    <Route path="sub-app2" component={SubApp2} />
    <Route path="sub-app3" component={SubApp3} />
  <Switch>
)
</code>```

right now, there was an app.bundle.js containing app and sub-apps and I import it in index.html

what I want is:

```<code>// index.html
<script src="/static/subApp1.bundle.js"></script>
<script src="/static/subApp2.bundle.js"></script>
<script src="/static/subApp3.bundle.js"></script>
<script src="/static/app.bundle.js"></script>

    // app.js
import { Route, Switch } from 'react-router-dom';
import SubApp1 from 'SubApp1'
import SubApp2 from 'SubApp2'
import SubApp3 from 'SubApp3'

const App = () => (
  <Switch>
    <Route path="sub-app1" component={SubApp1} />
    <Route path="sub-app2" component={SubApp2} />
    <Route path="sub-app3" component={SubApp3} />
  <Switch>
)
</code>```

I can splitting every subapps to sub-bundle by webpack (multiple entries), however I can not import them in app.js

anyone know how to configure webpack.config.js to implement it?

答:
You don't need to configure Webpack. it will review the imports and automatically create the bundle and the AJAX loader for importing at run time.

Try the following.

import * as React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function asyncComponent(getComponent) {
  return class AsyncComponent extends React.Component<any,any> {
    static Component = null;
    state = { Component: AsyncComponent.Component };

    componentWillMount() {
      if (!this.state.Component) {
        getComponent().then(Component => {
          AsyncComponent.Component = Component
          this.setState({ Component })
        })
      }
    }
    render() {
      const { Component } = this.state
      if (Component) {
        return <Component {...this.props} />
      }
      return null
    }
  }
}

const FooComponent = asyncComponent(() => (
  System.import('./foo').then(module => module.default)
));

const BarComponent = asyncComponent(() => (
  System.import('./bar').then(module => module.default)
));

const App = () => (
  <Router>

      <Link to="/">Home</Link>
      <Link to="/foo">Foo</Link>
      <Link to="/bar">Bar</Link>
      <Route path="/foo" component={FooComponent} />
      <Route path="/bar" component={BarComponent} />

  </Router>
 );

 render(<App />, document.getElementById('root'));```

PS, most of this code I stole from Kent Dodds :)

Title: webpack splitting code by module

Body:
since my react app bundle.js is too big, so I want to splitting it by module(via react router)

(react, react-router 4)

app is only endpoint and I import every sub-app router in app

what our module system like:

app

--> subApp1

--> subApp2

--> subApp3

how I import sub-app now:

// app.js
import { Route, Switch } from 'react-router-dom';
import SubApp1 from '../SubApp1'
import SubApp2 from '../SubApp2'
import SubApp3 from '../SubApp3'

const App = () => (
  <Switch>
    <Route path="sub-app1" component={SubApp1} />
    <Route path="sub-app2" component={SubApp2} />
    <Route path="sub-app3" component={SubApp3} />
  <Switch>
)

right now, there was an app.bundle.js containing app and sub-apps and I import it in index.html

what I want is:

// index.html

    // app.js
import { Route, Switch } from 'react-router-dom';
import SubApp1 from 'SubApp1'
import SubApp2 from 'SubApp2'
import SubApp3 from 'SubApp3'

const App = () => (
  <Switch>
    <Route path="sub-app1" component={SubApp1} />
    <Route path="sub-app2" component={SubApp2} />
    <Route path="sub-app3" component={SubApp3} />
  <Switch>
)

I can splitting every subapps to sub-bundle by webpack (multiple entries), however I can not import them in app.js

anyone know how to configure webpack.config.js to implement it?

Body:
You don't need to configure Webpack. it will review the imports and automatically create the bundle and the AJAX loader for importing at run time.

Try the following.

import * as React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function asyncComponent(getComponent) {
  return class AsyncComponent extends React.Component<any,any> {
    static Component = null;
    state = { Component: AsyncComponent.Component };

    componentWillMount() {
      if (!this.state.Component) {
        getComponent().then(Component => {
          AsyncComponent.Component = Component
          this.setState({ Component })
        })
      }
    }
    render() {
      const { Component } = this.state
      if (Component) {
        return <Component {...this.props} />
      }
      return null
    }
  }
}

const FooComponent = asyncComponent(() => (
  System.import('./foo').then(module => module.default)
));

const BarComponent = asyncComponent(() => (
  System.import('./bar').then(module => module.default)
));

const App = () => (
  <Router>
    <div>
      <Link to="/">Home</Link>
      <Link to="/foo">Foo</Link>
      <Link to="/bar">Bar</Link>
      <Route path="/foo" component={FooComponent} />
      <Route path="/bar" component={BarComponent} />
     </div>
  </Router>
 );

 render(<App />, document.getElementById('root'));

PS, most of this code I stole from Kent Dodds :)


问:
I'm trying to create a javascript Dom radio button and attribute dynamically
I'm trying to create a radio button using javascript. But it doesn't seem to work</p>

```<code>function div()
{
    var newDiv = document.createElement("div");

    newDiv.id = "myDiv";
    newDiv.style.width = "200px";
    newDiv.style.height = "100px";
    newDiv.style.background = "red";
    newDiv.style.border = "inset";
    newDiv.style.borderwidth = "20px";
    newDiv.style.borderColor = "blue";

    document.body.appendChild(newDiv);
}
</code>```

答:
Change the div with input .And add type="radio"

function div() {
  var newDiv = document.createElement("input");
  newDiv.id = "myDiv";
  newDiv.style.width = "200px";
  newDiv.style.height = "100px";
  newDiv.style.background = "red";
  newDiv.style.border = "inset";
  newDiv.style.borderwidth = "20px";
  newDiv.style.borderColor = "blue";
  newDiv.type="radio";
    document.body.appendChild(newDiv);
}
div();```
</div>
</div>
</p>

<p><strong><em>Updated</em></strong> </p>

<p><strong>how to set the attribute dynamically?</strong>
Its same as above .Dom element call via id</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function div() {
     // var newDiv = document.getElementById("input"); //its call the element
   //or
    var newDiv = document.getElementsByTagName("input")[0];
   newDiv.id = "myDiv";
      newDiv.style.width = "200px";
      newDiv.style.height = "100px";
      newDiv.style.background = "red";
      newDiv.style.border = "inset";
      newDiv.style.borderwidth = "20px";
      newDiv.style.borderColor = "blue";
      newDiv.type="radio";
        document.body.appendChild(newDiv);
        console.log(newDiv.outerHTML)
    }
    div();</code>```

<input id="input">```

Body:
I'm trying to create a radio button using javascript. But it doesn't seem to work

function div()
{
    var newDiv = document.createElement("div");

    newDiv.id = "myDiv";
    newDiv.style.width = "200px";
    newDiv.style.height = "100px";
    newDiv.style.background = "red";
    newDiv.style.border = "inset";
    newDiv.style.borderwidth = "20px";
    newDiv.style.borderColor = "blue";

    document.body.appendChild(newDiv);
}

Body:
Change the div with input .And add type="radio"

function div() {
  var newDiv = document.createElement("input");
  newDiv.id = "myDiv";
  newDiv.style.width = "200px";
  newDiv.style.height = "100px";
  newDiv.style.background = "red";
  newDiv.style.border = "inset";
  newDiv.style.borderwidth = "20px";
  newDiv.style.borderColor = "blue";
  newDiv.type="radio";
    document.body.appendChild(newDiv);
}
div();

Updated

how to set the attribute dynamically?
Its same as above .Dom element call via id

function div() {
     // var newDiv = document.getElementById("input"); //its call the element
   //or
    var newDiv = document.getElementsByTagName("input")[0];
   newDiv.id = "myDiv";
      newDiv.style.width = "200px";
      newDiv.style.height = "100px";
      newDiv.style.background = "red";
      newDiv.style.border = "inset";
      newDiv.style.borderwidth = "20px";
      newDiv.style.borderColor = "blue";
      newDiv.type="radio";
        document.body.appendChild(newDiv);
        console.log(newDiv.outerHTML)
    }
    div();

<input id="input">


问:
Why does spread syntax convert my string into an array?
Why does spread syntax convert my string into an array?

```<code>var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]
</code>```

Why is w not a string?

答:
In ES2015 the spread syntax is specifically acting against the internal String @@iterator property - any object can be iterated in this way by assigning your own iterator or generator / function* to the obj[Symbol.iterator] property.

For example you could change the default behaviour of your new array...

const a = [...'hello'];
a[Symbol.iterator] = function* (){
    for(let i=0; i<this.length; ++i)
        yield `${this[i]}!`;
};
console.log([...a]);```

You could change your string iterator too but you'd have to explicitly create a String object.

Body:
Why does spread syntax convert my string into an array?

var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]

Why is w not a string?

Body:
In ES2015 the spread syntax is specifically acting against the internal String @@iterator property - any object can be iterated in this way by assigning your own iterator or generator / function* to the obj[Symbol.iterator] property.

For example you could change the default behaviour of your new array...

const a = [...'hello'];
a[Symbol.iterator] = function* (){
    for(let i=0; i<this.length; ++i)
        yield `${this[i]}!`;
};
console.log([...a]);

You could change your string iterator too but you'd have to explicitly create a String object.


问:
Call a function on PHP file using jQuery
I have a php file (treatment.php) which contains some functions, for example :

```<code>public function connexion(){
    $user = 'invité';
    if($_POST){
        if(isset($_POST['user'])) {
            session_start();
            $user = $_POST['user'];
        }
    }
    echo $user;
}
</code>```

And I want to call this function via Ajax with the following code but it doesn't work :

```<code>$(document).on("click", "#valider-btn", function(){
  $.ajax({
    url : 'treatment.php/Connexion',
    type : 'POST',
    data : 'user=' + $("#name").val(),
    dataType : 'html',
    success : function(donnees) {
    $("#name").val("");
    $("#formulaire").hide();
    $("#decompte").html(donnees);
    }
  });
});
</code>```

So can someone help please ? Thanks

答:
First need to jquery library.

calling .php file extension in your ajax code

```<code>$(document).on("click", "#valider-btn", function(){
        $.ajax({
            url : 'treatment.php/Connexion',
            type : 'POST',
            data : 'user=' + $("#name").val(),
            dataType : 'html',
            success : function(donnees){
                $("#name").val("");
                $("#formulaire").hide();
                $("#decompte").html(donnees);
            }
        });
    });
</code>```

Body:
I have a php file (treatment.php) which contains some functions, for example :

public function connexion(){
    $user = 'invité';
    if($_POST){
        if(isset($_POST['user'])) {
            session_start();
            $user = $_POST['user'];
        }
    }
    echo $user;
}

And I want to call this function via Ajax with the following code but it doesn't work :

$(document).on("click", "#valider-btn", function(){
  $.ajax({
    url : 'treatment.php/Connexion',
    type : 'POST',
    data : 'user=' + $("#name").val(),
    dataType : 'html',
    success : function(donnees) {
    $("#name").val("");
    $("#formulaire").hide();
    $("#decompte").html(donnees);
    }
  });
});

So can someone help please ? Thanks

Body:
First need to jquery library.

calling .php file extension in your ajax code

$(document).on("click", "#valider-btn", function(){
        $.ajax({
            url : 'treatment.php/Connexion',
            type : 'POST',
            data : 'user=' + $("#name").val(),
            dataType : 'html',
            success : function(donnees){
                $("#name").val("");
                $("#formulaire").hide();
                $("#decompte").html(donnees);
            }
        });
    });


问:
Plotly not rendering correct plot with subset of dataframe
I am trying to subset a dataframe and using plotly for creating bar chart:

```<code>resort_pos %>% subset(resort + pos > 5000)%>%
mutate(pos_percentage = (pos*100)/(resort+pos)) %>%
mutate(Source = as.factor(src)) %>%
plot_ly(x= ~Source,y= ~pos_percentage, type = "bar")
</code>```

Below are the head of resort_pos and subset of resort_pos

```<code>>>head(resort_pos)
src resort positive
1 ABL  45686     7352
2 AGR     96        0
3 AMD  15857    21077
4 BAM   3806   141275
5 BBI    416       54
6 BDQ      5        0

>>head(resort_pos %>% subset(resort + pos > 5000)%>%
    mutate(pos_percentage = (pos*100)/(resort+pos)) %>%
    mutate(Source = as.factor(src)))

 src resort positive pos_percentage Source
1 ABL  45686     7352       13.86176    ABL
2 AMD  15857    21077       57.06666    AMD
3 BAM   3806   141275       97.37664    BAM
4 BIL  73847   142660       65.89163    BIL
5 BLR  52711   192061       78.46527    BLR
6 BNO  44069    71089       61.73171    BNO
</code>```

Here's the output:

x takes all the distinct values but since y is not available in the subsetted data frame, it shows blanks. How can I circumvent this?

答: Do droplevels() on the resulting data.frame.

Body:
I am trying to subset a dataframe and using plotly for creating bar chart:

resort_pos %>% subset(resort + pos > 5000)%>%
mutate(pos_percentage = (pos*100)/(resort+pos)) %>%
mutate(Source = as.factor(src)) %>%
plot_ly(x= ~Source,y= ~pos_percentage, type = "bar")

Below are the head of resort_pos and subset of resort_pos

>>head(resort_pos)
src resort positive
1 ABL  45686     7352
2 AGR     96        0
3 AMD  15857    21077
4 BAM   3806   141275
5 BBI    416       54
6 BDQ      5        0

>>head(resort_pos %>% subset(resort + pos > 5000)%>%
    mutate(pos_percentage = (pos*100)/(resort+pos)) %>%
    mutate(Source = as.factor(src)))

 src resort positive pos_percentage Source
1 ABL  45686     7352       13.86176    ABL
2 AMD  15857    21077       57.06666    AMD
3 BAM   3806   141275       97.37664    BAM
4 BIL  73847   142660       65.89163    BIL
5 BLR  52711   192061       78.46527    BLR
6 BNO  44069    71089       61.73171    BNO

Here's the output:

x takes all the distinct values but since y is not available in the subsetted data frame, it shows blanks. How can I circumvent this?


问:
generate password for auth-plug for mosquitto in c#
I have spent all day trying to make a usable pbkdf2 password for the mosquitto-auth-plug.  This program sets it up exactly the way it should be stored in the mysql database.  I have a password hash generated by the program that comes with auth-plug and mosquitto loves it.  I just can't replicate it in c#, if anyone can help please let me know.

```<code>public string CreatePasswordHash(string password)
    {

        var salt = GenerateRandomSalt();
        var iterationCount = GetIterationCount();
        var hashValue = GenerateHashValue(password, salt, iterationCount);
        string result = "PBKDF2$sha256$" + iterationCount + "$" + Convert.ToBase64String(salt) + "$" + Convert.ToBase64String(hashValue);
        return result;

    }

    private int GetIterationCount()
    {
        return 901;
    }

    private static byte[] GenerateRandomSalt()
    {
        var csprng = new RNGCryptoServiceProvider();
        var salt = new byte[SaltByteLength];
        csprng.GetBytes(salt);
        return salt;
        //return GetLetter();
    }

    private static byte[] GenerateHashValue(string password, byte[] salt, int iterationCount)
    {
         byte[] hashValue;
         var valueToHash = string.IsNullOrEmpty(password) ? string.Empty : password;
         using (var pbkdf2 = new Rfc2898DeriveBytes(valueToHash, salt, iterationCount))
         {
             hashValue = pbkdf2.GetBytes(DerivedKeyLength);
         }
        return hashValue;

    }
</code>```

---EDIT-----

Rfc2898DeriveBytes states --
Implements password-based key derivation functionality, PBKDF2, by using psuedo-random number generator based on HMACSHA1.

The program/auth-plug seems to be using sha256 is there a c# PBKDF2 that uses this.

答:
As you have already stated in your edit, the problem appears to be the difference in hash functions used between the mosquitto plugin (which only supports SHA-256, according to the source code) and the .NET implementation (which can only do SHA-1).

A more flexible implementation of PBKDF2 is available in BouncyCastle, a more lightweight implementation can be found here. If you are not satisfied with those two, you could chose to implemnt PBKDF2 yourself, which is not really hard.

Body:
I have spent all day trying to make a usable pbkdf2 password for the mosquitto-auth-plug.  This program sets it up exactly the way it should be stored in the mysql database.  I have a password hash generated by the program that comes with auth-plug and mosquitto loves it.  I just can't replicate it in c#, if anyone can help please let me know.

public string CreatePasswordHash(string password)
    {

        var salt = GenerateRandomSalt();
        var iterationCount = GetIterationCount();
        var hashValue = GenerateHashValue(password, salt, iterationCount);
        string result = "PBKDF2$sha256$" + iterationCount + "$" + Convert.ToBase64String(salt) + "$" + Convert.ToBase64String(hashValue);
        return result;

    }

    private int GetIterationCount()
    {
        return 901;
    }

    private static byte[] GenerateRandomSalt()
    {
        var csprng = new RNGCryptoServiceProvider();
        var salt = new byte[SaltByteLength];
        csprng.GetBytes(salt);
        return salt;
        //return GetLetter();
    }

    private static byte[] GenerateHashValue(string password, byte[] salt, int iterationCount)
    {
         byte[] hashValue;
         var valueToHash = string.IsNullOrEmpty(password) ? string.Empty : password;
         using (var pbkdf2 = new Rfc2898DeriveBytes(valueToHash, salt, iterationCount))
         {
             hashValue = pbkdf2.GetBytes(DerivedKeyLength);
         }
        return hashValue;

    }

---EDIT-----

Rfc2898DeriveBytes states --
Implements password-based key derivation functionality, PBKDF2, by using psuedo-random number generator based on HMACSHA1.

The program/auth-plug seems to be using sha256 is there a c# PBKDF2 that uses this.


问:
Indexing on sensitive data
We need to be able to search a lot of personally identifiable information. We were thinking of using ElasticSearch for this but have a problem with the fact that it stores the original document.

Is there a way to index on a field, but not store the field? In this case, if we got a hit on a record, we would get back the guid - or more likely the encrypted guid - of a record in dynamoDB that would contain the original document. But if someone managed to pinch the ES database they couldn't easily reconstruct the original information.

Thanks,

Adam.

答:
Just found the answer: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-source-field.html

You can disable storing the original source document, only having the index - just what I wanted. We will be storing the original docs in Amazon's DyanmoDB - encrypted, of course. The ES indexes will allow us to perform the searches we want without storing the original doc.

The ES doc's do stress thinking carefully about this approach - for example, if we needed to re-index we'd have to pull everything out of Dynamo and feed it through ES again.

As a side note, we've recently been to the AWS Summit and they encouraged us to look at Kinesis as the pipeline for indexing the docs and then storing them in DynamoDB.

Adam

Title: Indexing on sensitive data


问:
XML within an Android string resource?
I was wondering if I could place XML within /res/values/strings.xml? I ask this because I am checking for the XML data file for my application, if it does not exist yet then it creates it from the default contents that will be contained as a string resource.

Eclipse tries to change the less than and greater than tags to their corresponding HTML entities when using the GUI to edit the strings. Is eclipse on the right track? Because I should think that it will be written out into my file as HTML entities too. Could I use getText() rather than getString() to convert the entities back into tags?

答:
It will obviously not work unless you escape characters in there such as < or > or &.

If you do encode the XML, it should work fine but probably not the best way to do it. I would prefer binary resource.

For putting in string.xml, you may encode using

```<code>String encoded = URLEncoder.encode(xml);
</code>```

And decoding is the opposite.

For binary, you place it in RAW folder and you get a binary stream and turn it to string and load.

ContentLicense: CC BY-SA 4.0

Title: XML within an Android string resource?

Body:
It will obviously not work unless you escape characters in there such as < or > or &.

If you do encode the XML, it should work fine but probably not the best way to do it. I would prefer binary resource.

For putting in string.xml, you may encode using

String encoded = URLEncoder.encode(xml);

And decoding is the opposite.

For binary, you place it in RAW folder and you get a binary stream and turn it to string and load.

ContentLicense: CC BY-SA 2.5


问:
Convert text to columns in Excel using VBA
I'm trying to convert text to columns using a macro but I'm not able to do it, I have tried to record a macro to achieve this, however I'm running into some issues since the text to columns VBA function expects a selection, is there a way I can dinamically chose let's say range A7:A50000? or even better A7:lastnonempty cell?

Thanks,

FYI, the delimeter is not important since I need to do this to convert text into formula

Here is my code

```<code>Range("O6").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("O6"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
</code>```

答:
If someone is facing issue using texttocolumns function in UFT. Please try using below function.

```<code>myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true
</code>```

Here we are using coma(,) as delimiter.

Body:
I'm trying to convert text to columns using a macro but I'm not able to do it, I have tried to record a macro to achieve this, however I'm running into some issues since the text to columns VBA function expects a selection, is there a way I can dinamically chose let's say range A7:A50000? or even better A7:lastnonempty cell?

Thanks,

FYI, the delimeter is not important since I need to do this to convert text into formula

Here is my code

Range("O6").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("O6"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

Body:
If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.


问:
Replacing last occurrence of character group with Oracle REGEXP_REPLACE
I have strings like the following in my Oracle 11g table:

```<code>ABCDEF000xyz12345abcdefgh

GHIJK0000def67890abcdefgh
</code>```

I.e., the strings begin with capital letters followed by a series of zeros, followed by three characters, digits and characters again.

How can I replace the xyz12345abcdefgh and def67890abcdefgh with a certain string using REGEXP_REPLACE in Oracle?

答:
If you need to only select the records of the type you mentioned, consider using

```<code>select REGEXP_REPLACE(col, '^([[:upper:]]+0+)[[:alpha:]]{3}\d+[[:alpha:]]+$', '\1NEW_STRING')
</code>```

where

^ - a start of string

([[:upper:]]+0+) - capturing group #1 matching:

[[:upper:]]+ - 1 or more uppercase letters

0+ - one or more 0 chars

[[:alpha:]]{3}  - 3 alphabetic chars

\d+ - 1 or more digits

[[:alpha:]]+ - 1 or more alphabetic chars

$ - end of string.

The \1 in the replacement string is a backreference that inserts the value stored in the capturing group #1 buffer.

See the online demo.

Body:
I have strings like the following in my Oracle 11g table:

ABCDEF000xyz12345abcdefgh

GHIJK0000def67890abcdefgh

I.e., the strings begin with capital letters followed by a series of zeros, followed by three characters, digits and characters again.

How can I replace the xyz12345abcdefgh and def67890abcdefgh with a certain string using REGEXP_REPLACE in Oracle?

Body:
If you need to only select the records of the type you mentioned, consider using

select REGEXP_REPLACE(col, '^([[:upper:]]+0+)[[:alpha:]]{3}\d+[[:alpha:]]+$', '\1NEW_STRING')

where

^ - a start of string

([[:upper:]]+0+) - capturing group #1 matching:

[[:upper:]]+ - 1 or more uppercase letters

0+ - one or more 0 chars

[[:alpha:]]{3}  - 3 alphabetic chars

\d+ - 1 or more digits

[[:alpha:]]+ - 1 or more alphabetic chars

$ - end of string.

The \1 in the replacement string is a backreference that inserts the value stored in the capturing group #1 buffer.

See the online demo.


问:
c# EF Core Migration code First invalid column
I did several Migrations for my Core-Projekt for SQLite, now i try to switch from SQLite to SQL.

unfortunatly i Get a "System.Data.SqlClient.SqlException (0x80131904): invalid columnname1 'columnname1'. invalid columnname2 'columnname2'."-Exception with my existing SQL-Statements.

Using something like

```<code>migrationBuilder.Sql("INSERT INTO tablename ('columnname1', 'columnname2 ') VALUES ('columnname1value','columnname2value')");
</code>```

under SQLite it works fine.

I tried to add the "dbo."-Prefix to the Tablename due to different naming convetions between SQL and SQLite. Same Error.

Due to the statements the defined tables in the script were not created in the DB

I tried to seperate the SQL-Statements in a Migration after the table creation. The defined tables are created but Same Error.

making a seed is not an option because in some migrations i use update or delete statements.

What did i wrong with my statement? is it a syntax or a logical problem or did i do it wrong all the time and i was lucky that it works under SQLite.

Thanks for your answers

For All the Other Guys and Ladys with the same Problem. Here my Solution:

sle1306 got the right Tip.
Removing the Syntax-Error
I change the quotes to brackets.

To get it work with SQLite And MS SQL:
expand the genertated Code for SQLite on all Tables

```<code>Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true)
</code>```

with/to

```<code>Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true).Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
</code>```

now it works for both of my Databases

Body:
I did several Migrations for my Core-Projekt for SQLite, now i try to switch from SQLite to SQL.

unfortunatly i Get a "System.Data.SqlClient.SqlException (0x80131904): invalid columnname1 'columnname1'. invalid columnname2 'columnname2'."-Exception with my existing SQL-Statements.

Using something like

migrationBuilder.Sql("INSERT INTO tablename ('columnname1', 'columnname2 ') VALUES ('columnname1value','columnname2value')");

under SQLite it works fine.

I tried to add the "dbo."-Prefix to the Tablename due to different naming convetions between SQL and SQLite. Same Error.

Due to the statements the defined tables in the script were not created in the DB

I tried to seperate the SQL-Statements in a Migration after the table creation. The defined tables are created but Same Error.

making a seed is not an option because in some migrations i use update or delete statements.

What did i wrong with my statement? is it a syntax or a logical problem or did i do it wrong all the time and i was lucky that it works under SQLite.

Thanks for your answers

For All the Other Guys and Ladys with the same Problem. Here my Solution:

sle1306 got the right Tip.
Removing the Syntax-Error
I change the quotes to brackets.

To get it work with SQLite And MS SQL:
expand the genertated Code for SQLite on all Tables

Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true)

with/to

Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true).Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),

now it works for both of my Databases


问:
I have been working with azure web app and want to use common data service as database
I am developing a web app using microsoft azure service. I am to use common data service as database for the app. There is a tutorial provided here.

But while going through the tutorial, when I reach the Application Registration section, I am unable to select common data service as api. The section of tutorial is listed below:

Set up the required permissions for connecting to the Common Data Service:

a. Click Required permissions to open a new pane.

b. Click Add.

c. Navigate to Select an API.

d. Search for and select Common Data Service, and then
  click Select. If you can't find this service, see "Required
  permissions service isn't found" in the "Troubleshooting" section,
  later in this topic.

e. Select all the entries under Delegated permissions, and then click Select.

f. Click Done to complete the setup of permissions for this service.

g. Repeat the preceding steps for Windows Azure Service Management API.

答:
unable to select common data service as api

It seems that you can not find/select Common Data Service and Windows Azure Service Management API when you set up the required permissions.

If you see "Required permissions service isn't found" section, you can find that we can directly modify the application's JSON manifest and add the following entries under the JSON array that is named requiredResourceAccess.

```<code>{
    "resourceAppId": "82f77645-8a66-4745-bcdf-9706824f9ad0",
    "resourceAccess": [
    {
        "id": "4ae1b148-ab4d-496d-8183-9292090fcca4",
        "type": "Scope"
    }
    ]
},
{
    "resourceAppId": "797f4846-ba00-4fd7-ba43-dac1f8f63013",
    "resourceAccess": [
    {
        "id": "41094075-9dad-400e-a0bd-54e686782033",
        "type": "Scope"
    }
    ]
}
</code>```

After modify the application's JSON manifest, you should find Common Data Service and Windows Azure Service Management API are added.

Body:
unable to select common data service as api

It seems that you can not find/select Common Data Service and Windows Azure Service Management API when you set up the required permissions.

If you see "Required permissions service isn't found" section, you can find that we can directly modify the application's JSON manifest and add the following entries under the JSON array that is named requiredResourceAccess.

{
    "resourceAppId": "82f77645-8a66-4745-bcdf-9706824f9ad0",
    "resourceAccess": [
    {
        "id": "4ae1b148-ab4d-496d-8183-9292090fcca4",
        "type": "Scope"
    }
    ]
},
{
    "resourceAppId": "797f4846-ba00-4fd7-ba43-dac1f8f63013",
    "resourceAccess": [
    {
        "id": "41094075-9dad-400e-a0bd-54e686782033",
        "type": "Scope"
    }
    ]
}

After modify the application's JSON manifest, you should find Common Data Service and Windows Azure Service Management API are added.


问:
Cascade Multi Select Kendo Dropdown on change of another Multi Select Kendo Dropdown
I have a situation where I have two multi select Kendo dropdowns and on select of first multi select dropdown I wants to populate another multi select dropdown.

1st MultiSelect Kendo DD:

```<code>@(Html.Kendo().MultiSelect()
   .Name("FirstDropDown").Placeholder("-- Select --")
   .BindTo(new SelectList(Model.BusinessData, "Id", "Name"))
   .Enable(true)
   .AutoBind(false).Events(e => e.Change("onFirstDropDownChange"))
   .HtmlAttributes(new { style = "width: 300px" })
 )
</code>```

2nd MultiSelect Kendo DD:

```<code> @(Html.Kendo().MultiSelect()
   .Name("project")
   .Placeholder("-- Select --")
   .DataTextField("ProjectName")
   .DataValueField("Id")
   .Filter(FilterType.Contains)
   .DataSource(source =>
    {
       source.Read(read =>
       {
          read.Action("GetProjectByBu", "Reports").Data("filterProjects");
       })
    .ServerFiltering(true);
    })
   .Enable(true)
   .AutoBind(false).Events(e => e.Change("onProjectChange"))
   .HtmlAttributes(new { style = "width: 300px" })
 )
</code>```

JS Code:

```<code>function filterProjects() {
    return {
        buID: $("#FirstDropDown").data("kendoMultiSelect").input.val()
    };
}
</code>```

What I have tried:

I was trying to make AJAX call in onFirstDropDownChange function but that was not working as DataSource is not binding with 2nd dropdown.

Constraints:

I doesn't want to load data on both dropdowns at first.

Values of 2nd dropdown is dependent upon 1st dropdown, means all values selected in 1st dorpdown will be sent to database through MVC Controller and fetch the data from there.

What I wants to do:

When I will select any value in 1st multi select dropdown my 2nd multi select dropdown will be populated as per values selected in 1st dropdown.

答:
I have resolve this problem by using AJAX call, below are the detailed steps:

First, I have attached one JavaScript function onFirstDropDownChange on FirstDropDown.

Then in onFirstDropDownChange js function, I get all selected values in first dropdown and make an synchronous AJAX call and bind data in 2nd drop down, below is code for same.

var multiselect = $("#FirstDropDown").data("kendoMultiSelect");

```<code>var i; var stringArray = new Array();
    for (i = 0; i < multiselect.dataItems().length; i++)
    {
        stringArray[i] = parseInt(multiselect.dataItems()[i].Value,32);
    }

var postedData = { businessIds: stringArray };
var projectDataSource;

jQuery.ajaxSettings.traditional = true;

//AJAX Call
$.ajax({
    url: '/Reports/GetProjectByBu',
    dataType: 'json',
    data: postedData,
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    async: false,
    traditional: true,
    success: function (data) {
        projectDataSource = data;
    }
});

//Update DataSource of 2nd dropdown
$("#project").data("kendoMultiSelect").setDataSource(new kendo.data.DataSource({ data: projectDataSource }));
</code>```

Hope this will help you, if you are trying to looking for similar kind of solution.

Body:
I have a situation where I have two multi select Kendo dropdowns and on select of first multi select dropdown I wants to populate another multi select dropdown.

1st MultiSelect Kendo DD:

@(Html.Kendo().MultiSelect()
   .Name("FirstDropDown").Placeholder("-- Select --")
   .BindTo(new SelectList(Model.BusinessData, "Id", "Name"))
   .Enable(true)
   .AutoBind(false).Events(e => e.Change("onFirstDropDownChange"))
   .HtmlAttributes(new { style = "width: 300px" })
 )

2nd MultiSelect Kendo DD:

 @(Html.Kendo().MultiSelect()
   .Name("project")
   .Placeholder("-- Select --")
   .DataTextField("ProjectName")
   .DataValueField("Id")
   .Filter(FilterType.Contains)
   .DataSource(source =>
    {
       source.Read(read =>
       {
          read.Action("GetProjectByBu", "Reports").Data("filterProjects");
       })
    .ServerFiltering(true);
    })
   .Enable(true)
   .AutoBind(false).Events(e => e.Change("onProjectChange"))
   .HtmlAttributes(new { style = "width: 300px" })
 )

JS Code:

function filterProjects() {
    return {
        buID: $("#FirstDropDown").data("kendoMultiSelect").input.val()
    };
}

What I have tried:

I was trying to make AJAX call in onFirstDropDownChange function but that was not working as DataSource is not binding with 2nd dropdown.

Constraints:

I doesn't want to load data on both dropdowns at first.

Values of 2nd dropdown is dependent upon 1st dropdown, means all values selected in 1st dorpdown will be sent to database through MVC Controller and fetch the data from there.

What I wants to do:

When I will select any value in 1st multi select dropdown my 2nd multi select dropdown will be populated as per values selected in 1st dropdown.

Body:
I have resolve this problem by using AJAX call, below are the detailed steps:

First, I have attached one JavaScript function onFirstDropDownChange on FirstDropDown.

Then in onFirstDropDownChange js function, I get all selected values in first dropdown and make an synchronous AJAX call and bind data in 2nd drop down, below is code for same.

var multiselect = $("#FirstDropDown").data("kendoMultiSelect");

var i; var stringArray = new Array();
    for (i = 0; i < multiselect.dataItems().length; i++)
    {
        stringArray[i] = parseInt(multiselect.dataItems()[i].Value,32);
    }

var postedData = { businessIds: stringArray };
var projectDataSource;

jQuery.ajaxSettings.traditional = true;

//AJAX Call
$.ajax({
    url: '/Reports/GetProjectByBu',
    dataType: 'json',
    data: postedData,
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    async: false,
    traditional: true,
    success: function (data) {
        projectDataSource = data;
    }
});

//Update DataSource of 2nd dropdown
$("#project").data("kendoMultiSelect").setDataSource(new kendo.data.DataSource({ data: projectDataSource }));

Hope this will help you, if you are trying to looking for similar kind of solution.


问:
Changing a trained network to keep only a subset of its output
Suppose I have a trained TensorFlow classification network for 20 classes as in PASCAL VOC 2007: aeroplane, bicycle, ..., car, cat, ..., person, ..., tvmonitor.

Now, I would like to have a sub-network for only a subset of the classes, e.g., 3 classes: car, cat, person.

Then, I can use this network for testing or for re-training/fine-tuning on a new dataset, only for the 3 classes.

It should be possible to extract this sub-network out of the original network, since it is only the last layer that will change. We need to discard the neurons/weights for the discarded classes.

My question: Is there an easy way to do this in TensorFlow?
It will be great if you can point to some sample code or similar solution.
I have googled, but have not come across any mention of this.

The symmetric problem, expanding the number of classes without discarding the original weights, can potentially be useful for some people, but my current focus is the one above.

答:
It is possible to extract a pretrained subnet as you said. It is called transfer learning. There are different ways to do it, here you have one:

Find the layer you want to start with. You can use Tensorboard to find it and then use graph.get_tensor_by_name()  Usually you keep the convolutional layers and discard the fully connected ones.

Connect your new layers (normally fully connected ones) to the previous layer.

Freeze the variables (weights) of the pretrained layers using trainable=false. Alternatively, you can instruct the optimizer to update only the weights from the new layers.

Train your model with the new classes.


问:
How to build a layout of single line and multi line labels in iOS autolayout?
I have an application in swift,and have encountered an autolayout issue. I've come up with the solution to it, but it doesn't seem to work as expected.

So, here's the issue:
I have two labels in a table view cell. The first one should only have one line, and the second one must have as many lines as needed and take up as much vertical space as needed. The first label should always be shown fully and, therefore, determine the position, the size, and the number of lines of the second label. Texts for both are set programmatically when drawing the cell, of course.

The solution seems to be pretty simple: Anchor the first label to the left, center it vertically, anchor the second label to the parent top, right, bottom and the right side of the first one. Set the number of lines to 0 for the second label. The editor shows no warnings or errors.

This is how it looks like:

In most cases it looks good, like on the picture below, but sometimes not (red arrows at the picture below):

The first label should have absolute priority and never be truncated, wrapped, or cut, but this happens. What am I doing wrong?

UPD: For the question to be more clear, the first label is so called 'margin label', it represents the margin and the indicator of the cell. This is done to imitate a tree structure. The second is, of course, the text itself. '>' is for the closed comment, 'v' is for the opened.

答: you can set the trailing of the first label is >= to the leading of the second label</p>


问:
Connection Strings in the Code and Continuous Deployment
I am trying to setup connection string is my Azure resource deployment project. Which will be triggered via Octopus.We would like to have a clean system with every deployment. We want to accomplish Continuous deployment.  The projects should cope with changes.And the system should be ready for blue green deployments ?

I am thinking about

I.Using a load balancer and configurations point to the load balancer with the connection strings.

II.Have a different database names at every deployment so every resource is unique every time.

What are the challanges I would face ? Do I have to have a tool like ZooKeeper?

Project Structure by TYPE using Azure Resource Project

Parameters & variables focusing to keep them less than 20

答:
In your scenario you can create a deployment slots and use the Auto-swap feature. This will reduce the downtime and risk. See this for more details:
Configure Auto Swap

Also, for the first question, you can create 2 databases, one for production and one for staging. You can use sticky settings as shown below to stick  a DB to a specific slot. See this: Configuration for deployment slots

Additionally, you can also warm-up your slot so that it is ready to serve requests before it gets swapped.

HTH!


问:
How to send a Asp label value( from server side) from popup window to parent window dropdownlist
Trying to send label value from popupwindow to parent window drop down list  </p>

答:
Create a global variable that you pass this value in it

Create Global.asax file,  In it create public static string X;

Go to your page access the dropdown value save it in this X by calling Global File

Then Restore in in your Main Page


问:
How to remove Kubectl from ubuntu 16.04 LTS
I've followed guide to install kubectl for testing in development environment on Ubuntu 16.04.

Now I would like to remove Kubectl from ubuntu.

答:
Depending on the method you chose in https://kubernetes.io/docs/tasks/tools/install-kubectl/, it can be any of these:

Install kubectl binary via curl: sudo rm /usr/local/bin/kubectl

Download as part of the Google Cloud SDK: gcloud components remove kubectl

Install with snap on Ubuntu (just as Gparmar said): snap remove kubectl

In addition, you may need to remove the configuration files in ~/.kube.


问:
Cannot resolve method getOutputmediafile()
I want to make an application that takes picture it show the camera perfectly but i want to add the functionality of taking picture and storing it internaly in mobile this getOutMediafile() keeps popping up ?  </p>

```<code>package com.wordpress.bytedebugger.simplecamera;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.widget.Toast.LENGTH_LONG;

public class MainActivity extends Activity {
private Camera mCamera = null;
private CameraView mCameraView = null;
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null){
            Toast.makeText(MainActivity.this,"Error creating media file, check storage permissions: ",Toast.LENGTH_LONG).show();

            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try
    {
        mCamera = Camera.open();//you can use open(int) to use different cameras
    } catch (Exception e){
        Toast.makeText(MainActivity.this,"Failed to getCamera",Toast.LENGTH_LONG).show();
        //Log.d("ERROR", "Failed to get camera: " + e.getMessage());
    }

    if(mCamera != null)
    {
        mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
        FrameLayout camera_view = (FrameLayout)findViewById(R.id.camera_view);
        camera_view.addView(mCameraView);//add the SurfaceView to the layout
    }

   //button for taking picture
    ImageButton imgtaken =(ImageButton) findViewById(R.id.imgtaken);
    imgtaken.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // get an image from the camera
                    mCamera.takePicture(null, null, mPicture);
                }
            }
    );

    //btn to close the application
    ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose);
    imgClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.exit(0);
        }
    });
}
</code>```

<p>}</p>

答: You did not copy all necessary code from the Camera API guide. The method you ask about is shown tn the example here. Note that the tutorials do not perform full error checking required necessary production-grade code.</p>

Body:
I want to make an application that takes picture it show the camera perfectly but i want to add the functionality of taking picture and storing it internaly in mobile this getOutMediafile() keeps popping up ?

package com.wordpress.bytedebugger.simplecamera;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.widget.Toast.LENGTH_LONG;

public class MainActivity extends Activity {
private Camera mCamera = null;
private CameraView mCameraView = null;
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null){
            Toast.makeText(MainActivity.this,"Error creating media file, check storage permissions: ",Toast.LENGTH_LONG).show();

            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try
    {
        mCamera = Camera.open();//you can use open(int) to use different cameras
    } catch (Exception e){
        Toast.makeText(MainActivity.this,"Failed to getCamera",Toast.LENGTH_LONG).show();
        //Log.d("ERROR", "Failed to get camera: " + e.getMessage());
    }

    if(mCamera != null)
    {
        mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
        FrameLayout camera_view = (FrameLayout)findViewById(R.id.camera_view);
        camera_view.addView(mCameraView);//add the SurfaceView to the layout
    }

   //button for taking picture
    ImageButton imgtaken =(ImageButton) findViewById(R.id.imgtaken);
    imgtaken.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // get an image from the camera
                    mCamera.takePicture(null, null, mPicture);
                }
            }
    );

    //btn to close the application
    ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose);
    imgClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.exit(0);
        }
    });
}

}


答:
Ajax doesn't work like that. When you call treatment.php, you have to reroute the action given a certain attribute passed in the data. Like so (I'll assume your treatment.php isn't a class):

treatment.php

```<code><?php

if($_POST && isset($_POST['action'])
{
    //sanitize action
    switch($_POST['action'])
    {
        case 'connexion':
            connexion($_POST['data']);
            break;
        case 'anotheraction':
        //do something
        [...]
    }
}

function connexion($data = null){
    $user = 'invité';
    if($data){
        if(isset($data['user'])) {
            session_start();
            $user = $data['user'];
        }
    }
    echo $user;
}
</code>```

yourjs.js:

```<code>$(document).on("click", "#valider-btn", function(){
    $.ajax({
        url : 'treatment.php',
        type : 'POST',
        data : {user: $("#name").val(), action: "connexion"},
        dataType : 'html',
        success : function(donnees){
            $("#name").val("");
            $("#formulaire").hide();
            $("#decompte").html(donnees);
        }
    });
});
</code>```

Title: Call a function on PHP file using jQuery

Body:
Ajax doesn't work like that. When you call treatment.php, you have to reroute the action given a certain attribute passed in the data. Like so (I'll assume your treatment.php isn't a class):

treatment.php

<?php

if($_POST && isset($_POST['action'])
{
    //sanitize action
    switch($_POST['action'])
    {
        case 'connexion':
            connexion($_POST['data']);
            break;
        case 'anotheraction':
        //do something
        [...]
    }
}

function connexion($data = null){
    $user = 'invité';
    if($data){
        if(isset($data['user'])) {
            session_start();
            $user = $data['user'];
        }
    }
    echo $user;
}

yourjs.js:

$(document).on("click", "#valider-btn", function(){
    $.ajax({
        url : 'treatment.php',
        type : 'POST',
        data : {user: $("#name").val(), action: "connexion"},
        dataType : 'html',
        success : function(donnees){
            $("#name").val("");
            $("#formulaire").hide();
            $("#decompte").html(donnees);
        }
    });
});


问:
Laravel - Schema - MySql - Temp Table "Already Exists"
I am using Laravel 5.4 for a web app, RabbitMQ for a message queue layer, and the Laravel queue worker. I have two related issues:

Temporary Tables

I have the following table-creation code in my constructor:

```<code>Schema::create('tmp_products', function (Blueprint $table) {
            $table->temporary();
            $table->integer('id');
            $table->string('alias',     255);
            $table->string('include',   255)->nullable();
            $table->string('exclude',   255)->nullable();
        });
</code>```

Note the use of

```<code>$table->temporary();
</code>```

When multiple instances of this process run concurrently, I get the following error:

PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'tmp_products' already exists in /var/www/myproject/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:91

At first I thought the table may not be temporary, however I don't see the table in MySQL Workbench, so it's unlikely.

Maybe the multiple processes appear to be sharing connection state (as temp tables are session-specific).
The code is run as a Laravel php artisan queue:worker command, managed by supervisord (with numprocs=3), and I can see in htop that there are three processes with unique PIDs, so I don't understand how they could be sharing connection state.

Queue - Failed Jobs

What's more interesting is that I run the queue worker with the flag --tries=0 (i.e. do not retry processing messages), so after the above exception is thrown within the job->handle() method the message should immediately be transferred to the Laravel failed_jobs table, but what I see is an infinite loop of exceptions and the message never leaves the queue.

So I guess my questions are:

How can queue:worker processes share db-connection state

Why does this particular scenario stop messages failing, whereas they do fail as expected if I explicitly throw new Exception(); in my handle() function

Any help is appreciated.

Thanks,

EDIT: I figured out why the failing jobs were not entering the failed_jobs table. Setting --tries=0 to zero appears to make the jobs try forever. Setting it to 1 fixed it.

UPDATE: The same error occurs when using raw PDO:

```<code>$pdo = DB::connection()->getPdo();
$pdo->exec("CREATE TABLE tmp_products (id INT NOT NULL, alias VARCHAR(255) NOT NULL, include VARCHAR(255) NULL, exclude VARCHAR(255) NULL, PRIMARY KEY (id));");
</code>```

答:
ok I figured it out. I totally misunderstood how the Laravel workers operate. In the back of my head I assumed they work like apache - spawning a worker for each job in the background - and destroying each worker when finished. This is not the case. Each worker listens to the queue, waits, and processes jobs serially. It does not recreate a DB session on every job.

Incidentally, this means that the same error can affect a single worker, on the second job that it processes.

So the temp table from my previous job still existed on the next job. Now I just check, if table exists don't recreate.

Thanks

Body:
I am using Laravel 5.4 for a web app, RabbitMQ for a message queue layer, and the Laravel queue worker. I have two related issues:

Temporary Tables

I have the following table-creation code in my constructor:

Schema::create('tmp_products', function (Blueprint $table) {
            $table->temporary();
            $table->integer('id');
            $table->string('alias',     255);
            $table->string('include',   255)->nullable();
            $table->string('exclude',   255)->nullable();
        });

Note the use of

$table->temporary();

When multiple instances of this process run concurrently, I get the following error:

PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'tmp_products' already exists in /var/www/myproject/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:91

At first I thought the table may not be temporary, however I don't see the table in MySQL Workbench, so it's unlikely.

Maybe the multiple processes appear to be sharing connection state (as temp tables are session-specific).
The code is run as a Laravel php artisan queue:worker command, managed by supervisord (with numprocs=3), and I can see in htop that there are three processes with unique PIDs, so I don't understand how they could be sharing connection state.

Queue - Failed Jobs

What's more interesting is that I run the queue worker with the flag --tries=0 (i.e. do not retry processing messages), so after the above exception is thrown within the job->handle() method the message should immediately be transferred to the Laravel failed_jobs table, but what I see is an infinite loop of exceptions and the message never leaves the queue.

So I guess my questions are:

How can queue:worker processes share db-connection state

Why does this particular scenario stop messages failing, whereas they do fail as expected if I explicitly throw new Exception(); in my handle() function

Any help is appreciated.

Thanks,

EDIT: I figured out why the failing jobs were not entering the failed_jobs table. Setting --tries=0 to zero appears to make the jobs try forever. Setting it to 1 fixed it.

UPDATE: The same error occurs when using raw PDO:

$pdo = DB::connection()->getPdo();
$pdo->exec("CREATE TABLE tmp_products (id INT NOT NULL, alias VARCHAR(255) NOT NULL, include VARCHAR(255) NULL, exclude VARCHAR(255) NULL, PRIMARY KEY (id));");


问:
Cut string before certain word and paste into a different range: VBA
I need VBA code which

cuts part of a string, up to the word "HS", in each cell of column A

paste that part into column "N" in the previous row.

Some of the strings have nothing before "HS", so the code should not run for these ones. The sheet I'm working on has thousands of rows. I'm unsure how to do this...

答:
Here is some commented code which achieves what you want. Note you may find this answer useful for finding the last row.

This code avoids actually using cut and paste because that is slow. Instead, it directly accesses the cells' values.

```<code>Sub CopyBeforeHS()
    Dim r As Long, HSindex As Long
    ' There are many ways to find the last row, or just replace 100 manually here
    ' You must start at row 2, as r-1 is used in the loop
    For r = 2 To 100
        ' Your sheet name here...
        With ThisWorkbook.Sheets("Sheet1")
            ' Get location of "HS" in each cell in column A
            HSindex = InStr(.Range("A" & r).Value, "HS")
            ' If HS was found AND it wasn't the first characters
            If HSindex > 1 Then
                ' Copy cell text from before "HS" to previous row, column N
                .Range("N" & r - 1).Value = Left(.Range("A" & r).Value, HSindex - 1)
                ' Remove the same text from column A
                .Range("A" & r).Value = Mid(.Range("A" & r).Value, HSindex)
            End If
        End With
    Next r
End Sub
</code>```

Body:
Here is some commented code which achieves what you want. Note you may find this answer useful for finding the last row.

This code avoids actually using cut and paste because that is slow. Instead, it directly accesses the cells' values.

Sub CopyBeforeHS()
    Dim r As Long, HSindex As Long
    ' There are many ways to find the last row, or just replace 100 manually here
    ' You must start at row 2, as r-1 is used in the loop
    For r = 2 To 100
        ' Your sheet name here...
        With ThisWorkbook.Sheets("Sheet1")
            ' Get location of "HS" in each cell in column A
            HSindex = InStr(.Range("A" & r).Value, "HS")
            ' If HS was found AND it wasn't the first characters
            If HSindex > 1 Then
                ' Copy cell text from before "HS" to previous row, column N
                .Range("N" & r - 1).Value = Left(.Range("A" & r).Value, HSindex - 1)
                ' Remove the same text from column A
                .Range("A" & r).Value = Mid(.Range("A" & r).Value, HSindex)
            End If
        End With
    Next r
End Sub


问:
Expected specifier-qualifier-list before 'b3Vec'
This should be a simple one, but I can't figure out the problem.

I have a struct defining a vector in 3D space, in vectors.h:

```<code>/**
 * The struct defining vectors in 3D space.
 */
struct b3Vec {

  /**
   * The size of the vector.
   */
  double size;

  /**
   * The first direction of the vector in degrees.
   */
  double dir1;

  /**
   * The second direction of the vector in degrees.
   */
  double dir2;
};
</code>```

In another struct, called b3World in world.h I have this:

```<code>b3Vec gravitation;
</code>```

I'm getting the error on this line Expected specifier-qualifier-list before 'b3Vec'. I'm including the header files right and it's the only error I get.

Can anyone help me?

答:
You need to use the struct keyword:

```<code>struct b3Vec gravitation;
</code>```

Body:
This should be a simple one, but I can't figure out the problem.

I have a struct defining a vector in 3D space, in vectors.h:

/**
 * The struct defining vectors in 3D space.
 */
struct b3Vec {

  /**
   * The size of the vector.
   */
  double size;

  /**
   * The first direction of the vector in degrees.
   */
  double dir1;

  /**
   * The second direction of the vector in degrees.
   */
  double dir2;
};

In another struct, called b3World in world.h I have this:

b3Vec gravitation;

I'm getting the error on this line Expected specifier-qualifier-list before 'b3Vec'. I'm including the header files right and it's the only error I get.

Can anyone help me?

Body:
You need to use the struct keyword:

struct b3Vec gravitation;


问:
RxJs V4 Operator that combines forkJoin and map
I am trying to find an operator that lets me handle the operations performed by forkJoin and map in one step instead of two.

My input is an array of observables with varying lengths and I would like to wait until all of them have completed and then create a computed result from the observable outputs that I can subscribe to.

I haven't come across one that allows for those requirements and takes an array as input.

Below an example of a use case:

```<code>const observable1 = Rx.Observable.create(
  (observer) => {
    observer.onNext([1, 2, 3, 4]);
    observer.complete();
  }
);

const observable2 = Rx.Observable.create(
  (observer) => {
    observer.onNext([5, 6, 7, 8]);
    observer.complete();
  }
);

Rx.Observable.magigOperator([observable1, observable2])
   .subscribe(
     (result) => console.log
   );
</code>```

Now the result I am trying to get is an output of [1,2,3,4,5,6,7,8];
I can achieve it by using forkJoin and map and running a flatten function, but I was wondering whether there is a single operator that allows me to do this in one go.

Thanks.

答:
last argument of forkJoin is a function that can manipulate the results from observables. try something like this:

```<code>const observable1 = Rx.Observable.create(
    (observer) => {
        observer.next([1, 2, 3, 4]);
        observer.complete();
    }
);

const observable2 = Rx.Observable.create(
    (observer) => {
        observer.next([5, 6, 7, 8]);
        observer.complete();
    }
);

Rx.Observable.forkJoin([observable1, observable2], (res1, res2) => [...res1, ...res2]).subscribe((res) => {
    console.log(res);
});
</code>```

notice that observer has next no onNext method. Also if you want to you forkJoin the observer has to complete.

Body:
I am trying to find an operator that lets me handle the operations performed by forkJoin and map in one step instead of two.

My input is an array of observables with varying lengths and I would like to wait until all of them have completed and then create a computed result from the observable outputs that I can subscribe to.

I haven't come across one that allows for those requirements and takes an array as input.

Below an example of a use case:

const observable1 = Rx.Observable.create(
  (observer) => {
    observer.onNext([1, 2, 3, 4]);
    observer.complete();
  }
);

const observable2 = Rx.Observable.create(
  (observer) => {
    observer.onNext([5, 6, 7, 8]);
    observer.complete();
  }
);

Rx.Observable.magigOperator([observable1, observable2])
   .subscribe(
     (result) => console.log
   );

Now the result I am trying to get is an output of [1,2,3,4,5,6,7,8];
I can achieve it by using forkJoin and map and running a flatten function, but I was wondering whether there is a single operator that allows me to do this in one go.

Thanks.

Body:
last argument of forkJoin is a function that can manipulate the results from observables. try something like this:

const observable1 = Rx.Observable.create(
    (observer) => {
        observer.next([1, 2, 3, 4]);
        observer.complete();
    }
);

const observable2 = Rx.Observable.create(
    (observer) => {
        observer.next([5, 6, 7, 8]);
        observer.complete();
    }
);

Rx.Observable.forkJoin([observable1, observable2], (res1, res2) => [...res1, ...res2]).subscribe((res) => {
    console.log(res);
});

notice that observer has next no onNext method. Also if you want to you forkJoin the observer has to complete.


问:
Simple vs cryptic usernames
When creating users (for instance in a linux system), are there any security recommendations for the syntax of the username?

Let´s say:
Is "FTP_User1" less "secure" than something like "Xg_32_FTP_User1_043"?

I have already seen this attempt of trying to bloat usernames several times but never came to a conclusion whether it is actually helpful. It might prevent attackers from guessing account names, but that won´t help them a lot when a strong password is used.

Any thoughts?

答:
I don't think that cryptic usernames are very useful in terms of security, because they are often visible anyhow. For example:

Linux has commands like users to print the user names of users
currently logged in to the current host

in ${HOME} you can see all users' home directories in the form ${HOME}/FTP_User1/ (although you may not have permissions to access them)

usernames may appear as owner of files or folders, in logfiles and in various other places

Cryptic usernames are only "security through obscurity", but not "real security". If you want a secure Linux system, you'll need to carefully set access permissions and encourage good passwords.

Title: Simple vs cryptic usernames


问:
Manage sqlite in android system?
I want to know how to manage sqlite database in android system.
When I use SQLiteDatabase to save data, where is it save in android system?

I want to know it because when I save data via sqlite, other developer can or not to open and change it?

Thanks.

答:
It is saving in your mobile internal storage as a file of your database name:

directory is : (internal storage path)..../Android/data/packageName/database/

but the database file will not visible but you can write it to another path and then open with sqlite browser.

How to write the database into another file :

```<code>    private void write() throws IOException {
            File sd = Environment.getExternalStorageDirectory();
            if (sd.canWrite())
            {
                String currentDBPath = DBHelper.DATABASE_NAME;
                String backupDBPath= "QSDevice.db";

                File currentDB = new File(getDBPath(), currentDBPath);
                File backupDB = new File(sd, backupDBPath);
                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        }

 private String getDBPath() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return getFilesDir().getAbsolutePath().replace("files", "databases") +
                    File.separator;
        } else {
            return getFilesDir().getPath() + getPackageName() + "/databases/";
        }
    }
</code>```

Title: Manage sqlite in android system?

Body:
It is saving in your mobile internal storage as a file of your database name:

directory is : (internal storage path)..../Android/data/packageName/database/

but the database file will not visible but you can write it to another path and then open with sqlite browser.

How to write the database into another file :

    private void write() throws IOException {
            File sd = Environment.getExternalStorageDirectory();
            if (sd.canWrite())
            {
                String currentDBPath = DBHelper.DATABASE_NAME;
                String backupDBPath= "QSDevice.db";

                File currentDB = new File(getDBPath(), currentDBPath);
                File backupDB = new File(sd, backupDBPath);
                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        }

 private String getDBPath() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return getFilesDir().getAbsolutePath().replace("files", "databases") +
                    File.separator;
        } else {
            return getFilesDir().getPath() + getPackageName() + "/databases/";
        }
    }


问:
How to convert "SEL" and "id" to NSString?
```<code>id parent;
SEL selector;

// lot's of code...

if ([parent respondsToSelector:selector]) {

}
else {
    // This doesn't work:
    NSString *errorMessage = [NSString stringWithFormat:@"%@ in class %@ doesn't exist!", selector, parent];
}
</code>```

How do I convert "SEL" and "id" to a String?

答:
Call NSStringFromSelector() passing your selector as its argument to get the selector string, and use [parent class] for the parent object's class:

```<code>NSString *errorMessage = [NSString stringWithFormat:@"%@ in class %@ doesn't exist!",
    NSStringFromSelector(selector),
    [parent class]];
</code>```

Body:
id parent;
SEL selector;

// lot's of code...

if ([parent respondsToSelector:selector]) {

}
else {
    // This doesn't work:
    NSString *errorMessage = [NSString stringWithFormat:@"%@ in class %@ doesn't exist!", selector, parent];
}

How do I convert "SEL" and "id" to a String?

Body:
Call NSStringFromSelector() passing your selector as its argument to get the selector string, and use [parent class] for the parent object's class:

NSString *errorMessage = [NSString stringWithFormat:@"%@ in class %@ doesn't exist!",
    NSStringFromSelector(selector),
    [parent class]];


问:
How to make a background of a button transparent with visible border in Android?
This is the coding of the button. I want to make only borders visible and background of the button should be invisible.But with this code everything is becoming invisible.

```<code><Button
    android:id="@+id/button3"
    android:layout_width="200dp"
    android:layout_height="60dp"
    android:text="Sign In"
    android:textAllCaps="false"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:textColor="@color/white"
   android:background="@android:color/transparent"
</code>```

I want my button to look like this.

答:
You should put your button inside a rectangle shape like this :

create butoon_backgound.xml in the drawable directory:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient android:startColor="#FFFFFF"
    android:endColor="#00FF00"
    android:angle="270" />
  <corners android:radius="3dp" />
  <stroke android:width="2px" android:color="#000000" />
</shape>
<RelativeLayout
        android:id="@+id/container"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/butoon_backgound"
>

<Button
    android:id="@+id/button3"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:text="Sign In"
    android:textAllCaps="false"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:textColor="@color/white"
   android:background="@android:color/transparent"

</RelativeLayout>
</code>```

stroke attribute is the sroke of your border

Body:
This is the coding of the button. I want to make only borders visible and background of the button should be invisible.But with this code everything is becoming invisible.

<Button
    android:id="@+id/button3"
    android:layout_width="200dp"
    android:layout_height="60dp"
    android:text="Sign In"
    android:textAllCaps="false"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:textColor="@color/white"
   android:background="@android:color/transparent"

I want my button to look like this.

Body:
You should put your button inside a rectangle shape like this :

create butoon_backgound.xml in the drawable directory:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient android:startColor="#FFFFFF"
    android:endColor="#00FF00"
    android:angle="270" />
  <corners android:radius="3dp" />
  <stroke android:width="2px" android:color="#000000" />
</shape>
<RelativeLayout
        android:id="@+id/container"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/butoon_backgound"
>

<Button
    android:id="@+id/button3"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:text="Sign In"
    android:textAllCaps="false"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:textColor="@color/white"
   android:background="@android:color/transparent"

</RelativeLayout>

stroke attribute is the sroke of your border


问:
Presented ViewController ignores UIView animation
I have a simple animation that moves a slide up and down repeatedly. Here is the code:

```<code>    CGRect frm_down = slider.frame;
    frm_down.origin.y += 50;

    [UIView animateWithDuration:0.7
                          delay:0.0
                        options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                     animations:^{
                         slider.frame = frm_down;
                     }
                     completion:NULL];
</code>```

This is pretty straight forward and works great; however, when I am presenting the view (self presentViewController:animated:) the animation does not happen.

In fact, the slider is INSTANTLY moved to the lower position (as if it called the animation only once and moved it back down, but not back up).

I have also tried this:

```<code>CGRect frm_down = [[[slider layer] presentationLayer] frame]
</code>```

This will keep the slider in its original position instead of moving down once, and the animation still does not happen.

Any idea what I am missing? Thanks!

答:
On Swift :

```<code>override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(true)

    var from_down =  self.view.frame
    from_down.origin.y += 50

    UIView.animate(withDuration: 0.2, delay: 0.0, options: .autoreverse, animations: {
        self.view.frame = from_down
        }, completion: nil)
}
</code>```

Body:
I have a simple animation that moves a slide up and down repeatedly. Here is the code:

    CGRect frm_down = slider.frame;
    frm_down.origin.y += 50;

    [UIView animateWithDuration:0.7
                          delay:0.0
                        options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                     animations:^{
                         slider.frame = frm_down;
                     }
                     completion:NULL];

This is pretty straight forward and works great; however, when I am presenting the view (self presentViewController:animated:) the animation does not happen.

In fact, the slider is INSTANTLY moved to the lower position (as if it called the animation only once and moved it back down, but not back up).

I have also tried this:

CGRect frm_down = [[[slider layer] presentationLayer] frame]

This will keep the slider in its original position instead of moving down once, and the animation still does not happen.

Any idea what I am missing? Thanks!

Body:
On Swift :

override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(true)

    var from_down =  self.view.frame
    from_down.origin.y += 50

    UIView.animate(withDuration: 0.2, delay: 0.0, options: .autoreverse, animations: {
        self.view.frame = from_down
        }, completion: nil)
}


问:
JS:Want to animate on clicking the button
I want to animate/colorify the div on clicking the button 'Animate'
Can you test my code and suggest some changes or add some code ?

My code looks like this:-

.anime {
  animation: coloranimate 5s;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anime" class="anime">
</div>
<button>Animate</button></code>```

I want to animate/colorify the div using the animate button.

答:
You can use .addClass() on click on the button, once you add the class which contains the animation property, the animation will automatically start.

See code snippet:

$('button').click(function() {
  $('#anime').addClass("anime");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#anime {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

.anime {
  animation: coloranimate 5s;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}</code>```

<button>Animate</button>```

Body:
I want to animate/colorify the div on clicking the button 'Animate'
Can you test my code and suggest some changes or add some code ?

My code looks like this:-

.anime {
  animation: coloranimate 5s;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

<button>Animate</button>

I want to animate/colorify the div using the animate button.

Body:
You can use .addClass() on click on the button, once you add the class which contains the animation property, the animation will automatically start.

See code snippet:

$('button').click(function() {
  $('#anime').addClass("anime");
});

#anime {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

.anime {
  animation: coloranimate 5s;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anime">
</div>
<button>Animate</button>