问:
How to change mvc razor value according to onClick()?
I'm currently thinking of a layout where I can utilize the value from the razor value from onclick but I don't think I am doing it right. Does this code make sense and if it isn't what are some ways around it?</p>

```<code>@model ICollection<User>
@{
   int id = 0;
}

@foreach (var i in Model) {
   <button onclick = @{id = i.id} changeStatus(@i.id)> Test </button>
}

<div class="popup" style="display: none;">
     <form method=post>
          <input style="hidden" name="id" value="@id" />
          <input type="submit" value="submit" />
     </form>
</div>

<script>
    function changeStatus(id) {
        $('.popup').show();
     }
</script>
</code>```

答:
Razor variables are server side so they cannot be accessed on the client side. I would update the hidden field's value using jquery.</p>

```<code>@foreach (var i in Model) {
   <button onclick ="changeStatus(@i.id)"> Test </button>
}

<div class="popup" style="display: none;">
     <form method="post">
          <input type="hidden" id="userID" value="" />
          <input type="submit" value="submit" />
     </form>
</div>

<script>
    function changeStatus(id) {
        $('.popup').show();
        $("#userID").val(id);
     }
</script>
</code>```

Body:
I'm currently thinking of a layout where I can utilize the value from the razor value from onclick but I don't think I am doing it right. Does this code make sense and if it isn't what are some ways around it?

@model ICollection<User>
@{
   int id = 0;
}

@foreach (var i in Model) {
   <button onclick = @{id = i.id} changeStatus(@i.id)> Test </button>
}

     <form method=post>
          <input style="hidden" name="id" value="@id" />
          <input type="submit" value="submit" />
     </form>

Body:
Razor variables are server side so they cannot be accessed on the client side. I would update the hidden field's value using jquery.

@foreach (var i in Model) {
   <button onclick ="changeStatus(@i.id)"> Test </button>
}

<div class="popup" style="display: none;">
     <form method="post">
          <input type="hidden" id="userID" value="" />
          <input type="submit" value="submit" />
     </form>
</div>

<script>
    function changeStatus(id) {
        $('.popup').show();
        $("#userID").val(id);
     }
</script>


来源: stackexchange

问:
TextBox: TextChanged Event - Autovalidating when x chars have been entered
I have an app that reads in a barcode from a USB scanner. I want to do a DB lookup as soon as the barcode is entered in a particular textbox.

Clearly, I'm going to put my code in the TextChanged  event handler, but I have a slight problem in that the barcode being read could be either 41 or 43 characters. The question is, how will I know which type of code is being entered. The scanner simply enters the code into whatever field has focus as a string of characters - as if it were entered by a keyboard - so I can't query the scanner to determine the code length.

I've thought of two approaches so far:

Detect first character, wait x.x seconds, and then do my lookup - allow enough time for a full code to be entered

Detect the 41st character, wait 0.x seconds and then do my lookup.

OK, I'm sure these will work OK, but are there any more eloquent solutions?

CONCLUSION:

Some useful suggestions, however Ondrej has inspired the simplest solution for my scenario. The 43 char codes have two characters that are fixed for all codes - the presence (or not) of these two characters means I know to wait if these two characters are present but only 41 characters are present.

I just need to confirm my suspicion that the 41 character codes can't have this pair of characters in this particular position - which I'm fairly sure is the case.

答:
One option is to perform an Async lookup after the 41st character is read, while still waiting for two more characters in the UI thread. If you get a hit on that barcode you can stop waiting and show that result. Alternatively, if a 42nd character is entered while the lookup is in progress you can abort it and immediately begin a new lookup when the 43rd character is entered. This assumes, however, that no 43-character barcode begins with an existing 41-character barcode.

I'd also look and see if the barcodes contain some pattern (for example: 41-char codes have an X as the 9th character and 43-char codes do not), and scan for that as it's being entered.

ContentLicense: CC BY-SA 3.0


问:
How to setState with the array that has push method?
My main goal is to set a state with a array of objects, but I can't do it because this array is mutated with elements that are pushed to it. I understand the problem but I don't know how to solve it

so here is code and I would like to set state with the final actors array. Any ideas?

```<code>    const moviesToMap = this.state.movies;
    moviesToMap.map(movie => {
      return this.state.title === movie.title
        ? movie.characters.map(person => {
            const actorUrl = person;
            const actorId = parseInt(actorUrl.slice(31, -1));
            let peopleStateCopy = this.state.people;
            peopleStateCopy.map(persona => {
              const slugState = persona.url;
              const slugId = parseInt(slugState.slice(31, -1));
              if (slugId === actorId) {
                actors.push(persona);
                return persona.name;
              }
            });
          })
</code>```

答:
You've got a lot going on here - perhaps you could refactor this?

Where is your actors array initialized?  Where is your setState call?

When dealing with arrays in state, you may want to create a copy of your arrays - perform the mutations on the copy - and then set the state to the new array when you are finished.

For instance:

```<code>const moviesCopy = [...this.state.movies];
this.setState({ movies: moviesCopy });
</code>```

Hope this helps get you on the right track.

ContentLicense: CC BY-SA 4.0

Body:
My main goal is to set a state with a array of objects, but I can't do it because this array is mutated with elements that are pushed to it. I understand the problem but I don't know how to solve it

so here is code and I would like to set state with the final actors array. Any ideas?

    const moviesToMap = this.state.movies;
    moviesToMap.map(movie => {
      return this.state.title === movie.title
        ? movie.characters.map(person => {
            const actorUrl = person;
            const actorId = parseInt(actorUrl.slice(31, -1));
            let peopleStateCopy = this.state.people;
            peopleStateCopy.map(persona => {
              const slugState = persona.url;
              const slugId = parseInt(slugState.slice(31, -1));
              if (slugId === actorId) {
                actors.push(persona);
                return persona.name;
              }
            });
          })

Body:
You've got a lot going on here - perhaps you could refactor this?

Where is your actors array initialized?  Where is your setState call?

When dealing with arrays in state, you may want to create a copy of your arrays - perform the mutations on the copy - and then set the state to the new array when you are finished.

For instance:

const moviesCopy = [...this.state.movies];
this.setState({ movies: moviesCopy });

Hope this helps get you on the right track.


问:
How can I store the value of a Css Property (height in px) in a Javascript variable as a number?
How can I store the value of a Css Property (height in px) in a    Javascript variable as a number?
somediv.style.height (in px) should be stored in a
    variable.

```<code><style>

     #somediv {
        width: 100px;
        height: 20px;
     }

</style>

<script>

    let somediv = document.getElementById('somediv');
    let height = somediv.style.height;

</script
</code>```

but this doesnt work. Please help me!

答:
You can also do this with some simple jQuery, using .height() . The Code is as followed:

    var height = $(".somediv").height();
    console.log(height);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>     .somediv {
        width: 100px;
        height: 200px;
     }</code>```

Tokyo

Tokyo is the capital of Japan.

```

Body:
How can I store the value of a Css Property (height in px) in a    Javascript variable as a number?
somediv.style.height (in px) should be stored in a
    variable.

but this doesnt work. Please help me!

Body:
You can also do this with some simple jQuery, using .height() . The Code is as followed:

    var height = $(".somediv").height();
    console.log(height);

     .somediv {
        width: 100px;
        height: 200px;
     }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="somediv">
  <h2>Tokyo</h2>
  <p>Tokyo is the capital of Japan.</p>
</div>


问:
Swapping alternate digits of a number
I am working with some of the problems that are given under hackerrank modules. The question is about swapping the alternate digits of the given number.

I have tried my logic in C. It worked for most of the test cases but couldn't crack some corner case which i am unable to check with. Here is what i have tried.

```<code>int main() {
    int n,i,j;
    char a[20];
    scanf("%s",a);
    n=strlen(a);
    if(n==1){
        printf("%s",a);
    }
    else{
        for(i=0,j=i+1;i<n-1 && j<n;i=i+2,j=j+2){
            a[i]^=a[j]^=a[i]^=a[j];
        }
        printf("%s",a);
    }
    return 0;
}
</code>```

I am not able to visualize the test cases provided by the module owner as i don't have access to them. These were some of the practice problems given in my college for placement preparation. So i don't have access to the test cases and that's why am not able to provide with those failing test cases and their outputs.  Someone please help me with what i had gone wrong in the logic. Thanks in advance.

Title: Swapping alternate digits of a number

Body:
I am working with some of the problems that are given under hackerrank modules. The question is about swapping the alternate digits of the given number.

I have tried my logic in C. It worked for most of the test cases but couldn't crack some corner case which i am unable to check with. Here is what i have tried.

int main() {
    int n,i,j;
    char a[20];
    scanf("%s",a);
    n=strlen(a);
    if(n==1){
        printf("%s",a);
    }
    else{
        for(i=0,j=i+1;i<n-1 && j<n;i=i+2,j=j+2){
            a[i]^=a[j]^=a[i]^=a[j];
        }
        printf("%s",a);
    }
    return 0;
}

I am not able to visualize the test cases provided by the module owner as i don't have access to them. These were some of the practice problems given in my college for placement preparation. So i don't have access to the test cases and that's why am not able to provide with those failing test cases and their outputs.  Someone please help me with what i had gone wrong in the logic. Thanks in advance.

Body:
int n = strlen(a);
for ( int i=1; i < n; i+=2 ) {
   char c = a[i-1];
   a[i-1] = a[i];
   a[i] = c;
}


问:
Angular - button click event take priority over row click event
Having a table with rows, I can click on a row to access the details of one row via a seperate page. This is done via the [routerlink].

```<code> <tr *ngFor="let setting of applicatieData.settings" [routerLink]="['/settings-edit', setting.id]">
    <td class="col-3">{{ setting.shortName | slice:0:10 }}</td>
    <td class="col-4">{{ setting.value }}</td>
    <th class="col-3"><button class="btn btn-info" type="button" (click)="toggleValue(setting.id)">Toggle</button></th>
    <td class="col-2" (contextmenu)="onrightClick($event, setting.id)"><i class="icon-ellipsis-vert"></i></td>
</tr>
</code>```

I would like the 'Toggle' button click event to take priority over previously mentioned row click event. How can I do that?

The right click with the 'context menu' works fine.

答:
you need to stop the event from bubbling up the dom tree.

<button class="btn btn-info" type="button" (click)="toggleValue($event, setting.id)">Toggle</button>
```

```toggleValue(event: MouseEvent, id: string) {
  event.preventDefault();
  event.stopPropagation();

  ...
}
```

Body:
Having a table with rows, I can click on a row to access the details of one row via a seperate page. This is done via the [routerlink].

    {{ setting.shortName | slice:0:10 }}
    {{ setting.value }}
    <button class="btn btn-info" type="button" (click)="toggleValue(setting.id)">Toggle</button>

I would like the 'Toggle' button click event to take priority over previously mentioned row click event. How can I do that?

The right click with the 'context menu' works fine.

Body:
you need to stop the event from bubbling up the dom tree.

<th class="col-3"><button class="btn btn-info" type="button" (click)="toggleValue($event, setting.id)">Toggle</button></th>

toggleValue(event: MouseEvent, id: string) {
  event.preventDefault();
  event.stopPropagation();

  ...
}


问:
Find absolute difference between 2 columns with dates of different formats as number of days
I need to find the absolute difference in days between 2 columns which have dates in python.
This is pretty easy in excel but I want in python.

I have a xlsx file which I have read to a python dataframe(using pd.read_excel) with sample data reading as below:
The columns have the date details in the plain text format of ddmmyyyy/dmmyyyy.

A                   B

1102012

26071993        27122007

28062010        3122015

16012010        21022016

02082015        14092010

Now I need to create a new column C which contains the absolute number of days difference between A and B. A can be less than or greater than B.

If B is empty then it should consider current date for days calculation. But A will not have empty/NULL values.

So output will be the difference of number of days:

C

2432

5267

1984

2227

1783

The approach I followed was:

Convert A and B to 8 digits as we have only 7 digits in some values of A and B - using df['A'].apply(lambda x: '{0:0>8}'.format(x))

Convert A to datetime field using pd.to_datetime

Create another temporary column say CC by copying B values and with all not NULL date values(that is replacing NULL/empty with current date)

Then find the absolute difference between A and CC(number of days)

I am stuck in third step and not able to proceed. Is there any simpler way to do this?

答:
Edit: explain on error

As you said the error in comment. It means your column A is not dtype object. It is either int32 or int64. Run this command to confirm (I changed sample data column A dtype to demonstrate the error):

```<code>df.dtypes

Out[2866]:
A     int32
B    object
dtype: object
</code>```

Before using str.zfill, you need to change your df to object as follows:

```<code>df = df.astype(str)

Out[2870]:
A    object
B    object
dtype: object
</code>```

After converting dtype to object, everything will works.

zfill(8) to pad 0 to strings and convert them to datetime using pd.to_datetime with coerce, and filna on NaT with today date. Next, do subtraction A and B, make abs and get days from timedelta

Note: adding pre-process to convert df dtype to object using astype(str)

```<code>df = df.astype(str)
df1 = df.apply(lambda x: pd.to_datetime(x.str.zfill(8), format='%d%m%Y', errors='coerce')).fillna(pd.datetime.today().date())
df1.A.sub(df1.B).abs().dt.days

Out[2599]:
0    2432
1    5267
2    1984
3    2227
4    1783
dtype: int64
</code>```

Body:
Edit: explain on error

As you said the error in comment. It means your column A is not dtype object. It is either int32 or int64. Run this command to confirm (I changed sample data column A dtype to demonstrate the error):

df.dtypes

Out[2866]:
A     int32
B    object
dtype: object

Before using str.zfill, you need to change your df to object as follows:

df = df.astype(str)

Out[2870]:
A    object
B    object
dtype: object

After converting dtype to object, everything will works.

zfill(8) to pad 0 to strings and convert them to datetime using pd.to_datetime with coerce, and filna on NaT with today date. Next, do subtraction A and B, make abs and get days from timedelta

Note: adding pre-process to convert df dtype to object using astype(str)

df = df.astype(str)
df1 = df.apply(lambda x: pd.to_datetime(x.str.zfill(8), format='%d%m%Y', errors='coerce')).fillna(pd.datetime.today().date())
df1.A.sub(df1.B).abs().dt.days

Out[2599]:
0    2432
1    5267
2    1984
3    2227
4    1783
dtype: int64


问:
Custom Route Provider when is not a function
This is an updated version of a question from this morning.

I have two separate modules, 'admin' and 'authorization'. In the provider block of authorization, I extend $routeProvider in order to attach an identical route to all of the route definitions.

First, here is admin.js:

```<code>angular.module('authorization', [])
    .provider('$appRoute', function () {
        this.$get = function($routeProvider) {
            var universalResolves = {authorize: function($authorization) {
                    return $authorization.authorize();
                }};

            var extendedRouter = angular.extend({}, $routeProvider, {
                when: function(path, route) {
                    route.resolve = (route.resolve) ? route.resolve : {};
                    angular.extend(route.resolve, universalResolves);
                    $routeProvider.when(path, route);
                    return this;
                }
            });

            return new extendedRouter();
        }
    })
    .factory('$authorization', ['$http', '$location', function($http, $location) {

        var $authorization = {};

        $authorization.authorize = function() {

            var path = $location.path();

            return promise = $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                var data = response.data;
                if (response.data.result === 'NOT_AUTHORIZED') {
                    throw "NOT_AUTHORIZED";
                }

                return data;
            });

        };

        return $authorization;
    }]);
</code>```

Next, my admin module:

```<code>angular.module('admin', ['ngRoute', 'ngSanitize', 'ngCsv'
        , 'authorization'
    ])

    .controller('mainCtrl', function() {

    })
    .config(['$routeProvider', '$appRouteProvider', function($routeProvider, $appRouteProvider) {

        // old definition that needs to be changed to $appRouteProvider
        $routeProvider.when('/login', {
            templateUrl: '/login/auth.html',
            controller: 'loginCtrl'
        });

        $appRouteProvider.when('/page', {
            templateUrl: 'page.tmpl.html',
            controller: 'pageCtrl'
        });
</code>```

Unfortunately, I get the following error:

```<code>Error: [$injector:modulerr] Failed to instantiate module app due to:
$appRouteProvider.when is not a function
@https://localhost:8443/admin.js:87:9
invoke@https://localhost:8443/js/angular/angular.js:4718:16
runInvokeQueue@https://localhost:8443/js/angular/angular.js:4611:11
loadModules/<@https://localhost:8443/js/angular/angular.js:4620:11
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
loadModules/<@https://localhost:8443/js/angular/angular.js:4618:40
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
createInjector@https://localhost:8443/js/angular/angular.js:4523:19
doBootstrap@https://localhost:8443/js/angular/angular.js:1758:20
bootstrap@https://localhost:8443/js/angular/angular.js:1779:12
angularInit@https://localhost:8443/js/angular/angular.js:1664:5
@https://localhost:8443/js/angular/angular.js:31763:5
j@https://localhost:8443/js/jquery/jquery.min.js:2:29566
g/</k<@https://localhost:8443/js/jquery/jquery.min.js:2:29882
</code>```

So it sees the $appRouteProvider, but only the this.$get() method. Can anyone help?

答:
Just regarding the error, the $appRoute provider is not exposing any methods on  it self (other then $get). So its an empty api config provider object.

When using the base provider recipe, the $get method is used to provide a function to generate the service, and the this from the provider is used to bind extra config functions to put data the $get function can later use.

From Angular provider docs:

```<code>myApp.provider('unicornLauncher', function UnicornLauncherProvider() {
  var useTinfoilShielding = false;

  // provider config api method.
  this.useTinfoilShielding = function(value) {
    useTinfoilShielding = !!value;
  };

  this.$get = ["apiToken", function unicornLauncherFactory(apiToken) {

    // let's assume that the UnicornLauncher constructor was also changed to
    // accept and use the useTinfoilShielding argument
    return new UnicornLauncher(apiToken, useTinfoilShielding);
  }];
});
</code>```

If you want to add additional methods on the provider, you can use this.when = ... or Angular.extends(this, ....) for instance.

Body:
This is an updated version of a question from this morning.

I have two separate modules, 'admin' and 'authorization'. In the provider block of authorization, I extend $routeProvider in order to attach an identical route to all of the route definitions.

First, here is admin.js:

angular.module('authorization', [])
    .provider('$appRoute', function () {
        this.$get = function($routeProvider) {
            var universalResolves = {authorize: function($authorization) {
                    return $authorization.authorize();
                }};

            var extendedRouter = angular.extend({}, $routeProvider, {
                when: function(path, route) {
                    route.resolve = (route.resolve) ? route.resolve : {};
                    angular.extend(route.resolve, universalResolves);
                    $routeProvider.when(path, route);
                    return this;
                }
            });

            return new extendedRouter();
        }
    })
    .factory('$authorization', ['$http', '$location', function($http, $location) {

        var $authorization = {};

        $authorization.authorize = function() {

            var path = $location.path();

            return promise = $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                var data = response.data;
                if (response.data.result === 'NOT_AUTHORIZED') {
                    throw "NOT_AUTHORIZED";
                }

                return data;
            });

        };

        return $authorization;
    }]);

Next, my admin module:

angular.module('admin', ['ngRoute', 'ngSanitize', 'ngCsv'
        , 'authorization'
    ])

    .controller('mainCtrl', function() {

    })
    .config(['$routeProvider', '$appRouteProvider', function($routeProvider, $appRouteProvider) {

        // old definition that needs to be changed to $appRouteProvider
        $routeProvider.when('/login', {
            templateUrl: '/login/auth.html',
            controller: 'loginCtrl'
        });

        $appRouteProvider.when('/page', {
            templateUrl: 'page.tmpl.html',
            controller: 'pageCtrl'
        });

Unfortunately, I get the following error:

Error: [$injector:modulerr] Failed to instantiate module app due to:
$appRouteProvider.when is not a function
@https://localhost:8443/admin.js:87:9
invoke@https://localhost:8443/js/angular/angular.js:4718:16
runInvokeQueue@https://localhost:8443/js/angular/angular.js:4611:11
loadModules/<@https://localhost:8443/js/angular/angular.js:4620:11
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
loadModules/<@https://localhost:8443/js/angular/angular.js:4618:40
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
createInjector@https://localhost:8443/js/angular/angular.js:4523:19
doBootstrap@https://localhost:8443/js/angular/angular.js:1758:20
bootstrap@https://localhost:8443/js/angular/angular.js:1779:12
angularInit@https://localhost:8443/js/angular/angular.js:1664:5
@https://localhost:8443/js/angular/angular.js:31763:5
j@https://localhost:8443/js/jquery/jquery.min.js:2:29566
g/</k<@https://localhost:8443/js/jquery/jquery.min.js:2:29882

So it sees the $appRouteProvider, but only the this.$get() method. Can anyone help?

Body:
Just regarding the error, the $appRoute provider is not exposing any methods on  it self (other then $get). So its an empty api config provider object.

When using the base provider recipe, the $get method is used to provide a function to generate the service, and the this from the provider is used to bind extra config functions to put data the $get function can later use.

From Angular provider docs:

myApp.provider('unicornLauncher', function UnicornLauncherProvider() {
  var useTinfoilShielding = false;

  // provider config api method.
  this.useTinfoilShielding = function(value) {
    useTinfoilShielding = !!value;
  };

  this.$get = ["apiToken", function unicornLauncherFactory(apiToken) {

    // let's assume that the UnicornLauncher constructor was also changed to
    // accept and use the useTinfoilShielding argument
    return new UnicornLauncher(apiToken, useTinfoilShielding);
  }];
});

If you want to add additional methods on the provider, you can use this.when = ... or Angular.extends(this, ....) for instance.


问:
Can't convert JSONArray into a list (Kotlin)
This is my string:

```<code>{"array":[{"message":"test1","name":"test2","creation":"test3"},{"message":"test1","name":"test2","creation":"test3"}]}
</code>```

And I want it get that array into a list of object in Kotlin app for Android.
I tried to do it using two examples from this site... So here is my code (res = that string):

```<code>val gson = Gson()
val obj = gson.fromJson(res, JsonObject::class.java)
val arr = obj.getAsJsonArray("array")

println(arr.toString())
val list1 : List<JThread> = gson.fromJson(arr, object : TypeToken<List<JThread>>() {}.type)
val list2 = gson.fromJson(arr, Array<JThread>::class.java).asList()

for (x in list1){
   println(x.message)
}
for (x in list2){
   println(x.message)
}
</code>```

However I'm only getting null in x.message. I don't know what can go wrong.
I also tried changing arr to arr.toString() everywhere and that didn't work either.

Also JThread is:

```<code>object JThread {
var message: String? = null
var name: String? = null
var creation: String? = null }
</code>```

答:
Use this code:

```<code>import com.google.gson.annotations.SerializedName
import com.google.gson.Gson

data class Array(
    @SerializedName("message")
    var message: String,
    @SerializedName("name")
    var name: String,
    @SerializedName("creation")
    var creation: String
)

data class Example(
    @SerializedName("array")
    var array: List<Array>? = null
)

private fun fromJson(json:String):Example{
    return Gson().fromJson<Example>(json, Example::class.java)
}
</code>```

PS: I made it with this site:http://www.jsonschema2pojo.org/

Body:
This is my string:

{"array":[{"message":"test1","name":"test2","creation":"test3"},{"message":"test1","name":"test2","creation":"test3"}]}

And I want it get that array into a list of object in Kotlin app for Android.
I tried to do it using two examples from this site... So here is my code (res = that string):

val gson = Gson()
val obj = gson.fromJson(res, JsonObject::class.java)
val arr = obj.getAsJsonArray("array")

println(arr.toString())
val list1 : List<JThread> = gson.fromJson(arr, object : TypeToken<List<JThread>>() {}.type)
val list2 = gson.fromJson(arr, Array<JThread>::class.java).asList()

for (x in list1){
   println(x.message)
}
for (x in list2){
   println(x.message)
}

However I'm only getting null in x.message. I don't know what can go wrong.
I also tried changing arr to arr.toString() everywhere and that didn't work either.

Also JThread is:

object JThread {
var message: String? = null
var name: String? = null
var creation: String? = null }

Body:
Use this code:

import com.google.gson.annotations.SerializedName
import com.google.gson.Gson

data class Array(
    @SerializedName("message")
    var message: String,
    @SerializedName("name")
    var name: String,
    @SerializedName("creation")
    var creation: String
)

data class Example(
    @SerializedName("array")
    var array: List<Array>? = null
)

private fun fromJson(json:String):Example{
    return Gson().fromJson<Example>(json, Example::class.java)
}

PS: I made it with this site:http://www.jsonschema2pojo.org/


问:
Listen to all touch events in an iOS app
Is it possible to somehow listen to, and catch, all the touch events occurring in an app?

The app I'm currently developing will be used in showrooms and information kiosks and I would therefore like to revert to the start section of the app if no touches has been received for a given couple of minutes. A sort of screensaver functionality, if you will. I'm planning to implement this by having a timer running in the background, which should be reset and restarted every time a touch event occurs somewhere in the app. But how can I listen to the touch events? Any ideas or suggestions?

答:
In Swift 4.2
1. Create subclass of UIApplication object and print user action:

```<code>    import UIKit
    class ANUIApplication: UIApplication {

        override func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool {
            print("FILE= \(NSStringFromSelector(action)) METHOD=\(String(describing: target!)) SENDER=\(String(describing: sender))")
            return super.sendAction(action, to: target, from: sender, for: event)
        }
    }
</code>```

In AppDelegate.swift file you will find application entry point @UIApplicationMain Comment that and Add new swift file main.swift
and add following code to main.swift file

import UIKit

UIApplicationMain(
      CommandLine.argc, CommandLine.unsafeArgv,
      NSStringFromClass(ANUIApplication.self), NSStringFromClass(AppDelegate.self))

ANUIApplication is class where we added action logs.
AppDelegate is default app delegate where we wrote application delegate methods.(Helpful for tracking action and file name in big project)

Body:
In Swift 4.2
1. Create subclass of UIApplication object and print user action:

    import UIKit
    class ANUIApplication: UIApplication {

        override func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool {
            print("FILE= \(NSStringFromSelector(action)) METHOD=\(String(describing: target!)) SENDER=\(String(describing: sender))")
            return super.sendAction(action, to: target, from: sender, for: event)
        }
    }

In AppDelegate.swift file you will find application entry point @UIApplicationMain Comment that and Add new swift file main.swift
and add following code to main.swift file

import UIKit

UIApplicationMain(
      CommandLine.argc, CommandLine.unsafeArgv,
      NSStringFromClass(ANUIApplication.self), NSStringFromClass(AppDelegate.self))

ANUIApplication is class where we added action logs.
AppDelegate is default app delegate where we wrote application delegate methods.(Helpful for tracking action and file name in big project)


问:
I need delete two " " with sed command
I need to delete "" in file

```<code>"CITFFUSKD-E0"
</code>```

I have tried sed 's/\"//.

Result is:

```<code>CITFFUSKD-E0"
</code>```

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

```<code>"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"
</code>```

Result I want it:

```<code>CITFFUSKD
</code>```

答:
Many legitimate ways to solve this.

I favor using what you know about your data to simplify solutions -- this is usually an option. If everything in your file follows the same pattern, you can simply extract the first set of capitalized letters encountered:

```<code>sed 's/"\([A-Z]\+\).*$/\1/' file
</code>```

Title: I need delete two " " with sed command

Body:
I need to delete "" in file

"CITFFUSKD-E0"

I have tried sed 's/\"//.

Result is:

CITFFUSKD-E0"

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"

Result I want it:

CITFFUSKD

Body:
Many legitimate ways to solve this.

I favor using what you know about your data to simplify solutions -- this is usually an option. If everything in your file follows the same pattern, you can simply extract the first set of capitalized letters encountered:

sed 's/"\([A-Z]\+\).*$/\1/' file


问:
how replace a value of cookie in cookie string using regular expression in javascript
i have a cookie string like this
'user=sravan;XSRF-TOKEN=1212143;session=random'
i need to check for the XSRD-TOKEN in the cookie string, if we have the XSRF-TOKEN in the  string then need to replace the value with 'test'

expected new string is 'user=sravan;XSRF-TOKEN=test;session=random'

i tried this (?<=XSRF-TOKEN).*$ but it is selecting the entire string after XSRF-TOKEN=

答:
You could use (?<=XSRF-TOKEN=)([^;]+), example:

const str = 'user=sravan;XSRF-TOKEN=1212143;session=random';
const processed = str.replace(/(?<=XSRF-TOKEN=)([^;]+)/, "test");
console.log(processed);```

But a better solution will be to parse the cookies and recreate the string.

Body:
You could use (?<=XSRF-TOKEN=)([^;]+), example:

const str = 'user=sravan;XSRF-TOKEN=1212143;session=random';
const processed = str.replace(/(?<=XSRF-TOKEN=)([^;]+)/, "test");
console.log(processed);

But a better solution will be to parse the cookies and recreate the string.


问:
Unresolved symbols when linking libgio.so with libz.so (linux)

The Short Version

Linking my executable against several libraries, including libgio-2.0.so.0.4800.1 (libgio-2.0.so) and libz.so.1.2.8 (libz.so), I get two unresolved symbols - deflateSetHeader@ZLIB_1.2.2 and inflateGetHeader@ZLIB_1.2.2. Neither symbol is defined in libz.so, but inflateGetHeader@@ZLIB_1.2.2 and deflateSetHeader@@ZLIB_1.2.2 are:

```<code>readelf -s libz.so|grep Header
    63: 00007991    28 FUNC    GLOBAL DEFAULT   12 inflateGetHeader@@ZLIB_1.2.2
    98: 00003319    24 FUNC    GLOBAL DEFAULT   12 deflateSetHeader@@ZLIB_1.2.2
   367: 00003319    24 FUNC    GLOBAL DEFAULT   12 deflateSetHeader
   386: 00007991    28 FUNC    GLOBAL DEFAULT   12 inflateGetHeader
</code>```

Other symbols referenced in libgio are successfully resolved by libz, but not these two.

The Long Version

I'm cross-compiling from a Windows host (Xilinx SDK 2016.1 (Eclipse), toolchain "arm-linux-gnueabihf") for a Zynq 7010-based target (krtkl.com) running 32-bit Ubuntu 14.04 with a Linaro 4.4 kernel.

Both the host and target platforms are given, in case you feel the need to ask why I'm doing it that way.

The procedure for using an external shared library is this: download, configure and build library on the target (unless the library already exists on the target), then copy include and library (libabc.so.x.y.z) files to a bespoke project directory on the host, rename libabc.so.x.y.z to abc.so, and set the library path to project directory and library name to abc (i.e. gcc ... -L<project dir> -labc).

I'm using this procedure to include GLib (among others) in my project. GLib (libglib.so) requires GIO (libgio.so), which in turn requires (among others) ZLIB (libz.so).

These libraries are built from source: glib-2.48.1 (including gio, gobject, and gmodule), libffi-3.2.1, zlib-1.2.8. Others are from the Ubuntu distro.

When I run the cross-compiler on Windows ("Project|Build All" in Eclipse), all goes according to plan - libgio-2.0.so, libglib-2.0.so, gobject-2.0.so, libffi.so, libgmodule-2.0.so, libdl.so, libpcre.so, libresolv-2.19.so and libz.so satisfy all external references except deflateSetHeader@ZLIB_1.2.2 and inflateGetHeader@ZLIB_1.2.2.

readelf output (see above) shows similar, but not identical, symbols available in libz.so. I've seen a few mentions of similar problems while searching on-line, but the resolution always has to do with finding an outdated version of ZLIB - not a possibility given my development environment.

Both libgio and libz are well-established libraries in wide use - this can't be a bug, right?

I'm out of ideas - has anyone encountered this or anything similar?

[UPDATE]

gcc version 4.9.2 20140904 (prerelease) (crosstool-NG linaro-1.13.1-4.9-2014.09 - Linaro GCC 4.9-2014.09)

By request, here are example compiler and linker commands emitted by Eclipse:

```<code>19:53:13 **** Auto Build of configuration Debug for project Project_2 ****
make -j8 all
'Building file: ../src/Project.c'
'Invoking: ARM v7 Linux gcc compiler'
arm-linux-gnueabihf-gcc -DCONFIGURATION_DEBUG -Wall -O0 -mcpu=cortex-a9 -mfpu=vfpv3 -mfloat-abi=hard -g3 -I"C:\Users\Nick\XSDK\Workspace\snickerdoodle_bsp\ps7_cortexa9_0\include" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir1" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir2" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir3" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir4" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir5" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir6" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir7" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir8" -I"C:\Users\Nick\XSDK\Workspace\LibXml2\include" -I"C:\Users\Nick\XSDK\Workspace\LibXml2\include\libxml" -I"C:\Users\Nick\XSDK\Workspace\GLibC\include" -c -fmessage-length=0 -MT"src/Project.o" -MMD -MP -MF"src/Project.d" -MT"src/Project.o" -o "src/Project.o" "../src/Project.c"
'Finished building: ../src/Project.c'

'Invoking: ARM v7 Linux gcc linker'
arm-linux-gnueabihf-gcc -L"C:\Users\Nick\XSDK\Workspace\LibXml2\lib" -L"C:\Users\Nick\XSDK\Workspace\GLibC\lib" -o "Project_2.elf"  <all the .o files> -lpthread -lm -lxml2 -llzma -lgio-2.0 -lglib-2.0 -lgobject-2.0 -lffi -lgmodule-2.0 -ldl -lpcre -lresolv-2.19 -lz
c:/xilinx/sdk/2016.1/gnu/aarch32/nt/gcc-arm-linux-gnueabi/bin/../lib/gcc/arm-linux-gnueabihf/4.9.2/../../../../arm-linux-gnueabihf/bin/ld.exe: warning: libz.so.1, needed by C:\Users\Nick\XSDK\Workspace\GLibC\lib/libgio-2.0.so, not found (try using -rpath or -rpath-link)
C:\Users\Nick\XSDK\Workspace\GLibC\lib/libgio-2.0.so: undefined reference to `deflateSetHeader@ZLIB_1.2.2'
C:\Users\Nick\XSDK\Workspace\GLibC\lib/libgio-2.0.so: undefined reference to `inflateGetHeader@ZLIB_1.2.2'
</code>```

答: by removing -lz from LDFLAGS/LDLIBS, it got resolved for me</p>

Body:
The Short Version

Linking my executable against several libraries, including libgio-2.0.so.0.4800.1 (libgio-2.0.so) and libz.so.1.2.8 (libz.so), I get two unresolved symbols - deflateSetHeader@ZLIB_1.2.2 and inflateGetHeader@ZLIB_1.2.2. Neither symbol is defined in libz.so, but inflateGetHeader@@ZLIB_1.2.2 and deflateSetHeader@@ZLIB_1.2.2 are:

readelf -s libz.so|grep Header
    63: 00007991    28 FUNC    GLOBAL DEFAULT   12 inflateGetHeader@@ZLIB_1.2.2
    98: 00003319    24 FUNC    GLOBAL DEFAULT   12 deflateSetHeader@@ZLIB_1.2.2
   367: 00003319    24 FUNC    GLOBAL DEFAULT   12 deflateSetHeader
   386: 00007991    28 FUNC    GLOBAL DEFAULT   12 inflateGetHeader

Other symbols referenced in libgio are successfully resolved by libz, but not these two.

The Long Version

I'm cross-compiling from a Windows host (Xilinx SDK 2016.1 (Eclipse), toolchain "arm-linux-gnueabihf") for a Zynq 7010-based target (krtkl.com) running 32-bit Ubuntu 14.04 with a Linaro 4.4 kernel.

Both the host and target platforms are given, in case you feel the need to ask why I'm doing it that way.

The procedure for using an external shared library is this: download, configure and build library on the target (unless the library already exists on the target), then copy include and library (libabc.so.x.y.z) files to a bespoke project directory on the host, rename libabc.so.x.y.z to abc.so, and set the library path to project directory and library name to abc (i.e. gcc ... -L<project dir> -labc).

I'm using this procedure to include GLib (among others) in my project. GLib (libglib.so) requires GIO (libgio.so), which in turn requires (among others) ZLIB (libz.so).

These libraries are built from source: glib-2.48.1 (including gio, gobject, and gmodule), libffi-3.2.1, zlib-1.2.8. Others are from the Ubuntu distro.

When I run the cross-compiler on Windows ("Project|Build All" in Eclipse), all goes according to plan - libgio-2.0.so, libglib-2.0.so, gobject-2.0.so, libffi.so, libgmodule-2.0.so, libdl.so, libpcre.so, libresolv-2.19.so and libz.so satisfy all external references except deflateSetHeader@ZLIB_1.2.2 and inflateGetHeader@ZLIB_1.2.2.

readelf output (see above) shows similar, but not identical, symbols available in libz.so. I've seen a few mentions of similar problems while searching on-line, but the resolution always has to do with finding an outdated version of ZLIB - not a possibility given my development environment.

Both libgio and libz are well-established libraries in wide use - this can't be a bug, right?

I'm out of ideas - has anyone encountered this or anything similar?

[UPDATE]

gcc version 4.9.2 20140904 (prerelease) (crosstool-NG linaro-1.13.1-4.9-2014.09 - Linaro GCC 4.9-2014.09)

By request, here are example compiler and linker commands emitted by Eclipse:

19:53:13 **** Auto Build of configuration Debug for project Project_2 ****
make -j8 all
'Building file: ../src/Project.c'
'Invoking: ARM v7 Linux gcc compiler'
arm-linux-gnueabihf-gcc -DCONFIGURATION_DEBUG -Wall -O0 -mcpu=cortex-a9 -mfpu=vfpv3 -mfloat-abi=hard -g3 -I"C:\Users\Nick\XSDK\Workspace\snickerdoodle_bsp\ps7_cortexa9_0\include" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir1" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir2" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir3" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir4" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir5" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir6" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir7" -I"C:\Users\Nick\XSDK\Workspace\Project_2\src\Dir8" -I"C:\Users\Nick\XSDK\Workspace\LibXml2\include" -I"C:\Users\Nick\XSDK\Workspace\LibXml2\include\libxml" -I"C:\Users\Nick\XSDK\Workspace\GLibC\include" -c -fmessage-length=0 -MT"src/Project.o" -MMD -MP -MF"src/Project.d" -MT"src/Project.o" -o "src/Project.o" "../src/Project.c"
'Finished building: ../src/Project.c'

'Invoking: ARM v7 Linux gcc linker'
arm-linux-gnueabihf-gcc -L"C:\Users\Nick\XSDK\Workspace\LibXml2\lib" -L"C:\Users\Nick\XSDK\Workspace\GLibC\lib" -o "Project_2.elf"  <all the .o files> -lpthread -lm -lxml2 -llzma -lgio-2.0 -lglib-2.0 -lgobject-2.0 -lffi -lgmodule-2.0 -ldl -lpcre -lresolv-2.19 -lz
c:/xilinx/sdk/2016.1/gnu/aarch32/nt/gcc-arm-linux-gnueabi/bin/../lib/gcc/arm-linux-gnueabihf/4.9.2/../../../../arm-linux-gnueabihf/bin/ld.exe: warning: libz.so.1, needed by C:\Users\Nick\XSDK\Workspace\GLibC\lib/libgio-2.0.so, not found (try using -rpath or -rpath-link)
C:\Users\Nick\XSDK\Workspace\GLibC\lib/libgio-2.0.so: undefined reference to `deflateSetHeader@ZLIB_1.2.2'
C:\Users\Nick\XSDK\Workspace\GLibC\lib/libgio-2.0.so: undefined reference to `inflateGetHeader@ZLIB_1.2.2'


问:
I have a query that do 2 LEFT JOINs and 1 GROUP BY but I get missing results:
The following query should return around 1159 results but only returns around 880 results;
If I only JOIN the "c" width "mm" I still get the 1159 results. Only when all 3 tables I get 880 results. I also used with no luck: RIGHT JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, INNER JOIN. I tried with "()" and without "()" in the JOIN sintax no luck too.

Any help is appreciated

```<code>SELECT c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi,

Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END),

Sum(CASE WHEN m.mcdmv=2 THEN m.mqtd END),

Sum(CASE WHEN m.mcdmv=13 THEN m.mqtd END),
Sum(CASE WHEN m.mcdmv=14 THEN m.mqtd END),

MAX(CASE WHEN m.mcdmv=82 THEN m.mdata END)

FROM
(zzz.ccc c
LEFT JOIN zzz.mmmm mm ON c.crnp = mm.arncd)
LEFT JOIN zzz.mm m ON m.mrncd = c.crnp

WHERE
((c.cetcm='xcd') OR
(c.cetcm='ewfwe') OR
(c.cetcm='fewfew') OR
(c.cetcm='fewf')) AND

(m.MDATA Between 20100101 And 20110406) AND

((m.mcdmv=11) OR
(m.mcdmv=12) OR
(m.mcdmv=13) OR
(m.mcdmv=14)) AND

(mm.aarm=1)

GROUP BY c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi

ORDER BY c.ccod
</code>```

答:
As has been suggested, you need to move the criteria against the tables in the Left Joins into their respective ON clauses:

```<code>SELECT c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi
    , Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END) As Total11
    , Sum(CASE WHEN m.mcdmv=12 THEN m.mqtd END) As Total12
    , Sum(CASE WHEN m.mcdmv=13 THEN m.mqtd END) As Total13
    , Sum(CASE WHEN m.mcdmv=14 THEN m.mqtd END) As Total14
    , MAX(CASE WHEN m.mcdmv=82 THEN m.mdata END) As Max82
FROM (zzz.ccc c
    LEFT JOIN zzz.mmmm mm
        ON (c.crnp = mm.arncd
        And m.aarm = 1))
    LEFT JOIN zzz.mm m
        ON (m.mrncd = c.crnp
            And m.mcdmv In(11,12,13,14,82)
            And m.MDATA Between #20100101# And #20110406#)
WHERE c.cetcm In('xcd','ewfwe','fewfew','fewf')
GROUP BY c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi
ORDER BY c.ccod
</code>```

In addition, I've made use of the IN function which lets you pass a series of values. Btw, Access will likely also balk at not having column aliases for the columns aggregate functions. Here I've just used something simple.

Body:
The following query should return around 1159 results but only returns around 880 results;
If I only JOIN the "c" width "mm" I still get the 1159 results. Only when all 3 tables I get 880 results. I also used with no luck: RIGHT JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, INNER JOIN. I tried with "()" and without "()" in the JOIN sintax no luck too.

Any help is appreciated

SELECT c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi,

Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END),

Sum(CASE WHEN m.mcdmv=2 THEN m.mqtd END),

Sum(CASE WHEN m.mcdmv=13 THEN m.mqtd END),
Sum(CASE WHEN m.mcdmv=14 THEN m.mqtd END),

MAX(CASE WHEN m.mcdmv=82 THEN m.mdata END)

FROM
(zzz.ccc c
LEFT JOIN zzz.mmmm mm ON c.crnp = mm.arncd)
LEFT JOIN zzz.mm m ON m.mrncd = c.crnp

WHERE
((c.cetcm='xcd') OR
(c.cetcm='ewfwe') OR
(c.cetcm='fewfew') OR
(c.cetcm='fewf')) AND

(m.MDATA Between 20100101 And 20110406) AND

((m.mcdmv=11) OR
(m.mcdmv=12) OR
(m.mcdmv=13) OR
(m.mcdmv=14)) AND

(mm.aarm=1)

GROUP BY c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi

ORDER BY c.ccod

Body:
As has been suggested, you need to move the criteria against the tables in the Left Joins into their respective ON clauses:

SELECT c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi
    , Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END) As Total11
    , Sum(CASE WHEN m.mcdmv=12 THEN m.mqtd END) As Total12
    , Sum(CASE WHEN m.mcdmv=13 THEN m.mqtd END) As Total13
    , Sum(CASE WHEN m.mcdmv=14 THEN m.mqtd END) As Total14
    , MAX(CASE WHEN m.mcdmv=82 THEN m.mdata END) As Max82
FROM (zzz.ccc c
    LEFT JOIN zzz.mmmm mm
        ON (c.crnp = mm.arncd
        And m.aarm = 1))
    LEFT JOIN zzz.mm m
        ON (m.mrncd = c.crnp
            And m.mcdmv In(11,12,13,14,82)
            And m.MDATA Between #20100101# And #20110406#)
WHERE c.cetcm In('xcd','ewfwe','fewfew','fewf')
GROUP BY c.ccod, c.cetcm, c.cdscr, c.cpcul, c.cdent, mm.amexi
ORDER BY c.ccod

In addition, I've made use of the IN function which lets you pass a series of values. Btw, Access will likely also balk at not having column aliases for the columns aggregate functions. Here I've just used something simple.


答:
This should only only select up until ;

```<code>(?<=XSRF-TOKEN)[^;]+
</code>```

Or if you only like to select whats after = to ;

```<code>(?<=XSRF-TOKEN=)[^;]+
</code>```

'user=sravan;XSRF-TOKEN=1212143;session=random'

Title: how replace a value of cookie in cookie string using regular expression in javascript

Body:
i have a cookie string like this
'user=sravan;XSRF-TOKEN=1212143;session=random'
i need to check for the XSRD-TOKEN in the cookie string, if we have the XSRF-TOKEN in the  string then need to replace the value with 'test'

expected new string is 'user=sravan;XSRF-TOKEN=test;session=random'

i tried this (?<=XSRF-TOKEN).*$ but it is selecting the entire string after XSRF-TOKEN=

Body:
This should only only select up until ;

(?<=XSRF-TOKEN)[^;]+

Or if you only like to select whats after = to ;

(?<=XSRF-TOKEN=)[^;]+

'user=sravan;XSRF-TOKEN=1212143;session=random'


问:
How does one create a Stripe order with invoice?
I've got an api endpoint that listens to the invoice.payment_succces webhook event.  Whenever I get an invoice, I email a link to it to the user it is for.

This has worked so far for subscriptions, which automatically create an invoice, but does not appear to work the same for orders.

When ever I submit an order (like so)...

```<code>const order = await stripe.orders.create({
    customer: user.stripeCustomerId as string,
    currency: "usd",
    coupon: couponCode,
    items: [{
        type: "sku",
        parent: product.sku,
    }],
});
return stripe.orders.pay(order.id, {});
</code>```

... the order is logged, and the payment occurs, but no invoice is ever generated.

How does one make stripe create an invoice when submitting an order?

答:
If you are looking to send once-off invoices on a per-order basis, first configure your invoices

e.g.

```<code>const stripe = require('stripe')('<test key>');

stripe.invoiceItems.create({
  amount: 1000,
  currency: 'usd',
  customer: 'cus_4fdAW5ftNQow1a',
  description: 'Set-up fee',
});
</code>```

Next you prepare a 'draft' invoice using await.stripe.invoices.create

```<code>const stripe = require('stripe')('<test key>');

(async () => {
  const invoice = await stripe.invoices.create({
    customer: 'cus_4fdAW5ftNQow1a',
    billing: 'send_invoice',
    days_until_due: 30,
  });
})();
</code>```

The draft invoice can be updated and when you are ready to bill, you can finalise it:

```<code>const stripe = require('stripe')('<test key>');

stripe.invoices.sendInvoice(invoice.id, function(err, invoice) {
  // asynchronously called
});
</code>```

Source code taken from the stripe docs

If I've misunderstood the question, please comment. (It sounds like you are placing the order by the way your question is phrased... )

Hope this helps

Body:
I've got an api endpoint that listens to the invoice.payment_succces webhook event.  Whenever I get an invoice, I email a link to it to the user it is for.

This has worked so far for subscriptions, which automatically create an invoice, but does not appear to work the same for orders.

When ever I submit an order (like so)...

const order = await stripe.orders.create({
    customer: user.stripeCustomerId as string,
    currency: "usd",
    coupon: couponCode,
    items: [{
        type: "sku",
        parent: product.sku,
    }],
});
return stripe.orders.pay(order.id, {});

... the order is logged, and the payment occurs, but no invoice is ever generated.

How does one make stripe create an invoice when submitting an order?

Body:
If you are looking to send once-off invoices on a per-order basis, first configure your invoices

e.g.

const stripe = require('stripe')('<test key>');

stripe.invoiceItems.create({
  amount: 1000,
  currency: 'usd',
  customer: 'cus_4fdAW5ftNQow1a',
  description: 'Set-up fee',
});

Next you prepare a 'draft' invoice using await.stripe.invoices.create

const stripe = require('stripe')('<test key>');

(async () => {
  const invoice = await stripe.invoices.create({
    customer: 'cus_4fdAW5ftNQow1a',
    billing: 'send_invoice',
    days_until_due: 30,
  });
})();

The draft invoice can be updated and when you are ready to bill, you can finalise it:

const stripe = require('stripe')('<test key>');

stripe.invoices.sendInvoice(invoice.id, function(err, invoice) {
  // asynchronously called
});

Source code taken from the stripe docs

If I've misunderstood the question, please comment. (It sounds like you are placing the order by the way your question is phrased... )

Hope this helps


问:
Protobuf-net serialization on sockets. No parameterless constructor found ProtoException
I have created an application where interprocess communication is done using sockets. The procedure starts when a client connects with the server that I created and sends a serialized message. This message, I serialize using Protobuf-net, using SerializeWithLengthPrefix and deserialize it using DeserializeWithLengthPrefix. The client sends messages to the server who deserializes it perfectly, but the same is not true in the case of server to client.

The main class is BaseMessage, which is abstract.

```<code>[Serializable, ProtoContract, ProtoInclude(5001, typeof(LogonMessage))]
abstract public class BaseMessage
{
    public BaseMessage()
    {

    }

    abstract public int MessageType { get; }
}
</code>```

And LogonMessage implements the BaseMessage Class.

```<code>[Serializable, ProtoContract]
public class LogonMessage : BaseMessage
{
    public LogonMessage()
    {

    }

    [ProtoMember(1)]
    public string Broker { get; set; }

    [ProtoMember(2)]
    public int ClientType { get; set; }

    public override int MessageType
    {
        get { return 1; }
    }
}
</code>```

After the initial handshake, the client requests some service serialized with the help of protobuf-net and the local server at my end serves it by requesting data from another server on the web. This message transfer from the client to the server is done flawlessly.

When my server receives the data from the web server,  it serializes it and sends the data to the client. But this time, when I try to deserialize the data on the client-side using the same procedure, I get the following exception:
"No parameterless Constructor found for BaseMessage"

I deserialize using the following line of code(this is where the exception occurs).

```<code>BaseMessage baseMessage = Serializer.DeserializeWithLengthPrefix<BaseMessage>(networkStream, PrefixStyle.Base128);
</code>```

And this is how the message was serialized on the server.

```<code>Serializer.SerializeWithLengthPrefix(networkStream, baseMessage, PrefixStyle.Base128);
</code>```

The NetworkStream used at the start of the connection between the client and server is stored in an object and that object is stored in a dictionary. I pick out the same NetworkStream from that object in the dictionary and use it to send serialized data to the client(from the server). But the above mentioned problem occurs. Any help?

Thanks in advance...

答:
This error message seems to be a catch all for a variety of different errors like @isandburn and @JP Tissot have pointed out.

Another is if you Deserialize data that isn't protobuf.

```<code>var tdp = new DerivedObject("Test");
using (var ms  = new MemoryStream())
{
    JsonSerializer.Serialize(ms,tdp); //should be protobuf
    ms.Seek(0, SeekOrigin.Begin);

    var tdp2 = Serializer.Deserialize<DerivedObject>(ms);
}
</code>```

Body:
I have created an application where interprocess communication is done using sockets. The procedure starts when a client connects with the server that I created and sends a serialized message. This message, I serialize using Protobuf-net, using SerializeWithLengthPrefix and deserialize it using DeserializeWithLengthPrefix. The client sends messages to the server who deserializes it perfectly, but the same is not true in the case of server to client.

The main class is BaseMessage, which is abstract.

[Serializable, ProtoContract, ProtoInclude(5001, typeof(LogonMessage))]
abstract public class BaseMessage
{
    public BaseMessage()
    {

    }

    abstract public int MessageType { get; }
}

And LogonMessage implements the BaseMessage Class.

[Serializable, ProtoContract]
public class LogonMessage : BaseMessage
{
    public LogonMessage()
    {

    }

    [ProtoMember(1)]
    public string Broker { get; set; }

    [ProtoMember(2)]
    public int ClientType { get; set; }

    public override int MessageType
    {
        get { return 1; }
    }
}

After the initial handshake, the client requests some service serialized with the help of protobuf-net and the local server at my end serves it by requesting data from another server on the web. This message transfer from the client to the server is done flawlessly.

When my server receives the data from the web server,  it serializes it and sends the data to the client. But this time, when I try to deserialize the data on the client-side using the same procedure, I get the following exception:
"No parameterless Constructor found for BaseMessage"

I deserialize using the following line of code(this is where the exception occurs).

BaseMessage baseMessage = Serializer.DeserializeWithLengthPrefix<BaseMessage>(networkStream, PrefixStyle.Base128);

And this is how the message was serialized on the server.

Serializer.SerializeWithLengthPrefix(networkStream, baseMessage, PrefixStyle.Base128);

The NetworkStream used at the start of the connection between the client and server is stored in an object and that object is stored in a dictionary. I pick out the same NetworkStream from that object in the dictionary and use it to send serialized data to the client(from the server). But the above mentioned problem occurs. Any help?

Thanks in advance...

Body:
This error message seems to be a catch all for a variety of different errors like @isandburn and @JP Tissot have pointed out.

Another is if you Deserialize data that isn't protobuf.

var tdp = new DerivedObject("Test");
using (var ms  = new MemoryStream())
{
    JsonSerializer.Serialize(ms,tdp); //should be protobuf
    ms.Seek(0, SeekOrigin.Begin);

    var tdp2 = Serializer.Deserialize<DerivedObject>(ms);
}


问:
What is a memory-efficient method to spread then gather columns? (see example)
I'm trying to rearrange my data for downstream processing. I found a way to accomplish what I want, but it is memory-intensive and I'm sure there is a more-efficient way.

Here is an example from the data:

```<code>   X.1 Label       X
81  81    21 367.138
82  82    21 384.295
83  83    21 159.496
84  84    21 269.927
85  85    22 364.118
86  86    22 154.475
87  87    22 265.861
</code>```

I want to rearrange the data to create a table of X values for each separate object, as shown below:

```<code>    1       2       3       4
1 367.138 384.295 159.496 269.927
2 364.118 154.475 265.861      NA
</code>```

I can do this just fine using spread, apply, and ldply functions shown below:

```<code>X <- apply(tidyr::spread(X, Label,X), 2, function(x) na.omit(x))
X<-X[-1]
X<-plyr::ldply(X, rbind)
X<-as.data.frame(X[-1])
</code>```

Here's the problem, the spread function generates the following table as an intermediate step:

```<code>  X.1       1       2
1  81 367.138      NA
2  82 384.295      NA
3  83 159.496      NA
4  84 269.927      NA
5  85      NA 364.118
6  86      NA 154.475
7  87      NA 265.861
</code>```

This is fine for small data sets, but for large data sets the table generated is huge and I'm running out of memory which produces the following error:

Error: cannot allocate vector of size 8.4 Gb

I'm sure there must be a more efficient way of doing this without generating that massive intermediate table. Any ideas?

Body:
I'm trying to rearrange my data for downstream processing. I found a way to accomplish what I want, but it is memory-intensive and I'm sure there is a more-efficient way.

Here is an example from the data:

   X.1 Label       X
81  81    21 367.138
82  82    21 384.295
83  83    21 159.496
84  84    21 269.927
85  85    22 364.118
86  86    22 154.475
87  87    22 265.861

I want to rearrange the data to create a table of X values for each separate object, as shown below:

    1       2       3       4
1 367.138 384.295 159.496 269.927
2 364.118 154.475 265.861      NA

I can do this just fine using spread, apply, and ldply functions shown below:

X <- apply(tidyr::spread(X, Label,X), 2, function(x) na.omit(x))
X<-X[-1]
X<-plyr::ldply(X, rbind)
X<-as.data.frame(X[-1])

Here's the problem, the spread function generates the following table as an intermediate step:

  X.1       1       2
1  81 367.138      NA
2  82 384.295      NA
3  83 159.496      NA
4  84 269.927      NA
5  85      NA 364.118
6  86      NA 154.475
7  87      NA 265.861

This is fine for small data sets, but for large data sets the table generated is huge and I'm running out of memory which produces the following error:

Error: cannot allocate vector of size 8.4 Gb

I'm sure there must be a more efficient way of doing this without generating that massive intermediate table. Any ideas?

Body:
An option using data.table

dcast(DT, rleid(Label) ~ rowid(Label), value.var = "X")
#   Label       1       2       3       4
#1:     1 367.138 384.295 159.496 269.927
#2:     2 364.118 154.475 265.861      NA

data

library(data.table)
DT <- fread(text = "   X.1 Label       X
  81    21 367.138
  82    21 384.295
  83    21 159.496
  84    21 269.927
  85    22 364.118
  86    22 154.475
  87    22 265.861")


问:
Is there a way to "allow" a perl RegEx to ignore 1 character at a time when trying to match?
Basically, I have several files, each one with several lines of text, and I'm interested in finding a specific sequence of 7 letters and count how many time they appear per file using some basic regular expressions on Perl(v5.24.1).

So far no problem, but the "tricky" part is that if one of those seven letters doesn't match my pattern, I would like to count it as well (as long as it's just one).

Patterns I'm looking for:
'CCCAGGT', 'CCCAGTT', 'CCCAGCT', and 'CCCAGAT'.

Examples of non-matching text that I would like to count:

```<code>line1 - AGGCTCAGGAG'CCCATGT'GGGCGGACCCAT --> Count as 'CCCAGGT'
line2 - CGGCTCAGGAG'CCCGGGT'GGGCGGTCCCAT --> Count as 'CCCAGGT'
</code>```

I'm including a piece code (at the bottom) to further explain what I'm searching and what I've thought so far, but it has to be a better way of doing this.

So, do you know if it's possible to "tell" Perl that I can tolerate 1 mismatch in the sequence when using the =~ m/ operator? OR another function to use?

Thanks a lot for your help!

  if ($elements[0] =~ m/CCCAGGT/){
    $mutg = $mutg + $elements[1];
  }
  elsif ($elements[0] =~ m/CCCAGTT/){
    $mutt = $mutt + $elements[1];
  }
  elsif ($elements[0] =~ m/CCCAGAT/){
    $muta = $muta + $elements[1];
  }
  elsif ($elements[0] =~ m/CCCAGCT/){
    $mutc = $mutc + $elements[1];
  }
  else {
    if ($elements[0] =~ m/.CCAGGT/){
      $mutg = $mutg + $elements[1];
    }
    elsif ($elements[0] =~ m/.CCAGTT/){
    $mutt = $mutt + $elements[1];
    }
    elsif ($elements[0] =~ m/.CCAGAT/){
      $muta = $muta + $elements[1];
    }
    elsif ($elements[0] =~ m/.CCAGCT/){
      $mutc = $mutc + $elements[1];
    }
    else {
      [[AGAIN BUT WITH THE "." IN THE SECOND POSITION AND SO ON]]
    }
  }
```

答:
To simply check if there's a match (as opposed to finding the nearest match), we could build the patterns (.CCAGGT, C.CAGGT, etc) dynamically.

```<code>my $target_seq = "CCCAGGT";

my @parts = map quotemeta, split //, $target_seq;
my $fuzzy_pat =
   join "|",
      map { join("", @parts[0..$_-1], ".", @parts[$_+1..$#parts]) }
         0..$#parts;

my $fuzzy_re = qr/$fuzzy_pat/;
</code>```

This can be extended to check for multiple sequences at once, as long as one doesn't care which sequence is found.

```<code>use List::Util qw( uniq );

my @target_seqs = qw( CCCAGGT CCCAGTT CCCAGAT CCCAGCT );

my @fuzzy_pats;
for my $pat (@target_seqs) {
   my @parts = map quotemeta, split //, $pat;
   for my $i (0..$#parts) {
      push @fuzzy_pats, join("", @parts[0..$i-1], ".", @parts[$i+1..$#parts]);
   }
}

my $fuzzy_pat = join "|", sort uniq @fuzzy_pats;
my $fuzzy_re = qr/$fuzzy_pat/;

$mtg += $elements[1] if $elements[0] =~ $fuzzy_re;
</code>```

Body:
Basically, I have several files, each one with several lines of text, and I'm interested in finding a specific sequence of 7 letters and count how many time they appear per file using some basic regular expressions on Perl(v5.24.1).

So far no problem, but the "tricky" part is that if one of those seven letters doesn't match my pattern, I would like to count it as well (as long as it's just one).

Patterns I'm looking for:
'CCCAGGT', 'CCCAGTT', 'CCCAGCT', and 'CCCAGAT'.

Examples of non-matching text that I would like to count:

line1 - AGGCTCAGGAG'CCCATGT'GGGCGGACCCAT --> Count as 'CCCAGGT'
line2 - CGGCTCAGGAG'CCCGGGT'GGGCGGTCCCAT --> Count as 'CCCAGGT'

I'm including a piece code (at the bottom) to further explain what I'm searching and what I've thought so far, but it has to be a better way of doing this.

So, do you know if it's possible to "tell" Perl that I can tolerate 1 mismatch in the sequence when using the =~ m/ operator? OR another function to use?

Thanks a lot for your help!

  if ($elements[0] =~ m/CCCAGGT/){
    $mutg = $mutg + $elements[1];
  }
  elsif ($elements[0] =~ m/CCCAGTT/){
    $mutt = $mutt + $elements[1];
  }
  elsif ($elements[0] =~ m/CCCAGAT/){
    $muta = $muta + $elements[1];
  }
  elsif ($elements[0] =~ m/CCCAGCT/){
    $mutc = $mutc + $elements[1];
  }
  else {
    if ($elements[0] =~ m/.CCAGGT/){
      $mutg = $mutg + $elements[1];
    }
    elsif ($elements[0] =~ m/.CCAGTT/){
    $mutt = $mutt + $elements[1];
    }
    elsif ($elements[0] =~ m/.CCAGAT/){
      $muta = $muta + $elements[1];
    }
    elsif ($elements[0] =~ m/.CCAGCT/){
      $mutc = $mutc + $elements[1];
    }
    else {
      [[AGAIN BUT WITH THE "." IN THE SECOND POSITION AND SO ON]]
    }
  }

Body:
To simply check if there's a match (as opposed to finding the nearest match), we could build the patterns (.CCAGGT, C.CAGGT, etc) dynamically.

my $target_seq = "CCCAGGT";

my @parts = map quotemeta, split //, $target_seq;
my $fuzzy_pat =
   join "|",
      map { join("", @parts[0..$_-1], ".", @parts[$_+1..$#parts]) }
         0..$#parts;

my $fuzzy_re = qr/$fuzzy_pat/;

This can be extended to check for multiple sequences at once, as long as one doesn't care which sequence is found.

use List::Util qw( uniq );

my @target_seqs = qw( CCCAGGT CCCAGTT CCCAGAT CCCAGCT );

my @fuzzy_pats;
for my $pat (@target_seqs) {
   my @parts = map quotemeta, split //, $pat;
   for my $i (0..$#parts) {
      push @fuzzy_pats, join("", @parts[0..$i-1], ".", @parts[$i+1..$#parts]);
   }
}

my $fuzzy_pat = join "|", sort uniq @fuzzy_pats;
my $fuzzy_re = qr/$fuzzy_pat/;

$mtg += $elements[1] if $elements[0] =~ $fuzzy_re;


问:
How do I use php in sublimetext3?
I can't seem to use php on sublimetext3

I've tried this:

```<code>{
    "cmd": ["PHP", "$file"]
}
</code>```

Saving this under C:\Users\  \AppData\Roaming\Sublime Text 3\Packages\User

But when i try to execute this:

```<code><?php

echo"It worked"

?>
</code>```

I get this error:

```<code> [WinError 2] The system cannot find the file specified
</code>```

答:
You need to run a server. This can be done with Apache or NGINX or even IIS, or with a built-in server, but recommend xampp:

http://learningcn.com/SublimeServer/

https://www.apachefriends.org/

Title: How do I use php in sublimetext3?

Body:
I can't seem to use php on sublimetext3

I've tried this:

{
    "cmd": ["PHP", "$file"]
}

Saving this under C:\Users\  \AppData\Roaming\Sublime Text 3\Packages\User

But when i try to execute this:

<?php

echo"It worked"

?>

I get this error:

 [WinError 2] The system cannot find the file specified


问:
Laravel access name of foreign key in view
Inquries table contains client_id as a foreign key, I want to Access ist Name in my view.
The clients table has a name column.

I tried following to Show the Name in my view but it did not work.

```<code>@foreach($inquiries as $inquiryKey => $inquiryValue)
    <td>{{ $inquiryValue->client_id }}</td> // works
    <td>{{ $inquiryValue->client_id->name }}</td> // does not work
@endforeach
</code>```

Client Model

```<code>public function inquiry()
{
    return $this->hasMany(Inquiry::class);
}
</code>```

Inquiry

```<code>public function client()
{
    return $this->belongsTo(Client::class);
}
</code>```

答:
You Can Try This..

Client Model

```<code>public function inquiries()
  {
    return $this->hasMany(Inquiry::class);
  }
</code>```

Inquiry Model

```<code>public function client()
  {
     return $this->belongsTo(Client::class, 'client_id');
  }
</code>```

View

```<code>@foreach($inquiries as $inquiryKey => $inquiryValue)
  <td>{{ $inquiryValue->client_id }}</td>
  <td>{{ $inquiryValue->client->name }}</td>
@endforeach
</code>```

Body:
Inquries table contains client_id as a foreign key, I want to Access ist Name in my view.
The clients table has a name column.

I tried following to Show the Name in my view but it did not work.

@foreach($inquiries as $inquiryKey => $inquiryValue)
    {{ $inquiryValue->client_id }}	 // works
    {{ $inquiryValue->client_id->name }}	 // does not work
@endforeach

Client Model

public function inquiry()
{
    return $this->hasMany(Inquiry::class);
}

Inquiry

public function client()
{
    return $this->belongsTo(Client::class);
}

Body:
You Can Try This..

Client Model

public function inquiries()
  {
    return $this->hasMany(Inquiry::class);
  }

Inquiry Model

public function client()
  {
     return $this->belongsTo(Client::class, 'client_id');
  }

View

@foreach($inquiries as $inquiryKey => $inquiryValue)
  <td>{{ $inquiryValue->client_id }}</td>
  <td>{{ $inquiryValue->client->name }}</td>
@endforeach


问:
When to use composition and when to use inheritance
Is there a way of telling when to use composition and when to use inheritance in your code.

Example: Let's say we have 4 classes called Computer, MotherBoard, Monitor, Keyboard. I can make computer inherit from the other three classes and I can also declare  MotherBoard, Monitor, Keyboard in the field of computer, thus for the second case using composition. Which way is better? Which way is preferred by most developers?

答:
I prefer the inheritance in the following cases:

Both classes are in the same logical domain

The subclass is a proper subtype of the superclass

The superclass’s implementation is necessary or appropriate for the subclass

The enhancements made by the subclass are primarily additive.

Otherwise, the composition is appropriate.

Note that in this case, the computer is composed of the components you have listed. As a shortcut, I sometimes ask myself the following:

Does Computer have a Mouse? If so, then use composition. Notice a computer can have no mouse.

Is MacBook a Computer? If so, then use inheritance.

... but in general which way is preferred

In general, the decision should be based on the situation :)


问:
How can I turn a function used in many components into its own component which I can reuse across the app?
I have a fetch request used on multiple pages, and would like to turn it into a component to simply call in whenever it's needed. This is proving to be harder than I thought, and it's bring up a number of issues.

I have tried using the wrappedComponent function but not sure if that's the solution as it's still not working. It's now saying that the fetchPosts class constructor cannot be invoked without new.

```<code>        const that = this;
        fetch ('/testrouter')
        .then (response => {
            return response.json();
        }).then(jsonData => {
            that.setState({posts:jsonData})
        }).catch(err => {
            console.log('Error fetch posts data '+err)
        });
    }
</code>```

This is what I want to turn into a component, so that I can just call it by it's name from another one inside componentDidMount. I have tried doing this:

```<code>function fetchPosts(WrappedComponent) {
    class FetchPosts extends Component {
     constructor(props) {
         super(props)
         this.state = {
             posts: []
         }
     }

     fetchAllPosts() {
         const that = this;
        fetch ('/testrouter')
        .then (response => {
            return response.json();
        }).then(jsonData => {
            that.setState({posts:jsonData})
        }).catch(err => {
            console.log('Error fetch posts data '+err)
        });
    }
    render() {
        return (<WrappedComponent
        fetchAllPosts = {this.fetchAllPosts})
        />);
    }

}
    return FetchPosts;

}

export default fetchPosts
</code>```

Then importing it and calling it with fetchPosts but it's not working.

I was hoping I would be able to create a component, add the code then import the component, but this is not working.

答:
You might want to create a custom hook to do this:

useFetch.jsx

```<code>import React, { useState, useEffect } from 'react'

const useFetch = (url) =>
  const [state, setState] = useState({ loading: true, data: null, error: null })

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(data => setState(state => ({ ...state, loading: false, data }))
      .catch(error => setState(state => ({ ...state, loading: false, error }))
  },[])

  return state
}

export default useFetch
</code>```

MyComponent.jsx

```<code>import React from 'react'
import useFetch from './useFetch.jsx'

const MyComponent = () => {
  const data = useFetch('/testrouter')

  return (<>
    { data.loading && "Loading..." }
    { data.error && `There was an error during the fetch: {error.message}` }
    { data.data && <Posts posts={data.data}/> }
  </>)
}
</code>```

Body:
I have a fetch request used on multiple pages, and would like to turn it into a component to simply call in whenever it's needed. This is proving to be harder than I thought, and it's bring up a number of issues.

I have tried using the wrappedComponent function but not sure if that's the solution as it's still not working. It's now saying that the fetchPosts class constructor cannot be invoked without new.

        const that = this;
        fetch ('/testrouter')
        .then (response => {
            return response.json();
        }).then(jsonData => {
            that.setState({posts:jsonData})
        }).catch(err => {
            console.log('Error fetch posts data '+err)
        });
    }

This is what I want to turn into a component, so that I can just call it by it's name from another one inside componentDidMount. I have tried doing this:

function fetchPosts(WrappedComponent) {
    class FetchPosts extends Component {
     constructor(props) {
         super(props)
         this.state = {
             posts: []
         }
     }

     fetchAllPosts() {
         const that = this;
        fetch ('/testrouter')
        .then (response => {
            return response.json();
        }).then(jsonData => {
            that.setState({posts:jsonData})
        }).catch(err => {
            console.log('Error fetch posts data '+err)
        });
    }
    render() {
        return (<WrappedComponent
        fetchAllPosts = {this.fetchAllPosts})
        />);
    }

}
    return FetchPosts;

}

export default fetchPosts

Then importing it and calling it with fetchPosts but it's not working.

I was hoping I would be able to create a component, add the code then import the component, but this is not working.

Body:
You might want to create a custom hook to do this:

useFetch.jsx

import React, { useState, useEffect } from 'react'

const useFetch = (url) =>
  const [state, setState] = useState({ loading: true, data: null, error: null })

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(data => setState(state => ({ ...state, loading: false, data }))
      .catch(error => setState(state => ({ ...state, loading: false, error }))
  },[])

  return state
}

export default useFetch

MyComponent.jsx

import React from 'react'
import useFetch from './useFetch.jsx'

const MyComponent = () => {
  const data = useFetch('/testrouter')

  return (<>
    { data.loading && "Loading..." }
    { data.error && `There was an error during the fetch: {error.message}` }
    { data.data && <Posts posts={data.data}/> }
  </>)
}