问:
With printing Entry´s text, last character is dismissed. How to fix?
I want to print the text of an Entry each time a new character is written.
By doing this with binding  and a command to the widget the last character isn't printed.

I guess that the parameter 'textvariable' is getting updated after binding command had been executed. How to fix this?

```<code>from tkinter import *
master = Tk()
var = StringVar()

def execute_e(key):
    print(var.get())

E = Entry(master, width=30, textvariable=var)
E.pack()
E.bind('<Key>', execute_e)
</code>```

答:
It's because the bound event function is being executed before the new key has been added.

Here's a simple workaround that uses the ability to add validation to an Entry widget (the validator accepts any key because it always returns True). The trick is that validator function is set-up to receive the value that the text will have if the change is allowed by specifying the %P when it's configuration as part of the Entry construction via the validatecommand=(validator_command, '%P').

Here's some documentation about adding validation to Entry widgets with details about how it works.

```<code>from tkinter import *

master = Tk()
var = StringVar()

def validator(new_value):
    print(f'new_value: {new_value}')
    return True

validator_command = master.register(validator)

E = Entry(master, width=30, textvariable=var,
          validate='key',
          validatecommand=(validator_command, '%P'))
E.pack()

master.mainloop()
</code>```

Body:
I want to print the text of an Entry each time a new character is written.
By doing this with binding  and a command to the widget the last character isn't printed.

I guess that the parameter 'textvariable' is getting updated after binding command had been executed. How to fix this?

from tkinter import *
master = Tk()
var = StringVar()

def execute_e(key):
    print(var.get())

E = Entry(master, width=30, textvariable=var)
E.pack()
E.bind('<Key>', execute_e)

Body:
It's because the bound event function is being executed before the new key has been added.

Here's a simple workaround that uses the ability to add validation to an Entry widget (the validator accepts any key because it always returns True). The trick is that validator function is set-up to receive the value that the text will have if the change is allowed by specifying the %P when it's configuration as part of the Entry construction via the validatecommand=(validator_command, '%P').

Here's some documentation about adding validation to Entry widgets with details about how it works.

from tkinter import *

master = Tk()
var = StringVar()

def validator(new_value):
    print(f'new_value: {new_value}')
    return True

validator_command = master.register(validator)

E = Entry(master, width=30, textvariable=var,
          validate='key',
          validatecommand=(validator_command, '%P'))
E.pack()

master.mainloop()


来源: stackexchange

问:
Can't get SWF file to run. Get's stuck at please "Right click click to run adobe flash player"
I'm writing an application with NWJS and I'm trying to get pepperflash to work with it. When I try to open an swf file, I get a message that I can't address that says "Right click to run adobe flash player"

I think I have installed pepperflash correctly as this dialog is showing up, but I can't seem to get the swf to run. I have tried adding this block         of code to my javascript:

```<code> chrome.contentSettings.plugins.set({
 primaryPattern: "<all_urls>",
 resourceIdentifier: { id: "adobe-flash-player" },
 setting: "allow"
 });
</code>```

Here's my js code:

```<code>    var win = nw.Window.get();
    win.width = 1000;
    win.height = 800;

    chrome.contentSettings.plugins.set({
    primaryPattern: "<all_urls>",
    resourceIdentifier: { id: "adobe-flash-player" },
    setting: "allow"
    });

    nw.Window.open('fishy.swf', {}, function(new_win) {});
</code>```

答: Nevermind! I was missing a file or two from the flash plugin. Everything works now.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm writing an application with NWJS and I'm trying to get pepperflash to work with it. When I try to open an swf file, I get a message that I can't address that says "Right click to run adobe flash player"

I think I have installed pepperflash correctly as this dialog is showing up, but I can't seem to get the swf to run. I have tried adding this block         of code to my javascript:

 chrome.contentSettings.plugins.set({
 primaryPattern: "<all_urls>",
 resourceIdentifier: { id: "adobe-flash-player" },
 setting: "allow"
 });

Here's my js code:

    var win = nw.Window.get();
    win.width = 1000;
    win.height = 800;

    chrome.contentSettings.plugins.set({
    primaryPattern: "<all_urls>",
    resourceIdentifier: { id: "adobe-flash-player" },
    setting: "allow"
    });

    nw.Window.open('fishy.swf', {}, function(new_win) {});


问:
How to collapse pandas rows for select column values to minimal combinations and map back to original rows
Context:

I have a pandas dataframe with 7 columns (taste, color, temperature, texture, shape, age_of_participant, name_of_participant).

Of the 7 columns, taste, color, temperature, texture and shape can have overlapping values across multiple rows (i.e taste could be sour for more than one row)

I'm trying to collapse all the rows into the lowest number of combinations given
 taste,color,temperature,texture and shape values while ignoring NA's ( in other words, overwriting them). The next part is to map each of these rows to the original rows.

Mock data set:

data_set = [
   {'color':'brown', 'age_of_participant':23, 'name_of_participant':'feb'},
   {'taste': 'sour', 'color':'green', 'temperature': 'hot', 'age_of_participant':16,'name_of_participant': 'joe'},
   {'taste': 'sour', 'color':'green', 'texture':'soft', 'age_of_participant':17,'name_of_participant': 'jane'},
   {'color':'green','age_of_participant':18,'name_of_participant': 'jeff'},
   {'taste': 'sweet', 'color':'red', 'age_of_participant':19,'name_of_participant': 'joke'},
   {'taste': 'sweet', 'temperature': 'cold',  'age_of_participant':20,'name_of_participant': 'jolly'},
   {'taste': 'salty', 'color':'purple', 'texture':'soft', 'age_of_participant':21,'name_of_participant': 'jupyter'},
   {'taste': 'salty', 'color':'brown', 'age_of_participant':22,'name_of_participant': 'january'}

]

import pandas as pd
import random

data_set = random.sample(data_set, k=len(data_set))

data_frame = pd.DataFrame(data_set)

print(data_frame)

   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot     NaN
1                  17   green                jane   sour         NaN    soft
2                  18   green                jeff    NaN         NaN     NaN
3                  19     red                joke  sweet         NaN     NaN
4                  20     NaN               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

```

<p><strong>What I've attempted:</strong></p>

<pre class="lang-py prettyprint-override"><code>
# These columns are used to do the grouping since age_of_participant and name_of_participant are unique per row

values_that_can_be_grouped = ['taste', 'color','temperature','texture']

sub_set = data_frame[values_that_can_be_grouped].drop_duplicates().reset_index(drop=False)

my_unique_set = sub_set.groupby('taste', as_index=False).first()

print(my_unique_set)

   taste  index  color temperature texture
0             2  green
1  salty      6  brown
2   sour      1  green                soft
3  sweet      4               cold

</code>```

At this point I'm not quite sure how I can map the rows above to all original rows except for indices 2,6,1,4. I checked pandas code and doesn't look like the other indices are preserved anywhere?

What I'm trying to achieve:

```<code>
   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot    soft
1                  17   green                jane   sour         hot    soft
2                  18   green                jeff   sour         hot    soft
3                  19     red                joke  sweet        cold     NaN
4                  20     red               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

</code>```

答:
IIUC I feel using ffill and bfill for each taste and color, then groupby them is safer here

```<code>df.taste.fillna(df.groupby('color').taste.apply(lambda x : x.ffill().bfill()),inplace=True)
df.color.fillna(df.groupby('taste').color.apply(lambda x : x.ffill().bfill()),inplace=True)
df=df.groupby(['color','taste']).apply(lambda x : x.ffill().bfill())
df
   age_of_participant   color   ...   temperature texture
0                  16   green   ...           hot    soft
1                  17   green   ...           hot    soft
2                  18   green   ...           hot    soft
3                  19     red   ...          cold     NaN
4                  20     red   ...          cold     NaN
5                  21  purple   ...           NaN    soft
6                  22   brown   ...           NaN     NaN
[7 rows x 6 columns]
</code>```

Body:
Context:

I have a pandas dataframe with 7 columns (taste, color, temperature, texture, shape, age_of_participant, name_of_participant).

Of the 7 columns, taste, color, temperature, texture and shape can have overlapping values across multiple rows (i.e taste could be sour for more than one row)

I'm trying to collapse all the rows into the lowest number of combinations given
 taste,color,temperature,texture and shape values while ignoring NA's ( in other words, overwriting them). The next part is to map each of these rows to the original rows.

Mock data set:

data_set = [
   {'color':'brown', 'age_of_participant':23, 'name_of_participant':'feb'},
   {'taste': 'sour', 'color':'green', 'temperature': 'hot', 'age_of_participant':16,'name_of_participant': 'joe'},
   {'taste': 'sour', 'color':'green', 'texture':'soft', 'age_of_participant':17,'name_of_participant': 'jane'},
   {'color':'green','age_of_participant':18,'name_of_participant': 'jeff'},
   {'taste': 'sweet', 'color':'red', 'age_of_participant':19,'name_of_participant': 'joke'},
   {'taste': 'sweet', 'temperature': 'cold',  'age_of_participant':20,'name_of_participant': 'jolly'},
   {'taste': 'salty', 'color':'purple', 'texture':'soft', 'age_of_participant':21,'name_of_participant': 'jupyter'},
   {'taste': 'salty', 'color':'brown', 'age_of_participant':22,'name_of_participant': 'january'}

]

import pandas as pd
import random

data_set = random.sample(data_set, k=len(data_set))

data_frame = pd.DataFrame(data_set)

print(data_frame)

   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot     NaN
1                  17   green                jane   sour         NaN    soft
2                  18   green                jeff    NaN         NaN     NaN
3                  19     red                joke  sweet         NaN     NaN
4                  20     NaN               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

What I've attempted:

# These columns are used to do the grouping since age_of_participant and name_of_participant are unique per row

values_that_can_be_grouped = ['taste', 'color','temperature','texture']

sub_set = data_frame[values_that_can_be_grouped].drop_duplicates().reset_index(drop=False)

my_unique_set = sub_set.groupby('taste', as_index=False).first()

print(my_unique_set)

   taste  index  color temperature texture
0             2  green
1  salty      6  brown
2   sour      1  green                soft
3  sweet      4               cold

At this point I'm not quite sure how I can map the rows above to all original rows except for indices 2,6,1,4. I checked pandas code and doesn't look like the other indices are preserved anywhere?

What I'm trying to achieve:

   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot    soft
1                  17   green                jane   sour         hot    soft
2                  18   green                jeff   sour         hot    soft
3                  19     red                joke  sweet        cold     NaN
4                  20     red               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

Body:
IIUC I feel using ffill and bfill for each taste and color, then groupby them is safer here

df.taste.fillna(df.groupby('color').taste.apply(lambda x : x.ffill().bfill()),inplace=True)
df.color.fillna(df.groupby('taste').color.apply(lambda x : x.ffill().bfill()),inplace=True)
df=df.groupby(['color','taste']).apply(lambda x : x.ffill().bfill())
df
   age_of_participant   color   ...   temperature texture
0                  16   green   ...           hot    soft
1                  17   green   ...           hot    soft
2                  18   green   ...           hot    soft
3                  19     red   ...          cold     NaN
4                  20     red   ...          cold     NaN
5                  21  purple   ...           NaN    soft
6                  22   brown   ...           NaN     NaN
[7 rows x 6 columns]


问:
Selecting rows, where sum of individual rows are equal to the
I have below dataframe. I want to extract the rows where the individual 'ItemTotal' of each 'InvoiceNo' is equal to the 'InvoiceTotal'.
Data

The source data

in this example. I should be able to extract the Invoice Nos 1 & 3. coz, it's individual Item totals are equal to the Invoice total.

I tried the below code. but it doesn't work.

```<code>import pandas as pd
import numpy as np

np.where(df.groupby('InvoiceNo')['ItemTotal'].sum() == df['InvoiceTotal'])
</code>```

答:
You can do with transform

```<code>np.where(df.groupby('InvoiceNo')['ItemTotal'].transform('sum') == df['InvoiceNo'])
</code>```

Body:
I have below dataframe. I want to extract the rows where the individual 'ItemTotal' of each 'InvoiceNo' is equal to the 'InvoiceTotal'.
Data

The source data

in this example. I should be able to extract the Invoice Nos 1 & 3. coz, it's individual Item totals are equal to the Invoice total.

I tried the below code. but it doesn't work.

import pandas as pd
import numpy as np

np.where(df.groupby('InvoiceNo')['ItemTotal'].sum() == df['InvoiceTotal'])

Body:
You can do with transform

np.where(df.groupby('InvoiceNo')['ItemTotal'].transform('sum') == df['InvoiceNo'])


问:
How can I set an entire NGRX store and then trigger all reducers?
How can I?

Get entire NGRX store data

Set entire NGRX store data

Trigger all reducers

Background:

I have an angular application that has many components tightly coupled to an NGRX store.

I've reused these components for a flattened print layout of some of the information in the application. I use headless chrome to print the application to a pdf. Since the headless chrome is a different user-agent than the print-user's browser there is no data.

I initially solved this problem by posting over some of the NGRX store and having the headless chrome replace it in the store. However as the print view has expanded the amount of data needed from the store has grown to be unmanageable.

I would like to take the entire store data, then reinsert it into the other user-agent store, then trigger all reducers to ensure components update.

I already know how to get all of the store data. I could use some help on putting it back into the store. What I need most is how to trigger all reducers without writing hundreds of dispatch statements.

答:
Something like this will do it:

Get entire NGRX store:

```<code>let storeData$ = store.select(rootReducers.getRootState);
let subscription = storeData$.subscribe(everything => {
    let json = JSON.stringify(everything);
    //do what you want with all of your data here
});
</code>```

Set entire NGRX store: (my top level reducer interface looks like this)

```<code>export interface State {
    something: topLevelReducers1.State;
    anything: topLevelReducers2.State;
    moreThings: topLevelReducers3.State;
}
</code>```

This makes it necessary to set each of these top level fields:

```<code>// here is the method //
export const dispatchSetRootState = (store:Store<State>, payload: State): void => {
    store.dispatch(new SetSomethingState(payload.something));
    store.dispatch(new SetAnythingAction(payload.anything));
    store.dispatch(new SetMoreThingsAction(payload.moreThings));
};

// here is the usage //
let everything = JSON.parse(json);
dispatchSetRootState(store, data);

// since I have a lot of combineReducers I add a short-circuit//
export function reducers(state: any, action: any): any {
    if(action.type == SomethingActionTypes.SET_SOMETHING_PROFILE) { // Sets entire object
        return Object.assign({}, state, (<PayloadAction>action).payload);
    }
    else return combinedReducers(state, action);
}
</code>```

Is not necessary because setting as in #2 triggers all actions

Body:
Something like this will do it:

Get entire NGRX store:

let storeData$ = store.select(rootReducers.getRootState);
let subscription = storeData$.subscribe(everything => {
    let json = JSON.stringify(everything);
    //do what you want with all of your data here
});

Set entire NGRX store: (my top level reducer interface looks like this)

export interface State {
    something: topLevelReducers1.State;
    anything: topLevelReducers2.State;
    moreThings: topLevelReducers3.State;
}

This makes it necessary to set each of these top level fields:

// here is the method //
export const dispatchSetRootState = (store:Store<State>, payload: State): void => {
    store.dispatch(new SetSomethingState(payload.something));
    store.dispatch(new SetAnythingAction(payload.anything));
    store.dispatch(new SetMoreThingsAction(payload.moreThings));
};

// here is the usage //
let everything = JSON.parse(json);
dispatchSetRootState(store, data);

// since I have a lot of combineReducers I add a short-circuit//
export function reducers(state: any, action: any): any {
    if(action.type == SomethingActionTypes.SET_SOMETHING_PROFILE) { // Sets entire object
        return Object.assign({}, state, (<PayloadAction>action).payload);
    }
    else return combinedReducers(state, action);
}

Is not necessary because setting as in #2 triggers all actions


问:
Newton Raphsons method in Matlab?
Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don't get if I can pass a function to a function and how to use the derivative as a function.

```<code>newtonRaphson[f_, n_, guess_] :=
 If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] :=
 If[n == 0, guess,
  newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]
</code>```

It doesn't seem like you can derive neither function-handles nor functions defined in a file but I might be wrong.

答:
You could use an implementation like this:

```<code>function x = newton(f,dfdx,x0,tolerance)
err = Inf;
x = x0;
while abs(err) > tolerance
   xPrev = x;
   x = xPrev - f(xPrev)./dfdx(xPrev);
   % stop criterion: (f(x) - 0) < tolerance
   err = f(x); %
   % stop criterion: change of x < tolerance
   % err = x - xPrev;
end
</code>```

And pass it function handles of both the function and its derivative. This derivative is possible to acquire by some different methods: manual differentiation, symbolic differentiation or automatic differentiation. You can also perform the differentiation numerically, but this is both slow and requires you to use a modified implementation. So I will assume you have calculated the derivative in any suitable way. Then you can call the code:

```<code>f = @(x)((x-4).^2-4);
dfdx = @(x)(2.*(x-4));
x0 = 1;
xRoot = newton(@f,@dfdx,x0,1e-10);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Newton Raphsons method in Matlab?

Body:
Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don't get if I can pass a function to a function and how to use the derivative as a function.

newtonRaphson[f_, n_, guess_] :=
 If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] :=
 If[n == 0, guess,
  newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]

It doesn't seem like you can derive neither function-handles nor functions defined in a file but I might be wrong.

Body:
You could use an implementation like this:

function x = newton(f,dfdx,x0,tolerance)
err = Inf;
x = x0;
while abs(err) > tolerance
   xPrev = x;
   x = xPrev - f(xPrev)./dfdx(xPrev);
   % stop criterion: (f(x) - 0) < tolerance
   err = f(x); %
   % stop criterion: change of x < tolerance
   % err = x - xPrev;
end

And pass it function handles of both the function and its derivative. This derivative is possible to acquire by some different methods: manual differentiation, symbolic differentiation or automatic differentiation. You can also perform the differentiation numerically, but this is both slow and requires you to use a modified implementation. So I will assume you have calculated the derivative in any suitable way. Then you can call the code:

f = @(x)((x-4).^2-4);
dfdx = @(x)(2.*(x-4));
x0 = 1;
xRoot = newton(@f,@dfdx,x0,1e-10);


问:
How to select value from a python dictionary with multi items
I'm trying to get values from a python dictionary. As you can see below I have this example. I would like to get only keys which start with "BTC_" and select it if its "BTC" Value is greater than 100.

```<code>d = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}
</code>```

The expected result is the following list:

```<code>['BTC_LTC', 'BTC_TRX']
</code>```

Because of their key start with "BTC_" and their 'BTC' value is greater than 100.

Body:
I'm trying to get values from a python dictionary. As you can see below I have this example. I would like to get only keys which start with "BTC_" and select it if its "BTC" Value is greater than 100.

d = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}

The expected result is the following list:

['BTC_LTC', 'BTC_TRX']

Because of their key start with "BTC_" and their 'BTC' value is greater than 100.

Body:
dic = {
  BTC_LTC:  { BTC: '138.13504038', LTC: '4662.34229096' },
  BTC_MAID: { BTC: '10.38010322', MAID: '359919.71515255' },
  BTC_NEM: { BTC: '30.34435435', NEM: '34435345' },
  BTC_TRX: { BTC: '101.1122', TRX: '4546456456.343543543' },
  USDC_BTC: { USDC: '481389.13175764', BTC: '74.73988488' },
  USDC_ETH: { USDC: '72302.27016210', ETH: '357.72884034' },
  totalBTC: '2340.96441558',
  totalETH: '2771.63218462',
  totalUSDC: '681255.56961992',
  totalXMR: '267.83601213'
}

res = []
for i in dic:
    if isinstance(i,dict):
        if i['BTC']>100:
            res.append(i)

print(res)


问:
CSV file - RStudio does not recognize values in the columns [pcr package used]
I work on the data from qPCR experiment. The dataset I want to use was produced in Excel - table of 2 columns, 90 rows, all values are numeric (decimal place - period). The file was saved as CSV and opened in RStudio as such. For my work, I use pcr package (tidyverse and dplyr also loaded in).
However, upon using one of the commands in this package, I get an error.

Checked the length of the columns, one is shown as 2 (it should not be, as there are 10 variables, each of them is repeated 9 times). The other one is not recognized

> View(MIR393a_R)
> group_var <- rep(c("Col-0 B", "Col-0 A", "Kyoto B", "Kyoto A", "Kb-0 B", "Kb-0 A", "Db-1 B", "Db-1 A", "Durh-1 B", "Durh-1 A"), each = 9)
> pcr_analyze(MIR393a_R, group_var = group_var, reference_gene ='Reference', reference_group = 'MIR393a', method = 'delta_delta_ct', plot = FALSE)
```

<p>What should be there:
Calculated values and errors of double delta (plot is optional if plot = TRUE)
What I obtained:</p>

```Error: Column `MIR393a` must be length 10 (the number of rows) or one, not 0
In addition: Warning messages:
1: In mean.default(x) : argument is not numeric or logical: returning NA
2: In mean.default(x) : argument is not numeric or logical: returning NA
3: In mean.default(x) : argument is not numeric or logical: returning NA
4: In mean.default(x) : argument is not numeric or logical: returning NA
5: In mean.default(x) : argument is not numeric or logical: returning NA
6: In mean.default(x) : argument is not numeric or logical: returning NA
7: In mean.default(x) : argument is not numeric or logical: returning NA
8: In mean.default(x) : argument is not numeric or logical: returning NA
9: In mean.default(x) : argument is not numeric or logical: returning NA
10: In mean.default(x) : argument is not numeric or logical: returning NA
```

答:
Okay, it seems I have finally figured it out oon my own.

For reference_group in pcr_analyze, a group from previously defined group_var should be selected, not the entire column.

```<code>pcr_analyze(MIR, group_var = gvar, reference_gene = 'Reference', reference_group ='Col-0 B', method = 'delta_delta_ct')
</code>```

where MIR - is the data frame, gvar <- rep(c('name1', 'name2',...), each = 9), reference_gene = 'Ref' (previously assigned as Ref <- MIR$ReferenceGene), reference_group = 'name1', for example

The correct formula gave the output

```<code>   group    gene    normalized calibrated relative_expression error  lower upper
   <chr>    <chr>        <dbl>      <dbl>               <dbl> <dbl>  <dbl> <dbl>
 1 Col-0 A  MIR393a      11.3      4.44                0.0461 1.53  0.0160 0.133
 2 Col-0 B  MIR393a       6.90     0                   1      0.775 0.584  1.71
 3 Db-1 A   MIR393a       8.84     1.94                0.260  1.85  0.0723 0.936
 4 Db-1 B   MIR393a       8.34     1.45                0.366  1.33  0.146  0.922
 5 Durh-1 A MIR393a       7.72     0.826               0.564  2.89  0.0758 4.19
 6 Durh-1 B MIR393a       6.96     0.0601              0.959  1.40  0.363  2.54
 7 Kb-0 A   MIR393a      11.3      4.42                0.0467 1.69  0.0145 0.151
 8 Kb-0 B   MIR393a       8.00     1.11                0.465  2.20  0.101  2.13
 9 Kyoto A  MIR393a       9.70     2.80                0.143  1.64  0.0459 0.448
10 Kyoto B  MIR393a       9.74     2.84                0.140  1.58  0.0469 0.416
</code>```

Case is solved :)

Body:
I work on the data from qPCR experiment. The dataset I want to use was produced in Excel - table of 2 columns, 90 rows, all values are numeric (decimal place - period). The file was saved as CSV and opened in RStudio as such. For my work, I use pcr package (tidyverse and dplyr also loaded in).
However, upon using one of the commands in this package, I get an error.

Checked the length of the columns, one is shown as 2 (it should not be, as there are 10 variables, each of them is repeated 9 times). The other one is not recognized

> View(MIR393a_R)
> group_var <- rep(c("Col-0 B", "Col-0 A", "Kyoto B", "Kyoto A", "Kb-0 B", "Kb-0 A", "Db-1 B", "Db-1 A", "Durh-1 B", "Durh-1 A"), each = 9)
> pcr_analyze(MIR393a_R, group_var = group_var, reference_gene ='Reference', reference_group = 'MIR393a', method = 'delta_delta_ct', plot = FALSE)

What should be there:
Calculated values and errors of double delta (plot is optional if plot = TRUE)
What I obtained:

Error: Column `MIR393a` must be length 10 (the number of rows) or one, not 0
In addition: Warning messages:
1: In mean.default(x) : argument is not numeric or logical: returning NA
2: In mean.default(x) : argument is not numeric or logical: returning NA
3: In mean.default(x) : argument is not numeric or logical: returning NA
4: In mean.default(x) : argument is not numeric or logical: returning NA
5: In mean.default(x) : argument is not numeric or logical: returning NA
6: In mean.default(x) : argument is not numeric or logical: returning NA
7: In mean.default(x) : argument is not numeric or logical: returning NA
8: In mean.default(x) : argument is not numeric or logical: returning NA
9: In mean.default(x) : argument is not numeric or logical: returning NA
10: In mean.default(x) : argument is not numeric or logical: returning NA

Body:
Okay, it seems I have finally figured it out oon my own.

For reference_group in pcr_analyze, a group from previously defined group_var should be selected, not the entire column.

pcr_analyze(MIR, group_var = gvar, reference_gene = 'Reference', reference_group ='Col-0 B', method = 'delta_delta_ct')

where MIR - is the data frame, gvar <- rep(c('name1', 'name2',...), each = 9), reference_gene = 'Ref' (previously assigned as Ref <- MIR$ReferenceGene), reference_group = 'name1', for example

The correct formula gave the output

   group    gene    normalized calibrated relative_expression error  lower upper
   <chr>    <chr>        <dbl>      <dbl>               <dbl> <dbl>  <dbl> <dbl>
 1 Col-0 A  MIR393a      11.3      4.44                0.0461 1.53  0.0160 0.133
 2 Col-0 B  MIR393a       6.90     0                   1      0.775 0.584  1.71
 3 Db-1 A   MIR393a       8.84     1.94                0.260  1.85  0.0723 0.936
 4 Db-1 B   MIR393a       8.34     1.45                0.366  1.33  0.146  0.922
 5 Durh-1 A MIR393a       7.72     0.826               0.564  2.89  0.0758 4.19
 6 Durh-1 B MIR393a       6.96     0.0601              0.959  1.40  0.363  2.54
 7 Kb-0 A   MIR393a      11.3      4.42                0.0467 1.69  0.0145 0.151
 8 Kb-0 B   MIR393a       8.00     1.11                0.465  2.20  0.101  2.13
 9 Kyoto A  MIR393a       9.70     2.80                0.143  1.64  0.0459 0.448
10 Kyoto B  MIR393a       9.74     2.84                0.140  1.58  0.0469 0.416

Case is solved :)


问:
How do I retrieve a value in the IMemoryCache by the key provided on the API call
I have been playing around with the .Net Core Web API and have been trying to get the key and value that I have stored in cache. I store it in cache using the following statement:

```<code>if (!cache.TryGetValue<string>(store.id, out string failureString))
        {
            _cache.Set<string>(store.id, store.name);
        }
return CreatedAtAction("Get", new { store.id, store.name });
</code>```

With the JSON:

```<code>{
"id":1,
"name":"Tesco"
}
</code>```

But I am unsure what I need to put in the below method in order to return the id and value depending on what parameter is used on the api call?

```<code>[HttpGet("{id}")]
public IActionResult Get(int id)
    {

    }
</code>```

Is this at all possible?

Thanks in advance.

答:
I managed to get it to work with the following:</p>

```<code> [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        return Ok(_cache.Get(id));
    }
</code>```

Body:
I have been playing around with the .Net Core Web API and have been trying to get the key and value that I have stored in cache. I store it in cache using the following statement:

if (!cache.TryGetValue<string>(store.id, out string failureString))
        {
            _cache.Set<string>(store.id, store.name);
        }
return CreatedAtAction("Get", new { store.id, store.name });

With the JSON:

{
"id":1,
"name":"Tesco"
}

But I am unsure what I need to put in the below method in order to return the id and value depending on what parameter is used on the api call?

[HttpGet("{id}")]
public IActionResult Get(int id)
    {

    }

Is this at all possible?

Thanks in advance.

Body:
I managed to get it to work with the following:

 [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        return Ok(_cache.Get(id));
    }


问:
How to find documents with child collection containing only certain value
I have a following JSON structure:

```<code>    {
        "id": "5cea8bde0c80ee2af9590e7b",
        "name": "Sofitel",
        "pricePerNight": 88,
        "address": {
            "city": "Rome",
            "country": "Italy"
        },
        "reviews": [
            {
                "userName": "John",
                "rating": 10,
                "approved": true
            },
            {
                "userName": "Marry",
                "rating": 7,
                "approved": true
            }
        ]
    }
</code>```

I want to find a list of similar documents where ALL ratings values of a review meet a certain criteria eg. less than 8. The document above wouldn't qualify as on of the review has rating 10.

with Querydsl in the following form I still obtain that documnt

```<code>BooleanExpression filterByRating = qHotel.reviews.any().rating.lt(8);

</code>```

答:
You can use $filter and $match to filter out the transactions that you don't need. Following query should do it:

Note: The cond in the $filter is the opposite of your criteria. Since you need ratings less than 8, in this case you gonna need ratings greater than or equals 8

```<code>db.qHotel.aggregate([
{
    $addFields: {
        tempReviews: {
            $filter: {
                input: "$reviews",
                as: "review",
                cond: { $gte: [ "$$review.rating", 8 ] } // Opposite of < 8, which is >= 8
            }
        }
    }
},
{
    $match : {
        tempReviews : [] // This will exclude the documents for which there is at least one review with review.rating >= 8
    }
}
]);
</code>```

The result in the end will contain empty field named tempReviews, you can just use $project to remove it.

EDIT:

Check the example here.

Body:
I have a following JSON structure:

    {
        "id": "5cea8bde0c80ee2af9590e7b",
        "name": "Sofitel",
        "pricePerNight": 88,
        "address": {
            "city": "Rome",
            "country": "Italy"
        },
        "reviews": [
            {
                "userName": "John",
                "rating": 10,
                "approved": true
            },
            {
                "userName": "Marry",
                "rating": 7,
                "approved": true
            }
        ]
    }

I want to find a list of similar documents where ALL ratings values of a review meet a certain criteria eg. less than 8. The document above wouldn't qualify as on of the review has rating 10.

with Querydsl in the following form I still obtain that documnt

BooleanExpression filterByRating = qHotel.reviews.any().rating.lt(8);

Body:
You can use $filter and $match to filter out the transactions that you don't need. Following query should do it:

Note: The cond in the $filter is the opposite of your criteria. Since you need ratings less than 8, in this case you gonna need ratings greater than or equals 8

db.qHotel.aggregate([
{
    $addFields: {
        tempReviews: {
            $filter: {
                input: "$reviews",
                as: "review",
                cond: { $gte: [ "$$review.rating", 8 ] } // Opposite of < 8, which is >= 8
            }
        }
    }
},
{
    $match : {
        tempReviews : [] // This will exclude the documents for which there is at least one review with review.rating >= 8
    }
}
]);

The result in the end will contain empty field named tempReviews, you can just use $project to remove it.

EDIT:

Check the example here.


问:
How can I restructure this dataframe?
I'm trying to get data from a sqlite query into a format for pygal.

I need to get from something like this -

```<code>count(id)  pdate         station
1          2019-05-19    Gem 106
1          2019-05-14    Absolute Radio
2          2019-04-26    Gem 106
2          2019-05-01    Gem 106
2          2019-04-27    Gem 106
1          2019-05-17    Absolute Radio
1          2019-05-05    Gem 106
3          2019-05-12    Kiss
</code>```

to something like this -

```<code>pdate       Gem 106   Absolute Radio    Kiss
2019-05-19  3         0                 5
2019-05-20  6         6                 5
</code>```

I don't think pivots are the answer but don't understand stack / unstack well enough - could do with a pointer or two?

Many thanks

答:
IIUC, this is a case for pivot_table and your output doesn't reflect the sample data:

```<code># toy data
np.random.seed(1)
df = pd.DataFrame({
    'pdate': np.random.choice(['2019-05-19', '2019-05-20'], 30),
    'station': np.random.choice(['Gem 106', 'Absolute Radio', 'Kiss'], 30)
})

# pivot_table
df.pivot_table(index='pdate', columns='station', aggfunc='size')
</code>```

Output:

```<code>station     Absolute Radio  Gem 106     Kiss
pdate
2019-05-19  10              4           2
2019-05-20  4               5           5
</code>```

Title: How can I restructure this dataframe?

Body:
I'm trying to get data from a sqlite query into a format for pygal.

I need to get from something like this -

count(id)  pdate         station
1          2019-05-19    Gem 106
1          2019-05-14    Absolute Radio
2          2019-04-26    Gem 106
2          2019-05-01    Gem 106
2          2019-04-27    Gem 106
1          2019-05-17    Absolute Radio
1          2019-05-05    Gem 106
3          2019-05-12    Kiss

to something like this -

pdate       Gem 106   Absolute Radio    Kiss
2019-05-19  3         0                 5
2019-05-20  6         6                 5

I don't think pivots are the answer but don't understand stack / unstack well enough - could do with a pointer or two?

Many thanks

Body:
IIUC, this is a case for pivot_table and your output doesn't reflect the sample data:

# toy data
np.random.seed(1)
df = pd.DataFrame({
    'pdate': np.random.choice(['2019-05-19', '2019-05-20'], 30),
    'station': np.random.choice(['Gem 106', 'Absolute Radio', 'Kiss'], 30)
})

# pivot_table
df.pivot_table(index='pdate', columns='station', aggfunc='size')

Output:

station     Absolute Radio  Gem 106     Kiss
pdate
2019-05-19  10              4           2
2019-05-20  4               5           5


问:
For loop to filter by lat every 5 decimal places
I need to write a for loop to use the dplyr::filter() function to filter latitude every 5 points, and then average the trait for each 5 degree bin.

I would like to do this for in 5 degree lat bins continuously from -180 to 180 and then o

The data frame is organized with 2 columns: lat and trait

so for instance:

```<code>lat             trait
-0.830361   0.113935
-0.795028   0.113935
-0.729722   0.113935
-0.729722   0.113935
8.021833    0.113935
5.473333    0.113935
5.436333    0.113935
7.366667    0.113935
</code>```

I would like each trait to be average over the bin and then output into a df.

```<code>data.df %>%
  dplyr::filter(lat >= -180 & lat <= -175, .preserve= T)
</code>```

The end output will be a data frame with one column containing all the bins, and the second column containing the averages

Body:
I need to write a for loop to use the dplyr::filter() function to filter latitude every 5 points, and then average the trait for each 5 degree bin.

I would like to do this for in 5 degree lat bins continuously from -180 to 180 and then o

The data frame is organized with 2 columns: lat and trait

so for instance:

lat             trait
-0.830361   0.113935
-0.795028   0.113935
-0.729722   0.113935
-0.729722   0.113935
8.021833    0.113935
5.473333    0.113935
5.436333    0.113935
7.366667    0.113935

I would like each trait to be average over the bin and then output into a df.

data.df %>%
  dplyr::filter(lat >= -180 & lat <= -175, .preserve= T)

The end output will be a data frame with one column containing all the bins, and the second column containing the averages

Body:
data.df %>%
  group_by(avg_lat = round(lat/5)*5) %>%
  summarize(mean = mean(trait))

Given more varied sample data below, you'd see:

# A tibble: 3 x 2
  avg_lat  mean
    <dbl> <dbl>
1       0 1.34
2       5 0.114
3      10 3

data.df <- read.table(
  header = T,
  stringsAsFactors = F,
  text = "lat             trait
-0.830361   5
-0.795028   0.113935
-0.729722   0.113935
-0.729722   0.113935
8.021833    3
5.473333    0.113935
5.436333    0.113935
7.366667    0.113935")


答:
you can try this:

assuming assign a variable for given dictionary

a = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}
result = []
for k, v in a.items():
   if k.startswith('BTC') and float(v.get('BTC', 0)) > 100:
       result.append(k)
print(result)
```

in Python keys in dictionary must be immutable so your dictionary is not valid, you must convert keys to string or immutable object to use

https://docs.python.org/2.7/tutorial/datastructures.html#dictionaries

Title: How to select value from a python dictionary with multi items

Body:
you can try this:

assuming assign a variable for given dictionary

a = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}
result = []
for k, v in a.items():
   if k.startswith('BTC') and float(v.get('BTC', 0)) > 100:
       result.append(k)
print(result)

in Python keys in dictionary must be immutable so your dictionary is not valid, you must convert keys to string or immutable object to use

https://docs.python.org/2.7/tutorial/datastructures.html#dictionaries


问:
Promise inside Observable does not return value
I am trying to embed Microsoft PowerBi in my angular 6 project. the next codes is expecting return an powerbi report object, but nothing is returning, no idea why:

```<code> private embedPowerBiReportAndGetPages(htmlElement: HTMLElement, newMyPowerbiReport: MyPowerbiReport): Observable<MyPowerbiReport> {
const config: IEmbedConfiguration = PowerbiHelper.createReportConfig(newMyPowerbiReport);
const microsoftReport: msReport = this.msPowerBiService
  .embed(htmlElement, config) as msReport;
return fromEvent(microsoftReport, 'loaded')
  .pipe(
    tap(() => this.logger.debug('PowerBI: loaded')),
    mergeMap(async() => {
      this.logger.debug('PowerBI: embed pages loaded');
      const msPages: Page[] = await microsoftReport.getPages();
      this.logger.debug('PowerBI: msPages', msPages);
      newMyPowerbiReport.pages = msPages.map((page: Page) => PowerbiHelper.msPageToEmbeddedPageMapper(page, newMyPowerbiReport));
      this.logger.debug('PowerBI: newMyPowerbiReport pages updated', newMyPowerbiReport);
      return newMyPowerbiReport;
    }),
    finalize(() => microsoftReport.off('loaded'))
  );
</code>```

}

Well the promise inside mergeMap is called and also returns result, from the logger I can see PowerBI: newMyPowerbiReport pages updated and the pages array. but it nothing is returned.

答: finally fixed, there is nothing with this code, the problem was in the parent method, I've used forkjoin in the parent method, it seems that forkjoin does not subscribe this observable, change forkjoin with scan and everything work as the sun shines .</p>

Body:
I am trying to embed Microsoft PowerBi in my angular 6 project. the next codes is expecting return an powerbi report object, but nothing is returning, no idea why:

 private embedPowerBiReportAndGetPages(htmlElement: HTMLElement, newMyPowerbiReport: MyPowerbiReport): Observable<MyPowerbiReport> {
const config: IEmbedConfiguration = PowerbiHelper.createReportConfig(newMyPowerbiReport);
const microsoftReport: msReport = this.msPowerBiService
  .embed(htmlElement, config) as msReport;
return fromEvent(microsoftReport, 'loaded')
  .pipe(
    tap(() => this.logger.debug('PowerBI: loaded')),
    mergeMap(async() => {
      this.logger.debug('PowerBI: embed pages loaded');
      const msPages: Page[] = await microsoftReport.getPages();
      this.logger.debug('PowerBI: msPages', msPages);
      newMyPowerbiReport.pages = msPages.map((page: Page) => PowerbiHelper.msPageToEmbeddedPageMapper(page, newMyPowerbiReport));
      this.logger.debug('PowerBI: newMyPowerbiReport pages updated', newMyPowerbiReport);
      return newMyPowerbiReport;
    }),
    finalize(() => microsoftReport.off('loaded'))
  );

}

Well the promise inside mergeMap is called and also returns result, from the logger I can see PowerBI: newMyPowerbiReport pages updated and the pages array. but it nothing is returned.


问:
How to program shortcut for website with j2me and netbeans?
I want make application for my blackberry ..

the application is .. shortcut for my website .. like when I'm click he go to my website .

答: You can start reading some tutorials from Netbeans Docs & Support section on Java ME</p>


问:
What's the best way to call another resolver in Apollo Server?
Say you wanted to call the createdAt resolver from the updatedAt resolver. For example this doesn't work:

{
  Review: {
    createdAt: review => review._id.getTimestamp(),
    updatedAt: review => review.updatedAt || this.createdAt(review)
  },
}
```

I realize I could make a reviewCreatedAt() function that is called from both, but I'm looking for a way to call the createdAt resolver.

答:
There is no standard way to call another resolver. Using this won't work even if you don't use an arrow function because the context is lost when the resolver is called by the underlying code. You can do something like this:

```<code>const resolvers = {
  Review: {
    createdAt: review => review._id.getTimestamp(),
    updatedAt: review => review.updatedAt || resolvers.Review.createdAt(review)
  },
}
</code>```

If you're using a data model, though, you may find it easier to just lift this logic into the data model (using a calculated or virtual field).

Body:
Say you wanted to call the createdAt resolver from the updatedAt resolver. For example this doesn't work:

{
  Review: {
    createdAt: review => review._id.getTimestamp(),
    updatedAt: review => review.updatedAt || this.createdAt(review)
  },
}

I realize I could make a reviewCreatedAt() function that is called from both, but I'm looking for a way to call the createdAt resolver.

Body:
There is no standard way to call another resolver. Using this won't work even if you don't use an arrow function because the context is lost when the resolver is called by the underlying code. You can do something like this:

const resolvers = {
  Review: {
    createdAt: review => review._id.getTimestamp(),
    updatedAt: review => review.updatedAt || resolvers.Review.createdAt(review)
  },
}

If you're using a data model, though, you may find it easier to just lift this logic into the data model (using a calculated or virtual field).


问:
Function for testing system stability, which receives predicted time series as input
I want to write a function that gets a time series and a standard deviation as parameters and returns an adjusted time series which looks like a forecast.

With this function I want to test a system for stability, which gets a forecasted time series list for weather as input parameter.

My approach for such a function, which is described below:

```<code>vector<tuple<datetime, double>> get_adjusted_timeseries(vector<tuple<datetime, double>>& timeseries_original, const double stddev, const double dist_mid)
{

    auto timeseries_copy(timeseries_original);

    int sign = randInRange(0, 1) == 0 ? 1 : -1;

    auto left_limit = normal_cdf_inverse(0.5 - dist_mid, 0, stddev);
    auto right_limit = normal_cdf_inverse(0.5 + dist_mid, 0, stddev);

    for (auto& pair : timeseries_copy)
    {
        double number;
        do
        {
            nd_value = normal_distribution_r(0, stddev);
        }
        while (sign == -1 && nd_value > 0.0 || sign == 1 && nd_value < 0.0);

        pair = make_tuple(get<0>(pair), get<1>(pair) + (nd_value / 100) * get<1>(pair));

        if (nd_value > 0.0 && nd_value < right_limit || nd_value < 0.0 && nd_value > left_limit)
        {
            sign = sign == -1 ? 1 : -1;
        }
    }

    return timeseries_copy;
}
</code>```

Make a copy from the original time series, which is also from type vector<tuple<datetime, double>>

Get a random number that is either 0 or 1 and use the number to set the sign.

Use the Inverse Cumulative distribution function to get the limits, which indicate when the sign is changed. The sign is changed when the value of the copied time series is close to the original value. The implementation of the inverse CDF is shown here

For-loop for each item in the time series:

get a normal distributed value, which should be lower zero when sign == -1 and greater zero when sign == 1

adjust old value of time series according to the normal distributed
value

change sign if the normal distributed value is close to the original value.

The result for a low standard deviation, for example, can be seen here in yellow:

If the mean absolute percentage error (MAPE) of the two time series is calculated, the following relationship results:

stddev: 5 -> MAPE: ~0.04

stddev: 10 -> MAPE: ~0.08

stddev: 15 -> MAPE: ~0.12

stddev: 20 -> MAPE: ~0.16

What do you think of this approach?

Can this function be used to test a system that has to deal with predicted time series?

答:
You want to generate time series data that behave like some existing time series data that you have from real phenomena (weather and stock exchange). That generated time series data will be fed into some system to test its stability.

What you could do is: fit some model to your exiting data, and then use that model to generate data that follow the model, and hence your existing data. Fitting data to a model yields a set of model parameters and a set of deviations (differences not explained by the model). The deviations may follow some known density function but not necessarily. Given the model parameters and deviations, you can generate data that look like the original data. Note that if the model does not explain the data well, deviations will be large, and the data generated with the model will not look like the original data.

For example, if you know your data is linear, you fit a line through them, and your model would be:

```<code>y = M x + B + E
</code>```

where E is a random variable that follows the distribution of the error around the line that fits your data, and where M and B are the model parameters. You can now use that model to generate (x, y) coordinates that are rougly linear. When sampling the random variable E, you can assume that it follows some known distribution like a normal distribution, or use an histogram, to generate deviations that follow arbitrary density functions.

There are several time series models that you could use to fit your weather and stock exchange data. You could look at exponential smoothing. It has several different models. I am sure you can find many other models on Wikipedia.

If a model does not fit well your data, you can also see its parameters as random variables. In our example above, suppose that we have observed data where it seems that the slope is changing. We would fit several lines and obtain a distribution for M. We would then sample that variable along with E when generating data.

Body:
I want to write a function that gets a time series and a standard deviation as parameters and returns an adjusted time series which looks like a forecast.

With this function I want to test a system for stability, which gets a forecasted time series list for weather as input parameter.

My approach for such a function, which is described below:

vector<tuple<datetime, double>> get_adjusted_timeseries(vector<tuple<datetime, double>>& timeseries_original, const double stddev, const double dist_mid)
{

    auto timeseries_copy(timeseries_original);

    int sign = randInRange(0, 1) == 0 ? 1 : -1;

    auto left_limit = normal_cdf_inverse(0.5 - dist_mid, 0, stddev);
    auto right_limit = normal_cdf_inverse(0.5 + dist_mid, 0, stddev);

    for (auto& pair : timeseries_copy)
    {
        double number;
        do
        {
            nd_value = normal_distribution_r(0, stddev);
        }
        while (sign == -1 && nd_value > 0.0 || sign == 1 && nd_value < 0.0);

        pair = make_tuple(get<0>(pair), get<1>(pair) + (nd_value / 100) * get<1>(pair));

        if (nd_value > 0.0 && nd_value < right_limit || nd_value < 0.0 && nd_value > left_limit)
        {
            sign = sign == -1 ? 1 : -1;
        }
    }

    return timeseries_copy;
}

Make a copy from the original time series, which is also from type vector<tuple<datetime, double>>

Get a random number that is either 0 or 1 and use the number to set the sign.

Use the Inverse Cumulative distribution function to get the limits, which indicate when the sign is changed. The sign is changed when the value of the copied time series is close to the original value. The implementation of the inverse CDF is shown here

For-loop for each item in the time series:

get a normal distributed value, which should be lower zero when sign == -1 and greater zero when sign == 1

adjust old value of time series according to the normal distributed
value

change sign if the normal distributed value is close to the original value.

The result for a low standard deviation, for example, can be seen here in yellow:

If the mean absolute percentage error (MAPE) of the two time series is calculated, the following relationship results:

stddev: 5 -> MAPE: ~0.04

stddev: 10 -> MAPE: ~0.08

stddev: 15 -> MAPE: ~0.12

stddev: 20 -> MAPE: ~0.16

What do you think of this approach?

Can this function be used to test a system that has to deal with predicted time series?

Body:
You want to generate time series data that behave like some existing time series data that you have from real phenomena (weather and stock exchange). That generated time series data will be fed into some system to test its stability.

What you could do is: fit some model to your exiting data, and then use that model to generate data that follow the model, and hence your existing data. Fitting data to a model yields a set of model parameters and a set of deviations (differences not explained by the model). The deviations may follow some known density function but not necessarily. Given the model parameters and deviations, you can generate data that look like the original data. Note that if the model does not explain the data well, deviations will be large, and the data generated with the model will not look like the original data.

For example, if you know your data is linear, you fit a line through them, and your model would be:

y = M x + B + E

where E is a random variable that follows the distribution of the error around the line that fits your data, and where M and B are the model parameters. You can now use that model to generate (x, y) coordinates that are rougly linear. When sampling the random variable E, you can assume that it follows some known distribution like a normal distribution, or use an histogram, to generate deviations that follow arbitrary density functions.

There are several time series models that you could use to fit your weather and stock exchange data. You could look at exponential smoothing. It has several different models. I am sure you can find many other models on Wikipedia.

If a model does not fit well your data, you can also see its parameters as random variables. In our example above, suppose that we have observed data where it seems that the slope is changing. We would fit several lines and obtain a distribution for M. We would then sample that variable along with E when generating data.


问:
How to move up the values of each column in a matrix in R
I'm looking for a general way to do the following,
I have a triangular matrix of nxn, for example:

```<code>a NA NA
b  d NA
c  e f
</code>```

and convert it in:

```<code>a d f
b e NA
c NA NA
</code>```

The idea is: for each column move the values, until the first non-NA value is in the first row

I imagine that it is done with a for, for each column, so that it goes up, but I do not know how to make it ...

答:
Edit: Fixed it to not sort the values:

```<code>apply(m, 2, function(x) x[order(is.na(x))])
</code>```

Original: Another solution which uses sort(..., na.last = T) and is good if you need each column to be sorted:

```<code>m <- structure(c("a", "b", "c", NA, "d", "e", NA, NA, "f"), .Dim = c(3L,
                                                                     3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))

apply(m, 2, sort, na.last = T )

     V1  V2  V3
[1,] "a" "d" "f"
[2,] "b" "e" NA
[3,] "c" NA  NA
</code>```

Body:
I'm looking for a general way to do the following,
I have a triangular matrix of nxn, for example:

a NA NA
b  d NA
c  e f

and convert it in:

a d f
b e NA
c NA NA

The idea is: for each column move the values, until the first non-NA value is in the first row

I imagine that it is done with a for, for each column, so that it goes up, but I do not know how to make it ...

Body:
Edit: Fixed it to not sort the values:

apply(m, 2, function(x) x[order(is.na(x))])

Original: Another solution which uses sort(..., na.last = T) and is good if you need each column to be sorted:

m <- structure(c("a", "b", "c", NA, "d", "e", NA, NA, "f"), .Dim = c(3L,
                                                                     3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))

apply(m, 2, sort, na.last = T )

     V1  V2  V3
[1,] "a" "d" "f"
[2,] "b" "e" NA
[3,] "c" NA  NA


问:
Is there a way for publishing an Android App with API level 26 from UNITY 5.6.6?
I made an AR app using UNITY 5.6.6 and I'm trying to publish my app to Google Play that need at least API Level 26. I have tried different ways to achieve that targeted level of API but achieved nothing and the Google Console only recognize my app'S API as level 22. Yes, it can be done easily if I use Unity earlier version (I am using Unity 2018 for my other published Apps), but I have to use this particular version because I'm using a little old plugin that only can be stable using those early versions of UNITY.

Here above some ways I've tried on Unity 5.6.6 :

I have tried using SDK tools version 26.1

I have tried using SDK tools version r25.2.5
sdkmanager

Here is my configuration I've tried on Build Settings-Other Settings
config 1
config 2

Here is the message I received from Google Console
google console message

I hope someone have experienced this and solved the problem. I appreciate your time and help alot! Thank you!

答:
it seems unity 5.6 only goes up to api minimum of  25 (android 7.1)

api level 26 was released march of 2017 and unity 2017 was released in February 2017 for comparison

so unity 5.6 was done being updated before the release of api level 26


问:
IDEA 10.5.2 Aspectj compiler - can't determine superclass of missing type org.springframework.transaction.interceptor.TransactionAspectSupport
Trying to make a module with spring aspects gives me:

can't determine superclass of missing type org.springframework.transaction.interceptor.TransactionAspectSupport

Works in other modules, what's up with this one? Missing dep?

/S

答:
Add optional dependency, if not needed actually at runtime:

```<code><dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <optional>true</optional>
</dependency>
</code>```

Or Xlint option change to warning( or ignore).

Body:
Add optional dependency, if not needed actually at runtime:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <optional>true</optional>
</dependency>

Or Xlint option change to warning( or ignore).


问:
Compacting multiple similar if statements in C#
I would like to make some code for a game a little more compact. Here is the original.

```<code>if (killPosX != 0) // float x position you would like the object to be destroyed at
{
    killX = true;  // automatically makes the value of killX true
}

if (killPosY != 0) // float y position you would like the object to be destroyed at
{
    killY = true;  // automatically makes the value of killY true
}

if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
    killT = true;  // automatically makes the value of killT true
}
</code>```

And I want to turn it into something like this:

```<code>if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}
</code>```

How would I do that?

答:
I'm not sure if this applies to what you're working on (and there may be a better way in Unity), but it seems to me that one way to do it would be to make the KillN properties calculated on the value of their corresponding KillPosN property:

```<code>public class SomeClass
{
    public float KillPosX { get; set; }
    public float KillPosY { get; set; }
    public float KillPosT { get; set; }

    // Values are based on the related property values and cannot be set directly
    public bool KillX => !IsRoughlyZero(KillPosX);
    public bool KillY => !IsRoughlyZero(KillPosY);
    public bool KillT => !IsRoughlyZero(KillPosT);

    private static bool IsRoughlyZero(float input)
    {
        // Use a tolerance for comparing floating point numbers to 0
        return Math.Abs(input) < .0000001;
    }
}
</code>```

Body:
I would like to make some code for a game a little more compact. Here is the original.

if (killPosX != 0) // float x position you would like the object to be destroyed at
{
    killX = true;  // automatically makes the value of killX true
}

if (killPosY != 0) // float y position you would like the object to be destroyed at
{
    killY = true;  // automatically makes the value of killY true
}

if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
    killT = true;  // automatically makes the value of killT true
}

And I want to turn it into something like this:

if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}

How would I do that?

Body:
I'm not sure if this applies to what you're working on (and there may be a better way in Unity), but it seems to me that one way to do it would be to make the KillN properties calculated on the value of their corresponding KillPosN property:

public class SomeClass
{
    public float KillPosX { get; set; }
    public float KillPosY { get; set; }
    public float KillPosT { get; set; }

    // Values are based on the related property values and cannot be set directly
    public bool KillX => !IsRoughlyZero(KillPosX);
    public bool KillY => !IsRoughlyZero(KillPosY);
    public bool KillT => !IsRoughlyZero(KillPosT);

    private static bool IsRoughlyZero(float input)
    {
        // Use a tolerance for comparing floating point numbers to 0
        return Math.Abs(input) < .0000001;
    }
}


问:
How to capitalize every word including in the beginning of a quote?
For example, this sentence:

```<code>say "mosquito!"
</code>```

I try to capitalize with the following code:

```<code>'say "mosquito!"'.capitalize()
</code>```

Which returns this:

```<code>'Say "mosquito!"’
</code>```

However, the desired result is:

```<code>'Say "Mosquito!"’
</code>```

答:
This is quite tricky. I will look for the first letter (alphabet) of a word.  Split the string into words and join them again after converting the first letter of each word in upper case.

```<code>def start(word):
    for n in range(len(word)):
        if word[n].isalpha():
            return n
    return 0

strng = 'say mosquito\'s house'
print( ' '.join(word[:start(word)] + word[start(word)].upper() + word[start(word)+1:] for word in strng.split()))
</code>```

Result:

```<code>Say "Mosquito's House"
</code>```

Body:
For example, this sentence:

say "mosquito!"

I try to capitalize with the following code:

'say "mosquito!"'.capitalize()

Which returns this:

'Say "mosquito!"’

However, the desired result is:

'Say "Mosquito!"’

Body:
This is quite tricky. I will look for the first letter (alphabet) of a word.  Split the string into words and join them again after converting the first letter of each word in upper case.

def start(word):
    for n in range(len(word)):
        if word[n].isalpha():
            return n
    return 0

strng = 'say mosquito\'s house'
print( ' '.join(word[:start(word)] + word[start(word)].upper() + word[start(word)+1:] for word in strng.split()))

Result:

Say "Mosquito's House"


问:
Powered Link by Manychat on Facebook Messenger How to Remove?
I already remove ManyChat on my client Facebook Page Messenger and replace it with a new bot but the problem is it still shows the powered by manychat (see screenshot)

I cannot find any option in facebook page setting for this part, are there any documentation or how-to instruction to delete this part?

thanks,

答:
Try resetting the chatbot's persistent menu. This can be done with sending a POST HTTP request to Facebook Messenger API as explained here:

https://developers.facebook.com/docs/messenger-platform/send-messages/persistent-menu

This worked for another user in this thread.


问:
How do I fix my `itoa` implementation so it doesn't print reversed output?
I want to convert an integer into a string of numeric characters in C.

I've tried using itoa, but it's non-standard and not provided by my C library.

I tried to implement my own itoa, but it's not working properly:

```<code>#include <stdlib.h>
#include <stdio.h>

char *itoa(int val, char *buf, int base)
{
    size_t ctr = 0;
    for( ; val; val /= base )
    {
        buf[ctr++] = '0' + (val % base);
    }
    buf[ctr] = 0;
    return buf;
}

int main(void)
{
    unsigned char c = 201;
    char *buf = malloc(sizeof(c)*8+1);
    itoa(c, buf, 2);
    puts(buf);
    free(buf);
}
</code>```

It gives reversed output.

For example, if c is 'A' and base is 2, the output is this: 0101101

The output I want it to be is this: 1011010

How do I fix this issue?

Similar questions

I've already seen this question: Is there a printf converter to print in binary format?

I do not want a printf format specifier to print an integer as binary, I want to convert the binary to a string.

I've already seen this question: Print an int in binary representation using C

Although the answer does convert an integer into a string of binary digits, that's the only thing it can do.

Restrictions

I want itoa to be able to work with other bases, such as 10, 8, etc. and print correctly (i.e. 12345 translates to "12345" and not to "11000000111001").

I do not want to use printf or sprintf to do this.

I do not care about the length of the string as long is the result is correct.

I do not want to convert the integer into ASCII characters other than numeric ones, with the exception of bases greater than 10, in which case the characters may be alphanumeric.

The answer must fit this prototype exactly:

```<code>char *itoa(int val, char *buf, int base);
</code>```

There may be a function called nitoa that has this prototype and returns the number of characters required to hold the result of itoa:

```<code>size_t nitoa(int val, int base);
</code>```

答:
This solution works for me:</p>

```<code>#include <errno.h>
#include <stdlib.h>
#include <string.h>

#define itoa lltoa
#define utoa ulltoa
#define ltoa lltoa
#define ultoa ulltoa
#define nitoa nlltoa
#define nutoa nulltoa
#define nltoa nlltoa
#define nultoa nulltoa

#define BASE_BIN 2
#define BASE_OCT 8
#define BASE_DEC 10
#define BASE_HEX 16
#define BASE_02Z 36

__extension__
char *ulltoa(unsigned long long val, char *buf, int base)
{
    int remainder;
    char c, *tmp = buf;

    if(base < BASE_BIN)
    {
        errno = EINVAL;
        return NULL;
    }

    do {
        remainder = val % base;
        if(remainder >= BASE_DEC) c = 'a' - BASE_DEC;
        else c = '0';
        *tmp++ = remainder + c;
        val /= base;
    } while(val);

    *tmp = 0;
    return strrev(buf);
}

__extension__
size_t nulltoa(unsigned long long val, int base)
{
    size_t size = 0;

    if(base < BASE_BIN)
    {
        errno = EINVAL;
        return 0;
    }

    if(!val) size++;

    for( ; val; val /= base, size++ );

    return size;
}

__extension__
char *lltoa(long long val, char *buf, int base)
{
    if(val < 0 && base > BASE_BIN)
    {
         val = -val;
         *buf++ = '-';
    }

    return ulltoa(val, buf, base);
}

__extension__
size_t nlltoa(long long val, int base)
{
    size_t size = 0;

    if(val < 0 && base > BASE_BIN)
    {
        val = -val;
        size++;
    }

    return size + nulltoa(val, base);
}
</code>```

Body:
I want to convert an integer into a string of numeric characters in C.

I've tried using itoa, but it's non-standard and not provided by my C library.

I tried to implement my own itoa, but it's not working properly:

#include <stdlib.h>
#include <stdio.h>

char *itoa(int val, char *buf, int base)
{
    size_t ctr = 0;
    for( ; val; val /= base )
    {
        buf[ctr++] = '0' + (val % base);
    }
    buf[ctr] = 0;
    return buf;
}

int main(void)
{
    unsigned char c = 201;
    char *buf = malloc(sizeof(c)*8+1);
    itoa(c, buf, 2);
    puts(buf);
    free(buf);
}

It gives reversed output.

For example, if c is 'A' and base is 2, the output is this: 0101101

The output I want it to be is this: 1011010

How do I fix this issue?

Similar questions

I've already seen this question: Is there a printf converter to print in binary format?

I do not want a printf format specifier to print an integer as binary, I want to convert the binary to a string.

I've already seen this question: Print an int in binary representation using C

Although the answer does convert an integer into a string of binary digits, that's the only thing it can do.

Restrictions

I want itoa to be able to work with other bases, such as 10, 8, etc. and print correctly (i.e. 12345 translates to "12345" and not to "11000000111001").

I do not want to use printf or sprintf to do this.

I do not care about the length of the string as long is the result is correct.

I do not want to convert the integer into ASCII characters other than numeric ones, with the exception of bases greater than 10, in which case the characters may be alphanumeric.

The answer must fit this prototype exactly:

char *itoa(int val, char *buf, int base);

There may be a function called nitoa that has this prototype and returns the number of characters required to hold the result of itoa:

size_t nitoa(int val, int base);

Body:
This solution works for me:

#include <errno.h>
#include <stdlib.h>
#include <string.h>

#define itoa lltoa
#define utoa ulltoa
#define ltoa lltoa
#define ultoa ulltoa
#define nitoa nlltoa
#define nutoa nulltoa
#define nltoa nlltoa
#define nultoa nulltoa

#define BASE_BIN 2
#define BASE_OCT 8
#define BASE_DEC 10
#define BASE_HEX 16
#define BASE_02Z 36

__extension__
char *ulltoa(unsigned long long val, char *buf, int base)
{
    int remainder;
    char c, *tmp = buf;

    if(base < BASE_BIN)
    {
        errno = EINVAL;
        return NULL;
    }

    do {
        remainder = val % base;
        if(remainder >= BASE_DEC) c = 'a' - BASE_DEC;
        else c = '0';
        *tmp++ = remainder + c;
        val /= base;
    } while(val);

    *tmp = 0;
    return strrev(buf);
}

__extension__
size_t nulltoa(unsigned long long val, int base)
{
    size_t size = 0;

    if(base < BASE_BIN)
    {
        errno = EINVAL;
        return 0;
    }

    if(!val) size++;

    for( ; val; val /= base, size++ );

    return size;
}

__extension__
char *lltoa(long long val, char *buf, int base)
{
    if(val < 0 && base > BASE_BIN)
    {
         val = -val;
         *buf++ = '-';
    }

    return ulltoa(val, buf, base);
}

__extension__
size_t nlltoa(long long val, int base)
{
    size_t size = 0;

    if(val < 0 && base > BASE_BIN)
    {
        val = -val;
        size++;
    }

    return size + nulltoa(val, base);
}


问:
Why is this excel concatenation not working?
I'm trying to do this excel formula if something is true then concatenate the following cells:

```<code>=IF(O7>0,concatenate=(H7,J7,K7,L7,M7,N7),H7)
</code>```

however I keep getting a #NAME! error.

I have tried:

```<code>=IF(O7>0,(concatenate=(H7,J7,K7,L7,M7,N7)),H7)
</code>```

答:
Try without the = after CONCATENATE:

```<code>=IF(O7>0,CONCATENATE(H7,J7,K7,L7,M7,N7),H7)
</code>```

Body:
I'm trying to do this excel formula if something is true then concatenate the following cells:

=IF(O7>0,concatenate=(H7,J7,K7,L7,M7,N7),H7)

however I keep getting a #NAME! error.

I have tried:

=IF(O7>0,(concatenate=(H7,J7,K7,L7,M7,N7)),H7)

Body:
Try without the = after CONCATENATE:

=IF(O7>0,CONCATENATE(H7,J7,K7,L7,M7,N7),H7)


问:
Centering icon and text
Im having a hard time centering a text with awesome font icon, and also centering the icons themselves.

Im using styled components like so:

```<code>const StyledIcon = styled(FontAwesomeIcon)`
    width: 50px;
    display: flex;
    justify-content: center;
    font-size: 30px;
    margin-left: 50px;
`;
const Text = styled.div`
    font-size: 13px;
    display: flex;
    justify-content: center;
`;
</code>```

and in my component I have the following

```<code><StyledIcon icon={icon1} />
<Text>Charts + Graphs</Text>

<StyledIcon icon={icon2} />
<Text>Classes</Text>

<StyledIcon icon={icon3} />
<Text>Student Information</Text>

<StyledIcon icon={icon4} />
<Text>Knowledge Database</Text>

<StyledIcon icon={icon5}/>
<Text>Class Notes</Text>
</code>```

This is how it currently looks, any suggestions on how to center text & icon so that they appear in the center of the shaded box?

答:
Use flexbox.</p>

```<code>const WrapperAroundIconsAndText = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
`;
</code>```

Title: Centering icon and text

Body:
Im having a hard time centering a text with awesome font icon, and also centering the icons themselves.

Im using styled components like so:

const StyledIcon = styled(FontAwesomeIcon)`
    width: 50px;
    display: flex;
    justify-content: center;
    font-size: 30px;
    margin-left: 50px;
`;
const Text = styled.div`
    font-size: 13px;
    display: flex;
    justify-content: center;
`;

and in my component I have the following

Body:
Use flexbox.

const WrapperAroundIconsAndText = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
`;


问:
showing [object Object] displayed instead of the object properties
I'm using Strapi to create Api endpoints and consume those endpoints using expressjs. It's all for educational purposes.

Everything is working fine except displaying the object protperties in the browser. The endpoints is http://localhost:1337/restaurants
which display my data in json format:

```<code>[{"_id":"5cf19dd4a774126e9ca7f4fd","name":"Strapi Restaurant 1","description":"Strapi restaurant is a cosy restaurant delivering one of the very fastest and nicest dining experiences in the world, combining nods to tradition with fierce modernity, warmth with daring.\n# Strapi restaurant #\n- \n- \n1. \n2. \n3. ","createdAt":"2019-05-31T21:34:12.426Z","updatedAt":"2019-05-31T21:34:12.432Z","__v":0,"id":"5cf19dd4a774126e9ca7f4fd","categories":[{"restaurants":["5cf19dd4a774126e9ca7f4fd"],"_id":"5cf19e00a774126e9ca7f4fe","category":"Italian","createdAt":"2019-05-31T21:34:56.318Z","updatedAt":"2019-05-31T21:35:32.058Z","__v":0,"id":"5cf19e00a774126e9ca7f4fe"}]},{"_id":"5cf1af8ea774126e9ca7f500","name":"Strapi restaurant 2","description":"This is a restaurant that will serve you empty plates with no food. It is for your own good. You will loose weight quickly. Enjoy","createdAt":"2019-05-31T22:49:50.548Z","updatedAt":"2019-05-31T22:49:50.579Z","__v":0,"id":"5cf1af8ea774126e9ca7f500","categories":[{"restaurants":["5cf1af8ea774126e9ca7f500"],"_id":"5cf19e08a774126e9ca7f4ff","category":"Contemporary","createdAt":"2019-05-31T21:35:04.815Z","updatedAt":"2019-05-31T22:49:50.570Z","__v":0,"id":"5cf19e08a774126e9ca7f4ff"}]}]
</code>```

My express route uses axios to access api and response is showing data logged correctly in my cmd

Now my route code is:

```<code>var express = require('express');
var router = express.Router();
var axios = require("axios");

/* GET home page. */
router.get('/', function(req, res, next) {
     axios.get('http://localhost:1337/restaurants')
       .then(response => ( res.render('index', { title: response.data}), console.log(response) ));
          });
    module.exports = router;
</code>```

my PUG file is just trying to display the "reponse.data" using the variable "title":

```<code>extends layout
block content

  //  response from the strapiapp api
  //  p  restaurant name is : #{title}
  p  Restaurant name is: #{title.name}
</code>```

Here is a screenshot of my cmd

It is the typical setup and I have done it so many times with different apis. My browser renders [object Object] if I use #{title}and if I use #{title.name} it will show nothing. But the data is logged correctly to my cmd.

How to display the object in my browser? title.name and titel.description are not working but the data is logged in my cmd express is logging the data object correctly.

Any idea why it is not displaying the object properties?

答:
So as Alexander commented response.data is an array. So you can loop this array to display all data. I have not used pug before but i think this should work.

```<code>ul
  each val in title
    li= val.name
</code>```

Body:
I'm using Strapi to create Api endpoints and consume those endpoints using expressjs. It's all for educational purposes.

Everything is working fine except displaying the object protperties in the browser. The endpoints is http://localhost:1337/restaurants
which display my data in json format:

[{"_id":"5cf19dd4a774126e9ca7f4fd","name":"Strapi Restaurant 1","description":"Strapi restaurant is a cosy restaurant delivering one of the very fastest and nicest dining experiences in the world, combining nods to tradition with fierce modernity, warmth with daring.\n# Strapi restaurant #\n- \n- \n1. \n2. \n3. ","createdAt":"2019-05-31T21:34:12.426Z","updatedAt":"2019-05-31T21:34:12.432Z","__v":0,"id":"5cf19dd4a774126e9ca7f4fd","categories":[{"restaurants":["5cf19dd4a774126e9ca7f4fd"],"_id":"5cf19e00a774126e9ca7f4fe","category":"Italian","createdAt":"2019-05-31T21:34:56.318Z","updatedAt":"2019-05-31T21:35:32.058Z","__v":0,"id":"5cf19e00a774126e9ca7f4fe"}]},{"_id":"5cf1af8ea774126e9ca7f500","name":"Strapi restaurant 2","description":"This is a restaurant that will serve you empty plates with no food. It is for your own good. You will loose weight quickly. Enjoy","createdAt":"2019-05-31T22:49:50.548Z","updatedAt":"2019-05-31T22:49:50.579Z","__v":0,"id":"5cf1af8ea774126e9ca7f500","categories":[{"restaurants":["5cf1af8ea774126e9ca7f500"],"_id":"5cf19e08a774126e9ca7f4ff","category":"Contemporary","createdAt":"2019-05-31T21:35:04.815Z","updatedAt":"2019-05-31T22:49:50.570Z","__v":0,"id":"5cf19e08a774126e9ca7f4ff"}]}]

My express route uses axios to access api and response is showing data logged correctly in my cmd

Now my route code is:

var express = require('express');
var router = express.Router();
var axios = require("axios");

/* GET home page. */
router.get('/', function(req, res, next) {
     axios.get('http://localhost:1337/restaurants')
       .then(response => ( res.render('index', { title: response.data}), console.log(response) ));
          });
    module.exports = router;

my PUG file is just trying to display the "reponse.data" using the variable "title":

extends layout
block content

  //  response from the strapiapp api
  //  p  restaurant name is : #{title}
  p  Restaurant name is: #{title.name}

Here is a screenshot of my cmd

It is the typical setup and I have done it so many times with different apis. My browser renders [object Object] if I use #{title}and if I use #{title.name} it will show nothing. But the data is logged correctly to my cmd.

How to display the object in my browser? title.name and titel.description are not working but the data is logged in my cmd express is logging the data object correctly.

Any idea why it is not displaying the object properties?

Body:
So as Alexander commented response.data is an array. So you can loop this array to display all data. I have not used pug before but i think this should work.

ul
  each val in title
    li= val.name


问:
How to use array filter criteria agaist object in lodash?
How to filter object ageist another object in lodash? but the criteria object is array..

```<code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);
</code>```

The results should be xyz and abc:

```<code>results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]
</code>```

Is it something I can do using filter method?

答:
Simple in pure JS:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const res = items.filter(({ type, name }) => form.type.includes(type) && form.name == name);

console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

If you really want to, you can use Lodash's _.filter method like so:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const res = _.filter(items, ({ type, name }) => form.type.includes(type) && form.name == name);

console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

```

Body:
How to filter object ageist another object in lodash? but the criteria object is array..

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);

The results should be xyz and abc:

results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]

Is it something I can do using filter method?

Body:
Simple in pure JS:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const res = items.filter(({ type, name }) => form.type.includes(type) && form.name == name);

console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

If you really want to, you can use Lodash's _.filter method like so:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const res = _.filter(items, ({ type, name }) => form.type.includes(type) && form.name == name);

console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>


问:
Select columns based on sum
I have a data frame with many columns of genes and rows, for example

```<code>id  treatment time gene1 gene2 gene3 …
1      A       1     2     0    2    …
2      A       2     0     0    3    …
3      A       3     0     0    4    …
4      B       4     0     0    0    …
5      B       5     0     0    2    …
6      B       3     1     0    1    …
7      C       5     0     0    2    …
</code>```

I would like to keep the all the first several columns (in the example data is three, but there are many columns in real data) and the genes columns that the column sum is > 0.

I would appreciate any help on my question. Thank you very much!

答:
I'm not entirely sure on whether you want to retain rows or columns with the sum of entries > 0.

In case of the former, you can use rowSums like this

```<code>df[rowSums(df[, grep("gene", names(df))]) > 0, ]
#id treatment time gene1 gene2 gene3
#1  1         A    1     2     0     2
#2  2         A    2     0     0     3
#3  3         A    3     0     0     4
#5  5         B    5     0     0     2
#6  6         B    3     1     0     1
#7  7         C    5     0     0     2
</code>```

Or to retain only those columns with the sum of entries > 0 you can use colSums

```<code>df[, names(df) %in% c(
    names(df)[grep("gene", names(df), invert = T)],
    names(which(colSums(df[, grep("gene", names(df))]) > 0)))]
#  id treatment time gene1 gene3
#1  1         A    1     2     2
#2  2         A    2     0     3
#3  3         A    3     0     4
#4  4         B    4     0     0
#5  5         B    5     0     2
#6  6         B    3     1     1
#7  7         C    5     0     2
</code>```

This assumes that all gene columns contain the word "gene" (and all non-gene columns do not contain the word "gene").

Or more concise (thanks @Shree),

```<code>df[, c(rep(T, 3), colSums(df[, -c(1:3)]) > 0)]
</code>```

which assumes that the first 3 columns are non-gene columns (and the remaining columns are all gene columns).

Sample data

```<code>df <- read.table(text =
    "id  treatment   time    gene1   gene2   gene3
1   A   1   2   0   2
2   A   2   0   0   3
3   A   3   0   0   4
4   B   4   0   0   0
5   B   5   0   0   2
6   B   3   1   0   1
7   C   5   0   0   2", header = T)
</code>```

Title: Select columns based on sum

Body:
I have a data frame with many columns of genes and rows, for example

id  treatment time gene1 gene2 gene3 …
1      A       1     2     0    2    …
2      A       2     0     0    3    …
3      A       3     0     0    4    …
4      B       4     0     0    0    …
5      B       5     0     0    2    …
6      B       3     1     0    1    …
7      C       5     0     0    2    …

I would like to keep the all the first several columns (in the example data is three, but there are many columns in real data) and the genes columns that the column sum is > 0.

I would appreciate any help on my question. Thank you very much!

Body:
I'm not entirely sure on whether you want to retain rows or columns with the sum of entries > 0.

In case of the former, you can use rowSums like this

df[rowSums(df[, grep("gene", names(df))]) > 0, ]
#id treatment time gene1 gene2 gene3
#1  1         A    1     2     0     2
#2  2         A    2     0     0     3
#3  3         A    3     0     0     4
#5  5         B    5     0     0     2
#6  6         B    3     1     0     1
#7  7         C    5     0     0     2

Or to retain only those columns with the sum of entries > 0 you can use colSums

df[, names(df) %in% c(
    names(df)[grep("gene", names(df), invert = T)],
    names(which(colSums(df[, grep("gene", names(df))]) > 0)))]
#  id treatment time gene1 gene3
#1  1         A    1     2     2
#2  2         A    2     0     3
#3  3         A    3     0     4
#4  4         B    4     0     0
#5  5         B    5     0     2
#6  6         B    3     1     1
#7  7         C    5     0     2

This assumes that all gene columns contain the word "gene" (and all non-gene columns do not contain the word "gene").

Or more concise (thanks @Shree),

df[, c(rep(T, 3), colSums(df[, -c(1:3)]) > 0)]

which assumes that the first 3 columns are non-gene columns (and the remaining columns are all gene columns).

Sample data

df <- read.table(text =
    "id  treatment   time    gene1   gene2   gene3
1   A   1   2   0   2
2   A   2   0   0   3
3   A   3   0   0   4
4   B   4   0   0   0
5   B   5   0   0   2
6   B   3   1   0   1
7   C   5   0   0   2", header = T)


问:
Rollup with gulp and typescript outputs Cannot find module 'tslib/tslib.es6.js'
I followed the typescript gulp in the doc :https://rollupjs.org/guide/en#gulp

here is my gulp file :

```<code>const gulp = require("gulp");
const rollup = require("rollup");
const rollupTypescript = require("rollup-plugin-typescript");

gulp.task("build", () => {
  return rollup
    .rollup({
      input: "./main.ts",
      plugins: [rollupTypescript()]
    })
    .then(bundle => {
      return bundle.write({
        file: "./main.js",
        format: "umd",
        name: "library",
        sourcemap: true
      });
    });
});
</code>```

```<code>Error: Cannot find module 'tslib/tslib.es6.js' from 'C:\projets\Tests\rollup\node_modules\rollup-plugin-typescript\dist'
    at Function.module.exports [as sync] (C:\projets\Tests\rollup\node_modules\resolve\lib\sync.js:58:15)
    at typescript (C:\projets\Tests\rollup\node_modules\rollup-plugin-typescript\dist\rollup-plugin-typescript.cjs.js:109:29)
    at gulp.task (C:\projets\Tests\rollup\gulpfile.js:9:17)
    at taskWrapper (C:\projets\Tests\rollup\node_modules\undertaker\lib\set-task.js:13:15)
    at bound (domain.js:301:14)
    at runBound (domain.js:314:12)
    at asyncRunner (C:\projets\Tests\rollup\node_modules\async-done\index.js:55:18)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
</code>```

Anyone knows why this is happening is this a bug with rollup or am I doing something wrong?

答:
You need tslib, which is a peer dependency of rollup-plugin-typescript.

```<code>npm i -D tslib
</code>```

Body:
I followed the typescript gulp in the doc :https://rollupjs.org/guide/en#gulp

here is my gulp file :

const gulp = require("gulp");
const rollup = require("rollup");
const rollupTypescript = require("rollup-plugin-typescript");

gulp.task("build", () => {
  return rollup
    .rollup({
      input: "./main.ts",
      plugins: [rollupTypescript()]
    })
    .then(bundle => {
      return bundle.write({
        file: "./main.js",
        format: "umd",
        name: "library",
        sourcemap: true
      });
    });
});

Error: Cannot find module 'tslib/tslib.es6.js' from 'C:\projets\Tests\rollup\node_modules\rollup-plugin-typescript\dist'
    at Function.module.exports [as sync] (C:\projets\Tests\rollup\node_modules\resolve\lib\sync.js:58:15)
    at typescript (C:\projets\Tests\rollup\node_modules\rollup-plugin-typescript\dist\rollup-plugin-typescript.cjs.js:109:29)
    at gulp.task (C:\projets\Tests\rollup\gulpfile.js:9:17)
    at taskWrapper (C:\projets\Tests\rollup\node_modules\undertaker\lib\set-task.js:13:15)
    at bound (domain.js:301:14)
    at runBound (domain.js:314:12)
    at asyncRunner (C:\projets\Tests\rollup\node_modules\async-done\index.js:55:18)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Anyone knows why this is happening is this a bug with rollup or am I doing something wrong?

Body:
You need tslib, which is a peer dependency of rollup-plugin-typescript.

npm i -D tslib


答: concatenate= is not an Excel function, you need to do it without the =.

Title: Why is this excel concatenation not working?


问:
How to select value from a python dictionary with multi items
I'm trying to get values from a python dictionary. As you can see below I have this example. I would like to get only keys which start with "BTC_" and select it if its "BTC" Value is greater than 100.

```<code>d = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}
</code>```

The expected result is the following list:

```<code>['BTC_LTC', 'BTC_TRX']
</code>```

Because of their key start with "BTC_" and their 'BTC' value is greater than 100.

Body:
I'm trying to get values from a python dictionary. As you can see below I have this example. I would like to get only keys which start with "BTC_" and select it if its "BTC" Value is greater than 100.

d = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}

The expected result is the following list:

['BTC_LTC', 'BTC_TRX']

Because of their key start with "BTC_" and their 'BTC' value is greater than 100.

Body:
Assuming your keys are strings, you can use the following assigning your dictionary to a variable called d:

d = {
  'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
  'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
  'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
  'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
  'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
  'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
  'totalBTC': '2340.96441558',
  'totalETH': '2771.63218462',
  'totalUSDC': '681255.56961992',
  'totalXMR': '267.83601213'
}

>>> [k for k, v in d.items() if k.startswith('BTC_') and v.get('BTC', None) is not None and float(v.get('BTC')) > 100]

['BTC_LTC', 'BTC_TRX']


Body:
Keys as strings, using a list comprehension:

inp = {
    'BTC_LTC':  { 'BTC': '138.13504038', 'LTC': '4662.34229096' },
    'BTC_MAID': { 'BTC': '10.38010322', 'MAID': '359919.71515255' },
    'BTC_NEM': { 'BTC': '30.34435435', 'NEM': '34435345' },
    'BTC_TRX': { 'BTC': '101.1122', 'TRX': '4546456456.343543543' },
    'USDC_BTC': { 'USDC': '481389.13175764', 'BTC': '74.73988488' },
    'USDC_ETH': { 'USDC': '72302.27016210', 'ETH': '357.72884034' },
    'totalBTC': '2340.96441558',
    'totalETH': '2771.63218462',
    'totalUSDC': '681255.56961992',
    'totalXMR': '267.83601213'
}

outp = [k for k, v in inp.items() if k[:4] == "BTC_" and float(v["BTC"]) > 100]

print(outp)


问:
tracking e-mail
Is it possible to track an email sent from a proxy site.? sent from a gmail account.can anyone provide a suitable link on how to trace the original ip of that email. or any relevant details as such. ??</p>

答:
You want to look in the email header.  This link should help you out.

http://www.online-tech-tips.com/computer-tips/how-to-track-the-original-location-of-an-email-via-its-ip-address/

Title: tracking e-mail


问:
How to find date periods between 2 dates?
I have 2 dates one is stored inside my date and for other date I am using calculated column in order to store the end date into that, how an I calculate the difference in time period between those dates, I need the date period between all those dates is that possible with DAX?

How can I use calculated column inside my DAX and also I dont have a calender table inside my database.

2019-05-31 and end date is 2019-06-03 then the difference will give me 3 dates that is 2019-05-31,2019-06-01 2019-06-02 and 2019-06-03

答:
Totally possible and easy. If you just need the difference between dates in two columns you can create a calculated column using the following: </p>

```<code>DateDiff =
DATEDIFF ( 'Table'[Date1], 'Table'[Date2], DAY )
</code>```

<p>This will take the difference between Date1 and Date2 in days. </p>

Body:
Totally possible and easy. If you just need the difference between dates in two columns you can create a calculated column using the following:

DateDiff =
DATEDIFF ( 'Table'[Date1], 'Table'[Date2], DAY )

This will take the difference between Date1 and Date2 in days.