问:
On successful login, this.props.history.push does not take to new page as ProtectedRoute is not successful
After I receive a 200 status code, I try to go to the dashboard page. However, it does not work as intended. I am using React Context and ProtectedRoute. When I get the successful response, I call the login() function and it makes isAuthenticated as true but still does not take me to the dashboard Page.

PS: I checked and saw that in my protected route, it goes to the second part and gets redirected to "/" and hence I am on the same page. Do not know why that is happening

Signin

```<code>import { AuthContext } from './AuthContext'

async handleSubmit(event) {

        //I send the request before this

            const status = await res.status
            const json = await res.json();
            if(status === 200) {
                const {login} = this.context;
                login();
                this.props.history.push('/dashBoard')
                console.log('done')
            } else {
                console.log('not done')
            }
        } catch (error) {
            console.log('Error', error)
        }
    }
static contextType = AuthContext;

render() {
return (
<Container className="formlogin">
                <div>
                    <Form className = "signinform backg-sheet1" onSubmit={this.handleSubmit}>
                        <div>
                            <h3 style = {{color: 'white', textAlign: 'center'}}> SIGN IN </h3>
                            <Form.Group controlId = "formBasicUsername">
                                <Form.Label style = {{color: 'white'}}>Username</Form.Label>
                                <Form.Control required name = "username" type = "text" placeholder = "Enter username" onChange = {this.handleChange}/>
                            </Form.Group>

                            <Form.Group controlId = "formBasicPassword">
                                <Form.Label style = {{color: 'white'}}>Password</Form.Label>
                                <Form.Control required name = "password" type = "password" placeholder = "Enter password" onChange = {this.handleChange}/>
                            </Form.Group>

                            <div style={{textAlign: 'center'}}>
                                <Button variant="warning" type="submit">
                                    Submit
                                </Button>
                            </div>
                        </div>
                    </Form>
                </div>
            </Container>
        );
    }
}

export default withRouter(SignIn);
</code>```

App.js

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
  return (
    <div>
      <Router>
          <AuthProvider>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <ProtectedRoute exact path = '/dashBoard'
                component = {dashBoard}
              />
            </Switch>
          </AuthProvider>
      </Router>
    </div>
  );
}
}

export default App;
</code>```

AuthProvider

```<code>import React, { Component} from 'react';

export const AuthContext = React.createContext();

class AuthProvider extends Component {
    state = {
        isAuthenticated: false
    }

    constructor() {
        super()
        this.login = this.login.bind(this)
        this.logout = this.logout.bind(this)
    }

    login() {
        setTimeout(() => this.setState({ isAuthenticated: true }), 1000)
    }

    logout() {
        this.setState({ isAuthenticated: false })
    }

    render() {
        console.log(this.state.isAuthenticated)
        return(
            <AuthContext.Provider value={{isAuthenticated: this.state.isAuthenticated, login: this.login, logout: this.logout}}>
            {this.props.children}
            </AuthContext.Provider>
        )
    }
}

const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer }
</code>```

ProtectedRoute

```<code>import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthConsumer } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => (
        <AuthConsumer>
            {({ isAuthenticated }) => (
                <Route

                    render={(props) =>
                        isAuthenticated?<Component {...props} /> : <Redirect to="/" />
                    }
                    {...rest}
                />
            )}
        </AuthConsumer>
)

export default ProtectedRoute
</code>```

LandingPage

```<code>import React from 'react';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import {Row} from 'react-bootstrap';
import './Styles.css'

class LandingPage extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                    <div className = "backg">
                        <div className = "backg-sheet">
                            <SignIn />
                        </div>
                    </div>
            </div>
        )
    }

}

export default LandingPage
</code>```

答:
Make few corrections and you will successfully get navigated to dashboard page.

Your handleSubmit is a normal function and you are losing the context of this. So make it an arrow function

Use event.preventDefault else browser will reload and you end up back to / page.

I have placed your code in the sandbox and made it work.

Code snippet

handleSubmit = async event => {
    try {
      event.preventDefault();
      //I send the request before this
      // console.log("this.context", this.context); //<---- prints successfully

      const status = 200; //await res.status;
      // const json = await res.json();
      if (status === 200) {
        const { login } = this.context;
        await login();
        console.log("this.context", this.context);
        this.props.history.push("/dashBoard");
        console.log("done");
      } else {
        console.log("not done");
      }
    } catch (error) {
      console.log("Error", error);
    }
  };

```

Body:
After I receive a 200 status code, I try to go to the dashboard page. However, it does not work as intended. I am using React Context and ProtectedRoute. When I get the successful response, I call the login() function and it makes isAuthenticated as true but still does not take me to the dashboard Page.

PS: I checked and saw that in my protected route, it goes to the second part and gets redirected to "/" and hence I am on the same page. Do not know why that is happening

Signin

import { AuthContext } from './AuthContext'

async handleSubmit(event) {

        //I send the request before this

            const status = await res.status
            const json = await res.json();
            if(status === 200) {
                const {login} = this.context;
                login();
                this.props.history.push('/dashBoard')
                console.log('done')
            } else {
                console.log('not done')
            }
        } catch (error) {
            console.log('Error', error)
        }
    }
static contextType = AuthContext;

render() {
return (
<Container className="formlogin">

                    <Form className = "signinform backg-sheet1" onSubmit={this.handleSubmit}>

 SIGN IN

                            <Form.Group controlId = "formBasicUsername">
                                <Form.Label style = {{color: 'white'}}>Username</Form.Label>
                                <Form.Control required name = "username" type = "text" placeholder = "Enter username" onChange = {this.handleChange}/>
                            </Form.Group>

                            <Form.Group controlId = "formBasicPassword">
                                <Form.Label style = {{color: 'white'}}>Password</Form.Label>
                                <Form.Control required name = "password" type = "password" placeholder = "Enter password" onChange = {this.handleChange}/>
                            </Form.Group>

                                <Button variant="warning" type="submit">
                                    Submit
                                </Button>

                    </Form>

            </Container>
        );
    }
}

export default withRouter(SignIn);

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
  return (

      <Router>
          <AuthProvider>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <ProtectedRoute exact path = '/dashBoard'
                component = {dashBoard}
              />
            </Switch>
          </AuthProvider>
      </Router>

  );
}
}

export default App;

AuthProvider

import React, { Component} from 'react';

export const AuthContext = React.createContext();

class AuthProvider extends Component {
    state = {
        isAuthenticated: false
    }

    constructor() {
        super()
        this.login = this.login.bind(this)
        this.logout = this.logout.bind(this)
    }

    login() {
        setTimeout(() => this.setState({ isAuthenticated: true }), 1000)
    }

    logout() {
        this.setState({ isAuthenticated: false })
    }

    render() {
        console.log(this.state.isAuthenticated)
        return(
            <AuthContext.Provider value={{isAuthenticated: this.state.isAuthenticated, login: this.login, logout: this.logout}}>
            {this.props.children}
            </AuthContext.Provider>
        )
    }
}

const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer }

ProtectedRoute

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthConsumer } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => (
        <AuthConsumer>
            {({ isAuthenticated }) => (
                <Route

                    render={(props) =>
                        isAuthenticated?<Component {...props} /> : <Redirect to="/" />
                    }
                    {...rest}
                />
            )}
        </AuthConsumer>
)

export default ProtectedRoute

LandingPage

import React from 'react';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import {Row} from 'react-bootstrap';
import './Styles.css'

class LandingPage extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

                            <SignIn />

        )
    }

}

export default LandingPage


来源: stackexchange

问:
Select last row from csv in Azure Data Factory
I'm pulling in a small ( less than 100kb ) dataset as csv. All I want to do is select the last row of that data and sink it into a different location.

I cannot seem to find a simple way to do this.

I have tried a wrangling data flow, but the "keep rows" M function is not supported - though you can select it, it just results in an error. That's annoying because it does exactly what I need in one fell swoop.

I sort of get it working using a last() function on each field, but that is a lot of messing around and it's slow.

Surely there is a better way to do this simple task?

Would greatly appreciate any assistance.

Thanks

答: Mapping Data Flows: Surrogate Key, Aggregate (max), Filter (max row)</p>

ContentLicense: CC BY-SA 4.0


问:
zip a list with space delimited into tuple
I have a dataframe df with a column called columnList as str.

```<code>"1 2,7 8,10 7"
</code>```

Then I converted them to a list as shown :

```<code>[1 2,7 8,10 7]
</code>```

I want to convert the value inside list to tuple :

```<code>[(1,2),(7,8),(10,7)]
</code>```

Current code :

```<code>temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)
</code>```

I'm getting empty list.

df looks like this :

```<code>column1    columnList
  YY      1 2,7 8,10 7
</code>```

Name: df, dtype: object

答:
try this,

```<code>df.columnsList.apply(lambda x :
        [tuple(map(int, x.split())) for x in "1 2, 7 8, 10 7".split(",")])
</code>```

output,

```<code>0    [(1, 2), (7, 8), (10, 7)]
Name: columnsList, dtype: object
</code>```

Body:
I have a dataframe df with a column called columnList as str.

"1 2,7 8,10 7"

Then I converted them to a list as shown :

[1 2,7 8,10 7]

I want to convert the value inside list to tuple :

[(1,2),(7,8),(10,7)]

Current code :

temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)

I'm getting empty list.

df looks like this :

column1    columnList
  YY      1 2,7 8,10 7

Name: df, dtype: object

Body:
try this,

df.columnsList.apply(lambda x :
        [tuple(map(int, x.split())) for x in "1 2, 7 8, 10 7".split(",")])

output,

0    [(1, 2), (7, 8), (10, 7)]
Name: columnsList, dtype: object


问:
Cannot save a url as a value in a PropertiesConfiguration object
This one has me stumped.

I have something like:

```<code>PropertiesConfiguration pc = new PropertiesConfiguration();
pc.setProperty("url", "jdbc:postgres://localhost:5432/somedb");
pc.setBasePath(".");
pc.setFileName("my.properties");
</code>```

I have this code in a jar that was built on Linux.  When it gets run on a Windows box, then the file that gets saved comes out like:

```<code>url = jdbc:postgres:\/\/localhost:5432/somedb.
</code>```

This file is going to get consumed by some python code, and it's not at all happy with that URL.

I've searched and searched, but for the life of me, I don't understand why PC would be escaping a forward slash.

Any clues?

答:
Are you sure it is not the colons rather than the forward slashes which get escaped?

I tried this with java.util.Properties:

```<code>public class PropertiesTest {
  public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put("url", "jdbc:postgres://localhost:5432/somedb");
    OutputStream out = new FileOutputStream("my.properties");
    props.store(out, null);
  }
}
</code>```

The output to file is:

```<code>url=jdbc\:postgres\://localhost\:5432/somedb
</code>```

This is as documented in Properties.store, which says

The key and element characters #, !,
  =, and : are written with a preceding backslash to ensure that they are
  properly loaded.

I suspect your solution will be to use straight write to file, rather than going through Properties, e.g.

```<code>  public static void main(String[] args) throws Exception {
    File props = new File("my_raw.properties");
    BufferedWriter writer = new BufferedWriter(new FileWriter(props));
    writer.write("url=jdbc:postgres://localhost:5432/somedb");
    writer.close();
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This one has me stumped.

I have something like:

PropertiesConfiguration pc = new PropertiesConfiguration();
pc.setProperty("url", "jdbc:postgres://localhost:5432/somedb");
pc.setBasePath(".");
pc.setFileName("my.properties");

I have this code in a jar that was built on Linux.  When it gets run on a Windows box, then the file that gets saved comes out like:

url = jdbc:postgres:\/\/localhost:5432/somedb.

This file is going to get consumed by some python code, and it's not at all happy with that URL.

I've searched and searched, but for the life of me, I don't understand why PC would be escaping a forward slash.

Any clues?

Body:
Are you sure it is not the colons rather than the forward slashes which get escaped?

I tried this with java.util.Properties:

public class PropertiesTest {
  public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put("url", "jdbc:postgres://localhost:5432/somedb");
    OutputStream out = new FileOutputStream("my.properties");
    props.store(out, null);
  }
}

The output to file is:

url=jdbc\:postgres\://localhost\:5432/somedb

This is as documented in Properties.store, which says

The key and element characters #, !,
  =, and : are written with a preceding backslash to ensure that they are
  properly loaded.

I suspect your solution will be to use straight write to file, rather than going through Properties, e.g.

  public static void main(String[] args) throws Exception {
    File props = new File("my_raw.properties");
    BufferedWriter writer = new BufferedWriter(new FileWriter(props));
    writer.write("url=jdbc:postgres://localhost:5432/somedb");
    writer.close();
  }


问:
Snowflake Python Connector: Copy Command Status and Error Handling
According to the Snowflake docs, when a user executes a copy command it will return 1 of 3 status values:

loaded

load failed

partially loaded

My question is if I use the Python Snowflake Connector (see example code below) to execute a copy command is an exception raised if the status returned is load failed or partially loaded?

Thank you!

```<code>copy_dml = 'copy into database.schema.table ' \
'from @fully_qualified_stage pattern = \'.*'+ table_name +'.*[.]json\' ' \
'file_format = (format_name = fully_qualified_json_format) ' \
'force = true;'

 try:
        import snowflake.connector
#-------------------------------------------------------------------------------------------------------------------------------
        #snowflake variables
        snowflake_warehouse = credentials.iloc[0]['snowflake_warehouse']
        snowflake_account = credentials.iloc[0]['snowflake_account']
        snowflake_role = credentials.iloc[0]['snowflake_role']
        snowflake_username = credentials.iloc[0]['Username']
        snowflake_password = credentials.iloc[0]['Password']
        snowflake_connection = ''
        cs = ''#snowflake connection cursor
        exec_copy_dml = ''
        copy_result_field_metadata = ''
        copy_result = ''
        snowflake_copy_result_df = ''
#-------------------------------------------------------------------------------------------------------------------------------
        # load JSON file(s) into Snowflake
        snowflake_connection = snowflake.connector.connect(
        user = snowflake_username,
        password = snowflake_password,
        account = snowflake_account,
        warehouse = snowflake_warehouse,
        role = snowflake_role)
        cs = snowflake_connection.cursor()
        exec_copy_dml = cs.execute(copy_dml)
        copy_result =  exec_copy_dml.fetchall()
        copy_result_field_metadata = cs.description
        snowflake_copy_result_df = snowflake_results_df(copy_result_field_metadata,copy_result)
    except snowflake.connector.errors.ProgrammingError as copy_error:
        copy_exception_message = "There was a problem loading JSON files to Snowflake," + \
        "a snowflake.connector.errors.ProgrammingError exception was raised."
        print(copy_exception_message)
        raise
    except Exception as error_message:
        raise
    finally:
        snowflake_connection.close()
</code>```

答: I believe it won't raise exception for load status, you have to check the load status and take necessary action if required.</p>

Body:
According to the Snowflake docs, when a user executes a copy command it will return 1 of 3 status values:

loaded

load failed

partially loaded

My question is if I use the Python Snowflake Connector (see example code below) to execute a copy command is an exception raised if the status returned is load failed or partially loaded?

Thank you!

copy_dml = 'copy into database.schema.table ' \
'from @fully_qualified_stage pattern = \'.*'+ table_name +'.*[.]json\' ' \
'file_format = (format_name = fully_qualified_json_format) ' \
'force = true;'

 try:
        import snowflake.connector
#-------------------------------------------------------------------------------------------------------------------------------
        #snowflake variables
        snowflake_warehouse = credentials.iloc[0]['snowflake_warehouse']
        snowflake_account = credentials.iloc[0]['snowflake_account']
        snowflake_role = credentials.iloc[0]['snowflake_role']
        snowflake_username = credentials.iloc[0]['Username']
        snowflake_password = credentials.iloc[0]['Password']
        snowflake_connection = ''
        cs = ''#snowflake connection cursor
        exec_copy_dml = ''
        copy_result_field_metadata = ''
        copy_result = ''
        snowflake_copy_result_df = ''
#-------------------------------------------------------------------------------------------------------------------------------
        # load JSON file(s) into Snowflake
        snowflake_connection = snowflake.connector.connect(
        user = snowflake_username,
        password = snowflake_password,
        account = snowflake_account,
        warehouse = snowflake_warehouse,
        role = snowflake_role)
        cs = snowflake_connection.cursor()
        exec_copy_dml = cs.execute(copy_dml)
        copy_result =  exec_copy_dml.fetchall()
        copy_result_field_metadata = cs.description
        snowflake_copy_result_df = snowflake_results_df(copy_result_field_metadata,copy_result)
    except snowflake.connector.errors.ProgrammingError as copy_error:
        copy_exception_message = "There was a problem loading JSON files to Snowflake," + \
        "a snowflake.connector.errors.ProgrammingError exception was raised."
        print(copy_exception_message)
        raise
    except Exception as error_message:
        raise
    finally:
        snowflake_connection.close()


问:
How can I find the isnull() value in CSV file?
```<code>In[17]: train_data.isnull()
Out[17]:
       Category  Title
0         False  False
1         False  False
2         False  False
3         False  False
4         False  False
        ...    ...
98013     False  False
98014     False  False
98015     False  False
98016     False  False
98017     False  False

[98018 rows x 2 columns]

In [18]: print(train_data.isnull().sum())
Category    0
Title       1
dtype: int64
</code>```

In train_data, there is one null value in csv file.
I need to find a null value and remove it.

答:
1.Use this to drop the rows that contains null values from dataset: train_data.dropna()

Use this to fill null value with any value say 0: train_data.fillna(0)

If you want to know which column contains null value then try it:

Filtering out None value: train_data[train_data["column_name"].notnull()]

Body:
In[17]: train_data.isnull()
Out[17]:
       Category  Title
0         False  False
1         False  False
2         False  False
3         False  False
4         False  False
        ...    ...
98013     False  False
98014     False  False
98015     False  False
98016     False  False
98017     False  False

[98018 rows x 2 columns]

In [18]: print(train_data.isnull().sum())
Category    0
Title       1
dtype: int64

In train_data, there is one null value in csv file.
I need to find a null value and remove it.


问:
Continue executing code without interrupting output of looping function
I have a while loop counting in centiseconds and printing the current_step var, always on the same line.

I want to run, for example,

```<code>x = True

while x is True:
    pass #printing timer to CLI here

print('this is more code running while the timer is still running')
input('Press enter to stop the timer')
x = False
#When x becomes False, I want the while loop to terminate
</code>```

I know this must involve subprocess or something of the likes, but I don't know what direction to point myself in for learning to solve this issue.

Here is the function for reference:

```<code>def timer(stawt, stahp, step, time_step):
    from time import sleep

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        stahp = 1
    elif stahp > 1000:
        stahp = 1000

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    while True:
        try:
            current_step = str(next(titerator))
            if int(current_step) < 99:
                final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 999:
                final_time = current_step[:1] + '.' + current_step[1:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 9999:
                final_time = current_step[:2] + '.' + current_step[2:] + 's'
                print('\r' + final_time, end='')
            else:
                final_time = current_step[:3] + '.' + current_step[3:] + 's'
                print('\r' + final_time, end='')

            sleep(time_step)
        except:
            print(); break

    seconds = int((int(current_step) / 100) % 60)
    minutes = int((int(current_step) / 100) // 60)

    if minutes < 1:
        return ''
    else:
        final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
        print(final_time_human + '\n')

def MAIN():
    count_to = float(input('Enter max number of seconds to count:\n'))

    print()
    timer(0, count_to, 1, 0.01)

MAIN()
</code>```

答:
You need to use threading.

import threading

x = True

def thread_function():
    while x is True:
        pass #printing timer to CLI here

threading.Thread(target=thread_function).start()

# Continue with the other steps you want to take
# ...

# This will terminate the timer loop
x = False
```

Python threading documentation: https://docs.python.org/3/library/threading.html

If you want to print the time always at the same line you need to control terminal cursor. For more information checkout: How can move terminal cursor in Python?

Body:
I have a while loop counting in centiseconds and printing the current_step var, always on the same line.

I want to run, for example,

x = True

while x is True:
    pass #printing timer to CLI here

print('this is more code running while the timer is still running')
input('Press enter to stop the timer')
x = False
#When x becomes False, I want the while loop to terminate

I know this must involve subprocess or something of the likes, but I don't know what direction to point myself in for learning to solve this issue.

Here is the function for reference:

def timer(stawt, stahp, step, time_step):
    from time import sleep

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        stahp = 1
    elif stahp > 1000:
        stahp = 1000

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    while True:
        try:
            current_step = str(next(titerator))
            if int(current_step) < 99:
                final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 999:
                final_time = current_step[:1] + '.' + current_step[1:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 9999:
                final_time = current_step[:2] + '.' + current_step[2:] + 's'
                print('\r' + final_time, end='')
            else:
                final_time = current_step[:3] + '.' + current_step[3:] + 's'
                print('\r' + final_time, end='')

            sleep(time_step)
        except:
            print(); break

    seconds = int((int(current_step) / 100) % 60)
    minutes = int((int(current_step) / 100) // 60)

    if minutes < 1:
        return ''
    else:
        final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
        print(final_time_human + '\n')

def MAIN():
    count_to = float(input('Enter max number of seconds to count:\n'))

    print()
    timer(0, count_to, 1, 0.01)

MAIN()

Body:
You need to use threading.

import threading

x = True

def thread_function():
    while x is True:
        pass #printing timer to CLI here

threading.Thread(target=thread_function).start()

# Continue with the other steps you want to take
# ...

# This will terminate the timer loop
x = False

Python threading documentation: https://docs.python.org/3/library/threading.html

If you want to print the time always at the same line you need to control terminal cursor. For more information checkout: How can move terminal cursor in Python?


问:
Limelight Video player (Shuffle functionality)
I figured out there is no functionality of SHUFFLE in you delve player. I am trying to implement such functionality using delve player's javascript api.  Some strange reason we are not able to get this functionality because DelvePlayer.doSetMedia function is not working as it should under onMediaComplete event. Although DelvePlayer.doSetMedia is working on button click

please see code snippet below

```<code>function delvePlayerCallback(playerId, eventName, data) {

var id = "limelight_player_20758";
if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
  DelvePlayer.registerPlayer(id);
}

switch (eventName) {

  case 'onMediaComplete':
        var playIndex = 0;
        channel = DelvePlayer.doGetCurrentChannel();
        media_count = channel.mediaList.length;
        if(media_count > 1)
        {
            getRandomNum = randomFromTo(0, (media_count > 1) ? media_count - 1 : 0) ;

            //alert(getRandomNum + ' ' + channel.mediaList[getRandomNum].id + ' ' + channel.mediaList[getRandomNum].title + ' current index: ' + DelvePlayer.doGetCurrentIndex());

             //this function is not working
             DelvePlayer.doSetMedia(channel.mediaList[getRandomNum].id,true); // this function is not working

            //DelvePlayer.doPlay();
        }

    break;

    case 'onError' :
        alert ('error');
    break;
}   }
</code>```

Please advise

答:
I have resolved this issue after consult to limelight network team

they suggested to put slight delay on call to doSetMedia()

here is code snippet

```<code>switch (eventName)
{

case 'onMediaComplete':

t=setTimeout("DelvePlayer.doSetMedia('90ab7c3144c94337a8b94cf2c5c56407',true)",500);
break ;

}
</code>```

thanks to Huw Morgan at LimeLight

cheers

Body:
I figured out there is no functionality of SHUFFLE in you delve player. I am trying to implement such functionality using delve player's javascript api.  Some strange reason we are not able to get this functionality because DelvePlayer.doSetMedia function is not working as it should under onMediaComplete event. Although DelvePlayer.doSetMedia is working on button click

please see code snippet below

function delvePlayerCallback(playerId, eventName, data) {

var id = "limelight_player_20758";
if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
  DelvePlayer.registerPlayer(id);
}

switch (eventName) {

  case 'onMediaComplete':
        var playIndex = 0;
        channel = DelvePlayer.doGetCurrentChannel();
        media_count = channel.mediaList.length;
        if(media_count > 1)
        {
            getRandomNum = randomFromTo(0, (media_count > 1) ? media_count - 1 : 0) ;

            //alert(getRandomNum + ' ' + channel.mediaList[getRandomNum].id + ' ' + channel.mediaList[getRandomNum].title + ' current index: ' + DelvePlayer.doGetCurrentIndex());

             //this function is not working
             DelvePlayer.doSetMedia(channel.mediaList[getRandomNum].id,true); // this function is not working

            //DelvePlayer.doPlay();
        }

    break;

    case 'onError' :
        alert ('error');
    break;
}   }

Please advise

Body:
I have resolved this issue after consult to limelight network team

they suggested to put slight delay on call to doSetMedia()

here is code snippet

switch (eventName)
{

case 'onMediaComplete':

t=setTimeout("DelvePlayer.doSetMedia('90ab7c3144c94337a8b94cf2c5c56407',true)",500);
break ;

}

thanks to Huw Morgan at LimeLight

cheers


问:
Check if file exists in HDFS path?
How can I check if a file exists given a certain base path. I am providing the method a file list for example:
file1.snappy, file2,snappy,...

I need to check if file exists in either of the given paths for example: hdfs://a/b/c/source/file1.snappy or if file exists in hdfs://a/b/c/target/file1.snappy. How can I update/modify the method below to accept /a/b/c/target/ or /a/b/c/source/ as a basepath and check if file exists? If it exists in source add to a sourceList and if it is in destination add to a destination list.

```<code>  val fs = FileSystem.get(sprk.sparkContext.hadoopConfiguration)

  def fileExists(fileList:Array[String]) : Boolean = {
    var fileNotFound = 0
    fileList.foreach{
      file => {
        if(!fs.exists(new Path(file)))  fileNotFound+=1
        print("fileList",file)
      }
    }
    if(fileNotFound > 0) {
      println(fileNotFound + ": number of files not found probably moved")
      false
    }
    else
      true
  }
</code>```

答:
Updated code to work for hdfs & s3.

Please check below code.

```<code>scala> :paste
// Entering paste mode (ctrl-D to finish)

import org.apache.hadoop.fs.{FileSystem, Path, RemoteIterator}
import org.apache.hadoop.fs._

// For converting to scala Iterator
implicit def convertToScalaIterator[T](remoteIterator: RemoteIterator[T]): Iterator[T] = {
    case class wrapper(remoteIterator: RemoteIterator[T]) extends Iterator[T] {
      override def hasNext: Boolean = remoteIterator.hasNext
      override def next(): T = remoteIterator.next()
    }
    wrapper(remoteIterator)
}

import java.net.URI

def fs(path: String) = FileSystem.get(URI.create(path),spark.sparkContext.hadoopConfiguration)

// Exiting paste mode, now interpreting.

import org.apache.hadoop.fs.{FileSystem, Path, RemoteIterator}
import org.apache.hadoop.fs._
convertToScalaIterator: [T](remoteIterator: org.apache.hadoop.fs.RemoteIterator[T])Iterator[T]
fs: org.apache.hadoop.fs.FileSystem = org.apache.hadoop.fs.LocalFileSystem@640517de

</code>```

Sample Directories

```<code>scala> "tree /tmp/examples".!
/tmp/examples

0 directories, 0 files

scala> "tree /tmp/sample".!
/tmp/sample
├── aaa
│   └── sample.json
├── bbb
│   └── bbb.json
├── ccc
└── ddd

4 directories, 2 files
</code>```

Result

```<code>scala> List("/tmp/sample","/tmp/examples")
.flatMap(dir => {
    fs(dir)
    .listFiles(new Path(dir),true)
    .toList
    .filter(_.isFile)
    .map(d => (d.getPath.getParent,d.getPath))
// If you want only Boolean values, May be change above line to ```.map(d => (d.getPath.getParent,d.isFile))```
})
.foreach(println)

(/tmp/sample/bbb,file:/tmp/sample/bbb/bbb.json)
(/tmp/sample/aaa,file:/tmp/sample/aaa/sample.json)

</code>```

Title: Check if file exists in HDFS path?

Body:
How can I check if a file exists given a certain base path. I am providing the method a file list for example:
file1.snappy, file2,snappy,...

I need to check if file exists in either of the given paths for example: hdfs://a/b/c/source/file1.snappy or if file exists in hdfs://a/b/c/target/file1.snappy. How can I update/modify the method below to accept /a/b/c/target/ or /a/b/c/source/ as a basepath and check if file exists? If it exists in source add to a sourceList and if it is in destination add to a destination list.

  val fs = FileSystem.get(sprk.sparkContext.hadoopConfiguration)

  def fileExists(fileList:Array[String]) : Boolean = {
    var fileNotFound = 0
    fileList.foreach{
      file => {
        if(!fs.exists(new Path(file)))  fileNotFound+=1
        print("fileList",file)
      }
    }
    if(fileNotFound > 0) {
      println(fileNotFound + ": number of files not found probably moved")
      false
    }
    else
      true
  }

Body:
Updated code to work for hdfs & s3.

Please check below code.

scala> :paste
// Entering paste mode (ctrl-D to finish)

import org.apache.hadoop.fs.{FileSystem, Path, RemoteIterator}
import org.apache.hadoop.fs._

// For converting to scala Iterator
implicit def convertToScalaIterator[T](remoteIterator: RemoteIterator[T]): Iterator[T] = {
    case class wrapper(remoteIterator: RemoteIterator[T]) extends Iterator[T] {
      override def hasNext: Boolean = remoteIterator.hasNext
      override def next(): T = remoteIterator.next()
    }
    wrapper(remoteIterator)
}

import java.net.URI

def fs(path: String) = FileSystem.get(URI.create(path),spark.sparkContext.hadoopConfiguration)

// Exiting paste mode, now interpreting.

import org.apache.hadoop.fs.{FileSystem, Path, RemoteIterator}
import org.apache.hadoop.fs._
convertToScalaIterator: [T](remoteIterator: org.apache.hadoop.fs.RemoteIterator[T])Iterator[T]
fs: org.apache.hadoop.fs.FileSystem = org.apache.hadoop.fs.LocalFileSystem@640517de

Sample Directories

scala> "tree /tmp/examples".!
/tmp/examples

0 directories, 0 files

scala> "tree /tmp/sample".!
/tmp/sample
├── aaa
│   └── sample.json
├── bbb
│   └── bbb.json
├── ccc
└── ddd

4 directories, 2 files

Result

scala> List("/tmp/sample","/tmp/examples")
.flatMap(dir => {
    fs(dir)
    .listFiles(new Path(dir),true)
    .toList
    .filter(_.isFile)
    .map(d => (d.getPath.getParent,d.getPath))
// If you want only Boolean values, May be change above line to ```.map(d => (d.getPath.getParent,d.isFile))```
})
.foreach(println)

(/tmp/sample/bbb,file:/tmp/sample/bbb/bbb.json)
(/tmp/sample/aaa,file:/tmp/sample/aaa/sample.json)


问:
How do i find a file in Windows cmd that is not owned by Administrator?
Currently i am using dir,
dir c:\path*.* /s /q | find -i "Administrator"
this gives me the files owned by Administrator, how do i modify the command so it gives me an output of files not owned by Adminstrator? Thank you.</p>

答:
Since you want to show the lines where there's no match, just add /v, from docs

/v Displays all lines that don't contain the specified string.

but that will show you the lines about directories and size. As mentioned by   @aschipfl barebones format don't contain owner information, I also can't find an alternative to show the barebones file path with the owner information. Since files might contain "Administrator", you'll want to specify"BUILTIN\Administrator" instead. So your command becomes

```<code>dir c:\path\*.* /a-d /s /q | find /i /v "BUILTIN\Administrator"
</code>```

Body:
Since you want to show the lines where there's no match, just add /v, from docs

/v Displays all lines that don't contain the specified string.

but that will show you the lines about directories and size. As mentioned by   @aschipfl barebones format don't contain owner information, I also can't find an alternative to show the barebones file path with the owner information. Since files might contain "Administrator", you'll want to specify"BUILTIN\Administrator" instead. So your command becomes

dir c:\path\*.* /a-d /s /q | find /i /v "BUILTIN\Administrator"


问:
How to detach the associated record in memory only which is related to has_many association in rails-4.2
In Rails 3.2.16 we are having association as user has_many activities while querying has_many association, we can detach the association in memory by using the pop method which will not update the database, once we reloading the main object then it will remove changes in memory.

```<code>**Rails 3.12.16**

@user = User.find(1) # Identifying the user
@user.activities # Fetching activities of that user having one record
[#<Activity id: 205501, title: "Logging", user_id: 1, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

@user.activities.pop # will detach the first object and @activities will have an empty array in the whole application until reloading main object
[]

@user.activities # will return []
@user.activities.build(id: 1234567, title: "Signing Out") # will return only new built object
[#<Activity id: 1234567, title: "Signing Out", user_id: 1>]

@user.reload
@user.activities # will retain the association records
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

**Rails 4.2**

@user = User.find(1) # Identifying the user
@user.activities # Fetching activities of that user
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

@user.activities.pop # will throw an error because ActiveRecord::CollectionProxy is not having the pop method

# So we tried the to_a method
@user.activities.to_a.pop # it is affecting the array but not detaching the association in memory due it is not mutated
[]

@user.activities # > Rails 4 the association is reloaded defaultly
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

# If we are trying to build a new object
@user.activities.build(id: 1234567, title: "Signing Out")

@user.activities # We are receiving both existing and new build object but we needed only newly build object like rails 3
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">,
 #<Activity id: 1234567, title: "Signing Out", user_id: 1>]

</code>```

As Rails Document suggests to use the delete method,
but it is updating the association record in Database and removing the record as well.
Anyone can suggest the replacement of the rails 3.12.16 pop method, in rails 4.2

Currently, we are upgrading our Ruby on Rails application from 3 to 4,2.

Gems Listing:-

```<code>Rails 4.2.0 -
1) ruby (2.3.3)
2) activerecord (4.2.0)

Rails 3.2.16 -
1) ruby (2.0.0)
2) activerecord (3.2.16)
</code>```

答:
According to a rails contributor, this is expected behavior.

See here: https://github.com/rails/rails/issues/30612#issuecomment-329884753

I suspect you're going to have to find a different way to do what you want to do, but you haven't really stated what you're trying to accomplish.

Body:
In Rails 3.2.16 we are having association as user has_many activities while querying has_many association, we can detach the association in memory by using the pop method which will not update the database, once we reloading the main object then it will remove changes in memory.

**Rails 3.12.16**

@user = User.find(1) # Identifying the user
@user.activities # Fetching activities of that user having one record
[#<Activity id: 205501, title: "Logging", user_id: 1, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

@user.activities.pop # will detach the first object and @activities will have an empty array in the whole application until reloading main object
[]

@user.activities # will return []
@user.activities.build(id: 1234567, title: "Signing Out") # will return only new built object
[#<Activity id: 1234567, title: "Signing Out", user_id: 1>]

@user.reload
@user.activities # will retain the association records
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

**Rails 4.2**

@user = User.find(1) # Identifying the user
@user.activities # Fetching activities of that user
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

@user.activities.pop # will throw an error because ActiveRecord::CollectionProxy is not having the pop method

# So we tried the to_a method
@user.activities.to_a.pop # it is affecting the array but not detaching the association in memory due it is not mutated
[]

@user.activities # > Rails 4 the association is reloaded defaultly
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">]

# If we are trying to build a new object
@user.activities.build(id: 1234567, title: "Signing Out")

@user.activities # We are receiving both existing and new build object but we needed only newly build object like rails 3
[#<Activity id: 205501, title: "Logging", user_id: 133, created_at: "2020-06-01 14:29:23", updated_at: "2020-06-01 14:29:43">,
 #<Activity id: 1234567, title: "Signing Out", user_id: 1>]

As Rails Document suggests to use the delete method,
but it is updating the association record in Database and removing the record as well.
Anyone can suggest the replacement of the rails 3.12.16 pop method, in rails 4.2

Currently, we are upgrading our Ruby on Rails application from 3 to 4,2.

Gems Listing:-

Rails 4.2.0 -
1) ruby (2.3.3)
2) activerecord (4.2.0)

Rails 3.2.16 -
1) ruby (2.0.0)
2) activerecord (3.2.16)


问:
parameter for navigation service (INavigationService)
I create a project with infragistic which generates the view and views models folders, what I want to do now is create a binding context to the view model as it is normally done, but this view model has INavigationService parameters and I don't know how to configure it. Those parameters, if someone helps me, I would really appreciate it, I attach images so that they understand me more.

enter image description here

enter image description here

答:
In the mainPage background code you can use following code.

```<code> public partial class MainPage : ContentPage
    {

        public MainPage()
        {
           InitializeComponent();

            this.BindingContext= new PersonsViewModel(Navigation);

        }
}
</code>```

This Navigation comes from  NavigableElement you can use Navigation directly in ContentPage.

NavigableElement is under the Xamarin.Forms namespace like following code.

============Prism==============

If you use Prism. you should registe it the App.xaml.cs.

```<code>public partial class App
    {
        /*
         * The Xamarin Forms XAML Previewer in Visual Studio uses System.Activator.CreateInstance.
         * This imposes a limitation in which the App class must have a default constructor.
         * App(IPlatformInitializer initializer = null) cannot be handled by the Activator.
         */
        public App() : this(null) { }

        public App(IPlatformInitializer initializer) : base(initializer) { }

        protected override async void OnInitialized()
        {
            InitializeComponent();

            await NavigationService.NavigateAsync("NavigationPage/MainPage");
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<NavigationPage>();
            containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
        }
    }
</code>```

In your MainPage.xaml.cs you do not need other binding code.

Here is a demo about it.

https://github.com/manacespereira/xamarin-prism-navigation

Body:
In the mainPage background code you can use following code.

 public partial class MainPage : ContentPage
    {

        public MainPage()
        {
           InitializeComponent();

            this.BindingContext= new PersonsViewModel(Navigation);

        }
}

This Navigation comes from  NavigableElement you can use Navigation directly in ContentPage.

NavigableElement is under the Xamarin.Forms namespace like following code.

============Prism==============

If you use Prism. you should registe it the App.xaml.cs.

public partial class App
    {
        /*
         * The Xamarin Forms XAML Previewer in Visual Studio uses System.Activator.CreateInstance.
         * This imposes a limitation in which the App class must have a default constructor.
         * App(IPlatformInitializer initializer = null) cannot be handled by the Activator.
         */
        public App() : this(null) { }

        public App(IPlatformInitializer initializer) : base(initializer) { }

        protected override async void OnInitialized()
        {
            InitializeComponent();

            await NavigationService.NavigateAsync("NavigationPage/MainPage");
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<NavigationPage>();
            containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
        }
    }

In your MainPage.xaml.cs you do not need other binding code.

Here is a demo about it.

https://github.com/manacespereira/xamarin-prism-navigation


问:
Challenging MySQL query
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt
</code>```

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

```<code>/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8
</code>```

答:
I take as granted that every child has exactly one parent. Then, I think this will work:

```<code>SELECT p.*             <-- post details
     , u.*             <-- user details
     , cc.*            <-- comment details
FROM
  ( ( SELECT parentid AS id
      FROM posts
      WHERE posts.id = @mypostid     <-- the id of the post we want
    )
    UNION ALL
    ( SELECT child.id
      FROM posts AS parent
        JOIN posts AS child
          ON child.parentid = parent.id
      WHERE parent.id =
            ( SELECT posts.parentid
              FROM posts
              WHERE posts.id = @mypostid)   <-- the id of the post we want
      ORDER BY child.createdat            <-- any order you prefer
      LIMIT x, 5                          <-- 5 children posts
    )
  ) AS pp
  JOIN posts p
    ON p.id = pp.id
  JOIN users
    ON users.id = p.userid
  JOIN comments cc
    ON cc.postid = pp.id
WHERE cc.postid IN
  ( SELECT c.id
    FROM comments c
    WHERE c.postid = pp.id
    ORDER BY c.createdat             <-- any order you prefer
    LIMIT y, 5                       <-- 5 comments for every post
  )
</code>```

The x,5 should be replaced with 0,5 for first five childen posts and y,5 with 0,5 for first five comments. Then with 5,5 for next five, 10,5 for next five, etc.

UPDATE

Sorry, my mistake. The above gives the error:

```<code>This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
</code>```

I'll wrap my head up to work around this :)

Title: Challenging MySQL query

Body:
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8

Body:
I take as granted that every child has exactly one parent. Then, I think this will work:

SELECT p.*             <-- post details
     , u.*             <-- user details
     , cc.*            <-- comment details
FROM
  ( ( SELECT parentid AS id
      FROM posts
      WHERE posts.id = @mypostid     <-- the id of the post we want
    )
    UNION ALL
    ( SELECT child.id
      FROM posts AS parent
        JOIN posts AS child
          ON child.parentid = parent.id
      WHERE parent.id =
            ( SELECT posts.parentid
              FROM posts
              WHERE posts.id = @mypostid)   <-- the id of the post we want
      ORDER BY child.createdat            <-- any order you prefer
      LIMIT x, 5                          <-- 5 children posts
    )
  ) AS pp
  JOIN posts p
    ON p.id = pp.id
  JOIN users
    ON users.id = p.userid
  JOIN comments cc
    ON cc.postid = pp.id
WHERE cc.postid IN
  ( SELECT c.id
    FROM comments c
    WHERE c.postid = pp.id
    ORDER BY c.createdat             <-- any order you prefer
    LIMIT y, 5                       <-- 5 comments for every post
  )

The x,5 should be replaced with 0,5 for first five childen posts and y,5 with 0,5 for first five comments. Then with 5,5 for next five, 10,5 for next five, etc.

UPDATE

Sorry, my mistake. The above gives the error:

This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

I'll wrap my head up to work around this :)


问:
How do I change the background color in JavaScript?
I am trying to change the background color of the wrapper every time I click the button. When it is clicked, it is supposed to change to a random color that is in the array. Any thoughts for a beginner? Also the CSS was done with SASS so it may not look pretty.

function change_Color() {
  var color = ["blue", "red", "green", "yellow"];
  document.getElementById("wrapper").style.backgroundColor = color;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  width: 100%;
  height: 100vh;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
  button {
    padding: 10px;
    background: orange;
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 2rem;
    transition: .5s ease;
    &:hover {
      box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
      cursor: pointer;
    }
    &:focus {
      outline: 0;
      color: skyblue;
    }
  }
}</code>```

  <button onclick="change_Color()">Click me!</button>

```

答:
You should try this:

```<code>function changeBackground(color) {
   document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });
</code>```

instead of:

```<code>function change_Color() {
  var color = ["blue", "red", "green", "yellow"];
  document.getElementById("wrapper").style.backgroundColor = color;
}
</code>```

Body:
I am trying to change the background color of the wrapper every time I click the button. When it is clicked, it is supposed to change to a random color that is in the array. Any thoughts for a beginner? Also the CSS was done with SASS so it may not look pretty.

function change_Color() {
  var color = ["blue", "red", "green", "yellow"];
  document.getElementById("wrapper").style.backgroundColor = color;
}

body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  width: 100%;
  height: 100vh;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
  button {
    padding: 10px;
    background: orange;
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 2rem;
    transition: .5s ease;
    &:hover {
      box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
      cursor: pointer;
    }
    &:focus {
      outline: 0;
      color: skyblue;
    }
  }
}

  <button onclick="change_Color()">Click me!</button>

Body:
You should try this:

function changeBackground(color) {
   document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });

instead of:

function change_Color() {
  var color = ["blue", "red", "green", "yellow"];
  document.getElementById("wrapper").style.backgroundColor = color;
}


问:
How to get custom task tags to work in Eclipse?
tried this many times but I just can't figure out how to define custom tags in Tasks. I used the dialog and created different things like "TODO2" , or "V2" or "TOVO" (just for testing)... but none of these will ever scan into tasks, even though I do things like //TODO2 or //V2 or //TOVO in source code.

I also tried restarting eclipse but that didn't help?

anyone have any ideas how to use this functionality properly?

I want to make a tag I can use for future version TODOs... like for V2 of my program.

Right now I'm just hacking it like this //TODO FUTURE blah ... so that I can quickly see that I should ignore reading this task for now (since I'm only on v1 development)

答: add new task tags for java:  Windows -> Preferences


问:
Numpy blockwise reduce operations
I consider myself an experienced numpy user, but im not able to find a solution for the following problem. Assume there are the following arrays:

```<code># sorted array of times
t = numpy.cumsum(numpy.random.random(size = 100))
#  some values associated with the times
x = numpy.random.random(size=100)
# some indices into the time/data array
indices = numpy.cumsum(numpy.random.randint(low = 1, high=10,size = 20))
indices = indices[indices <90] # respect size of 100
if len(indices) % 2: # make number of indices even
    indices = indices[:-1]

# select some starting and end indices
istart = indices[0::2]
iend   = indices[1::2]
</code>```

What I now want is to reduce the value array x given the intervals denoted by istart and iend. I.e.

```<code># e.g. use max reduce, I'll probably also need mean and stdv
what_i_want = numpy.array([numpy.max(x[is:ie]) for is,ie in zip(istart,iend)])
</code>```

I have already googled a lot but all I could find was blockwise operations via stride_tricks which only allows for regular blocks. I was not able to find a solution without performing a pyhthon loop :-(
In my real application arrays are much larger and performance does matter, so i use numba.jit for the moment.

Is there any numpy function I'm missing which is able to do that?

答:
(A non-numpy solution, using astropy)

import numpy as np
from astropy.nddata.utils import block_reduce
data = np.arange(16).reshape(4, 4)
block_reduce(data, 2)
```

<p>will convert:</p>

```array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
```

<p>to:</p>

```array([[10, 18],
       [42, 50]])
```

See this for more examples.

Title: Numpy blockwise reduce operations

Body:
I consider myself an experienced numpy user, but im not able to find a solution for the following problem. Assume there are the following arrays:

# sorted array of times
t = numpy.cumsum(numpy.random.random(size = 100))
#  some values associated with the times
x = numpy.random.random(size=100)
# some indices into the time/data array
indices = numpy.cumsum(numpy.random.randint(low = 1, high=10,size = 20))
indices = indices[indices <90] # respect size of 100
if len(indices) % 2: # make number of indices even
    indices = indices[:-1]

# select some starting and end indices
istart = indices[0::2]
iend   = indices[1::2]

What I now want is to reduce the value array x given the intervals denoted by istart and iend. I.e.

# e.g. use max reduce, I'll probably also need mean and stdv
what_i_want = numpy.array([numpy.max(x[is:ie]) for is,ie in zip(istart,iend)])

I have already googled a lot but all I could find was blockwise operations via stride_tricks which only allows for regular blocks. I was not able to find a solution without performing a pyhthon loop :-(
In my real application arrays are much larger and performance does matter, so i use numba.jit for the moment.

Is there any numpy function I'm missing which is able to do that?

Body:
(A non-numpy solution, using astropy)

import numpy as np
from astropy.nddata.utils import block_reduce
data = np.arange(16).reshape(4, 4)
block_reduce(data, 2)

will convert:

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

to:

array([[10, 18],
       [42, 50]])

See this for more examples.


问:
how do I select one word from array list like this one?
I have this

```<code>$words = array("Car", "Dog", "Ship");
</code>```

now I want to randomly select only one word, please help!

答:
This could work. </p>

```<code>  $words[rand(0, sizeof($words) - 1)]
</code>```

Body:
I have this

$words = array("Car", "Dog", "Ship");

now I want to randomly select only one word, please help!

Body:
This could work.

  $words[rand(0, sizeof($words) - 1)]


问:
My display function does not display File content in C++ console, the second time I enter the option to display (which is 2 in the menu)
```<code>#include <iostream>
#include <string>
#include <fstream>
using namespace std;

//code to register, display and delete a constituency for election using file handling

fstream constituencies("constituencies.txt", ios::out | ios::in);
fstream temp("temp.txt", ios::out | ios::in);

/* declaring files for constituencies registration and when to delete, a temp file to copy the previous data into it and later rename it as constituencies*/

void registerConstituency() // function to register constituency
{
    // Proccess for constituency
    string consti;
    cout << "\n\nEnter unique constituency\n";
    getline(cin, consti);

    string get_file;
    static bool flag = false;
    /* flag to detect whether the constituency to be registered is already registered or not */

    // searching file if entry by user already exists or not through while loop

    while (getline(constituencies, get_file)) {
        if (get_file == consti) {
            flag = true;
            break;
        }
    }

    if (flag == true) {
        cout << "\nConstituency already exists, try another one\n";
    }
    else {
        ofstream constituencies("constituencies.txt", ios::app);
        constituencies << consti << endl;
        cout << "Your Constituency has been registered\n";
        constituencies.close();
    }
}

void displayConstituency()
{
    string get_file;
    while (getline(constituencies, get_file))
        cout << get_file << endl;
}

void updateOrDelete()
{
    string deleteline;
    string line;

    ofstream temp("temp.txt", ios::app);
    cout << "Which constituency do you want to remove? \n";
    cin >> deleteline;

    while (getline(constituencies, line)) {
        if (line != deleteline) {
            temp << line << endl;
        }
    }

    remove("constituencies.txt");
    rename("temp.txt", "constituencies.txt");
}

void menu()
{
    cout << "Select an option:" << endl
         << endl;
    cout << "1) Register a national assembly constituency (e.g. NA-1)\n";
    cout << "2) List all constituencies\n";
    cout << "3) Update/Delete Constituencies \n";

    int option;
    cout << "option: ";
    cin >> option;

    switch (option) {
    case 1:
        registerConstituency();
        break;

    case 2:
        displayConstituency();
        break;

    case 3:
        updateOrDelete();
        break;

    default: // Invalid option
        cout << "INVALID OPTION!!" << endl;
        break;
    }
}

int main()
{
    for (;;) {
        menu();

        int exit;
        cout << "\nENTER ANY NUMBER TO EXIT\n";
        cin >> exit;
        system("CLS");
    }
}
</code>```

答:
First of all, you need to add fflush(stdin) before getline(cin, consti) in the first defined function, since it's skipping to ask for an input.

And now, let's solve the main problem.

The problem was, the file content in second time execution didn't show up anything.

The reason is: Even after not reading, it'll go to end of file of that file after while(getline()) statement.

To solve that, jump to the second function void displayConstituency():

```<code>void displayConstituency()
{
    string file = "";

    while (getline(constituencies, file))
        cout << file << endl;
        // goes end of file and never jumps to beginning for next execution
}
</code>```

Rather than that, do this:

```<code>void displayConstituency()
{
    string file = "";

    constituencies.clear(); // this
    constituencies.seekg(0, ios::beg); // this

    while (getline(constituencies, file))
        cout << file << endl;
}
</code>```

It clears the EOF and the second lines seeks to beginning of the file again for future use.

Body:
First of all, you need to add fflush(stdin) before getline(cin, consti) in the first defined function, since it's skipping to ask for an input.

And now, let's solve the main problem.

The problem was, the file content in second time execution didn't show up anything.

The reason is: Even after not reading, it'll go to end of file of that file after while(getline()) statement.

To solve that, jump to the second function void displayConstituency():

void displayConstituency()
{
    string file = "";

    while (getline(constituencies, file))
        cout << file << endl;
        // goes end of file and never jumps to beginning for next execution
}

Rather than that, do this:

void displayConstituency()
{
    string file = "";

    constituencies.clear(); // this
    constituencies.seekg(0, ios::beg); // this

    while (getline(constituencies, file))
        cout << file << endl;
}

It clears the EOF and the second lines seeks to beginning of the file again for future use.


问:
How to add text at center of the chart js donut chart
I want to place the text my data values at the center of the chart js donut charts, I don't know how to do that, I checked the chart js official docs, but they didn't provide any information about this, how can I achieve this.

Here is my code:

HTML:

```<code><canvas id="gx_150s_658Ed8745321" width="200" height="120"></canvas>
</code>```

JS:

```<code>var randomScalingFactor = function () {
    return Math.round(Math.random() * 100);
};

var gx_150s_658Ed8745321_ctx = document.getElementById('gx_150s_658Ed8745321').getContext('2d');
var gx_150s_658Ed8745321 = new Chart(gx_150s_658Ed8745321_ctx, {
    type: 'doughnut',
    data: {
        labels: ['Utilized', 'Balence'],
        datasets: [{
            label: 'Utilized',
            data: [95, 5],
            backgroundColor: [
                'rgb(0, 153, 0, 0.7)',

            ],
            borderColor: [
                'rgba(54, 162, 235, 2)',

            ],
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: false
        },
        title: {
            display: true,
            text: ' Utilized  :  95 %'
        },
        animation: {
            animateScale: true,
            animateRotate: true
        },
    }
});
</code>```

Expected output:

答:
I'm using a simple plug-in:

```<code>config = {
    options: {
      //...
    }

    //...

    plugin: [{
            id: 'my-doughnut-text-plugin',
            afterDraw: function (chart, option) {
                let theCenterText = "50%" ;
                const canvasBounds = canvas.getBoundingClientRect();
                const fontSz = Math.floor( canvasBounds.height * 0.10 ) ;
                chart.ctx.textBaseline = 'middle';
                chart.ctx.textAlign = 'center';
                chart.ctx.font = fontSz+'px Arial';
                chart.ctx.fillText(theCenterText, canvasBounds.width/2, canvasBounds.height*0.70 )
            }
    }];

}
</code>```

You still need to calculate what you wan't in the center text (variable theCenterText).

Body:
I want to place the text my data values at the center of the chart js donut charts, I don't know how to do that, I checked the chart js official docs, but they didn't provide any information about this, how can I achieve this.

Here is my code:

HTML:

<canvas id="gx_150s_658Ed8745321" width="200" height="120"></canvas>

JS:

var randomScalingFactor = function () {
    return Math.round(Math.random() * 100);
};

var gx_150s_658Ed8745321_ctx = document.getElementById('gx_150s_658Ed8745321').getContext('2d');
var gx_150s_658Ed8745321 = new Chart(gx_150s_658Ed8745321_ctx, {
    type: 'doughnut',
    data: {
        labels: ['Utilized', 'Balence'],
        datasets: [{
            label: 'Utilized',
            data: [95, 5],
            backgroundColor: [
                'rgb(0, 153, 0, 0.7)',

            ],
            borderColor: [
                'rgba(54, 162, 235, 2)',

            ],
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: false
        },
        title: {
            display: true,
            text: ' Utilized  :  95 %'
        },
        animation: {
            animateScale: true,
            animateRotate: true
        },
    }
});

Expected output:

Body:
I'm using a simple plug-in:

config = {
    options: {
      //...
    }

    //...

    plugin: [{
            id: 'my-doughnut-text-plugin',
            afterDraw: function (chart, option) {
                let theCenterText = "50%" ;
                const canvasBounds = canvas.getBoundingClientRect();
                const fontSz = Math.floor( canvasBounds.height * 0.10 ) ;
                chart.ctx.textBaseline = 'middle';
                chart.ctx.textAlign = 'center';
                chart.ctx.font = fontSz+'px Arial';
                chart.ctx.fillText(theCenterText, canvasBounds.width/2, canvasBounds.height*0.70 )
            }
    }];

}

You still need to calculate what you wan't in the center text (variable theCenterText).


问:
Why does the pre-decrement cause strange changes?
I have the following code in C++

```<code>int factorial_recursivo(int factorial) {

 if(factorial <= 1) return 1;

 // To show all the factors in each iteration std::cout << factorial << std::endl;

 return factorial * factorial_recursivo(--factorial);

}
</code>```

However, if i write a number n, the result is the factorial of the number n-1.

If i change the last line of code the factorial_recursivo(--factorial) by factorial_recursivo(factorial - 1) works properly.

Why this happen? I even printed the factors in console and it correctly showed. Per example, with factoria_recursivo(5) i got 5 4 3 2, however the result was 24.

答:
You should do value - 1 instead:

```<code>return factorial * factorial_recursivo(factorial-1);
</code>```

Executing:

```<code>return factorial * factorial_recursivo(--factorial);
</code>```

results in unsequenced modification and access to factorial. On my laptop it actually produces 6 regardless of what I input as a parameter. Thank you M.M for asking me to clarify this in the comments. This is an example of undefined behavior.

Unsequencing occurs when the end result depends on which operand gets executed first. A simple example of this would be: arr[j] = arr2[++j]; The result of this would depend on whichever gets executed first, whether it would be arr[j] or arr2[++j].
.

Body:
I have the following code in C++

int factorial_recursivo(int factorial) {

 if(factorial <= 1) return 1;

 // To show all the factors in each iteration std::cout << factorial << std::endl;

 return factorial * factorial_recursivo(--factorial);

}

However, if i write a number n, the result is the factorial of the number n-1.

If i change the last line of code the factorial_recursivo(--factorial) by factorial_recursivo(factorial - 1) works properly.

Why this happen? I even printed the factors in console and it correctly showed. Per example, with factoria_recursivo(5) i got 5 4 3 2, however the result was 24.

Body:
You should do value - 1 instead:

return factorial * factorial_recursivo(factorial-1);

Executing:

return factorial * factorial_recursivo(--factorial);

results in unsequenced modification and access to factorial. On my laptop it actually produces 6 regardless of what I input as a parameter. Thank you M.M for asking me to clarify this in the comments. This is an example of undefined behavior.

Unsequencing occurs when the end result depends on which operand gets executed first. A simple example of this would be: arr[j] = arr2[++j]; The result of this would depend on whichever gets executed first, whether it would be arr[j] or arr2[++j].
.


问:
Why .zip is not being created by azure devops for specific webjob project
I have 3 webjob projects on my application

Webjob A, B, and C

When running visual studio ci/cd I got this error on release for Webjob.A project

[error]Error: No package found with specified pattern:

After some investigation I found out that zip files were created for webjob.B and webjob.C but not for webjob.A during publishing artefact.

Anyone have idea what the problem is?

答:
Summary your comment to here to help others who have same issue.

Add the following line in webjob's .csproj file.

```<code><Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.9\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.9\tools\webjobs.targets')" />
</code>```

Body:
Summary your comment to here to help others who have same issue.

Add the following line in webjob's .csproj file.

<Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.9\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.9\tools\webjobs.targets')" />


问:
How to change the color of an svg image?
I'm trying to change the color of this svg img, using TailwindCSS classes:

```<code><svg class="fill-current text-white-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path class="heroicon-ui" d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2zm16 3.38V6H4v1.38l8 4 8-4zm0 2.24l-7.55 3.77a1 1 0 0 1-.9 0L4 9.62V18h16V9.62z"/></svg>
</code>```

and I have the following:

```<code><svg
    class="fill-current text-white inline-block h-20 w-20"
    xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path class="heroicon-ui" d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2zm16 3.38V6H4v1.38l8 4 8-4zm0 2.24l-7.55 3.77a1 1 0 0 1-.9 0L4 9.62V18h16V9.62z"/>
</svg>
</code>```

But it doesn't work. What am I doing wrong?

答:
In Tailwind, there is no text-white-500 it's just text-white.

So far you are doing it right by using fill-current. Simply added fill-current text-red-600. This will change the svg color to #E53E3E. Check the color palette

Body:
I'm trying to change the color of this svg img, using TailwindCSS classes:

<svg class="fill-current text-white-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path class="heroicon-ui" d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2zm16 3.38V6H4v1.38l8 4 8-4zm0 2.24l-7.55 3.77a1 1 0 0 1-.9 0L4 9.62V18h16V9.62z"/></svg>

and I have the following:

<svg
    class="fill-current text-white inline-block h-20 w-20"
    xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path class="heroicon-ui" d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2zm16 3.38V6H4v1.38l8 4 8-4zm0 2.24l-7.55 3.77a1 1 0 0 1-.9 0L4 9.62V18h16V9.62z"/>
</svg>

But it doesn't work. What am I doing wrong?


问:
How to store drawable in an array
I want to download a bunch of images and would like to store it as drawable in an array. So I tried declaring a drawable array.But it returns me nullPointer exception when I access that array.

My question is, how to declare an array type as drawable ?

答:
If you want to store list of elements(any type) dynamically use the classes in the collection. why because Array size is static.
Example:</p>

```<code>ArrayList<Generic> list=new ArrayList<Generic>();

list.add(Generic);
</code>```

Title: How to store drawable in an array

Body:
If you want to store list of elements(any type) dynamically use the classes in the collection. why because Array size is static.
Example:

ArrayList<Generic> list=new ArrayList<Generic>();

list.add(Generic);


问:
Regex help to filter unexpected string
Sorry, I didn't make my quest clear. In the code comment, I hope the first string match=true, and the second string match=false. With the current Regex, both return true. </p>

```<code>public static void main(String[] args) {
    // create a REGEX String
    // Solved: I should use "^/apps/[^/]*/config.*"
    String REGEX = "^/apps/.*/config.*";

    // creare the string
    // in which you want to search
    //this one match
    String actualString = "/apps/test/config.author.dev";

    //I need this one doesn't match
    //String actualString = "/apps/test/test/config.author.dev";

    // compile the regex to create pattern
    // using compile() method
    Pattern pattern = Pattern.compile(REGEX);

    // check whether Regex string is
    // found in actualString or not
    boolean matches = pattern
                          .matcher(actualString)
                          .matches();

    System.out.println("actualString "
                       + "contains REGEX = "
                       + matches);
}
</code>```

答:
I'm going to assume that what you mean is that the string represents some sort of file path, and the "config.author.dev" file must be inside the "apps" folder, but with only one folder between them.

Well, this regex ^/apps/[^/]*/config.* can garantee that no other slash ("/") must exist in the string that separates the "/apps/" from "/config". The "^" means "not the following characters" when inside and at the start of [].

Title: Regex help to filter unexpected string

Body:
Sorry, I didn't make my quest clear. In the code comment, I hope the first string match=true, and the second string match=false. With the current Regex, both return true.

public static void main(String[] args) {
    // create a REGEX String
    // Solved: I should use "^/apps/[^/]*/config.*"
    String REGEX = "^/apps/.*/config.*";

    // creare the string
    // in which you want to search
    //this one match
    String actualString = "/apps/test/config.author.dev";

    //I need this one doesn't match
    //String actualString = "/apps/test/test/config.author.dev";

    // compile the regex to create pattern
    // using compile() method
    Pattern pattern = Pattern.compile(REGEX);

    // check whether Regex string is
    // found in actualString or not
    boolean matches = pattern
                          .matcher(actualString)
                          .matches();

    System.out.println("actualString "
                       + "contains REGEX = "
                       + matches);
}


问:
Preparing JSON tree structure from a JSON javascript
am looking for a JSON tree from a plain JSON.
below is the Input and expected output json.
the input json doesnt have any order
There can be multiple items at each level and each item can have n number of childrens.
leafFlag = 0 means no children
leafFlag = 1 means has chidlren
path is the property which tells where the item will be placed
The expectedOutputJson needs to be placed in a table to display level wise data

var inputJson = [
  {
  "level": "1",
  "leafFlag": "1",
  "path":"p123",
  "name":"food"
},
  {
  "level": "1",
  "leafFlag": "1",
  "path":"r125",
  "name":"car"
},
  {
  "level": "2",
  "leafFlag": "0",
  "path":"p123/p345",
  "name":"apple"
},
 {
  "level": "2",
  "leafFlag": "1",
  "path":"p123/p095",
  "name":"banana"
},
{
  "level": "3",
  "leafFlag": "0",
  "path":"p123/p095/p546",
  "name":"grapes"
},
{
  "level": "2",
  "leafFlag": "1",
  "path":"r125/yhes",
  "name":"tata"
},

]

var expectedOutput = [
  {
    "level": "1",
    "leafFlag": "1",
    "path": "p123",
    "name": "food",
    "children": [
      {
        "level": "2",
        "leafFlag": "0",
        "path": "p123/p345",
        "name": "apple"
      },
      {
        "level": "2",
        "leafFlag": "1",
        "path": "p123/p095",
        "name": "banana",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "p123/p095/p546",
            "name": "grapes"
          }
        ]
      }
    ]
  },
  {
    "level": "1",
    "leafFlag": "1",
    "path": "r125",
    "name": "car",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "r125/yhes",
        "name": "tata",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "r125/yhes/sdie",
            "name": "Range Rover"
          }
        ]
      },
      {
        "level": "2",
        "leafFlag": "0",
        "path": "r125/theys",
        "name": "suzuki"
      }
    ]
  }
]

i tried the below code but not able to proceed further

private prepareTreeStructure = (inputJson) => {
    const treeFormat = (key, index, result) => {
      if (key.indexOf('/') === -1) {
        result = [...result, ...d[key]];
      } else {
        result.forEach((item, index) => {
          let splitKeyArray = key.split('/');
          splitKeyArray.forEach((splitItem, splitIndex) => {
            if (splitKeyArray.indexOf(item.path) !== -1) {
              if (!item['children']) {
                item['children'] = [];
              }
              if (splitKeyArray.length === splitIndex + 1) {
                result[index]['children'] = [...result[index]['children'], ...d[key]];
              }
            }
          });
          if (splitKeyArray.indexOf(item.path) !== -1) {
            if (!result[index]['children']) {
              result[index]['children'] = [];
            }
            result[index]['children'] = [...result[index]['children'], ...d[key]];
          }
        });
      }
      return result;
    }

    const d = inputJson.reduce((acc, ele) => {
      if (!acc[ele.path]) {
        acc[ele.path] = [];
      }
      acc[ele.path].push(ele);
      return acc;
    }, {});
    console.log('dddd  ', d);
    this.result = [];
    Object.keys(d).forEach((key, index) => {
      this.result = treeFormat(key, index, this.result);
      console.log('out ', this.result);
    })

  }

  prepareTreeStructure(inputJson);```

答:
I think you're looking for something like this, works for an n number of levels:

```<code>var inputJson = [
  {
  "level": "1",
  "leafFlag": "1",
  "path":"p123",
  "name":"food"
},
  {
  "level": "1",
  "leafFlag": "1",
  "path":"r125",
  "name":"car"
},
  {
  "level": "2",
  "leafFlag": "0",
  "path":"p123/p345",
  "name":"apple"
},
 {
  "level": "2",
  "leafFlag": "1",
  "path":"p123/p095",
  "name":"banana"
},
{
  "level": "3",
  "leafFlag": "0",
  "path":"p123/p095/p546",
  "name":"grapes"
},
{
  "level": "2",
  "leafFlag": "1",
  "path":"r125/yhes",
  "name":"tata"
}
]
</code>```

And the actual code:

```<code>var output = [];

inputJson = inputJson.sort((a, b) => (parseInt(a.level) > parseInt(b.level)) ? 1 : -1)
inputJson.forEach(v => {
    if (v.level == "1") {
    v.children = [];
    output.push(v);
  }
  else {
    pathValues = v.path.split("/");
    pathValues.pop();
    var node = null;
    var fullPath = "";
    pathValues.forEach(p => {
        fullPath = fullPath === "" ? p : fullPath + "/" + p;
        node = (node == null ? output : node.children).find(o => o.path === fullPath);
    })
    node.children = node.children || [];
    node.children.push(v);
  }
})

console.log(output)
</code>```

See the jsfiddle: https://jsfiddle.net/L984bo6x/8/

Body:
I think you're looking for something like this, works for an n number of levels:

var inputJson = [
  {
  "level": "1",
  "leafFlag": "1",
  "path":"p123",
  "name":"food"
},
  {
  "level": "1",
  "leafFlag": "1",
  "path":"r125",
  "name":"car"
},
  {
  "level": "2",
  "leafFlag": "0",
  "path":"p123/p345",
  "name":"apple"
},
 {
  "level": "2",
  "leafFlag": "1",
  "path":"p123/p095",
  "name":"banana"
},
{
  "level": "3",
  "leafFlag": "0",
  "path":"p123/p095/p546",
  "name":"grapes"
},
{
  "level": "2",
  "leafFlag": "1",
  "path":"r125/yhes",
  "name":"tata"
}
]

And the actual code:

var output = [];

inputJson = inputJson.sort((a, b) => (parseInt(a.level) > parseInt(b.level)) ? 1 : -1)
inputJson.forEach(v => {
    if (v.level == "1") {
    v.children = [];
    output.push(v);
  }
  else {
    pathValues = v.path.split("/");
    pathValues.pop();
    var node = null;
    var fullPath = "";
    pathValues.forEach(p => {
        fullPath = fullPath === "" ? p : fullPath + "/" + p;
        node = (node == null ? output : node.children).find(o => o.path === fullPath);
    })
    node.children = node.children || [];
    node.children.push(v);
  }
})

console.log(output)

See the jsfiddle: https://jsfiddle.net/L984bo6x/8/


问:
Firebase said insecure rules
Firebase is mailing me
That your entire database can be read and write by any user
I have only enabled the email and password system.
My firebase rules are like below.

Here my code :

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
    allow read, write;
    //:if request.auth.uid != null
    }
  }
}
</code>```

答:
I suggest you read up on it here:

https://firebase.google.com/docs/firestore/security/insecure-rules#access_for_any_authenticated_user

All you're doing right now is checking if they've logged in, if so, they can read and write. If that's what you want there's no problem.

Title: Firebase said insecure rules

Body:
Firebase is mailing me
That your entire database can be read and write by any user
I have only enabled the email and password system.
My firebase rules are like below.

Here my code :

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
    allow read, write;
    //:if request.auth.uid != null
    }
  }
}


问:
Using ADF How to Copy Cosmos DB every record individually as complete JSON into a Single column in Azure SQL Table
Using ADF how to Copy Cosmos DB every record individually as complete JSON into a Single column nvarchar(MAX) in Azure SQL Table

答:
Others have posted almost the same questions, per my experience, I tested and didn't find any way could load JSON data into one row nvarchar(MAX) in Azure SQL database table.

No document and blog talks about this,  I'm sorry that I can't give more evidences to prove it.

Hope this helps.


问:
Django: django.db.utils.OperationalError: no such table: #deprecated_bug_assignee when to use "POST" method, but "GET" method is ok
GET Method can response data, happened error when using "POST" method，the error is:

```<code>Django: django.db.utils.OperationalError: no such table: #deprecated_bug_assignee when to use “POST” method, but “GET” method is ok
</code>```

Why? They are using the same table!

views.py

```<code>from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class DeprecatedBugAssigneeList(APIView):
    """
    列出所有的snippets或者创建一个新的snippet。
    """

    def get(self, request, format=None):
        dbsa = DeprecatedBugAssignee.objects.using('slave').all()
        serializer = DeprecatedBugAssigneeSerializer(dbsa, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = DeprecatedBugAssigneeSerializer(data=request.data)
        if serializer.is_valid():
            bug_serializer = serializer.save()
            bug_info = DeprecatedBugAssignee.objects.filter(bugid__exact=request.data['bugid'])
            bug_serializer.add(*bug_info)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

serializer.py

```<code>from apps.cn_relnotes.models import DeprecatedBugAssignee, DeprecatedBugCode

class DeprecatedBugAssigneeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = DeprecatedBugAssignee
        fields = ('bugid', 'oassignee', 'nassignee', 'opdatime', 'operatornm', 'state', 'duration')
</code>```

models.py

```<code>from django.db import models

class DeprecatedBugAssignee(models.Model):
    bugid = models.IntegerField()
    oassignee = models.CharField(max_length=255)
    nassignee = models.CharField(max_length=255)
    opdatime = models.DateTimeField()
    operatornm = models.CharField(max_length=255)
    state = models.CharField(max_length=64, blank=True, null=True)
    duration = models.FloatField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = '#deprecated_bug_assignee'
        unique_together = (('bugid', 'opdatime'),)
</code>```

urls.py

```<code>from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from apps.cn_relnotes import views

urlpatterns = [
    url(r'^v1/bug/$', views.DeprecatedBugAssigneeList.as_view())
]

urlpatterns = format_suffix_patterns(urlpatterns)
</code>```

答:
settings.py

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'slave': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
    },
}

DATABASE_ROUTERS = ['relnotes.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    'project': 'default',
    'app': 'slave'
}
</code>```

Body:
GET Method can response data, happened error when using "POST" method，the error is:

Django: django.db.utils.OperationalError: no such table: #deprecated_bug_assignee when to use “POST” method, but “GET” method is ok

Why? They are using the same table!

views.py

from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class DeprecatedBugAssigneeList(APIView):
    """
    列出所有的snippets或者创建一个新的snippet。
    """

    def get(self, request, format=None):
        dbsa = DeprecatedBugAssignee.objects.using('slave').all()
        serializer = DeprecatedBugAssigneeSerializer(dbsa, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = DeprecatedBugAssigneeSerializer(data=request.data)
        if serializer.is_valid():
            bug_serializer = serializer.save()
            bug_info = DeprecatedBugAssignee.objects.filter(bugid__exact=request.data['bugid'])
            bug_serializer.add(*bug_info)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer.py

from apps.cn_relnotes.models import DeprecatedBugAssignee, DeprecatedBugCode

class DeprecatedBugAssigneeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = DeprecatedBugAssignee
        fields = ('bugid', 'oassignee', 'nassignee', 'opdatime', 'operatornm', 'state', 'duration')

models.py

from django.db import models

class DeprecatedBugAssignee(models.Model):
    bugid = models.IntegerField()
    oassignee = models.CharField(max_length=255)
    nassignee = models.CharField(max_length=255)
    opdatime = models.DateTimeField()
    operatornm = models.CharField(max_length=255)
    state = models.CharField(max_length=64, blank=True, null=True)
    duration = models.FloatField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = '#deprecated_bug_assignee'
        unique_together = (('bugid', 'opdatime'),)

urls.py

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from apps.cn_relnotes import views

urlpatterns = [
    url(r'^v1/bug/$', views.DeprecatedBugAssigneeList.as_view())
]

urlpatterns = format_suffix_patterns(urlpatterns)

Body:
settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'slave': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
    },
}

DATABASE_ROUTERS = ['relnotes.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    'project': 'default',
    'app': 'slave'
}