问:
Defer notification deep linking until after react-native expo app is fully loaded
I would like to defer the deep-link navigation event tied to a notification until the app is fully loaded after my react-native app is opened on notification click.

Currently, my notification listener is in my App.tsx file. The deep linking works as expected when the app is backgrounded, but when the notification triggers the app to open, the navigation event is kicked off before the App has a chance to fully load. This means that although I do get deep linked to the correct location, some of my assets aren't yet loaded and my auth logic is all bypassed.

Is there a way to have a notification open the app, but wait until everything is loaded (specifically the AppLoading component has finished running its functions) to navigate to the deep linking location? I can think of some hack-y seeming ways to do this but is there an established pattern that is commonly used?

答:
Ok so I'm not sure if this is the best way to handle this but I found a way to get my notifications working.

(1) I created an action called registerAppLoaded and a state variable appLoaded that I dispatch once my AppLoading component finishes its startAsync functions.

(2) When a notification comes in, I first check to see if appLoaded is true. If so, I navigate to the destination sent along with the notification. If not, I put the notification in the store and carry on with firing up the app.

(3) in the AppLoading onFinish function, I check to see if there is a notification. If so, and it is marked new, I grab it and use the params to navigate. Then I dispatch an action that sets navigation.new = false

Seems to work exactly the way i need it to!

Here is my code if anyone else is dealing with this issue:

App.tsx:

```<code>export default class App extends React.Component {

  componentDidMount() {
    Notifications.addListener((notification) => {
      if (notification.origin === "received") {
        return;
      } else {
        const appLoaded = store.getState().general.appLoaded
        if (appLoaded) {
          NavigationService.navigate(notification.data.navigate, {id:notification.data.id , shouldRefresh: true})
        } else {
          // save notification as new
          store.dispatch(addNotification(notification, true));
        }
      };
    })
  }

  render() {
    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <View style={styles.container}>
            {Platform.OS === "ios" && <StatusBar barStyle="default" />}
            <ErrorBoundary backup={<AppError />}>
              <AppNavigator />
            </ErrorBoundary>
          </View>
        </PersistGate>
      </Provider>
    );
  }
}
</code>```

AppLoading.tsx:

```<code>class AppLoadingScreen extends React.Component {
  _loadResourcesAsync = async() => {
    await this.props.fetchUserOnboarding(this.props.userId);
    if (this.props.userDevice && this.props.userDevice.id) {
      this.props.registerUserDevice(this.props.userId, this.props.userDevice.id)
    }
    // register that the app has finished loading in the store; this will be used to determine if a notification's deep
    // link should be immediatedly navigated to or if the navigation even shuold be deferred until after the app
    // finishes loading
    await this.props.registerAppLoaded()
  };

  _handleFinishLoading = async () => {
    // if a notification triggers the event listener but the app is not yet fully loaded, the deep link will be
    // navigated to here instead of directly from the listener
    const notification = this.props.userNotifications && this.props.userNotifications[0]
    if (notification && notification.new && notification.origin != 'recieved') {
      this.props.addNotification(notification, false) // set notification.new = false
      this.props.navigation.navigate(notification.data.navigate, {id: notification.data.id, shouldRefresh: true})
    } else if (this.props.showGoalsPrompt) {
      this.props.navigation.navigate("Goal");
    } else {
      this.props.navigation.navigate("HomeFeed");
    }
  };

  render() {
    return (
      <AppLoading
        startAsync={this._loadResourcesAsync}
        onFinish={this._handleFinishLoading}
      />
    );
  }
}
</code>```

actions.tsx:

```<code>export const registerAppLoaded = () => {
  return dispatch => {
    dispatch({
      type: types.REGISTER_APP_LOADED,
      payload: true
    });
  };
}

export const addNotification = (notification, isNew=false) => {
  return dispatch => {
    notification.new = isNew // indicate whether this is a new notification or if it has been seen
    dispatch({
      type:types.ADD_USER_NOTIFICATION,
      payload: notification,
    })
  };
}
</code>```

Body:
Ok so I'm not sure if this is the best way to handle this but I found a way to get my notifications working.

(1) I created an action called registerAppLoaded and a state variable appLoaded that I dispatch once my AppLoading component finishes its startAsync functions.

(2) When a notification comes in, I first check to see if appLoaded is true. If so, I navigate to the destination sent along with the notification. If not, I put the notification in the store and carry on with firing up the app.

(3) in the AppLoading onFinish function, I check to see if there is a notification. If so, and it is marked new, I grab it and use the params to navigate. Then I dispatch an action that sets navigation.new = false

Seems to work exactly the way i need it to!

Here is my code if anyone else is dealing with this issue:

App.tsx:

export default class App extends React.Component {

  componentDidMount() {
    Notifications.addListener((notification) => {
      if (notification.origin === "received") {
        return;
      } else {
        const appLoaded = store.getState().general.appLoaded
        if (appLoaded) {
          NavigationService.navigate(notification.data.navigate, {id:notification.data.id , shouldRefresh: true})
        } else {
          // save notification as new
          store.dispatch(addNotification(notification, true));
        }
      };
    })
  }

  render() {
    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <View style={styles.container}>
            {Platform.OS === "ios" && <StatusBar barStyle="default" />}
            <ErrorBoundary backup={<AppError />}>
              <AppNavigator />
            </ErrorBoundary>
          </View>
        </PersistGate>
      </Provider>
    );
  }
}

AppLoading.tsx:

class AppLoadingScreen extends React.Component {
  _loadResourcesAsync = async() => {
    await this.props.fetchUserOnboarding(this.props.userId);
    if (this.props.userDevice && this.props.userDevice.id) {
      this.props.registerUserDevice(this.props.userId, this.props.userDevice.id)
    }
    // register that the app has finished loading in the store; this will be used to determine if a notification's deep
    // link should be immediatedly navigated to or if the navigation even shuold be deferred until after the app
    // finishes loading
    await this.props.registerAppLoaded()
  };

  _handleFinishLoading = async () => {
    // if a notification triggers the event listener but the app is not yet fully loaded, the deep link will be
    // navigated to here instead of directly from the listener
    const notification = this.props.userNotifications && this.props.userNotifications[0]
    if (notification && notification.new && notification.origin != 'recieved') {
      this.props.addNotification(notification, false) // set notification.new = false
      this.props.navigation.navigate(notification.data.navigate, {id: notification.data.id, shouldRefresh: true})
    } else if (this.props.showGoalsPrompt) {
      this.props.navigation.navigate("Goal");
    } else {
      this.props.navigation.navigate("HomeFeed");
    }
  };

  render() {
    return (
      <AppLoading
        startAsync={this._loadResourcesAsync}
        onFinish={this._handleFinishLoading}
      />
    );
  }
}

actions.tsx:

export const registerAppLoaded = () => {
  return dispatch => {
    dispatch({
      type: types.REGISTER_APP_LOADED,
      payload: true
    });
  };
}

export const addNotification = (notification, isNew=false) => {
  return dispatch => {
    notification.new = isNew // indicate whether this is a new notification or if it has been seen
    dispatch({
      type:types.ADD_USER_NOTIFICATION,
      payload: notification,
    })
  };
}


来源: stackexchange

问:
Javascript\JQuery function does not work without an alert
I have a problem with my 2 JQuery\Javascript functions. My problem is that when I dont have alerts in both my functions, both the functions don't work properly, and the event agument and eventtarget parameters are overwritten.

please advise on the solution for this.

```<code> function SubmitAdded() {

      $(document).ready(function (){
      var arrAdded = new Array();
      $('#JQAddedList li').each(function (i) {
          arrAdded[i] = $(this).text();
      });

          __doPostBack("AddActivity", arrAdded);
         // alert('if this alert is commented out, function does not work.');

 });
  }
</code>```

答:
I usually take situations like this to mean that there is a timing issue involved. The alert box causes the script to pause long enough for the the state to change. If the alert doesnt occur then the script speeds through too quickly and your page/script wasnt in the state you thought it would be in when it runs through.

I'm not sure without more details, but offhand your script looks wrong in that it is wiring up a document ready event inside another function. You should try refactoring it into two functions and see if that fixes it.

```<code>$(document).ready(function (){
    var arrAdded = new Array();
    $('#JQAddedList li').each(function (i) {
        arrAdded[i] = $(this).text();
    });
});

function SubmitAdded() {
    __doPostBack("AddActivity", arrAdded);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with my 2 JQuery\Javascript functions. My problem is that when I dont have alerts in both my functions, both the functions don't work properly, and the event agument and eventtarget parameters are overwritten.

please advise on the solution for this.

 function SubmitAdded() {

      $(document).ready(function (){
      var arrAdded = new Array();
      $('#JQAddedList li').each(function (i) {
          arrAdded[i] = $(this).text();
      });

          __doPostBack("AddActivity", arrAdded);
         // alert('if this alert is commented out, function does not work.');

 });
  }

Body:
I usually take situations like this to mean that there is a timing issue involved. The alert box causes the script to pause long enough for the the state to change. If the alert doesnt occur then the script speeds through too quickly and your page/script wasnt in the state you thought it would be in when it runs through.

I'm not sure without more details, but offhand your script looks wrong in that it is wiring up a document ready event inside another function. You should try refactoring it into two functions and see if that fixes it.

$(document).ready(function (){
    var arrAdded = new Array();
    $('#JQAddedList li').each(function (i) {
        arrAdded[i] = $(this).text();
    });
});

function SubmitAdded() {
    __doPostBack("AddActivity", arrAdded);
}


问:
How to handle a C++ header file with a extern call to C function and a class object
I am trying to compile an application involving both C and C++ files. With one particular header I face issues. The file in question (a C++ header file), would look something like this:

```<code>#ifndef TASK_H
#define TASK_H

#include "MyCCPObject.h"

int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type

#ifdef __cplusplus
extern "C" {
#endif
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H
</code>```

I have a function fooObject() which has a MyCCPObject class type as a parameter. Also, one of the functions, foo3() would be called from a C file.
When the C compiler, compiles this header, I get the following error:  "error: #20:identifier "class" is undefined". To avoid this, I had to:

Place the fooObject() declaration within compiler guards:

```<code>#ifdef __cplusplus
int fooObject(MyCCPObject myCppObject);
#endif
</code>```

Place compiler guards also in the class declaration in the header file MyCCPObject.h:

```<code>#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#endif
</code>```

Note: The MyCCPObject would not be called in any C file.
So, what would be a better approach, when I have a C++ header file, which involves:

Function would involves a class object

A extern call to a C file

答:
Use separate headers for your C and C++ code.

Move the foo3 declaration (including the __cplusplus guards) inside a separate header. Let's call it Foo3.h
You now have the following files:

Task.h - contains the declarations for foo1 and foo2, fooObject and includes MyCCPObject.h

Foo3.h - contains the declarations for foo3

Task.cpp - includes Task.h and Foo3.h and provides definitions for foo1, foo2 and foo3

App.c - includes Foo3.h and uses foo3

From your build system (make, cmake etc.), when building the C++ library, add the files Task.h, Foo3.h, Task.cpp (and the other files related to MyCCPObject)

When building the C application, add only Foo3.h and App.c. That way, the other headers (which contain C++ code) will not be compiled and hence not give out any errors.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to compile an application involving both C and C++ files. With one particular header I face issues. The file in question (a C++ header file), would look something like this:

#ifndef TASK_H
#define TASK_H

#include "MyCCPObject.h"

int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type

#ifdef __cplusplus
extern "C" {
#endif
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H

I have a function fooObject() which has a MyCCPObject class type as a parameter. Also, one of the functions, foo3() would be called from a C file.
When the C compiler, compiles this header, I get the following error:  "error: #20:identifier "class" is undefined". To avoid this, I had to:

Place the fooObject() declaration within compiler guards:

#ifdef __cplusplus
int fooObject(MyCCPObject myCppObject);
#endif

Place compiler guards also in the class declaration in the header file MyCCPObject.h:

#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#endif

Note: The MyCCPObject would not be called in any C file.
So, what would be a better approach, when I have a C++ header file, which involves:

Function would involves a class object

A extern call to a C file


问:
How to find the common words between 2 strings and return those sorted
I'm trying to resolve a dilemma in Javascript. I would like to find the common words between 2 strings. For example, I have the next strings "hello, world", "hello, earth" and the common word is "hello" and also "one,two,three", "four,five,one,two,six,three" ==> "one,three,two"

I tried to use thee for loop but not in a classic way but I got issues and I 'm printing the wrong result.

```<code>const commonWords = (a, b) => {
  const w = [];

  const first = a.split(",");
  const second = b.split(",");

  for (let c in first) {
    if (second, c.length >= 1) {
      w.push(c);
      w.sort();
    }
  }

  return (w);
};

console.log(commonWords("hello,world", "hello,earth"));
</code>```

I would like to understand if my approach is good or there is the best way of doing it

答:
```<code>const commonWords = (a, b) => {
let w;
let first = a.split(",");
let second = b.split(",");
let temp;

if (second.length > first.length) {temp = second; second = first; first = temp;}
w =  first.filter(function (e) {
    return second.indexOf(e) > -1;
});

return w.sort();
};

console.log(commonWords("one,two,three", "four,five,one,two,six,three"));
</code>```

["one", "three", "two"]

Body:
I'm trying to resolve a dilemma in Javascript. I would like to find the common words between 2 strings. For example, I have the next strings "hello, world", "hello, earth" and the common word is "hello" and also "one,two,three", "four,five,one,two,six,three" ==> "one,three,two"

I tried to use thee for loop but not in a classic way but I got issues and I 'm printing the wrong result.

const commonWords = (a, b) => {
  const w = [];

  const first = a.split(",");
  const second = b.split(",");

  for (let c in first) {
    if (second, c.length >= 1) {
      w.push(c);
      w.sort();
    }
  }

  return (w);
};

console.log(commonWords("hello,world", "hello,earth"));

I would like to understand if my approach is good or there is the best way of doing it

Body:
const commonWords = (a, b) => {
let w;
let first = a.split(",");
let second = b.split(",");
let temp;

if (second.length > first.length) {temp = second; second = first; first = temp;}
w =  first.filter(function (e) {
    return second.indexOf(e) > -1;
});

return w.sort();
};

console.log(commonWords("one,two,three", "four,five,one,two,six,three"));

["one", "three", "two"]


问:
Apply a fading-effect to main container but not to its content with jQuery
I am using the following code to make my homepage to fade-out when scrolling down and fade-in when scrolling up. But I would like this effect to be applied only to the background colour (#top) and not to the text on it (.intro-top) Is it possible?

```<code><!-- Fade Home Page -->
<script type="text/javascript">

var $socialDiv = $('#top');

$(window).scroll(function() {
  //Get scroll position of window
  var windowScroll = $(this).scrollTop();

  //Slow scroll of home-page and fade it out
  $socialDiv.css({
    'opacity': 1 - (windowScroll / 770) // Number of pixels to fade
  });
});

</script>
</code>```

HTML:

```<code><section class="full-height section-scroll" id="top">
     <div class="wow fadeInUp">
        <div class="intro-top">
           <h1>Lorem Ipsum - Lorem Ipsum</h1>
        </div>
     </div>
  </section>
</code>```

CSS:

```<code>#top {
height: 100vh;
background-color: yellow;
}
</code>```

答:
I believe the simplest way is to transition the background-color property, and use rgba colours:

```<code>#top {
  height: 100vh;
  background-color: rgba(255, 255, 0, 1); /* Still yellow, but in rgba */
}
</code>```

```<code>let opacity = 1 - (windowScroll / 770)
$socialDiv.css({
  'background-color': `rgba(255, 255, 0, ${opacity})`
});
</code>```

Body:
I am using the following code to make my homepage to fade-out when scrolling down and fade-in when scrolling up. But I would like this effect to be applied only to the background colour (#top) and not to the text on it (.intro-top) Is it possible?

HTML:

Lorem Ipsum - Lorem Ipsum

CSS:

#top {
height: 100vh;
background-color: yellow;
}

Body:
I believe the simplest way is to transition the background-color property, and use rgba colours:

#top {
  height: 100vh;
  background-color: rgba(255, 255, 0, 1); /* Still yellow, but in rgba */
}

let opacity = 1 - (windowScroll / 770)
$socialDiv.css({
  'background-color': `rgba(255, 255, 0, ${opacity})`
});


问:
Converting value into a Decimal
I have a percent column that saves values as a whole number. I need to calculate the percent of payments from a payment column by multiplying by the percent column. Currently my table looks like the following:

```<code>+----+---------+---------+
| ID | PAYMENT | PERCENT |
+----+---------+---------+
|  1 |     500 |      15 |
|  2 |      75 |       5 |
|  3 |    1250 |      20 |
+----+---------+---------+
</code>```

I need the output to look as follows:

```<code>+----+---------+---------+-------------+
| ID | PAYMENT | PERCENT |  COMMISSION |
+----+---------+---------+-------------+
|  1 |     500 |     .15 |          75 |
|  2 |      75 |     .05 |        3.75 |
|  3 |    1250 |     .20 |         250 |
+----+---------+---------+-------------+

</code>```

I have tried different variations of the below to convert the percent column into a decimal:

```<code>cast(percent as numeric (5,2))
cast(percent as decimal(5,2))
to_char(percent,'9999.99')
</code>```

答:
Divide by 100.

SELECT id,
       payment,
       percent / 100 AS percent,
       payment * percent / 100 AS commission
FROM   table_name;
```

<p>So for your data:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name ( id, payment, percent ) AS
SELECT 1,  500, 15 FROM DUAL UNION ALL
SELECT 2,   75,  5 FROM DUAL UNION ALL
SELECT 3, 1250, 20 FROM DUAL;
</code>```

This would output:

```
ID | PAYMENT | PERCENT | COMMISSION
-: | ------: | ------: | ---------:
 1 |     500 |     .15 |         75
 2 |      75 |     .05 |       3.75
 3 |    1250 |      .2 |        250
```

db<>fiddle here

Is there another way [to divide by 100]?

Any of these would work:

SELECT id,
       percent / 100 AS opt1,
       percent * 0.01 AS opt2,
       TO_NUMBER( percent || 'e-2' ) AS opt3,
       percent * POWER( 10, -2 ) AS opt4,
       ROUND(POWER(10,LOG(10, percent)-2),2) AS opt5
FROM   table_name;
```

<p>and outputs:</p>

<blockquote>
```
ID | OPT1 | OPT2 | OPT3 | OPT4 | OPT5
-: | ---: | ---: | ---: | ---: | ---:
 1 |  .15 |  .15 |  .15 |  .15 |  .15
 2 |  .05 |  .05 |  .05 |  .05 |  .05
 3 |   .2 |   .2 |   .2 |   .2 |   .2
```

But don't; just use the simplest method that you can.

db<>fiddle here

Title: Converting value into a Decimal

Body:
I have a percent column that saves values as a whole number. I need to calculate the percent of payments from a payment column by multiplying by the percent column. Currently my table looks like the following:

+----+---------+---------+
| ID | PAYMENT | PERCENT |
+----+---------+---------+
|  1 |     500 |      15 |
|  2 |      75 |       5 |
|  3 |    1250 |      20 |
+----+---------+---------+

I need the output to look as follows:

+----+---------+---------+-------------+
| ID | PAYMENT | PERCENT |  COMMISSION |
+----+---------+---------+-------------+
|  1 |     500 |     .15 |          75 |
|  2 |      75 |     .05 |        3.75 |
|  3 |    1250 |     .20 |         250 |
+----+---------+---------+-------------+

I have tried different variations of the below to convert the percent column into a decimal:

cast(percent as numeric (5,2))
cast(percent as decimal(5,2))
to_char(percent,'9999.99')

Body:
Divide by 100.

SELECT id,
       payment,
       percent / 100 AS percent,
       payment * percent / 100 AS commission
FROM   table_name;

So for your data:

CREATE TABLE table_name ( id, payment, percent ) AS
SELECT 1,  500, 15 FROM DUAL UNION ALL
SELECT 2,   75,  5 FROM DUAL UNION ALL
SELECT 3, 1250, 20 FROM DUAL;

This would output:

ID | PAYMENT | PERCENT | COMMISSION
-: | ------: | ------: | ---------:
 1 |     500 |     .15 |         75
 2 |      75 |     .05 |       3.75
 3 |    1250 |      .2 |        250

db<>fiddle here

Is there another way [to divide by 100]?

Any of these would work:

SELECT id,
       percent / 100 AS opt1,
       percent * 0.01 AS opt2,
       TO_NUMBER( percent || 'e-2' ) AS opt3,
       percent * POWER( 10, -2 ) AS opt4,
       ROUND(POWER(10,LOG(10, percent)-2),2) AS opt5
FROM   table_name;

and outputs:

ID | OPT1 | OPT2 | OPT3 | OPT4 | OPT5
-: | ---: | ---: | ---: | ---: | ---:
 1 |  .15 |  .15 |  .15 |  .15 |  .15
 2 |  .05 |  .05 |  .05 |  .05 |  .05
 3 |   .2 |   .2 |   .2 |   .2 |   .2

But don't; just use the simplest method that you can.

db<>fiddle here


问:
MongoDB return where array contains at least one item from query array
I have a collection with records that have a tags field, similar to this:

```<code>[
  {
    "title": "foo",
    "tags": [ "fizz", "buzz", "quz" ]
  }
]
</code>```

I would like to be able to search these against an array, so I could search for records matching at least one of the passed in array values, so query with [ "fizz" ] would match, or [ "fizz", "quz" ] would match but [ "bar" ] would not.

I've tried $elemMatch but that seems to only return the record when all elements from the query array match the tags array in the record.

答:
The $in query operator should accomplish what you need:

For a quick demo, I created a collection with several variations of an array:

```<code>[
  { arr: [ "a", "b", "c" ] },
  { arr: [ "b", "c", "d" ] },
  { arr: [ "c", "d", "e" ] },
  { arr: [ "d", "e", "f" ] }
]
</code>```

Query for documents that contain "a" or "b" returns the first 2:

```<code>db.collection.find({ arr: { $in: [ "a", "b", ] } })
</code>```

Playground

Body:
I have a collection with records that have a tags field, similar to this:

[
  {
    "title": "foo",
    "tags": [ "fizz", "buzz", "quz" ]
  }
]

I would like to be able to search these against an array, so I could search for records matching at least one of the passed in array values, so query with [ "fizz" ] would match, or [ "fizz", "quz" ] would match but [ "bar" ] would not.

I've tried $elemMatch but that seems to only return the record when all elements from the query array match the tags array in the record.

Body:
The $in query operator should accomplish what you need:

For a quick demo, I created a collection with several variations of an array:

[
  { arr: [ "a", "b", "c" ] },
  { arr: [ "b", "c", "d" ] },
  { arr: [ "c", "d", "e" ] },
  { arr: [ "d", "e", "f" ] }
]

Query for documents that contain "a" or "b" returns the first 2:

db.collection.find({ arr: { $in: [ "a", "b", ] } })

Playground


问:
How to use sleep to limit data put in logs?
I am totally new to python and just started with it.
I wrote following script go get some data from the SenseHat, but unfortunately it doesn't do what it should.

It should get the temp, humidity and pressure from the SenseHat and write in to a file "data.csv" every 10 minutes.

Without the sleep(600) the script works fine, but logs to much data. With the sleep function it seems it does nothing...

This is my script:

```<code>from sense_hat import SenseHat
from datetime import datetime
from csv import writer
from time import sleep

sense = SenseHat()

def get_sense_data():
    sense_data = []
    sense_data.append(datetime.now())
    sense_data.append(sense.get_temperature())
    sense_data.append(sense.get_pressure())
    sense_data.append(sense.get_humidity())

    return sense_data

#while True:
#    print(get_sense_data())

with open('data.csv', 'wb') as f:
    data_writer = writer(f)
    data_writer.writerow(['time','temp','pres','hum'])

    while True:
        data = get_sense_data()
        data_writer.writerow(data)

        sleep(600)from sense_hat import SenseHat
from datetime import datetime
from csv import writer
from time import sleep

sense = SenseHat()

def get_sense_data():
    sense_data = []
    sense_data.append(datetime.now())
    sense_data.append(sense.get_temperature())
    sense_data.append(sense.get_pressure())
    sense_data.append(sense.get_humidity())

    return sense_data

#while True:
#    print(get_sense_data())

with open('data.csv', 'wb') as f:
    data_writer = writer(f)
    data_writer.writerow(['time','temp','pres','hum'])

    while True:
        data = get_sense_data()
        data_writer.writerow(data)

        sleep(600)
</code>```

Please could anyone help me and explain to me what is wrong...?

答:
Output to files is buffered. If you want to see the intermediate results of the script while it's sleeping, you need to flush the buffer.</p>

```<code>with open('data.csv', 'wb') as f:
    data_writer = writer(f)
    data_writer.writerow(['time','temp','pres','hum'])

    while True:
        data = get_sense_data()
        data_writer.writerow(data)
        f.flush()
        sleep(600)
</code>```

Body:
I am totally new to python and just started with it.
I wrote following script go get some data from the SenseHat, but unfortunately it doesn't do what it should.

It should get the temp, humidity and pressure from the SenseHat and write in to a file "data.csv" every 10 minutes.

Without the sleep(600) the script works fine, but logs to much data. With the sleep function it seems it does nothing...

This is my script:

from sense_hat import SenseHat
from datetime import datetime
from csv import writer
from time import sleep

sense = SenseHat()

def get_sense_data():
    sense_data = []
    sense_data.append(datetime.now())
    sense_data.append(sense.get_temperature())
    sense_data.append(sense.get_pressure())
    sense_data.append(sense.get_humidity())

    return sense_data

#while True:
#    print(get_sense_data())

with open('data.csv', 'wb') as f:
    data_writer = writer(f)
    data_writer.writerow(['time','temp','pres','hum'])

    while True:
        data = get_sense_data()
        data_writer.writerow(data)

        sleep(600)from sense_hat import SenseHat
from datetime import datetime
from csv import writer
from time import sleep

sense = SenseHat()

def get_sense_data():
    sense_data = []
    sense_data.append(datetime.now())
    sense_data.append(sense.get_temperature())
    sense_data.append(sense.get_pressure())
    sense_data.append(sense.get_humidity())

    return sense_data

#while True:
#    print(get_sense_data())

with open('data.csv', 'wb') as f:
    data_writer = writer(f)
    data_writer.writerow(['time','temp','pres','hum'])

    while True:
        data = get_sense_data()
        data_writer.writerow(data)

        sleep(600)

Please could anyone help me and explain to me what is wrong...?

Body:
Output to files is buffered. If you want to see the intermediate results of the script while it's sleeping, you need to flush the buffer.

with open('data.csv', 'wb') as f:
    data_writer = writer(f)
    data_writer.writerow(['time','temp','pres','hum'])

    while True:
        data = get_sense_data()
        data_writer.writerow(data)
        f.flush()
        sleep(600)


问:
Store representations in SQL rather than whole strings?
I want to mark my users with one out of four static strings: indestructible, unstoppable, superefficient and megafantastic.

Would it be faster and more efficient to store a one char representation of the string rather than the whole string? Sort of like a key<->value mapping. The DB would only need to match one letter instead of a whole string when I do a search.

In the DB these words would only be represented as i,u,s and m. On the users profile I print indesctuctible if I get an i, unstoppable if I get a u etc.

Do I actually speed up anything by doing like this or is it just unnecessary work?

What if I have 10 more of these representations?

答:
If you are talking about database design, you should have a normalized design.

Create a lookup table id/name, store the id value in your user table (use something like a tinyint).

```<code>ID  Name
1   indestructible
2   unstoppable
3   superefficient
4   megafantastic
</code>```

This way you can query the database directly for the string.

If you cache this table, you will not be hitting the database for these values, and you will only be storing a small amount of data per user (not to mention transfer less data over the wire) - these all translate to better performance on your DB.

Body:
If you are talking about database design, you should have a normalized design.

Create a lookup table id/name, store the id value in your user table (use something like a tinyint).

ID  Name
1   indestructible
2   unstoppable
3   superefficient
4   megafantastic

This way you can query the database directly for the string.

If you cache this table, you will not be hitting the database for these values, and you will only be storing a small amount of data per user (not to mention transfer less data over the wire) - these all translate to better performance on your DB.


问:
TypeScript type definition for flatten function
I have simple flatten function. The idea is that it can take array of strings or array of arrays of strings and always return just 1 level array of strings. For example:

```<code>flatten(['a', ['b']]) // returns ['a', 'b']
flatten(['a', 'b']) // returns ['a', 'b']
</code>```

Here is implementation of this function

```<code>function flatten(arr: ReadonlyArray<string | string[]>): string[] {
   return [].concat(...arr);
}
</code>```

I'm getting following TypeScript compiler Error:

```<code>  error TS2769: No overload matches this call.
    Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
      Argument of type 'string | string[]' is not assignable to parameter of type 'ConcatArray<never>'.
        Type 'string' is not assignable to type 'ConcatArray<never>'.
    Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
      Argument of type 'string | string[]' is not assignable to parameter of type 'ConcatArray<never>'.
        Type 'string' is not assignable to type 'ConcatArray<never>'.

  105   return [].concat(...arr);
                        ~~~~~~
</code>```

How can I define types for input and output of this flatten function? I want to avoid using any type.

答:
You have to specify the type for the returned value, in this case, an array of strings.</p>

```<code>function flatten(arr: ReadonlyArray<string | string[]>): string[] {
    const output: string[] = [];
    return output.concat(...arr);
}
</code>```

Body:
I have simple flatten function. The idea is that it can take array of strings or array of arrays of strings and always return just 1 level array of strings. For example:

flatten(['a', ['b']]) // returns ['a', 'b']
flatten(['a', 'b']) // returns ['a', 'b']

Here is implementation of this function

function flatten(arr: ReadonlyArray<string | string[]>): string[] {
   return [].concat(...arr);
}

I'm getting following TypeScript compiler Error:

  error TS2769: No overload matches this call.
    Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
      Argument of type 'string | string[]' is not assignable to parameter of type 'ConcatArray<never>'.
        Type 'string' is not assignable to type 'ConcatArray<never>'.
    Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
      Argument of type 'string | string[]' is not assignable to parameter of type 'ConcatArray<never>'.
        Type 'string' is not assignable to type 'ConcatArray<never>'.

  105   return [].concat(...arr);
                        ~~~~~~

How can I define types for input and output of this flatten function? I want to avoid using any type.

Body:
You have to specify the type for the returned value, in this case, an array of strings.

function flatten(arr: ReadonlyArray<string | string[]>): string[] {
    const output: string[] = [];
    return output.concat(...arr);
}


问:
JSON Feed to RSS (Problems)
I am having a problem with converting a JSON feed into a RSS feed. I am attempting to do this in a single function, seen below.

I found code on GitHub — but it doesn't work properly — and I don't know how to fix it.

In the bottom of the PHP code: echo convert_jsonfeed_to_rss($content)."\n";
I am expecting this to print out the RSS XML feed — it doesn't.

<?php

//Convert JSONfeed to RSS in a single function as a drop in to make adding JSONfeed
//support to an aggregator easier
function convert_jsonfeed_to_rss($content = NULL, $max = NULL)
{
    //Test if the content is actual JSON
    json_decode($content);
    if( json_last_error() !== JSON_ERROR_NONE) return FALSE;

    //Now, is it valid JSONFeed?
    $jsonFeed = json_decode($content, TRUE);
    if (!isset($jsonFeed['version'])) return FALSE;
    if (!isset($jsonFeed['title'])) return FALSE;
    if (!isset($jsonFeed['items'])) return FALSE;

    //Decode the feed to a PHP array
    $jf = json_decode($content, TRUE);

    //Get the latest item publish date to use as the channel pubDate
    $latestDate = 0;
    foreach ($jf['items'] as $item) {
        if (strtotime($item['date_published']) > $latestDate) $latestDate = strtotime($item['date_published']);
    }
    $lastBuildDate = date(DATE_RSS, $latestDate);

    //Create the RSS feed
    $xmlFeed = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"></rss>');
    $xmlFeed->addChild("channel");

    //Required elements
    $xmlFeed->channel->addChild("title", $jf['title']);
    $xmlFeed->channel->addChild("pubDate", $lastBuildDate);
    $xmlFeed->channel->addChild("lastBuildDate", $lastBuildDate);

    //Optional elements
    if (isset($jf['description'])) $xmlFeed->channel->description = $jf['description'];
    if (isset($jf['home_page_url'])) $xmlFeed->channel->link = $jf['home_page_url'];

    //Items
    foreach ($jf['items'] as $item) {
        $newItem = $xmlFeed->channel->addChild('item');

        //Standard stuff
        if (isset($item['id'])) $newItem->addChild('guid', $item['id']);
        if (isset($item['title'])) $newItem->addChild('title', $item['title']);
        if (isset($item['content_text'])) $newItem->addChild('description', $item['content_text']);
        if (isset($item['content_html'])) $newItem->addChild('description', $item['content_html']);
        if (isset($item['date_published'])) $newItem->addChild('pubDate', $item['date_published']);
        if (isset($item['url'])) $newItem->addChild('link', $item['url']);

        //Enclosures?
        if(isset($item['attachments'])) {
            foreach($item['attachments'] as $attachment) {
                $enclosure = $newItem->addChild('enclosure');
                $enclosure['url'] = $attachment['url'];
                $enclosure['type'] = $attachment['mime_type'];
                $enclosure['length'] = $attachment['size_in_bytes'];
            }
        }
    }

    //Make the output pretty
    $dom = new DOMDocument("1.0");
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($xmlFeed->asXML());
    return $dom->saveXML();
}

$content = @file_get_contents("http://timetable.manton.org/feed.json");
echo convert_jsonfeed_to_rss($content)."\n";
```

<p>I tried to put the <code>$content</code> variable before the <code>convert_jsonfeed_to_rss</code> function — same problem.</p>

<pre class="lang-php prettyprint-override"><code>$content = @file_get_contents("http://timetable.manton.org/feed.json");
</code>```

答:
The conversion to a DOMDocument at the end seems to be the issue, it objects to a few parts of the document.

A quicker way (and seems to be more reliable in this case) is to just use dom_import_simplexml()

```<code>$dom = dom_import_simplexml($xmlFeed)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
return $dom->saveXML();
</code>```

(from https://stackoverflow.com/a/799792/1213708).

Edit

From your updated code, you aren't using the hierarchy properly (and probably don't have errors enabled to show what is not working).

You need something like...

```<code>foreach ($jf['data']['feed'] as $item1) {
//      foreach ($item1['feed'] as $item) {

        $item = $item1['article'];
</code>```

Title: JSON Feed to RSS (Problems)

Body:
I am having a problem with converting a JSON feed into a RSS feed. I am attempting to do this in a single function, seen below.

I found code on GitHub — but it doesn't work properly — and I don't know how to fix it.

In the bottom of the PHP code: echo convert_jsonfeed_to_rss($content)."\n";
I am expecting this to print out the RSS XML feed — it doesn't.

<?php

//Convert JSONfeed to RSS in a single function as a drop in to make adding JSONfeed
//support to an aggregator easier
function convert_jsonfeed_to_rss($content = NULL, $max = NULL)
{
    //Test if the content is actual JSON
    json_decode($content);
    if( json_last_error() !== JSON_ERROR_NONE) return FALSE;

    //Now, is it valid JSONFeed?
    $jsonFeed = json_decode($content, TRUE);
    if (!isset($jsonFeed['version'])) return FALSE;
    if (!isset($jsonFeed['title'])) return FALSE;
    if (!isset($jsonFeed['items'])) return FALSE;

    //Decode the feed to a PHP array
    $jf = json_decode($content, TRUE);

    //Get the latest item publish date to use as the channel pubDate
    $latestDate = 0;
    foreach ($jf['items'] as $item) {
        if (strtotime($item['date_published']) > $latestDate) $latestDate = strtotime($item['date_published']);
    }
    $lastBuildDate = date(DATE_RSS, $latestDate);

    //Create the RSS feed
    $xmlFeed = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"></rss>');
    $xmlFeed->addChild("channel");

    //Required elements
    $xmlFeed->channel->addChild("title", $jf['title']);
    $xmlFeed->channel->addChild("pubDate", $lastBuildDate);
    $xmlFeed->channel->addChild("lastBuildDate", $lastBuildDate);

    //Optional elements
    if (isset($jf['description'])) $xmlFeed->channel->description = $jf['description'];
    if (isset($jf['home_page_url'])) $xmlFeed->channel->link = $jf['home_page_url'];

    //Items
    foreach ($jf['items'] as $item) {
        $newItem = $xmlFeed->channel->addChild('item');

        //Standard stuff
        if (isset($item['id'])) $newItem->addChild('guid', $item['id']);
        if (isset($item['title'])) $newItem->addChild('title', $item['title']);
        if (isset($item['content_text'])) $newItem->addChild('description', $item['content_text']);
        if (isset($item['content_html'])) $newItem->addChild('description', $item['content_html']);
        if (isset($item['date_published'])) $newItem->addChild('pubDate', $item['date_published']);
        if (isset($item['url'])) $newItem->addChild('link', $item['url']);

        //Enclosures?
        if(isset($item['attachments'])) {
            foreach($item['attachments'] as $attachment) {
                $enclosure = $newItem->addChild('enclosure');
                $enclosure['url'] = $attachment['url'];
                $enclosure['type'] = $attachment['mime_type'];
                $enclosure['length'] = $attachment['size_in_bytes'];
            }
        }
    }

    //Make the output pretty
    $dom = new DOMDocument("1.0");
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($xmlFeed->asXML());
    return $dom->saveXML();
}

$content = @file_get_contents("http://timetable.manton.org/feed.json");
echo convert_jsonfeed_to_rss($content)."\n";

I tried to put the $content variable before the convert_jsonfeed_to_rss function — same problem.

$content = @file_get_contents("http://timetable.manton.org/feed.json");

Body:
The conversion to a DOMDocument at the end seems to be the issue, it objects to a few parts of the document.

A quicker way (and seems to be more reliable in this case) is to just use dom_import_simplexml()

$dom = dom_import_simplexml($xmlFeed)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
return $dom->saveXML();

(from https://stackoverflow.com/a/799792/1213708).

Edit

From your updated code, you aren't using the hierarchy properly (and probably don't have errors enabled to show what is not working).

You need something like...

foreach ($jf['data']['feed'] as $item1) {
//      foreach ($item1['feed'] as $item) {

        $item = $item1['article'];


问:
Powershell: select XML node value into variable by element index
I have this PowerShell script which I use to parse through different aspects of an XML-file. Therefore, I Would like to retrieve the value of a specific XML-node and save it into a variable. This node I would like to select, exists multiple times in the XML-file, so I need to be able to mention the specific number of the node I want to retrieve.

XML-file:

```<code><lvl1>
    <lvl2>
        <lvl3>
            <lvl4>test1</lvl4>
            <lvl4>test2</lvl4>
            <lvl4>test3</lvl4>
        </lvl3>
    </lvl2>
</lvl1>
</code>```

Powershell scripts I've tried:

1 returning nothing and no errors

```<code>[xml] $response = get-content "FilePath\Resp.xml"
[string] $Var = $response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').InnerText
</code>```

2 returning error: "cannot index into a null array."

```<code>[xml] $response = get-content "FilePath\Resp.xml"
$Var = $response.lvl1.lvl2.lvl3.lvl4[2].'#text'
</code>```

答:
BACON essentially provided the crucial pointers in comments on the question:

Using PowerShell's dot notation directly returns the text content of leaf elements (elements with only a text child node), so there's no need for '.#text':

```<code># Note: `.lvl4` is an *array* provided by PowerShell, so the index is
#       0-based. Therefore, [2] retrieves the *3rd* element.
$response.lvl1.lvl2.lvl3.lvl4[2]  # -> 'test3'
</code>```

Note that PowerShell exposes the multiple lvl4 elements as an array, so indexing into that array is 0-based.

Your XPath-based command should work as-is, but note that indices in XPath are 1-based, so [2] would refer to the 2nd element:

```<code>$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').InnerText # -> 'test2'

# Equivalent commands:
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').'#text'
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]/text()').Value
</code>```

Body:
I have this PowerShell script which I use to parse through different aspects of an XML-file. Therefore, I Would like to retrieve the value of a specific XML-node and save it into a variable. This node I would like to select, exists multiple times in the XML-file, so I need to be able to mention the specific number of the node I want to retrieve.

XML-file:

<lvl1>
    <lvl2>
        <lvl3>
            <lvl4>test1</lvl4>
            <lvl4>test2</lvl4>
            <lvl4>test3</lvl4>
        </lvl3>
    </lvl2>
</lvl1>

Powershell scripts I've tried:

1 returning nothing and no errors

[xml] $response = get-content "FilePath\Resp.xml"
[string] $Var = $response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').InnerText

2 returning error: "cannot index into a null array."

[xml] $response = get-content "FilePath\Resp.xml"
$Var = $response.lvl1.lvl2.lvl3.lvl4[2].'#text'

Body:
BACON essentially provided the crucial pointers in comments on the question:

Using PowerShell's dot notation directly returns the text content of leaf elements (elements with only a text child node), so there's no need for '.#text':

# Note: `.lvl4` is an *array* provided by PowerShell, so the index is
#       0-based. Therefore, [2] retrieves the *3rd* element.
$response.lvl1.lvl2.lvl3.lvl4[2]  # -> 'test3'

Note that PowerShell exposes the multiple lvl4 elements as an array, so indexing into that array is 0-based.

Your XPath-based command should work as-is, but note that indices in XPath are 1-based, so [2] would refer to the 2nd element:

$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').InnerText # -> 'test2'

# Equivalent commands:
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').'#text'
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]/text()').Value


问:
generate sample example in swagger UI (in Spring boot project)
I am using a spring boot application and have configured using Swagger UI.

I want to know whether we could pre-populate the example value with sample value so we can hit the "Try it out!" button without having to type in some sample values to get a response.

It must be present there.

Is there a way we can do this using annotations or a separate file which Swagger uses?

I am using a spring boot project with springfox-swagger2:2.7.0 and springfox-swagger-ui:2.7.0 with dependencies added using gradle.

答:
Here is a workaround for providing an example:

Inject html into swagger

```<code>@ApiParam(
    name="whatever",
    value="whatever",
    defaultValue="none</p><p>Example: xyz</p>"
)
</code>```

They don't protect against it in the latest version 2.9.2.

Body:
Here is a workaround for providing an example:

Inject html into swagger

@ApiParam(
    name="whatever",
    value="whatever",
    defaultValue="none</p><p>Example: xyz</p>"
)

They don't protect against it in the latest version 2.9.2.


问:
How do you get text from dynamically created QLineEdit in a QToolBox?
I am trying to make a variable number of pages on a QToolbox with a set number of QLineEdit fields. The number of pages and their names is determined by a vector of strings. Each page of the QToolbox has two QLineEdits. After the fillToolbox function is called, the printExtractedData function is called. As stated in the name I am just looking to print the std::string form of the data.

```<code>void fillToolbox(vector <string> toolboxLabels){
    QLineEdit *l1, *l2;
    QGridLayout *gridLayout;
    for (int i = 0; i < numEntries; i++)
    {
        gridLayout = new QGridLayout;
        l1 = new QLineEdit;
        l2 = new QLineEdit;
        QFrame *frm = new QFrame;
        QLabel *l1Label = new QLabel("Field 1:");
        QLabel *l2Label = new QLabel("Field 2:");
        gridLayout->addWidget(l1Label, 0, 0);
        gridLayout->addWidget(l1, 0, 1);
        gridLayout->addWidget(l2Label, 1, 0);
        gridLayout->addWidget(l2, 1, 1);
        frm->setLayout(gridLayout);
        ui.myToolBox->addItem(frm, QString(toolboxLabels[i].c_str()));
    }
}
</code>```

User adds input to LineEdit fields.

```<code>void printExtractedData() {
    int numPages = ui.myToolBox->count();
    cout << numPages << endl;
    for (int i = 0; i < numPages; i++)
    {
        string key = ui.myToolBox->itemText(i).toLocal8Bit().constData();
        if (QWidget* wg = qobject_cast<QWidget*>(ui.myToolBox->widget(i))) {
            QLayout *layout = wg->layout();
            for (int j = 0; j < layout->count(); j++)
            {
                if (QLineEdit* le = qobject_cast<QLineEdit*>(layout->itemAt(j)->widget())) {
                    string text = le->text().toLocal8Bit().constData();
                    cout << le <<endl;
                }
            }
        }
    }
}
</code>```

When I insert a two element list, I receive the output:

2

00000245E5A77260

00000245E5A76FE0

00000245E5A0A510

00000245E5B17540

The desired result is a printed string of the content from the QLineEdit fields.

Any help or advice would be appreciated.

答: Just realized I am printing le instead of text. I should have been more careful. That is the only problem.</p>

Body:
I am trying to make a variable number of pages on a QToolbox with a set number of QLineEdit fields. The number of pages and their names is determined by a vector of strings. Each page of the QToolbox has two QLineEdits. After the fillToolbox function is called, the printExtractedData function is called. As stated in the name I am just looking to print the std::string form of the data.

void fillToolbox(vector <string> toolboxLabels){
    QLineEdit *l1, *l2;
    QGridLayout *gridLayout;
    for (int i = 0; i < numEntries; i++)
    {
        gridLayout = new QGridLayout;
        l1 = new QLineEdit;
        l2 = new QLineEdit;
        QFrame *frm = new QFrame;
        QLabel *l1Label = new QLabel("Field 1:");
        QLabel *l2Label = new QLabel("Field 2:");
        gridLayout->addWidget(l1Label, 0, 0);
        gridLayout->addWidget(l1, 0, 1);
        gridLayout->addWidget(l2Label, 1, 0);
        gridLayout->addWidget(l2, 1, 1);
        frm->setLayout(gridLayout);
        ui.myToolBox->addItem(frm, QString(toolboxLabels[i].c_str()));
    }
}

User adds input to LineEdit fields.

void printExtractedData() {
    int numPages = ui.myToolBox->count();
    cout << numPages << endl;
    for (int i = 0; i < numPages; i++)
    {
        string key = ui.myToolBox->itemText(i).toLocal8Bit().constData();
        if (QWidget* wg = qobject_cast<QWidget*>(ui.myToolBox->widget(i))) {
            QLayout *layout = wg->layout();
            for (int j = 0; j < layout->count(); j++)
            {
                if (QLineEdit* le = qobject_cast<QLineEdit*>(layout->itemAt(j)->widget())) {
                    string text = le->text().toLocal8Bit().constData();
                    cout << le <<endl;
                }
            }
        }
    }
}

When I insert a two element list, I receive the output:

2

00000245E5A77260

00000245E5A76FE0

00000245E5A0A510

00000245E5B17540

The desired result is a printed string of the content from the QLineEdit fields.

Any help or advice would be appreciated.


问:
shopify theme api create theme
I am a complete noob when it comes to developing but i am trying to create my first app on shopify. Within the app I wish to create a button that when clicked installs a theme just how it is on shopify now. However, I am completely lost on how you do that.

```<code>POST /admin/api/2020-01/themes.json
{
  "theme": {
    "name": "Lemongrass",
    "src": "http://themes.shopify.com/theme.zip",
    "role": "main"
  }
}
</code>```

How do I make it so when a user clicks a button a theme installs on their store. I am using node.js and react to create the app.

I have this code inside a themedownload.js file

```<code>const themeDownload = async (ctx, accessToken, shop) => {
  const query = JSON.stringify({
          "theme": {
            "name": "Lemongrass",
            "src": "https://codeload.github.com/Shopify/skeleton-theme/zip/master",
            "role": "unpublished"
            }
  });

  const response = await fetch(`https://${shop}/admin/api/2020-01/themes.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      "X-Shopify-Access-Token": accessToken,
    },
    body: query
  })

  const responseJson = await response.json();
};

module.exports = themeDownload;
</code>```

Not sure how well this would work, however, how would i then in another file create a function so when a button is clicked it will run the themedownload.js file. I do hope what I am asking/saying is making sense.

React page structure

```<code>const themeDownload = require('../server/themeDownload');

import React, {useCallback, useState} from 'react';
import {
  Button,
  Card,
  Form,
  FormLayout,
  Layout,
  Page,
  SettingToggle,
  Stack,
  TextField,
  TextStyle,
  DisplayText,
SkeletonBodyText, SkeletonPage, Modal, TextContainer, Heading, Badge
} from '@shopify/polaris';

export default function ModalExample() {
  const [active, setActive] = useState(false);

  const handleChange = useCallback(() => setActive(!active), [active]);

  const themeDown = useCallback(
      () => themeDownload(),
      [],
  );

  return (
    <div style={{height: '500px'}}>
      <SkeletonPage title="Theme Library">
          <Layout>
            <Layout.Section>
              <Card sectioned>
                <Stack>
                  <Stack.Item fill>
                    <Heading>Themes</Heading>
                  </Stack.Item>
                  <Stack.Item>
                    <Button primary onClick={handleChange}>Add theme</Button>
                  </Stack.Item>
                </Stack>
              </Card>
            </Layout.Section>
          </Layout>
        </SkeletonPage>
      <Modal
        open={active}
        onClose={handleChange}
        title="Add Debutle"
        primaryAction={{
          content: 'Add to theme library',
          onAction: themeDown,
        }}
      >
        <Modal.Section>
          <TextContainer>
            <p>
              When adding theme to library, the theme will be set as unpublished.
            </p>
          </TextContainer>
        </Modal.Section>
      </Modal>
    </div>
  );
}
</code>```

答:
That's quite a complicated task honestly. Working with Shopify I know how frustrating themes can be, I would start off by writing some pseudocode. </p>

```<code>User clicks button, post request gets sent, app catches request, themes gets installed, configuration.
</code>```

<p>I would start with the button & modifying your own theme. @hat code do you have so far? </p>

Title: shopify theme api create theme

Body:
I am a complete noob when it comes to developing but i am trying to create my first app on shopify. Within the app I wish to create a button that when clicked installs a theme just how it is on shopify now. However, I am completely lost on how you do that.

POST /admin/api/2020-01/themes.json
{
  "theme": {
    "name": "Lemongrass",
    "src": "http://themes.shopify.com/theme.zip",
    "role": "main"
  }
}

How do I make it so when a user clicks a button a theme installs on their store. I am using node.js and react to create the app.

I have this code inside a themedownload.js file

const themeDownload = async (ctx, accessToken, shop) => {
  const query = JSON.stringify({
          "theme": {
            "name": "Lemongrass",
            "src": "https://codeload.github.com/Shopify/skeleton-theme/zip/master",
            "role": "unpublished"
            }
  });

  const response = await fetch(`https://${shop}/admin/api/2020-01/themes.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      "X-Shopify-Access-Token": accessToken,
    },
    body: query
  })

  const responseJson = await response.json();
};

module.exports = themeDownload;

Not sure how well this would work, however, how would i then in another file create a function so when a button is clicked it will run the themedownload.js file. I do hope what I am asking/saying is making sense.

React page structure

const themeDownload = require('../server/themeDownload');

import React, {useCallback, useState} from 'react';
import {
  Button,
  Card,
  Form,
  FormLayout,
  Layout,
  Page,
  SettingToggle,
  Stack,
  TextField,
  TextStyle,
  DisplayText,
SkeletonBodyText, SkeletonPage, Modal, TextContainer, Heading, Badge
} from '@shopify/polaris';

export default function ModalExample() {
  const [active, setActive] = useState(false);

  const handleChange = useCallback(() => setActive(!active), [active]);

  const themeDown = useCallback(
      () => themeDownload(),
      [],
  );

  return (

      <SkeletonPage title="Theme Library">
          <Layout>
            <Layout.Section>
              <Card sectioned>
                <Stack>
                  <Stack.Item fill>
                    <Heading>Themes</Heading>
                  </Stack.Item>
                  <Stack.Item>
                    <Button primary onClick={handleChange}>Add theme</Button>
                  </Stack.Item>
                </Stack>
              </Card>
            </Layout.Section>
          </Layout>
        </SkeletonPage>
      <Modal
        open={active}
        onClose={handleChange}
        title="Add Debutle"
        primaryAction={{
          content: 'Add to theme library',
          onAction: themeDown,
        }}
      >
        <Modal.Section>
          <TextContainer>

              When adding theme to library, the theme will be set as unpublished.

          </TextContainer>
        </Modal.Section>
      </Modal>

  );
}

Body:
That's quite a complicated task honestly. Working with Shopify I know how frustrating themes can be, I would start off by writing some pseudocode.

User clicks button, post request gets sent, app catches request, themes gets installed, configuration.

I would start with the button & modifying your own theme. @hat code do you have so far?


问:
I am trying to create a VBA macro that duplicates a worksheet and then copies data in the worksheet to a new column
this is my first time posting on stack overflow, so any feedback is appreciated.

Right now I am trying to program a macro that does the following:

Duplicates current worksheet and moves new sheet to beginning of workbook (new sheet is also named by user via input screen)

Copies data in Column D to Column E based on 3 criteria in Columns A-C

I've coded Step 1, but Step 2 is where I am having trouble. I need to copy data from one location on the worksheet to another based on criteria. Below is an example of something what I'm trying to do

Example for Step 2 Macro:

Basically, I want it to copy the "Day's Sales" to the "Previous Day's Sales" in the new worksheet according to each of the 3 criteria (Name, Country, Product) in case anything changes and to make sure the values are being copied correctly.

Please let me know if any other information needs to be provided!

FYI here is the code I already have for Step 1:

```<code>Public Sub CopySheetAndRename()

Dim newName As String

    On Error Resume Next
    newName = InputBox("Enter the date for the new worksheet")

    If newName <> "" Then
        ActiveSheet.Copy Before:=Sheets(1)
        On Error Resume Next
        ActiveSheet.Name = newName
    End If
End Sub
</code>```

答:
```<code>Sub MoveOver()

'create variables
Dim lastRow As Long

'find lastRow
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

'change i to whatever your starting row is. Cells(i, #), the # indicates the column index
For i = 2 To lastRow
Cells(i, 5).Value = Cells(i, 4)
Cells(i, 4).Value = 0
Next i 'new loop starts

End Sub
</code>```

Having a closer look it seems like you just want to move today's sales data to the previous day, and then clear out "today". The code above should get you going.

Edit: Changed Cells().Clear to .Value and set to 0 to preserve formatting.

Body:
this is my first time posting on stack overflow, so any feedback is appreciated.

Right now I am trying to program a macro that does the following:

Duplicates current worksheet and moves new sheet to beginning of workbook (new sheet is also named by user via input screen)

Copies data in Column D to Column E based on 3 criteria in Columns A-C

I've coded Step 1, but Step 2 is where I am having trouble. I need to copy data from one location on the worksheet to another based on criteria. Below is an example of something what I'm trying to do

Example for Step 2 Macro:

Basically, I want it to copy the "Day's Sales" to the "Previous Day's Sales" in the new worksheet according to each of the 3 criteria (Name, Country, Product) in case anything changes and to make sure the values are being copied correctly.

Please let me know if any other information needs to be provided!

FYI here is the code I already have for Step 1:

Public Sub CopySheetAndRename()

Dim newName As String

    On Error Resume Next
    newName = InputBox("Enter the date for the new worksheet")

    If newName <> "" Then
        ActiveSheet.Copy Before:=Sheets(1)
        On Error Resume Next
        ActiveSheet.Name = newName
    End If
End Sub

Body:
Sub MoveOver()

'create variables
Dim lastRow As Long

'find lastRow
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

'change i to whatever your starting row is. Cells(i, #), the # indicates the column index
For i = 2 To lastRow
Cells(i, 5).Value = Cells(i, 4)
Cells(i, 4).Value = 0
Next i 'new loop starts

End Sub

Having a closer look it seems like you just want to move today's sales data to the previous day, and then clear out "today". The code above should get you going.

Edit: Changed Cells().Clear to .Value and set to 0 to preserve formatting.


Title: How to apply this function to a dataframe?

Body:
Suppose I have this df:

i      A     B     C

0     4     5    13
1    11    42    27
2     3     6    2.21
3     4     8    10
4    10     5    4
5     2    11    .5

and want to apply a this function to each row:
log[(df['A']

$log((A_i - A_{i+1})^2+(B_i - B_{i+1})^2+(C_i - C_{i+1})^2)$
$log((A_i - A_{i+2})^2+(B_i - B_{i+2})^2+(C_i - C_{i+2})^2)$
.
.
.
$log((A_i - A_{i+5})^2+(B_i - B_{i+5})^2+(C_i - C_{i+5})^2)$

For example for i=0 and i=1:

$log((4 - 11)^2+(5 - 42)^2+(13 - 27)^2)=3.2$

I have this code. But is not working.

for point in df:
    x = [np.log((A[0]-A[1] )**2+ (B[0]-B[1] )**2+(C[0]-C[1] )**2) for x in df]

Body:
Difference the rows forward via df[['A', 'B', 'C']].diff(-1), square the result via .apply(lambda x: x * x) (or .pow(2)), sum the result via .sum(axis=1) and then take the log of these sums.  Assign the result back to the dataframe.

>>> df.assign(result=np.log(df[['A', 'B', 'C']].diff(-1).apply(lambda x: x * x).sum(axis=1)))
   i   A   B      C    result
0  0   4   5  13.00  7.386471  # np.log((4 - 11) ** 2 + (5 - 42) ** 2 + (13 - 27) ** 2) = 7.386...
1  1  11  42  27.00  7.588093
2  2   3   6   2.21  4.184857
3  3   4   8  10.00  4.394449
4  4  10   5   4.00  4.720729
5  5   2  11   0.50      -inf

Alternatively, to difference every row from the first, use (df[['A', 'B', 'C']].iloc[0, :] - df[['A', 'B', 'C']]). Everything else is the same.

>>> df.assign(
        result=np.log(
            (df[['A', 'B', 'C']].iloc[0, :] - df[['A', 'B', 'C']]).pow(2).sum(axis=1))
    )

   i   A   B      C    result
0  0   4   5  13.00      -inf
1  1  11  42  27.00  7.386471
2  2   3   6   2.21  4.774272
3  3   4   8  10.00  2.890372
4  4  10   5   4.00  4.762174
5  5   2  11   0.50  5.279389


问:
manual bin size selection in R ggplot geom.tile function?
Is there a way I can manually set bin sizes that do not have same size and colour them after specific colour codes?

I want to have a heatmap with binsizes: 0-0.05, 0.05-0.25, 0.25-0.5, 0.5-0.75 and 0.75-1
For bin 0-0.05 I want to have the set colour: "#ecefb7" for the remaining bins I want to have a gradient from low="#7fc8b9" to high="#3a81b5".

I did manage to get the bins in my legend, but not with the specific color coding. Does perhaps anyone know how I can achieve this?

Sample minimal data:

```<code>    Group sample     pvalue
1   OG0000010:Up  EB1_D 0.04900000
2 OG0000050:Down  EB1_D 0.19019725
3   OG0000638:Up  EB1_D 0.52008137
4   OG0000010:Up  EN1_D         NA
5   OG0000050:Down  EN1_D 0.01615993
6 OG0000638:Up  EN1_D 0.48958058
</code>```

The code I use so far:

```<code>ggplot(pvaldata2, aes(x=sample, y=Group)) +
  geom_tile(colour="black", size=0.25, aes(fill=pvalue)) +
  scale_fill_gradient(low="#ecefb7", high="#3a81b5", na.value = "white",
                      breaks = c(0.05, 0.25, 0.5, 0.75),
                      labels = c("0.05", "0.25", "0.5", "0.75")) +
  theme(axis.text.y = element_text(size = 8))
</code>```

The resulting heatmap but still with the wrong bin colours:

答:
You can get complete control over the colour scale by changing to scale_fill_gradientn, setting limits to c(0, 1), specfiying all your colours in a vector, and their location as a vector in values. In your case that would look like this:

ggplot(pvaldata2, aes(x = sample, y = Group)) +
  geom_tile(colour="black", size = 0.25, aes(fill = pvalue)) +
  scale_fill_gradientn(colours = c(rep("#ecefb7", 2), "#7fc8b9", "#3a81b5"),
                       na.value = "white",
                       values = c(0, 0.05, 0.0501, 1),
                       limits = c(0, 1)) +
  theme(axis.text.y = element_text(size = 8))
```

As you can see, this has coloured the NA white, the p values below 0.05 (even those very close to 0.05) in the desired buff colour, and the rest in the chosen gradient.

Body:
Is there a way I can manually set bin sizes that do not have same size and colour them after specific colour codes?

I want to have a heatmap with binsizes: 0-0.05, 0.05-0.25, 0.25-0.5, 0.5-0.75 and 0.75-1
For bin 0-0.05 I want to have the set colour: "#ecefb7" for the remaining bins I want to have a gradient from low="#7fc8b9" to high="#3a81b5".

I did manage to get the bins in my legend, but not with the specific color coding. Does perhaps anyone know how I can achieve this?

Sample minimal data:

    Group sample     pvalue
1   OG0000010:Up  EB1_D 0.04900000
2 OG0000050:Down  EB1_D 0.19019725
3   OG0000638:Up  EB1_D 0.52008137
4   OG0000010:Up  EN1_D         NA
5   OG0000050:Down  EN1_D 0.01615993
6 OG0000638:Up  EN1_D 0.48958058

The code I use so far:

ggplot(pvaldata2, aes(x=sample, y=Group)) +
  geom_tile(colour="black", size=0.25, aes(fill=pvalue)) +
  scale_fill_gradient(low="#ecefb7", high="#3a81b5", na.value = "white",
                      breaks = c(0.05, 0.25, 0.5, 0.75),
                      labels = c("0.05", "0.25", "0.5", "0.75")) +
  theme(axis.text.y = element_text(size = 8))

The resulting heatmap but still with the wrong bin colours:

Body:
You can get complete control over the colour scale by changing to scale_fill_gradientn, setting limits to c(0, 1), specfiying all your colours in a vector, and their location as a vector in values. In your case that would look like this:

ggplot(pvaldata2, aes(x = sample, y = Group)) +
  geom_tile(colour="black", size = 0.25, aes(fill = pvalue)) +
  scale_fill_gradientn(colours = c(rep("#ecefb7", 2), "#7fc8b9", "#3a81b5"),
                       na.value = "white",
                       values = c(0, 0.05, 0.0501, 1),
                       limits = c(0, 1)) +
  theme(axis.text.y = element_text(size = 8))

As you can see, this has coloured the NA white, the p values below 0.05 (even those very close to 0.05) in the desired buff colour, and the rest in the chosen gradient.


问:
block at the bottom of a printed page html css
I have this page in JSFile : My test case

```<code>.qr-bill {
    box-sizing: border-box;
    width: 210mm;
    height: 105mm;
    font-family: Arial, Frutiger, Helvetica, "Liberation Sans";
    border-collapse: collapse;
    color: #000;
    page-break-after: always;
    page-break-inside: avoid;
}
</code>```

When I print my page, I would like to have any of div bloc .qr-bill that need to showed at the bottom of the current page... I can't success to do it with position... Do you have any idea how to do that ?

Thank you

答:
Give it a position of fixed and bottom of 0 for it to appear at the bottom of every page that is printed. If you want the page to look different when printed, provide a media query like this:

@media print {
  .qr-bill {
    position: fixed;
    bottom: 0;
  }
}
```

Body:
I have this page in JSFile : My test case

.qr-bill {
    box-sizing: border-box;
    width: 210mm;
    height: 105mm;
    font-family: Arial, Frutiger, Helvetica, "Liberation Sans";
    border-collapse: collapse;
    color: #000;
    page-break-after: always;
    page-break-inside: avoid;
}

When I print my page, I would like to have any of div bloc .qr-bill that need to showed at the bottom of the current page... I can't success to do it with position... Do you have any idea how to do that ?

Thank you


问:
Silverlight IsolatedStorageFile.IncreaseQuotaTo
Msdn doc for IsolatedStorageFile.IncreaseQuotaTo states that:

To increase the quota, you must call
  this method from a user-initiated
  event, such as in an event handler for
  a button-click event. When you call
  the IncreaseQuotaTo method, the common
  language runtime in Silverlight
  presents a dialog box for the user to
  approve the request. If the user
  declines the request, this method
  returns false and the quota remains
  the same size.

How does Silverlight know that the method was called from a user-initiated event like a button click and not from some other thread?

More specifically: What is a user initiated event? Is there any way to overcome this limitation?

And another question:

I do some automatic downloads of files when user first accesses my application, but I don't want the user to press "Download" and then when I detect more space is needed call IncreaseQuota and have the "Silverlight dialog" appearing asking for more space.

I want to start the download automatically (not user initiated), and if I detect more space is needed, call IncreaseQuota and hence have the "Silverlight dialog" appear. (No user pressing download).

答:
The documentation isn't incomplete.

If I do this... button_click(..) { new UserControl() }... Does this still count as a user initiated event?

Yes. But what has that little bit of extra code really achieved?

What i've personally never experimented with is exactly what consitutes a user event; IOW is a mouse-over considered a user event? This will be very simple for you to try, and there are a multitude of other things you can experiment with. If necessary you could have a splash screen popup that welcomes the user and they have to click on it to dismiss it, at which point you make the request. It may seem a bit corny, but you can get away with things like this if you present it well.

Note that the prompt is a one-time thing. If you prompt the user and they accept, that storage is persisted for your application between visits, which means you don't need to prompt them again the next time they use your control, your quota is still increased from last time (unless the user has deliberately deleted it, which they can do by right clicking on the Silverlight control and then going to the Application Storage tab).


问:
Using a different test/train split for each target
I plan on using a data set which contains 3 target values of interest. Ultimately I will be trying classification methods on a binary target and also plan on using regression methods for two separate continuous targets.

Is is it a bad practice to do a different train/test split for each target variable?

Otherwise, I am not sure how to split the data in a way that will allow me to predict each target, separately.

答: If they're effectively 3 different models trained and evaluated separately then for the purposes of scientifically evaluating each model's performance it doesn't matter if you use different test-train splits for each model, as no information will be leaking from model to model. But if you plan on comparing the results of the 3 models or combining all 3 scores into some aggregate metric then you would want to use the same test-train split so that all 3 models are working from the same training data, as otherwise the performance of each model will likely depend to some extent on the test data for the other models, and therefore your combined score will to some extent be a function of your test data.</p>


问:
Implementing a Typescript class interface does not preserve method types
I'm trying to write a Typescript interface, then write a class that implements that interface.

The problem is that I can't seem to get the method signatures from the interface to apply to the class.

Here's a slimmed-down example:

export interface Foo {
  bar(value: string): void;
}

export class MyFoo implements Foo {
  // ✔ Typescript error:
  // Property 'bar' is missing in type 'MyFoo' but required in type 'Foo'
}

export class MyFoo implements Foo {
  // value is inferred as `any` instead of `string`,
  // and there aren't any errors with the return type mismatch
  bar(value) { return true; }
}

```

It seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.

答:
seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.

Correct. Reasons are covered here : https://github.com/Microsoft/TypeScript/pull/6118#issuecomment-216595207

So it is made the responsibility of the developer to add the annotations they need.

Body:
I'm trying to write a Typescript interface, then write a class that implements that interface.

The problem is that I can't seem to get the method signatures from the interface to apply to the class.

Here's a slimmed-down example:

export interface Foo {
  bar(value: string): void;
}

export class MyFoo implements Foo {
  // ✔ Typescript error:
  // Property 'bar' is missing in type 'MyFoo' but required in type 'Foo'
}

export class MyFoo implements Foo {
  // value is inferred as `any` instead of `string`,
  // and there aren't any errors with the return type mismatch
  bar(value) { return true; }
}

It seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.


问:
Why am I getting a result opposite from what I expected?
I wrote a code to figure out whether a small binary tree t1 is a subtree of t2.
I am supposed to get true as the result but I am getting the opposite.

Here is my code:

```<code>class Node {
    int val;
    Node left, right;
    public Node(int v) {
        val = v;
        left = right = null;
    }
}
public class BT {
    Node root;
    public BT() {
        root = null;
    }
    public boolean containsTree(Node t1, Node t2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        getOrderString(t1, s1);
        getOrderString(t2, s2);
        return s1.indexOf(s2.toString()) != -1;
    }
    public void getOrderString(Node t, StringBuilder s) {
        if (t == null) {
            s.append("X");
            return;
        }
        s.append(t.val);
        getOrderString(t.left, s);
        getOrderString(t.right, s);
    }
    public static void main(String[] args) {
        BT bt = new BT();
        bt.root = new Node(10);
        bt.root.left = new Node(12);
        bt.root.right = new Node(15);
        bt.root.left.left = new Node(25);
        bt.root.left.right = new Node(30);
        bt.root.right.left = new Node(36);
        BT bt2 = new BT();
        bt2.root = new Node(10);
        bt2.root.left = new Node(12);
        bt2.root.right = new Node(15);
        bt2.root.left.left = new Node(25);
        System.out.println(bt.containsTree(bt.root, bt2.root));
    }
}
</code>```

Could anyone explain to me why i am getting false?

答: 2nd tree is not the subtree of 1st one. That's why it returns false so your code is actually correct :)

Body:
I wrote a code to figure out whether a small binary tree t1 is a subtree of t2.
I am supposed to get true as the result but I am getting the opposite.

Here is my code:

class Node {
    int val;
    Node left, right;
    public Node(int v) {
        val = v;
        left = right = null;
    }
}
public class BT {
    Node root;
    public BT() {
        root = null;
    }
    public boolean containsTree(Node t1, Node t2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        getOrderString(t1, s1);
        getOrderString(t2, s2);
        return s1.indexOf(s2.toString()) != -1;
    }
    public void getOrderString(Node t, StringBuilder s) {
        if (t == null) {
            s.append("X");
            return;
        }
        s.append(t.val);
        getOrderString(t.left, s);
        getOrderString(t.right, s);
    }
    public static void main(String[] args) {
        BT bt = new BT();
        bt.root = new Node(10);
        bt.root.left = new Node(12);
        bt.root.right = new Node(15);
        bt.root.left.left = new Node(25);
        bt.root.left.right = new Node(30);
        bt.root.right.left = new Node(36);
        BT bt2 = new BT();
        bt2.root = new Node(10);
        bt2.root.left = new Node(12);
        bt2.root.right = new Node(15);
        bt2.root.left.left = new Node(25);
        System.out.println(bt.containsTree(bt.root, bt2.root));
    }
}

Could anyone explain to me why i am getting false?


问:
Excluding intervals from a real number line
A long time ago I asked the following question:

Python: delete substring by indices

Last week I was asked a very similar question, but with continuous real-number line.

Imagine you are given an interval (X, Y), and a bunch of sub-intervals blocks=[(x1, y1), (x2, y2), ...]. Your goal is to find a list of intervals remaining=[(a1, b1), (a2, b2), ..] that is (1) in (X, Y), but (2) not in any of the sub-intervals in blocks. The intervals in blocks can overlap.

In other words, the function signature looks something like:

```<code>def delete_blocks_from_interval(X, Y, blocks):
    ```
    X: start of the given interval
    Y: end of the given interval
    blocks: list of intervals (x, y) to be removed, can overlap

    returns remaining = [(a, b), ...] intervals remaining after removal of blocks
    ```
    pass
</code>```

I can construct a graph of connected intervals in blocks, and find both the minimum of the start and the maximum of end for each connected component in the graph. But this is quadratic in length of blocks. I wonder if there is a better-runtime algorithm.

Please also discuss what code routine you think is more efficient for the algorithm if you will.

Many many thanks.

As requested, please consider the following illustrative inputs:

X = -1

Y = 20

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]

the expected output is remaining = [(-1, 1), (11, 16), (17.5, 20)]

答:
Would something like this work?</p>

```<code>def delete_blocks_from_interval(a, b, blocks):
    sorted_blocks = sorted(blocks)
    for i, (c, d) in enumerate(sorted_blocks):
        if a <= c <= b:
            yield (a, c)
            if d > a:
               a = d
            for (e, f) in sorted_blocks[i + 1:]:
                if e <= a <= f:
                    a = f
                elif e > a:
                    break
    if a <= d <= b:
        yield (d, b)

blocks = ((1, 10), (4, 5), (9, 11), (16, 17.5))
print(list(delete_blocks_from_interval(-1, 20, blocks)))
# (-1, 1), (11, 16), (17.5, 20)
</code>```

Body:
A long time ago I asked the following question:

Python: delete substring by indices

Last week I was asked a very similar question, but with continuous real-number line.

Imagine you are given an interval (X, Y), and a bunch of sub-intervals blocks=[(x1, y1), (x2, y2), ...]. Your goal is to find a list of intervals remaining=[(a1, b1), (a2, b2), ..] that is (1) in (X, Y), but (2) not in any of the sub-intervals in blocks. The intervals in blocks can overlap.

In other words, the function signature looks something like:

def delete_blocks_from_interval(X, Y, blocks):
    ```
    X: start of the given interval
    Y: end of the given interval
    blocks: list of intervals (x, y) to be removed, can overlap

    returns remaining = [(a, b), ...] intervals remaining after removal of blocks
    ```
    pass

I can construct a graph of connected intervals in blocks, and find both the minimum of the start and the maximum of end for each connected component in the graph. But this is quadratic in length of blocks. I wonder if there is a better-runtime algorithm.

Please also discuss what code routine you think is more efficient for the algorithm if you will.

Many many thanks.

As requested, please consider the following illustrative inputs:

X = -1

Y = 20

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]

the expected output is remaining = [(-1, 1), (11, 16), (17.5, 20)]

Body:
Would something like this work?

def delete_blocks_from_interval(a, b, blocks):
    sorted_blocks = sorted(blocks)
    for i, (c, d) in enumerate(sorted_blocks):
        if a <= c <= b:
            yield (a, c)
            if d > a:
               a = d
            for (e, f) in sorted_blocks[i + 1:]:
                if e <= a <= f:
                    a = f
                elif e > a:
                    break
    if a <= d <= b:
        yield (d, b)

blocks = ((1, 10), (4, 5), (9, 11), (16, 17.5))
print(list(delete_blocks_from_interval(-1, 20, blocks)))
# (-1, 1), (11, 16), (17.5, 20)


问:
Pandas don't recognize "||" as string to split
I'm trying to split a DataFrame in two columns and get the left part in result, but pandas don't recognize that string and give me an out in empty.</p>

```<code>q=['Sar || var','lol ||']
y=pd.DataFrame(q)
split_data = y[0].str.split("||", n = 1, expand = False).str[0]
print(split_data)

out

0
1
Name: 0, dtype: object
</code>```

答:
The documentation is somewhat deceptive for this method. What is happening is that for patterns longer than 1 character, pandas interprets the separator as a regular expression. You can see the implementation here.

You can use "||" as a literal, non-regex separator by escaping the character "|" (which has special meaning in regular expressions) using a backslash:

```<code>series.str.split("\\|\\|")
</code>```

Note that python provides a "raw" syntax for string literals that can be useful for writing regular expressions, removing the need to escape the backslashes themselves:

```<code>series.str.split(r"\|\|")
</code>```

You can consult the documentation for the re module for a list of special characters that will need to be escaped when using multi-character separators. Alternatively, just use the function re.escape:

```<code>import re
series.str.split(re.escape("||"))
</code>```

Body:
I'm trying to split a DataFrame in two columns and get the left part in result, but pandas don't recognize that string and give me an out in empty.

q=['Sar || var','lol ||']
y=pd.DataFrame(q)
split_data = y[0].str.split("||", n = 1, expand = False).str[0]
print(split_data)

out

0
1
Name: 0, dtype: object

Body:
The documentation is somewhat deceptive for this method. What is happening is that for patterns longer than 1 character, pandas interprets the separator as a regular expression. You can see the implementation here.

You can use "||" as a literal, non-regex separator by escaping the character "|" (which has special meaning in regular expressions) using a backslash:

series.str.split("\\|\\|")

Note that python provides a "raw" syntax for string literals that can be useful for writing regular expressions, removing the need to escape the backslashes themselves:

series.str.split(r"\|\|")

You can consult the documentation for the re module for a list of special characters that will need to be escaped when using multi-character separators. Alternatively, just use the function re.escape:

import re
series.str.split(re.escape("||"))


问:
get the unique values from the associative array in PHP?
I am having the array like below

```<code>Array
(
    [0] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [1] => Array
        (
            [catid] => 5
            [parent_id] => 2
            [catname] => Category 2
            [catdesc] =>
            [nleft] => 7
            [nright] => 8
            [nlevel] => 2
        )

    [2] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [3] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [4] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [5] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [6] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [7] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [8] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [9] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [10] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [11] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [12] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [13] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [14] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

)
</code>```

From this array I want to get the Unique Arrays.ie. If catId is same it needs to eliminate from the list.
How can I do this?

答:
You can use this for Convert Multidimentional array to Single array.

```<code>$out = array();
for($i=0;$i<count($rows);$i++) {
    $out = $rows[$i];
}
</code>```

And you can check this by

```<code>print_r($out);
</code>```

Body:
I am having the array like below

Array
(
    [0] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [1] => Array
        (
            [catid] => 5
            [parent_id] => 2
            [catname] => Category 2
            [catdesc] =>
            [nleft] => 7
            [nright] => 8
            [nlevel] => 2
        )

    [2] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [3] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [4] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [5] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [6] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [7] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [8] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [9] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [10] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [11] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [12] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [13] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [14] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

)

From this array I want to get the Unique Arrays.ie. If catId is same it needs to eliminate from the list.
How can I do this?

Body:
You can use this for Convert Multidimentional array to Single array.

$out = array();
for($i=0;$i<count($rows);$i++) {
    $out = $rows[$i];
}

And you can check this by

print_r($out);