问:
XGboost: cannot pass validation data for eval_set in pipeline
I want to implement GridSearchCV for XGboost model in pipeline. I have preprocessor for data, defined above the code, some grid params

```<code>XGBmodel = XGBRegressor(random_state=0)
pipe = Pipeline(steps=[
    ('preprocess', preprocessor),
    ('XGBmodel', XGBmodel)
])
</code>```

And I want to pass these fit params

```<code>fit_params = {"XGBmodel__eval_set": [(X_valid, y_valid)],
              "XGBmodel__early_stopping_rounds": 10,
              "XGBmodel__verbose": False}
</code>```

I am trying to fit model

```<code>searchCV = GridSearchCV(pipe, cv=5, param_grid=param_grid, fit_params=fit_params)
searchCV.fit(X_train, y_train)
</code>```

but I get error on the line with eval_set: DataFrame.dtypes for data must be int, float or bool

I guess it is because validation data aren't going through the preprocessing, but when I google I find that everywhere it is done by this way and seems it should work.
Also I tried to find a way to apply preprocessor for validation data separately, but it is not possible to transform validation data without fitting train data before it.

Full code

```<code>columns = num_cols + cat_cols
X_train = X_full_train[columns].copy()
X_valid = X_full_valid[columns].copy()

num_preprocessor = SimpleImputer(strategy = 'mean')
cat_preprocessor = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy = 'most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

preprocessor = ColumnTransformer(transformers=[
    ('num', num_preprocessor, num_cols),
    ('cat', cat_preprocessor, cat_cols)
])

XGBmodel = XGBRegressor(random_state=0)
pipe = Pipeline(steps=[
    ('preprocess', preprocessor),
    ('XGBmodel', XGBmodel)
])

param_grid = {
    "XGBmodel__n_estimators": [10, 50, 100, 500],
    "XGBmodel__learning_rate": [0.1, 0.5, 1],
}

fit_params = {"XGBmodel__eval_set": [(X_valid, y_valid)],
              "XGBmodel__early_stopping_rounds": 10,
              "XGBmodel__verbose": False}

searchCV = GridSearchCV(pipe, cv=5, param_grid=param_grid, fit_params=fit_params)
searchCV.fit(X_train, y_train)
</code>```

Is there any way to preprocess validation data in pipeline? Or maybe completely different way to implement this thing?

答:
There is no good way. If you have a long pipeline of transformers before fitting a model, then you can consider to fit those in the pipeline and then apply the model separately.

The underlying issue is that a pipeline has no notion of a validation set used in the model fitting. You can see a discussion on LightGBM github here. Their proposal is to pre-train transformers and apply those to the validation data before you fit the full pipeline. This can be fine, if you use fast transformers, but can double CPU time in an extreme scenario.

Body:
I want to implement GridSearchCV for XGboost model in pipeline. I have preprocessor for data, defined above the code, some grid params

XGBmodel = XGBRegressor(random_state=0)
pipe = Pipeline(steps=[
    ('preprocess', preprocessor),
    ('XGBmodel', XGBmodel)
])

And I want to pass these fit params

fit_params = {"XGBmodel__eval_set": [(X_valid, y_valid)],
              "XGBmodel__early_stopping_rounds": 10,
              "XGBmodel__verbose": False}

I am trying to fit model

searchCV = GridSearchCV(pipe, cv=5, param_grid=param_grid, fit_params=fit_params)
searchCV.fit(X_train, y_train)

but I get error on the line with eval_set: DataFrame.dtypes for data must be int, float or bool

I guess it is because validation data aren't going through the preprocessing, but when I google I find that everywhere it is done by this way and seems it should work.
Also I tried to find a way to apply preprocessor for validation data separately, but it is not possible to transform validation data without fitting train data before it.

Full code

columns = num_cols + cat_cols
X_train = X_full_train[columns].copy()
X_valid = X_full_valid[columns].copy()

num_preprocessor = SimpleImputer(strategy = 'mean')
cat_preprocessor = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy = 'most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

preprocessor = ColumnTransformer(transformers=[
    ('num', num_preprocessor, num_cols),
    ('cat', cat_preprocessor, cat_cols)
])

XGBmodel = XGBRegressor(random_state=0)
pipe = Pipeline(steps=[
    ('preprocess', preprocessor),
    ('XGBmodel', XGBmodel)
])

param_grid = {
    "XGBmodel__n_estimators": [10, 50, 100, 500],
    "XGBmodel__learning_rate": [0.1, 0.5, 1],
}

fit_params = {"XGBmodel__eval_set": [(X_valid, y_valid)],
              "XGBmodel__early_stopping_rounds": 10,
              "XGBmodel__verbose": False}

searchCV = GridSearchCV(pipe, cv=5, param_grid=param_grid, fit_params=fit_params)
searchCV.fit(X_train, y_train)

Is there any way to preprocess validation data in pipeline? Or maybe completely different way to implement this thing?


来源: stackexchange

问:
How can I get specific object key in map iteration
I have one json file and I iterate it with map but I have a deep object key with name 'content' and  I want to get specific key from it when I return my json array with map

JSON:

```<code>{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}
</code>```

My javascript code:

```<code>getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts)
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title,
       link: item.link,
       image: item.content._url,
       // and here I try get _url
       id: item.guide,

    }

}
</code>```

答:
Try </p>

```<code>return {
   title: item.title,
   link: item.link,
   image: item['content']['_url'],
   id: item.guide,
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have one json file and I iterate it with map but I have a deep object key with name 'content' and  I want to get specific key from it when I return my json array with map

JSON:

{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}

My javascript code:

getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts)
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title,
       link: item.link,
       image: item.content._url,
       // and here I try get _url
       id: item.guide,

    }

}

Body:
Try

return {
   title: item.title,
   link: item.link,
   image: item['content']['_url'],
   id: item.guide,
}


问:
Remove Line If It Contains Exact String From Line Of Another File
I have a large file and would like to remove any lines from the file that contain an exact string listed in another file. However, the string must match exactly (I'm sorry I don't know how to describe this better).

Here is the file:

```<code>one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

And here is the example list to filter with:

```<code>one@email.com
three@email.com
</code>```

The desired output is:

```<code>two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

I have tried to do this using the following:

```<code>grep -v -f 2.txt 1.txt > 3.txt
</code>```

However this produces the output:

```<code>two@email.com,name,surname,city,state
</code>```

I assume it's doing this because "anotherone@email.com" contains "one@email.com". I've searched for a way to include beginning of the line, but not found anything suitable.

I'm open to doing in something other than grep too, I used grep because I couldn't figure it out any other way.

答:
Assuming that your input file contains three@gmail.com not three@email.com (typo perhaps)

```<code>$ grep -vw -f 2.txt 1.txt
two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

-w, --word-regexp -
               The expression is searched for as a word (as if surrounded by [[:<:]]' and[[:>:]]';

Body:
I have a large file and would like to remove any lines from the file that contain an exact string listed in another file. However, the string must match exactly (I'm sorry I don't know how to describe this better).

Here is the file:

one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

And here is the example list to filter with:

one@email.com
three@email.com

The desired output is:

two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

I have tried to do this using the following:

grep -v -f 2.txt 1.txt > 3.txt

However this produces the output:

two@email.com,name,surname,city,state

I assume it's doing this because "anotherone@email.com" contains "one@email.com". I've searched for a way to include beginning of the line, but not found anything suitable.

I'm open to doing in something other than grep too, I used grep because I couldn't figure it out any other way.

Body:
Assuming that your input file contains three@gmail.com not three@email.com (typo perhaps)

$ grep -vw -f 2.txt 1.txt
two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

-w, --word-regexp -
               The expression is searched for as a word (as if surrounded by [[:<:]]' and[[:>:]]';


问:
Copy information from Sheet2 to Sheet1
I have two sheets (sheet1 / Sheet2).  Sheet2 contains random numbers where one random is selected and I would that last number generated to be copied to last row in Sheet1 Column I

I have tried various code

```<code>Sub passpop()

    Dim v As Variant
    Dim strPassword As String

    With Worksheets("Sheet2")
        v = .Cells(.Rows.Count, "A").End(xlUp).Value
            .Cells(.Rows.Count, "A").End(xlUp).Cut .Cells(.Rows.Count, "B").End(xlUp)(2)
    End With

    With Worksheets("Sheet1")
        Sheet1.Range("I13:I13") = v
    End With

End Sub
</code>```

答:
Two way to copy paste:</p>

```<code>Option Explicit

Sub Paste()

    'Copy Paste with value and formatting
    Sheet1.Range("A1").Copy Sheet2.Range("A1")

    'Copy Paste only value
    Sheet1.Range("A2").Copy
    Sheet2.Range("A2").PasteSpecial Paste:=xlPasteValues

End Sub
</code>```

Title: Copy information from Sheet2 to Sheet1

Body:
I have two sheets (sheet1 / Sheet2).  Sheet2 contains random numbers where one random is selected and I would that last number generated to be copied to last row in Sheet1 Column I

I have tried various code

Sub passpop()

    Dim v As Variant
    Dim strPassword As String

    With Worksheets("Sheet2")
        v = .Cells(.Rows.Count, "A").End(xlUp).Value
            .Cells(.Rows.Count, "A").End(xlUp).Cut .Cells(.Rows.Count, "B").End(xlUp)(2)
    End With

    With Worksheets("Sheet1")
        Sheet1.Range("I13:I13") = v
    End With

End Sub

Body:
Two way to copy paste:

Option Explicit

Sub Paste()

    'Copy Paste with value and formatting
    Sheet1.Range("A1").Copy Sheet2.Range("A1")

    'Copy Paste only value
    Sheet1.Range("A2").Copy
    Sheet2.Range("A2").PasteSpecial Paste:=xlPasteValues

End Sub


答:
I do not know, if my solution will be helpful, because it is brute force one. However, have a look.

The main idea is to split dataframe to smaller ones, based on the combination of customer_id and account_id. After that you fill values in the smaller dataframes (by your algorithm being described above). In the end, you merge them as filled.

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

# make df, as you have written above
df = pd.DataFrame(
    {'customer_id':[1,1,1,1,1,1,2,2,2,2,2,2],
     'account_id':[1,1,1,2,2,2,1,1,1,2,2,2],
     'date':['01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019',
             '01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019'],
     'amount':[np.NAN,np.NAN,100, np.NAN,200,np.NAN, np.NAN,300,np.NAN, 400, np.NAN,np.NAN],
     'transaction':[10,-20,30,10,-20,30,10,-20,30,10,-20,30]})

# make a new identifier (combination of customer_id and acount_id)
def get_cid_aid_combination(row):
    cid = row['customer_id']
    aid = row['account_id']
    return f'{cid}-{aid}'

df['cid_aid'] = df.apply(lambda row: get_cid_aid_combination(row), axis=1)

# fill it up
list_with_dfs = []

for cid_aid in df.cid_aid.unique():
    df_part = df[df['cid_aid']==cid_aid]
    cnt = 0
    while cnt < len(df_part):
        for i, amount, trans in zip(df_part.index, df_part.amount, df_part.transaction):
            if pd.isnull(amount) and i+1 in df_part.index:
                if pd.notnull(df_part.loc[i+1, 'amount']):
                    df_part.loc[i, 'amount'] = df_part.loc[i+1, 'amount'] - df_part.loc[i+1, 'transaction']
            if pd.isnull(amount) and i-1 in df_part.index:
                if pd.notnull(df_part.loc[i-1, 'amount']):
                    df_part.loc[i, 'amount'] = df_part.loc[i-1, 'amount'] + df_part.loc[i, 'transaction']

        cnt += 1
    list_with_dfs.append(df_part)

# make a df with filled amount feature
df = pd.concat(list_with_dfs)
</code>```

Title: how to fill NA with value in other rows in python

Body:
I have a table like this :

 df =   pd.DataFrame({'customer_id':[1,1,1,1,1,1,2,2,2,2,2,2],
                   'account_id':[1,1,1,2,2,2,1,1,1,2,2,2],
                   'date':['01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019'],
                   'amount':[np.NAN,np.NAN,100, np.NAN,200,np.NAN, np.NAN,300,np.NAN, 400, np.NAN,np.NAN],
                   'transaction':[10,-20,30,10,-20,30,10,-20,30,10,-20,30]})
    print(df.head(5))
        customer_id account_id  date    amount  transaction
    0   1   1   01/01/2019  NaN 10
    1   1   1   01/02/2019  NaN -20
    2   1   1   01/03/2019  100.0   30
    3   1   2   01/01/2019  NaN 10
    4   1   2   01/02/2019  200.0   -20

The Amount is the sum total at the end of a given day, and the transaction is the daily transaction amount.
The problem here is that not every account has balance or transaction. I need find a way to deal with accounts with only transaction

I want to fillna in amount_x using this logic:

For each financial_account_id if the amount_x is NA

then check if next row's value is NA or not.

For example, here for for customer_id 1 and account_id 1, on 01/02/2019 the amount should be 01/03/2019's 100-30=70, and on 01/01/2019 the amount should be01/02/2019's 70-(-20)=90
The ideal output should be:

df = pd.DataFrame({'customer_id':[1,1,1,1,1,1,2,2,2,2,2,2],
                   'account_id':[1,1,1,2,2,2,1,1,1,2,2,2],
                   'date':['01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019'],
                   'amount':[90,70,100, 220,200,230, 320,300,330, 400, 380,410],
                   'transaction':[10,-20,30,10,-20,30,10,-20,30,10,-20,30]})
    print(df.head(5))
        customer_id account_id  date    amount  transaction
    0   1   1   01/01/2019  90  10
    1   1   1   01/02/2019  70  -20
    2   1   1   01/03/2019  100 30
    3   1   2   01/01/2019  220 10
    4   1   2   01/02/2019  200 -20

Body:
I do not know, if my solution will be helpful, because it is brute force one. However, have a look.

The main idea is to split dataframe to smaller ones, based on the combination of customer_id and account_id. After that you fill values in the smaller dataframes (by your algorithm being described above). In the end, you merge them as filled.

# imports
import pandas as pd
import numpy as np

# make df, as you have written above
df = pd.DataFrame(
    {'customer_id':[1,1,1,1,1,1,2,2,2,2,2,2],
     'account_id':[1,1,1,2,2,2,1,1,1,2,2,2],
     'date':['01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019',
             '01/01/2019','01/02/2019','01/03/2019','01/01/2019','01/02/2019','01/03/2019'],
     'amount':[np.NAN,np.NAN,100, np.NAN,200,np.NAN, np.NAN,300,np.NAN, 400, np.NAN,np.NAN],
     'transaction':[10,-20,30,10,-20,30,10,-20,30,10,-20,30]})

# make a new identifier (combination of customer_id and acount_id)
def get_cid_aid_combination(row):
    cid = row['customer_id']
    aid = row['account_id']
    return f'{cid}-{aid}'

df['cid_aid'] = df.apply(lambda row: get_cid_aid_combination(row), axis=1)

# fill it up
list_with_dfs = []

for cid_aid in df.cid_aid.unique():
    df_part = df[df['cid_aid']==cid_aid]
    cnt = 0
    while cnt < len(df_part):
        for i, amount, trans in zip(df_part.index, df_part.amount, df_part.transaction):
            if pd.isnull(amount) and i+1 in df_part.index:
                if pd.notnull(df_part.loc[i+1, 'amount']):
                    df_part.loc[i, 'amount'] = df_part.loc[i+1, 'amount'] - df_part.loc[i+1, 'transaction']
            if pd.isnull(amount) and i-1 in df_part.index:
                if pd.notnull(df_part.loc[i-1, 'amount']):
                    df_part.loc[i, 'amount'] = df_part.loc[i-1, 'amount'] + df_part.loc[i, 'transaction']

        cnt += 1
    list_with_dfs.append(df_part)

# make a df with filled amount feature
df = pd.concat(list_with_dfs)


问:
Many calculated columns based on other columns
I have a data frame where I want to create new calculated columns based on other:

```<code>dat <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-15",
                  "2017-02-05","2018-05-23", "2018-02-22"),
                  var1 = c(1,3,6,7,8,5), var2 = c(1,3,18,15,25,5),
                  var3= c(8, 4,6, 5, 5,4), var4 = c(8, 4,6, 5, 5,3))
</code>```

Now I want to create a data frame with this results.

```<code>dat$var5 = dat$var1 + dat$var2
dat$var6 = dat$var3 + dat$var4
</code>```

But in a fast way

答:
We can use split.default to split the data frame every other column, and use Reduce to add them, i.e.

```<code>Reduce(`+`, split.default(dat[-1], c(TRUE, FALSE)))
#  var2 var4
#1    2   16
#2    6    8
#3   24   12
#4   22   10
#5   33   10
#6   10    7
</code>```

Body:
I have a data frame where I want to create new calculated columns based on other:

dat <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-15",
                  "2017-02-05","2018-05-23", "2018-02-22"),
                  var1 = c(1,3,6,7,8,5), var2 = c(1,3,18,15,25,5),
                  var3= c(8, 4,6, 5, 5,4), var4 = c(8, 4,6, 5, 5,3))

Now I want to create a data frame with this results.

dat$var5 = dat$var1 + dat$var2
dat$var6 = dat$var3 + dat$var4

But in a fast way

Body:
We can use split.default to split the data frame every other column, and use Reduce to add them, i.e.

Reduce(`+`, split.default(dat[-1], c(TRUE, FALSE)))
#  var2 var4
#1    2   16
#2    6    8
#3   24   12
#4   22   10
#5   33   10
#6   10    7


问:
Lexical Scope in JavaScript
I am slightly confused as to how exactly scope works in JavaScript, mainly lexical scope. I understand that variables in global scope are accessible anywhere, and the only way to create a new scope in JavaScript is through the creation of functions (or with let in ES6). However, I do not really understand what lexical scope is/means. I have looked all over the internet and could not find a clear explanation.

I feel like I am kind of starting to understand it, but just let me confirm with you JavaScript wizards out there to make sure that I am correct.

So, from my understanding, lexical scope means statically scoped, so for example, a function's scope is not created by where it is called but by where the function itself is created. The following code below demonstrates this concept:

```<code>var x = "global";

function foo() {
   console.log(x);
}

function bar() {
   var x = "bar";
   foo();
}

function baz() {
   var x = "baz";
   foo();
}

bar();
baz();
</code>```

What is printed to the console is "global" twice. This is because when the function foo is invoked, the interpreter first checks foo's scope to see if it has a variable "x" then checks the global scope, not bar or baz scope. The variable "x" is grabbed, not from where the function foo is called, but from where it is created, hence lexically scoped. Am I correct, and is this making sense?

Another example of lexical scope would be closures, right? So for example, the inner function has access to the outer function's variables, no matter where the inner function is called because of lexical scope, correct?

Finally, my last example would be arrow functions. They allow for the lexical scoping of "this", right? So, for example,

```<code>   var obj = {
       name: "Rob",
       print() {
       setTimeout(() => {
         console.log(this.name)
       }, 1000);
     }
   };
</code>```

Rather than "this" being bound to the global object if it were a standard inline function, "this" is bound to obj because of the lexical scoping of "this" with arrow functions.

Is everything I have said correct? Also, can someone just give me a clear-cut definition of lexical scope? Are there any other examples of lexical scope in JavaScript that I should know about?

Thanks.

答:
To understand the lexical scope you need to have a basic understanding of the scope. In javascript, we have classified scope in three types

Function scope

Block Scope

Lexical Scope

Function Scope -> The variables defined inside the function are considered in function scope.the var keyword is used to define the variable in the function scope.

Block scope -> The variables defined in the area within if,switch condition,for,and while loops.
whenever you see '{}' curly braces, its a block. In Es6 const and let keywords allow developers to declare a variable in the block scope. which means those variables exist only within the corresponding block.

```<code>   function animal(){
    if(true){
        var animal1 = "cat";
        const animal2 = "dog";
        let animal3 = "rat";
    }
    console.log(animal1);
    console,log(animal2); //animal2 is not defiend
    console,log(animal3); //animal3 is not defiend
}
animal();
</code>```

result

cat

animal2 is not defined

animal3 is not defined

Lexical scope-> In 1 line I want to say "children scope have access to the variable in parent scope"
`

```<code>var outerFunction = function()
{
    if(true){
        var x = 5;
        const y = 10;
    }

    var innerFunction = function(){
        if(true){
            alert(x);
            //alert(y);   //y is not defiend on line 13

        }
    }
    innerFunction();
}
 outerFunction();
 //console.log(x); // x is not defiend on line 20
</code>```

`.
The scope of a variable is defined by their position in the source code.
In order to resolve variable javascript starts at the innermost scope and searches outward until it finds the variable it was looking for.
lexical scoping is nice because we can easily figure out what the value of a variable will be by looking at the code; whereas in dynamic scoping the meaning of a variable can change at runtime by making it more difficult

ContentLicense: CC BY-SA 3.0

Title: Lexical Scope in JavaScript

Body:
I am slightly confused as to how exactly scope works in JavaScript, mainly lexical scope. I understand that variables in global scope are accessible anywhere, and the only way to create a new scope in JavaScript is through the creation of functions (or with let in ES6). However, I do not really understand what lexical scope is/means. I have looked all over the internet and could not find a clear explanation.

I feel like I am kind of starting to understand it, but just let me confirm with you JavaScript wizards out there to make sure that I am correct.

So, from my understanding, lexical scope means statically scoped, so for example, a function's scope is not created by where it is called but by where the function itself is created. The following code below demonstrates this concept:

var x = "global";

function foo() {
   console.log(x);
}

function bar() {
   var x = "bar";
   foo();
}

function baz() {
   var x = "baz";
   foo();
}

bar();
baz();

What is printed to the console is "global" twice. This is because when the function foo is invoked, the interpreter first checks foo's scope to see if it has a variable "x" then checks the global scope, not bar or baz scope. The variable "x" is grabbed, not from where the function foo is called, but from where it is created, hence lexically scoped. Am I correct, and is this making sense?

Another example of lexical scope would be closures, right? So for example, the inner function has access to the outer function's variables, no matter where the inner function is called because of lexical scope, correct?

Finally, my last example would be arrow functions. They allow for the lexical scoping of "this", right? So, for example,

   var obj = {
       name: "Rob",
       print() {
       setTimeout(() => {
         console.log(this.name)
       }, 1000);
     }
   };

Rather than "this" being bound to the global object if it were a standard inline function, "this" is bound to obj because of the lexical scoping of "this" with arrow functions.

Is everything I have said correct? Also, can someone just give me a clear-cut definition of lexical scope? Are there any other examples of lexical scope in JavaScript that I should know about?

Thanks.

Body:
To understand the lexical scope you need to have a basic understanding of the scope. In javascript, we have classified scope in three types

Function scope

Block Scope

Lexical Scope

Function Scope -> The variables defined inside the function are considered in function scope.the var keyword is used to define the variable in the function scope.

Block scope -> The variables defined in the area within if,switch condition,for,and while loops.
whenever you see '{}' curly braces, its a block. In Es6 const and let keywords allow developers to declare a variable in the block scope. which means those variables exist only within the corresponding block.

   function animal(){
    if(true){
        var animal1 = "cat";
        const animal2 = "dog";
        let animal3 = "rat";
    }
    console.log(animal1);
    console,log(animal2); //animal2 is not defiend
    console,log(animal3); //animal3 is not defiend
}
animal();

result

cat

animal2 is not defined

animal3 is not defined

Lexical scope-> In 1 line I want to say "children scope have access to the variable in parent scope"
`

var outerFunction = function()
{
    if(true){
        var x = 5;
        const y = 10;
    }

    var innerFunction = function(){
        if(true){
            alert(x);
            //alert(y);   //y is not defiend on line 13

        }
    }
    innerFunction();
}
 outerFunction();
 //console.log(x); // x is not defiend on line 20

`.
The scope of a variable is defined by their position in the source code.
In order to resolve variable javascript starts at the innermost scope and searches outward until it finds the variable it was looking for.
lexical scoping is nice because we can easily figure out what the value of a variable will be by looking at the code; whereas in dynamic scoping the meaning of a variable can change at runtime by making it more difficult


问:
Iterating over substrings of equal size
I want to convert my String object to Enumerable of its 1-sized substrings (not chars), how can I do this efficiently in Ruby?</p>

答:
Maybe I don't understand your question, but there's no difference between a character and a string of 1 character in Ruby.</p>

```<code>'hello world'.each_char {|c| puts "substring is #{c}"}
</code>```

OwnerDisplayName: Dmitriy Matveev

ContentLicense: CC BY-SA 2.5

Title: Iterating over substrings of equal size

Body:
Maybe I don't understand your question, but there's no difference between a character and a string of 1 character in Ruby.

'hello world'.each_char {|c| puts "substring is #{c}"}

OwnerDisplayName: Chuck


问:
Keeping track of boolean data
I need to keep track of n samples. The information I am keeping track of is of boolean type, i.e. something is true or false. As soon as I am on sample n+1, i basically want to ignore the oldest sample and record information about the newest one.

So say I keep track of samples, I may have something like

OLDEST 0   0   1   1  0   NEWEST

If the next sample is 1, this will become

OLDEST 0   1   1   0  1   NEWEST

if the next one is 0, this will become...

OLDEST 1   1   0   1  0   NEWEST

So what is the best way to implement this in terms of simplicity and memory?

Some ideas I had:

Vector of bool (this would require shifting elements so seems expensive)
    Storing it as bits...and using bit shifting (memorywise --cheap? but is there a limit on the number of samples?)
    Linked lists? (might be an overkill for the task)

Thanks for the ideas and suggestions :)

答:
Sounds like a perfect use of a ring buffer. Unfortunately there isn't one in the standard library, but you could use boost.

Alternately roll your own using a fixed-length std::list and splice the head node to the tail when you need to overwrite an old element.

Title: Keeping track of boolean data


问:
Determine if Unity Remote is being used?
Is there a way to check if Unity Remote is being used in the editor? This doesn't seem to be working with Unity Remote 5?</p>

答:
It appears that UnityRemote has a small delay before running your application, and UnityEditor.EditorApplication.isRemoteConnected is only true once it has detected that your application is successfully running on your device.

Initially I was checking whether a handheld device was connected in the Awake function, but because my application had not yet successfully started running on my device yet, it displayed as false.

The fix was therefore to instead test for this in the Update function.


问:
Jenkins Pipeline Copy Artifact to Local tomcat instance
Using Jenkins pipeline I am not able to copy artifact to a local tomcat instance

I tried using CopyArtifact provided by JenkinsPipeline

Syntax: copyArtifacts(projectName: 'sourceproject'); - but it is not working

```<code>stage('Deploy to Tomcat Server'){
      copyArtifacts /Users/web/.jenkins/workspace/app/target/myweb-0.0.5.war /Users/web/apache-tomcat-9.0.16/webapps/
   }

Not able to copy artifact to tomcat webapps directory

Error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 32: unexpected token: . @ line 32, column 33.
         copyArtifacts Users/web/.jenkins/workspace/app/target/myweb-0.0.5.war /Users/web/apache-tomcat-9.0.16/webapps/
</code>```

答:
The correct syntax would be (please refer to documentation)</p>

```<code>stage('Deploy to Tomcat Server') {
    copyArtifacts('project_name') {
        includePatterns('*.xml', '*.properties')
        excludePatterns('test.xml', 'test.properties')
        targetDirectory('files')
        flatten()
        optional()
        buildSelector {
            latestSuccessful(true)
        }
    }
}
</code>```

Body:
Using Jenkins pipeline I am not able to copy artifact to a local tomcat instance

I tried using CopyArtifact provided by JenkinsPipeline

Syntax: copyArtifacts(projectName: 'sourceproject'); - but it is not working

stage('Deploy to Tomcat Server'){
      copyArtifacts /Users/web/.jenkins/workspace/app/target/myweb-0.0.5.war /Users/web/apache-tomcat-9.0.16/webapps/
   }

Not able to copy artifact to tomcat webapps directory

Error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 32: unexpected token: . @ line 32, column 33.
         copyArtifacts Users/web/.jenkins/workspace/app/target/myweb-0.0.5.war /Users/web/apache-tomcat-9.0.16/webapps/

Body:
The correct syntax would be (please refer to documentation)

stage('Deploy to Tomcat Server') {
    copyArtifacts('project_name') {
        includePatterns('*.xml', '*.properties')
        excludePatterns('test.xml', 'test.properties')
        targetDirectory('files')
        flatten()
        optional()
        buildSelector {
            latestSuccessful(true)
        }
    }
}


问:
Using @ComponentScan or <context:component-scan /> with only one class
I'm maintaining a project with two set of main packages, the project is using Spring and Spring MVC, one of these packages contains several controllers and is scanned using XML configuration (<context:component-scan />).

The problem is that there is a single class in the other package (not scanned), and I need this class to be scanned, but only this class and nothing else in the package. I can't change its package now since it would be too risky now.

So is there a way to do this using annotations or XML ?

答:
In addition to the method described by Emerson Farrugia there is a less verbose solution which has been supported since Spring Framework 4.2 as mentioned in the documentation here.

As of Spring Framework 4.2, @Import also supports references regular
  component classes, analogous to the
  AnnotationConfigApplicationContext.register method. This is
  particularly useful if you want to avoid component scanning, by using
  a few configuration classes as entry points to explicitly define all
  your components.

So your example would simply become:

```<code>@Import(YourClass.class)
</code>```

Body:
In addition to the method described by Emerson Farrugia there is a less verbose solution which has been supported since Spring Framework 4.2 as mentioned in the documentation here.

As of Spring Framework 4.2, @Import also supports references regular
  component classes, analogous to the
  AnnotationConfigApplicationContext.register method. This is
  particularly useful if you want to avoid component scanning, by using
  a few configuration classes as entry points to explicitly define all
  your components.

So your example would simply become:

@Import(YourClass.class)


问:
How to toggle current 'active' class of div and remove 'active' class of sibling divs in ng-repeat
I have following code. I want to toggle the 'active' class of current div when it is clicked and remove the 'active' class of sibling divs. I used ng-repeat

```<code><div class="" ng-repeat="data in people">
<p>{{data.name}}</p>
</div>
</code>```

Controller

```<code>$scope.people=[{
"name" : "john snow"
},
{
"name" : "daenerys"
}]
</code>```

答:
You can achieve this using the ng-class directive.

You need to track the index of the last selected value and update the selected value using setActive(). Call setActive() from your HTML on click and pass the index of the object.

Here is a working snippet

var app = angular.module("app", []);

app.controller("myCtrl", ["$scope", ($scope) => {
  $scope.people=[{
    "name" : "john snow"
  },
  {
    "name" : "daenerys"
  },
  {
    "name": "stark"
  }];

  $scope.selected = null;

  $scope.toggleStatus = (index) => {
      $scope.selected = $scope.selected !== index ? index : null;
  }
}]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  background-color: yellow;
  // enter active class css here
}</code>```

        {{data.name}}

```

Check out the documentation of ngClass for more information here: https://docs.angularjs.org/api/ng/directive/ngClass

Body:
I have following code. I want to toggle the 'active' class of current div when it is clicked and remove the 'active' class of sibling divs. I used ng-repeat

{{data.name}}

Controller

$scope.people=[{
"name" : "john snow"
},
{
"name" : "daenerys"
}]

Body:
You can achieve this using the ng-class directive.

You need to track the index of the last selected value and update the selected value using setActive(). Call setActive() from your HTML on click and pass the index of the object.

Here is a working snippet

var app = angular.module("app", []);

app.controller("myCtrl", ["$scope", ($scope) => {
  $scope.people=[{
    "name" : "john snow"
  },
  {
    "name" : "daenerys"
  },
  {
    "name": "stark"
  }];

  $scope.selected = null;

  $scope.toggleStatus = (index) => {
      $scope.selected = $scope.selected !== index ? index : null;
  }
}]);

.active {
  background-color: yellow;
  // enter active class css here
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <div ng-repeat="data in people">
      <p ng-class="{active: selected === $index}" ng-click="toggleStatus($index)">
        {{data.name}}
      </p>
  </div>
</div>

Check out the documentation of ngClass for more information here: https://docs.angularjs.org/api/ng/directive/ngClass


问:
Sending commands via I2C to PIC16F1503 using Windows 10 IoT Core
Scenario

I want to communicate with a PIC16F1503 controller using C# while running as an UWP app on a Raspberry Pi using Windows 10 IoT Core.

It seems that my source detects the controller using I2cDevice.FromIdAsync(...). But if I try to send the "Servo1" command 0x01 via:

```<code>pic16f1503.Write(new byte[] { COMMANDO_SERVO_1 });
pic16f1503.Write(data.ToArray());
</code>```

Nothing happens. I (hopefully) enabled the "Servo1" with:

```<code>private void WriteConfiguration()
{
    // Create configuration mask.
    byte config = 0;

    // Enable servo 1
    config |= 1;

    // Enable servo 2
    config |= 0 << 1;

    // Enable lights
     config |= 0 << 2;

     // Light mode
     config |= 0 << 3;

    // Light on
    config |= 0 << 4;

    // Write configuration to device.
    pic16f1503.Write(new byte[] { COMMAND_CONFIG});
    pic16f1503.Write(new byte[] { config });
}
</code>```

Full source

GitHub Gist

Does somebody know further tutorials or new "entry" points to get along with C# und this mc? Thanks!

答:
You send several bytes from Raspberry Pi to PIC16F1503 via I2C and I get them via debugging your code: 1, 1, 1, 1-43-7-0-0, 1.

But they seems not all match what you want to send actually because I found a problem in your WriteByte function like:

(You are trying to change a value-type variable: byte[] data. Refer to "Passing Parameters (C# Programming Guide)")

```<code>private void WriteByte(byte command, byte[] data)
{
    data.ToList().Insert(0, command);
    data.ToArray();
    pic16f1503.Write(data);
}
</code>```

I edit above function to this:

```<code>private void WriteByte(byte command, byte[] data)
{
    var sendData = data.ToList();
    sendData.Insert(0, command);
    pic16f1503.Write(sendData.ToArray());
}
</code>```

Then send datas: 0-1, 0-1, 1, 1-43-7-0-0, 0-1

Little issue when print the int array.

Edit this line: Debug.WriteLine($"PIC16F1503 - SetDegrees to {ms} start.\nData: {data}");

To this in order to print the right format data:

```<code>        Debug.WriteLine($"PIC16F1503 - SetDegrees to {ms} start.\n");
        Debug.WriteLine("Data: ");
        foreach (var element in data)
        {
            Debug.WriteLine(element);
        }
        Debug.WriteLine("\n");
</code>```

After that you will send right data to PIC16F1503. If still not working please check two devices I2C speed match or not. And hardware pins connection correct or not.

Body:
Scenario

I want to communicate with a PIC16F1503 controller using C# while running as an UWP app on a Raspberry Pi using Windows 10 IoT Core.

It seems that my source detects the controller using I2cDevice.FromIdAsync(...). But if I try to send the "Servo1" command 0x01 via:

pic16f1503.Write(new byte[] { COMMANDO_SERVO_1 });
pic16f1503.Write(data.ToArray());

Nothing happens. I (hopefully) enabled the "Servo1" with:

private void WriteConfiguration()
{
    // Create configuration mask.
    byte config = 0;

    // Enable servo 1
    config |= 1;

    // Enable servo 2
    config |= 0 << 1;

    // Enable lights
     config |= 0 << 2;

     // Light mode
     config |= 0 << 3;

    // Light on
    config |= 0 << 4;

    // Write configuration to device.
    pic16f1503.Write(new byte[] { COMMAND_CONFIG});
    pic16f1503.Write(new byte[] { config });
}

Full source

GitHub Gist

Does somebody know further tutorials or new "entry" points to get along with C# und this mc? Thanks!

Body:
You send several bytes from Raspberry Pi to PIC16F1503 via I2C and I get them via debugging your code: 1, 1, 1, 1-43-7-0-0, 1.

But they seems not all match what you want to send actually because I found a problem in your WriteByte function like:

(You are trying to change a value-type variable: byte[] data. Refer to "Passing Parameters (C# Programming Guide)")

private void WriteByte(byte command, byte[] data)
{
    data.ToList().Insert(0, command);
    data.ToArray();
    pic16f1503.Write(data);
}

I edit above function to this:

private void WriteByte(byte command, byte[] data)
{
    var sendData = data.ToList();
    sendData.Insert(0, command);
    pic16f1503.Write(sendData.ToArray());
}

Then send datas: 0-1, 0-1, 1, 1-43-7-0-0, 0-1

Little issue when print the int array.

Edit this line: Debug.WriteLine($"PIC16F1503 - SetDegrees to {ms} start.\nData: {data}");

To this in order to print the right format data:

        Debug.WriteLine($"PIC16F1503 - SetDegrees to {ms} start.\n");
        Debug.WriteLine("Data: ");
        foreach (var element in data)
        {
            Debug.WriteLine(element);
        }
        Debug.WriteLine("\n");

After that you will send right data to PIC16F1503. If still not working please check two devices I2C speed match or not. And hardware pins connection correct or not.


问:
git shows mysterious changes
I'm facing this issue constantly when working in a team. Every time I push changes, there are some changes that weren't made by me, and I can't seem to understand what has changed. I attached an example screenshot from Fork.

You can see there are tiny character highlighted at the end of line 64.
The file has LF line ending format, and I don't think it is mixing it with CRLF.

The team uses different OS and IDE's

Note: the highlighted character is not a space. I can't post the text here as it get reformatted by SO.

答:
I can be end of line spaces or new line characters.
For example, maybe they added (accidentally) spaces after the brackets and their editors don't automatically trim them, and yours might be configured to trim them, making them disappear, creating the changes.

You should really synchronize with your team to use the same editor settings (type of new lines characters, trimming end of lines and so on) to avoid situations like that.

Title: git shows mysterious changes


问:
Python logic to compare two files iteratively and build parent child relation
Could someone please help me with a simpler logic? I have been scratching my head for 2 days.

Problem: - I have two CSV files. Trying to establish a parent/child relationship until the relation gets exhausted b/w the two files.

Assume, both the files have 2 columns  A, B in 1st csv and C, D in second CSV.

"A" should be matched with "C" and for the matching rows [Inner Join], take the "D" and compare it with "B" [Again an inner join]. Then again, from the result, A should be matched against "C" till the relation or chain stops somewhere.

Basically, in my problem B is the child of D and B by itself might have another Child.

Not sure I am making it clear

Thanks for offering to help. I have created the dummy data.    Please see if it helps

Input data in two csv files as below

```<code>A   B            C    D
310 9000        310 8000
320 8000        320 2000
330 2000        330 1000
340 1000        350 2500
</code>```

Expected output in new file or dataframe:- Chain stops at 1000 as 340 doesn't have row in second csv.

Expected output data:-

```<code>    A   B    C   D    E   F
1. 310 8000 320 2000 330 1000
</code>```

答:
From my understanding, I think this is what you need:

```<code>df1

    A   B
0   310 9000
1   320 8000
2   330 2000

df2

     C  D
0   310 8000
1   320 2000
2   330 1000
</code>```

Merge the dfs:

```<code>merged_df = pd.merge(df1, df2, left_on = ['A'], right_on = ['C'])
merged_df
     A   B       C  D
0   310 9000    310 8000
1   320 8000    320 2000
2   330 2000    330 1000
</code>```

Assuming that D is child of B when B>D:

```<code>result = merged_df.loc[merged_df['B']>merged_df['D'],['C', 'D']].values.ravel()
result
array([ 310, 8000,  320, 2000,  330, 1000], dtype=int64)
</code>```

Convert them to a series:

```<code>pd.Series(result, index = list('ABCDEF'))
A     310
B    8000
C     320
D    2000
E     330
F    1000
</code>```

Body:
Could someone please help me with a simpler logic? I have been scratching my head for 2 days.

Problem: - I have two CSV files. Trying to establish a parent/child relationship until the relation gets exhausted b/w the two files.

Assume, both the files have 2 columns  A, B in 1st csv and C, D in second CSV.

"A" should be matched with "C" and for the matching rows [Inner Join], take the "D" and compare it with "B" [Again an inner join]. Then again, from the result, A should be matched against "C" till the relation or chain stops somewhere.

Basically, in my problem B is the child of D and B by itself might have another Child.

Not sure I am making it clear

Thanks for offering to help. I have created the dummy data.    Please see if it helps

Input data in two csv files as below

A   B            C    D
310 9000        310 8000
320 8000        320 2000
330 2000        330 1000
340 1000        350 2500

Expected output in new file or dataframe:- Chain stops at 1000 as 340 doesn't have row in second csv.

Expected output data:-

    A   B    C   D    E   F
1. 310 8000 320 2000 330 1000

Body:
From my understanding, I think this is what you need:

df1

    A   B
0   310 9000
1   320 8000
2   330 2000

df2

     C  D
0   310 8000
1   320 2000
2   330 1000

Merge the dfs:

merged_df = pd.merge(df1, df2, left_on = ['A'], right_on = ['C'])
merged_df
     A   B       C  D
0   310 9000    310 8000
1   320 8000    320 2000
2   330 2000    330 1000

Assuming that D is child of B when B>D:

result = merged_df.loc[merged_df['B']>merged_df['D'],['C', 'D']].values.ravel()
result
array([ 310, 8000,  320, 2000,  330, 1000], dtype=int64)

Convert them to a series:

pd.Series(result, index = list('ABCDEF'))
A     310
B    8000
C     320
D    2000
E     330
F    1000


问:
How to add initial value without edit initial value on Flutter?
I added initial value like this, But user can edit initial text. How to disable to edit initial value? But user can be able to add value with initial value?

```<code> var _myController = TextEditingController(text: "https://");
</code>```

Output should be like this

```<code>print(url);
</code>```

https://(user_type_value)

答:
You can try this logic, this way https:// will always be shown to the user, if user enters a url without https:// we are good, and if a user enters url with https:// we are again good.

```<code>Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    TextField(
      controller: _controller,
      decoration: InputDecoration(prefixText: "https://"),
    ),
    RaisedButton(
      child: Text("Submit"),
      onPressed: () {
        String text = _controller.text.toString();
        if (!text.contains("https://")) {
          text = "https://" + text;
        }
        // text here will always have https://
      },
    ),
  ],
),
</code>```

Body:
I added initial value like this, But user can edit initial text. How to disable to edit initial value? But user can be able to add value with initial value?

 var _myController = TextEditingController(text: "https://");

Output should be like this

print(url);

https://(user_type_value)

Body:
You can try this logic, this way https:// will always be shown to the user, if user enters a url without https:// we are good, and if a user enters url with https:// we are again good.

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    TextField(
      controller: _controller,
      decoration: InputDecoration(prefixText: "https://"),
    ),
    RaisedButton(
      child: Text("Submit"),
      onPressed: () {
        String text = _controller.text.toString();
        if (!text.contains("https://")) {
          text = "https://" + text;
        }
        // text here will always have https://
      },
    ),
  ],
),


问:
npm ERR! Failed at the fibers@3.1.1 install script

I'm getting this error

```<code>npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fibers@3.1.1 install: `node build.js || nodejs build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fibers@3.1.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yaeesh\AppData\Roaming\npm-cache\_logs\2019-05-07T10_36_05_651Z-debug.log
</code>```

答:
I had the same problem, and fixed it by removing my latest nodejs, 12.3.1, and installing the last version of 11

https://nodejs.org/download/release/v11.15.0/

Body:
I'm getting this error

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fibers@3.1.1 install: `node build.js || nodejs build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fibers@3.1.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yaeesh\AppData\Roaming\npm-cache\_logs\2019-05-07T10_36_05_651Z-debug.log


答:
If you only need 8 bits... then use a char and do logical shifts "<<, >>" and do a mask to look at the one you need.

16 Bits - short

32 Bits - int

64 Bits - long

etc...

Example:

Oldest 00110010 Newest -> Oldest 1001100101 Newest

Done by:

```<code>char c = 0x32; // 50 decimal or 00110010 in binary
c<<1; // Logical shift left once.
c++; // Add one, sense LSB is the newest.

//Now look at the 3rd newest bit
print("The 3rd newest bit is: %d\n", (c & 0x4));
</code>```

Simple and EXTREMELY cheap on resources. Will be VERY VERY high performance.

Title: Keeping track of boolean data

Body:
I need to keep track of n samples. The information I am keeping track of is of boolean type, i.e. something is true or false. As soon as I am on sample n+1, i basically want to ignore the oldest sample and record information about the newest one.

So say I keep track of samples, I may have something like

OLDEST 0   0   1   1  0   NEWEST

If the next sample is 1, this will become

OLDEST 0   1   1   0  1   NEWEST

if the next one is 0, this will become...

OLDEST 1   1   0   1  0   NEWEST

So what is the best way to implement this in terms of simplicity and memory?

Some ideas I had:

Vector of bool (this would require shifting elements so seems expensive)
    Storing it as bits...and using bit shifting (memorywise --cheap? but is there a limit on the number of samples?)
    Linked lists? (might be an overkill for the task)

Thanks for the ideas and suggestions :)

Body:
If you only need 8 bits... then use a char and do logical shifts "<<, >>" and do a mask to look at the one you need.

16 Bits - short

32 Bits - int

64 Bits - long

etc...

Example:

Oldest 00110010 Newest -> Oldest 1001100101 Newest

Done by:

char c = 0x32; // 50 decimal or 00110010 in binary
c<<1; // Logical shift left once.
c++; // Add one, sense LSB is the newest.

//Now look at the 3rd newest bit
print("The 3rd newest bit is: %d\n", (c & 0x4));

Simple and EXTREMELY cheap on resources. Will be VERY VERY high performance.


问:
Laravel /broadcasting/auth returns (302 found) and redirects to login page
I have a custom user App\Models\Client for which I want to broadcast notifications, Pusher works fine with public channels in my app but I can't get it to work with private channels.

So the problem is: /broadcasting/auth can't really authenticate the current user.

App\Providers\BroadcastServiceProvider.php:

```<code>public function boot()
{
    Broadcast::routes(['middleware' => ['auth:client']]);

    Broadcast::channel('App.Models.Client.{id}', function ($user, $id) {
        return true;
    });
}
</code>```

bootstrap.js:

```<code>window.Pusher = require('pusher-js');
import Echo from "laravel-echo";

Pusher.logToConsole = true;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '***********',
    cluster: 'us2',
    encrypted: true,

    //auth: {
    //    headers: {
    //        'X-CSRF-TOKEN': token.content // already set in the request by axios
    //    }
    //},
});

if (Laravel.clientId) {

    window.Echo.private(`App.Models.Client.${Laravel.clientId}`)
        .notification((notification) => {
            console.log(notification);
        });
}
</code>```

I'm using the normal Laravel session, so no auth:api middleware or Authorization header needed. the X-CSRF-TOKEN is included with the request.

/broadcasting/auth request/response screenshot here

Any help would be much appreciated!

答:
Laravel 5.8</p>

```<code>app/Providers/BroadcastServiceProvider.php
</code>```

```<code>public function boot()
{
   Broadcast::routes([ 'middleware' => [ 'web', 'isLoginFrontend']]);
   require base_path('routes/channels.php');
}
</code>```

```<code>routes/channels.php
</code>```

```<code>Broadcast::channel('messages.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['frontend']]);
</code>```

Body:
I have a custom user App\Models\Client for which I want to broadcast notifications, Pusher works fine with public channels in my app but I can't get it to work with private channels.

So the problem is: /broadcasting/auth can't really authenticate the current user.

App\Providers\BroadcastServiceProvider.php:

public function boot()
{
    Broadcast::routes(['middleware' => ['auth:client']]);

    Broadcast::channel('App.Models.Client.{id}', function ($user, $id) {
        return true;
    });
}

bootstrap.js:

window.Pusher = require('pusher-js');
import Echo from "laravel-echo";

Pusher.logToConsole = true;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '***********',
    cluster: 'us2',
    encrypted: true,

    //auth: {
    //    headers: {
    //        'X-CSRF-TOKEN': token.content // already set in the request by axios
    //    }
    //},
});

if (Laravel.clientId) {

    window.Echo.private(`App.Models.Client.${Laravel.clientId}`)
        .notification((notification) => {
            console.log(notification);
        });
}

I'm using the normal Laravel session, so no auth:api middleware or Authorization header needed. the X-CSRF-TOKEN is included with the request.

/broadcasting/auth request/response screenshot here

Any help would be much appreciated!

Body:
Laravel 5.8

app/Providers/BroadcastServiceProvider.php

public function boot()
{
   Broadcast::routes([ 'middleware' => [ 'web', 'isLoginFrontend']]);
   require base_path('routes/channels.php');
}

routes/channels.php

Broadcast::channel('messages.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['frontend']]);


问:
NoSuchFieldError when reading Excel sheet in java
I've followed a simple guide to constructing a workbook using Apache POI XSSF. Following the same guide I was able to WRITE an Excel sheet, however when attempting to read from one, I'm receiving the error displayed after the code.

Code:

```<code>try {
    FileInputStream file = new FileInputStream(new File("howtodoinjava_demo.xlsx"));

    // Create Workbook instance holding reference to .xlsx file
    XSSFWorkbook workbook = new XSSFWorkbook(file);

    // Get first/desired sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);

    // Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        // For each row, iterate through all the columns
        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            // Check the cell type and format accordingly
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "t");
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "t");
                break;
            }
        }
        System.out.println("");
    }
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Error output:

Exception in thread "main" java.lang.NoSuchFieldError:
  RAW_XML_FILE_HEADER   at
  org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:179)
    at
  org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:228)
    at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:93)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:294)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)    at
  org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:273)
    at com.wtolliver.spring.test.ReadExcel.readExcel(ReadExcel.java:18)
    at com.wtolliver.spring.test.App.main(App.java:17)

答:
For the following error "java.lang.NoSuchFieldError: RETURN_NULL_AND_BLANK"

Please perform following task: upgrade the APACHE POI 3.** to the latest version in my case i have done the following thing i was previously using the apache poi 3.09 later i have upgraded the lib to latest version i.e 3.12 and its work !!

Perform the following steps and your code will but make sure the error should be same.

Body:
I've followed a simple guide to constructing a workbook using Apache POI XSSF. Following the same guide I was able to WRITE an Excel sheet, however when attempting to read from one, I'm receiving the error displayed after the code.

Code:

try {
    FileInputStream file = new FileInputStream(new File("howtodoinjava_demo.xlsx"));

    // Create Workbook instance holding reference to .xlsx file
    XSSFWorkbook workbook = new XSSFWorkbook(file);

    // Get first/desired sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);

    // Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        // For each row, iterate through all the columns
        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            // Check the cell type and format accordingly
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "t");
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "t");
                break;
            }
        }
        System.out.println("");
    }
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Error output:

Exception in thread "main" java.lang.NoSuchFieldError:
  RAW_XML_FILE_HEADER   at
  org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:179)
    at
  org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:228)
    at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:93)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:294)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)    at
  org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:273)
    at com.wtolliver.spring.test.ReadExcel.readExcel(ReadExcel.java:18)
    at com.wtolliver.spring.test.App.main(App.java:17)


问:
Using semantic ui want to generate dynamic dropdown
Got a problem with semantic-ui dropdown. I've been using Semantic-Ui, and wanted to change the dropdown item dynamically. That is, when i choose the value from the first dropdown, the second dropdown's item is getting generated,but when I choose the value from second dropdown,the third dropdown and its item are not getting generated. </p>

```<code><script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>

<div class="ui selection dropdown select">
    <input type="hidden" name="programmetype">
    <div class="text">First dropdown</div>
    <i class="dropdown icon"></i>
    <div class="menu">
        <div class="item" data-value="val1">Car</div>
        <div class="item" data-value="val2">Tank</div>
        <div class="item" data-value="val3">Plane</div>
    </div>
</div>

<div id="servicetype"></div>
<script>
$(".select").dropdown({
    onChange: function() {
        $('.select').remove();
        $('#servicetype').addClass('ui selection dropdown select-language');

        $('#servicetype').html(
            '<input type="hidden" name="servicetype">'
            +'<div class="text">Second dropdown</div>'
            +'<i class="dropdown icon "></i>'
            +'<div class="menu">'
            +'<div class="item" data-value="acp">ACP</div>'
            +'<div class="item" data-value="art"> ART</div>'
            +'</div>'
            +'</div>'
        );
        $('#servicetype').dropdown();
        $(".select-language").dropdown({
            onChange: function() {
                $('.select-language').remove();
                $('#servicetype').addClass('ui selection dropdownselect');

                $('#servicetype').html(
                    '<input type="hidden" name="servicetype">'
                    +'<div class="text">Third dropdown</div>'
                    +'<i class="dropdown icon "></i>'
                    +'<div class="menu">'
                    +'<div class="item" data-value="acp">AC</div>'
                    +'<div class="item" data-value="art"> AR</div>'
                    +'</div>'
                    +'</div>'
                );
                $('#servicetype').dropdown();
            }
        });
    }
});
</script>
</code>```

答:
Deleted the standalone

 in the markup
and creating it on the fly

Chaining of the methods

addClass changed

Suggestion: You can create a function with a template literal containing all the dropdown markup and pass the values as arguments

$(".select").dropdown({
  onChange: function () {
    $(this).remove();
    $('body').append('

');
    $("#servicetype").addClass("ui selection dropdown select-language").html(
      "<input type='hidden' name='servicetype'>" +
      "
Second dropdown
" +
      "" +
      "
" +
      "
ACP
" +
      "
 ART
" +
      "
" +
      "
"
    ).dropdown();

    $(".select-language").dropdown({
      onChange: function () {
        $(this).remove();
        $('body').append('

');
        $("#servicetype").addClass("ui selection dropdown").html(
          "<input type='hidden' name='servicetype'>" +
          "
Third dropdown
" +
          "" +
          "
" +
          "
AC
" +
          "
 AR
" +
          "
" +
          "
"
        ).dropdown();
      }
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ui selection dropdown select">
  <input type="hidden" name="programmetype">
  <div class="text">First dropdown</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="val1">Car</div>
    <div class="item" data-value="val2">Tank</div>
    <div class="item" data-value="val3">Plane</div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script></code>```

Body:
Got a problem with semantic-ui dropdown. I've been using Semantic-Ui, and wanted to change the dropdown item dynamically. That is, when i choose the value from the first dropdown, the second dropdown's item is getting generated,but when I choose the value from second dropdown,the third dropdown and its item are not getting generated.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

    <input type="hidden" name="programmetype">

First dropdown

Car

Tank

Plane

Body:
Deleted the standalone <div id="servicetype"></div> in the markup
and creating it on the fly

Chaining of the methods

addClass changed

Suggestion: You can create a function with a template literal containing all the dropdown markup and pass the values as arguments

$(".select").dropdown({
  onChange: function () {
    $(this).remove();
    $('body').append('<div id="servicetype"></div>');
    $("#servicetype").addClass("ui selection dropdown select-language").html(
      "<input type='hidden' name='servicetype'>" +
      "<div class='text'>Second dropdown</div>" +
      "<i class='dropdown icon'></i>" +
      "<div class='menu'>" +
      "<div class='item' data-value='acp'>ACP</div>" +
      "<div class='item' data-value='art'> ART</div>" +
      "</div>" +
      "</div>"
    ).dropdown();

    $(".select-language").dropdown({
      onChange: function () {
        $(this).remove();
        $('body').append('<div id="servicetype"></div>');
        $("#servicetype").addClass("ui selection dropdown").html(
          "<input type='hidden' name='servicetype'>" +
          "<div class='text'>Third dropdown</div>" +
          "<i class='dropdown icon'></i>" +
          "<div class='menu'>" +
          "<div class='item' data-value='acp'>AC</div>" +
          "<div class='item' data-value='art'> AR</div>" +
          "</div>" +
          "</div>"
        ).dropdown();
      }
    });
  }
});

<div class="ui selection dropdown select">
  <input type="hidden" name="programmetype">
  <div class="text">First dropdown</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="val1">Car</div>
    <div class="item" data-value="val2">Tank</div>
    <div class="item" data-value="val3">Plane</div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>


问:
How to refactor method to replace OrganizationServiceProxy with IOrganizationService
I'm attempting to refactor my code so that I can unit test using fakexrmeasy.

As part of the suggested refactor mentioned here, I've attempted to pass IOrganizationService into all of my classes and methods. However, some of my classes use variables and methods that IOrganizationService doesn't have, such as Timeout. I'm trying to find a way to refactor to use IOrganizationService without losing functionality.

This is how it exists before refactoring.

```<code>class testClass () {

    public void testMethod(OrganizationServiceProxy service) {
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}
</code>```

This is after the refactor.
I've tried casting IOrganizationService to OrganizationServiceProxy, but the faked service context can't handle this cast. An exception is thrown.

```<code>class testClass () {

    public void testMethod(IOrganizationService service) {
        var serviceProxy = (OrganizationServiceProxy) service; //This breaks when given a fake context
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}
</code>```

I've tried using an IOrganizationServiceFactory, as suggested in this post. The problem is, factory.CreateOrganizationService() generates an IOrganizationService, not an OrganizationSeriviceProxy.

How can I refactor to use IOrganizationService instead of OrganizationServiceProxy without losing functionality? I'm guessing I might have to implement the IOrganizationService as an OrganizationServiceProxy somehow.

答:
I am not sure if this would help, but this is what I used</p>

```<code>CrmServiceClient c = new CrmServiceClient(connectionstring); //various parameters available
(OrganizationServiceProxy) service = c.OrganizationWebProxyClient ?? c.OrganizationServiceProxy;
</code>```

Body:
I'm attempting to refactor my code so that I can unit test using fakexrmeasy.

As part of the suggested refactor mentioned here, I've attempted to pass IOrganizationService into all of my classes and methods. However, some of my classes use variables and methods that IOrganizationService doesn't have, such as Timeout. I'm trying to find a way to refactor to use IOrganizationService without losing functionality.

This is how it exists before refactoring.

class testClass () {

    public void testMethod(OrganizationServiceProxy service) {
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}

This is after the refactor.
I've tried casting IOrganizationService to OrganizationServiceProxy, but the faked service context can't handle this cast. An exception is thrown.

class testClass () {

    public void testMethod(IOrganizationService service) {
        var serviceProxy = (OrganizationServiceProxy) service; //This breaks when given a fake context
        service.Timeout = new TimeSpan(0, 15, 0);
    }

}

I've tried using an IOrganizationServiceFactory, as suggested in this post. The problem is, factory.CreateOrganizationService() generates an IOrganizationService, not an OrganizationSeriviceProxy.

How can I refactor to use IOrganizationService instead of OrganizationServiceProxy without losing functionality? I'm guessing I might have to implement the IOrganizationService as an OrganizationServiceProxy somehow.

Body:
I am not sure if this would help, but this is what I used

CrmServiceClient c = new CrmServiceClient(connectionstring); //various parameters available
(OrganizationServiceProxy) service = c.OrganizationWebProxyClient ?? c.OrganizationServiceProxy;


问:
Add named namespace in Web.Config
In my razor view I name a include namespace like this: @using Resources = Project.Resources. I want to include this namespace in every view. So I went to the Web.config of my views folder and added this:

```<code><configuration>
  <system.web.webPages.razor>
    <namespaces>
      <add namespace="Project.Resources" />
    </namespace>
  </system.web.webPages.razor>
</configuration>
</code>```

Is there a way to add a name to this namespace? So I can type @Resource.Label in my views?

答:
I know this is an old question but,
There is also another way for adding a named namespace:

```<code><configuration>
    <system.web.webPages.razor>
        <namespaces>
            <add namespace="Projects = Project.Resources" />
        </namespace>
    </system.web.webPages.razor>
</configuration>
</code>```

and as you mentioned, you can type @Resource.Label your views.

Title: Add named namespace in Web.Config

Body:
In my razor view I name a include namespace like this: @using Resources = Project.Resources. I want to include this namespace in every view. So I went to the Web.config of my views folder and added this:

<configuration>
  <system.web.webPages.razor>
    <namespaces>
      <add namespace="Project.Resources" />
    </namespace>
  </system.web.webPages.razor>
</configuration>

Is there a way to add a name to this namespace? So I can type @Resource.Label in my views?

Body:
I know this is an old question but,
There is also another way for adding a named namespace:

<configuration>
    <system.web.webPages.razor>
        <namespaces>
            <add namespace="Projects = Project.Resources" />
        </namespace>
    </system.web.webPages.razor>
</configuration>

and as you mentioned, you can type @Resource.Label your views.


问:
Is there a way to set a specific amount of maximum spaces for TAB character (backslash t) "\t" in C++?
I want to print a square matrix that needs to be spaced each between the elements by 3 spaces. Then I found that char '\t' might be the easiest way. But, I think the number of spaces is somehow defined in certain algorithm. Could someone give me a guide through the algorithm or is there a way to set certain spaces in C++ for '\t'?

I know how to output manually by determining the number of space character. However '\t' seems simple to code rather than looping certain algorithm.

For a simple square matrix :

```<code>for (int x = 0, num = 1; x < 5; x++) {
        for (int y = 0; y < 5; y++, num++) {
            cout << num << "\t";
        }
        cout << endl;
    }
</code>```

The code outputs

```<code>1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25
</code>```

while I need

```<code>1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25
</code>```

Is there a way to set '\t'?

答:
I'm pretty sure the size of a tab is defined by your console, so this will be a setting of your IDE.
If you want a consistent quantity of spaces, you're better off using spaces. That way you don't have to alter the console  settings of everything you run your code on. Why not just do something like

```<code>"    "
</code>```

instead of "\t" ?

EDIT: Apparently Stack overflow doesn't appreciate multiple spaces in-text.

Body:
I want to print a square matrix that needs to be spaced each between the elements by 3 spaces. Then I found that char '\t' might be the easiest way. But, I think the number of spaces is somehow defined in certain algorithm. Could someone give me a guide through the algorithm or is there a way to set certain spaces in C++ for '\t'?

I know how to output manually by determining the number of space character. However '\t' seems simple to code rather than looping certain algorithm.

For a simple square matrix :

for (int x = 0, num = 1; x < 5; x++) {
        for (int y = 0; y < 5; y++, num++) {
            cout << num << "\t";
        }
        cout << endl;
    }

The code outputs

1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25

while I need

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25

Is there a way to set '\t'?

Body:
I'm pretty sure the size of a tab is defined by your console, so this will be a setting of your IDE.
If you want a consistent quantity of spaces, you're better off using spaces. That way you don't have to alter the console  settings of everything you run your code on. Why not just do something like

"    "

instead of "\t" ?

EDIT: Apparently Stack overflow doesn't appreciate multiple spaces in-text.


问:
Could not cast value of type '_SwiftValue' (0x1106695f8) to 'NSArray' (0x110112598)
I am fetching JSON dictionary data and appending them into a [[String:Anyobject]] variable but when i try to put fetched "image" data . as [String] array in a variable it prints nil when i try to print the array elements as [String]

var productsDetails = [String: AnyObject]

```<code>            guard let response = data else {return}

            if response["success"].boolValue == true , error == nil{

                //cell.titleLabel.text = response["data"]["product"]["title"] as? String
                self.productsDetails.append(response["data"]["product"].dictionary! as [String : AnyObject])

            }
            self.cartTableView.reloadData()
</code>```

in table view cell

```<code>    let data = self.productsDetails[indexPath.row]
    cell.titleLabel.text =  "\(data["title"]!)"

    cell.amountLabel.text = "\(data["price"]!)"

    cell.decriptionLabel.text = "\(data["details"]!)"

    let strum :[String] = (data["image"]! as? [String])! // this line is giving error
    print(strum)

    print(String(describing: type(of: data["image"])))
    return cell
</code>```

答:
First of all a JSON dictionary in Swift 3+ is never [String:AnyObject], it's [String:Any]

The error is clear. data["image"] contains a (Swifty)JSON object, that's the mentioned _SwiftValue type.

To get a dictionary of product use dictionaryObject which returns [String:Any]?

```<code>self.productsDetails.append(response["data"]["product"].dictionaryObject!)
</code>```

And please don't use a horrible syntax like (data["image"]! as? [String])! which is

force downcast an optional to an optional and then force unwrap it.

If it's supposed to be optional downcast it conditionally (data["image"] as? [String]) or force downcast it once  (data["image"] as! [String])

Note: You are encouraged to drop SwiftyJSON in favor of Codable. It's built-in and more efficient.

Body:
I am fetching JSON dictionary data and appending them into a [[String:Anyobject]] variable but when i try to put fetched "image" data . as [String] array in a variable it prints nil when i try to print the array elements as [String]

var productsDetails = [String: AnyObject]

            guard let response = data else {return}

            if response["success"].boolValue == true , error == nil{

                //cell.titleLabel.text = response["data"]["product"]["title"] as? String
                self.productsDetails.append(response["data"]["product"].dictionary! as [String : AnyObject])

            }
            self.cartTableView.reloadData()

in table view cell

    let data = self.productsDetails[indexPath.row]
    cell.titleLabel.text =  "\(data["title"]!)"

    cell.amountLabel.text = "\(data["price"]!)"

    cell.decriptionLabel.text = "\(data["details"]!)"

    let strum :[String] = (data["image"]! as? [String])! // this line is giving error
    print(strum)

    print(String(describing: type(of: data["image"])))
    return cell

Body:
First of all a JSON dictionary in Swift 3+ is never [String:AnyObject], it's [String:Any]

The error is clear. data["image"] contains a (Swifty)JSON object, that's the mentioned _SwiftValue type.

To get a dictionary of product use dictionaryObject which returns [String:Any]?

self.productsDetails.append(response["data"]["product"].dictionaryObject!)

And please don't use a horrible syntax like (data["image"]! as? [String])! which is

force downcast an optional to an optional and then force unwrap it.

If it's supposed to be optional downcast it conditionally (data["image"] as? [String]) or force downcast it once  (data["image"] as! [String])

Note: You are encouraged to drop SwiftyJSON in favor of Codable. It's built-in and more efficient.


问:
Convert multiline bytestring, typed as string type to proper string
My log files have some multiline bytestring in them, like

[2019-05-25 19:16:31] b'logstring\r\n\r\nmore log'

After I try to extract the original multiline string, how do I convert that to a real string
using Python 3?

As a simplified example, after reading the log file and stripping the time, I end up with a variable that has the type str and has the b' prefix, as a string.

```<code># note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
# convert here
print(tmp)
</code>```

I'm looking for a way to tell python that the content needs to get decoded. But str doesn't allow decoding.

The result I'd like to see from the print command is

```<code>logstring
more log
</code>```

UPDATE: The "eval" function will produce this result, but this would execute the code, so it's not safe.

```<code># note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
tmp = eval(tmp)
print(tmp)
</code>```

Is there a better way?

答:
It seems that you can lock down the eval function so that it can't run functions and python builtins. You do this by passing a dictionary of allowed global and local functions.
By mapping all builtins to None you can block the execution of regular python commands. With that in place, using eval to evaluate the string content is safe.

Source this article

```<code># note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
tmp = eval(tmp, {'__builtins__': None}, {})
print(tmp)
</code>```

And in the comments above @juanpa.arrivillaga offered another solution, that also solves the eval security problem:

```<code>import ast

tmp =  "b'logstring\r\n\r\nmore log'"
tmp = ast.literal_eval(tmp)
print(tmp)
</code>```

Body:
My log files have some multiline bytestring in them, like

[2019-05-25 19:16:31] b'logstring\r\n\r\nmore log'

After I try to extract the original multiline string, how do I convert that to a real string
using Python 3?

As a simplified example, after reading the log file and stripping the time, I end up with a variable that has the type str and has the b' prefix, as a string.

# note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
# convert here
print(tmp)

I'm looking for a way to tell python that the content needs to get decoded. But str doesn't allow decoding.

The result I'd like to see from the print command is

logstring
more log

UPDATE: The "eval" function will produce this result, but this would execute the code, so it's not safe.

# note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
tmp = eval(tmp)
print(tmp)

Is there a better way?

Body:
It seems that you can lock down the eval function so that it can't run functions and python builtins. You do this by passing a dictionary of allowed global and local functions.
By mapping all builtins to None you can block the execution of regular python commands. With that in place, using eval to evaluate the string content is safe.

Source this article

# note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
tmp = eval(tmp, {'__builtins__': None}, {})
print(tmp)

And in the comments above @juanpa.arrivillaga offered another solution, that also solves the eval security problem:

import ast

tmp =  "b'logstring\r\n\r\nmore log'"
tmp = ast.literal_eval(tmp)
print(tmp)


问:
Receive any Keyboard input and use with Switch statement on Unity
I don't want to use if statement. For simplicity and performance I want to use switch case and execute that method. I want all the keyboard Input to get detected. But is there any method that will pass any key press information?
My current approach is :

```<code>// Update is called once per frame
void Update()
{
    char a = Input.GetKey();//anything like this method?
    switch (a)
    {
        case 'a':
                //print'';
                break;
        case 'b':
                //print'';
                break;
        default:
            break;
    }

}
</code>```

How can I achieve this any key press information detection without if statement?

答:
I've not used Unity, however, I understand your problem and I am a C# developer.

From a quick search I have found someone on Unity forums with a similar problem to you. Here is the thread https://answers.unity.com/questions/1520939/check-if-there-is-a-keyboard-input.html.

```<code>if (Input.anyKeyDown)
 {
     Event e = Event.current;
     if (e.isKey)
     {
         Debug.Log("Current Key is : " + e.keyCode.ToString());
     }
 }
</code>```

The code above (from the Unity forum link) enables you to detect input.anyKeyDown (keyboard and mouse). Then you can filter the mouse detections by checking if the input was only a keyboard input  with e.isKey

Here is documentation for KeyCode. This also includes all the properties available to it (many keyboard related properties that you can potential check against).

For example (not tested):

```<code>Event e = Event.current;
if (e.isKey)
{
    Debug.Log("Current Key is : " + e.keyCode.ToString());

    if(e.keyCode == KeyCode.A) //checks if the keycode returned equals the 'A' key
    {
         // Do something
    }
}
</code>```

EDIT: As mentioned by the other answer you can try Input.inputString. According to the documentation insputString contains "Only ASCII characters". So for example you could do something like this in the 'Update' method if letters was what you were only looking to check.

```<code>void Update()
{
    //get the input
    var input = Input.inputString;

    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
    {
        switch(input)
        {
            case 'a': break;
            case 'b': break;
        }
    }
}
</code>```

Hope this can help.

Body:
I don't want to use if statement. For simplicity and performance I want to use switch case and execute that method. I want all the keyboard Input to get detected. But is there any method that will pass any key press information?
My current approach is :

// Update is called once per frame
void Update()
{
    char a = Input.GetKey();//anything like this method?
    switch (a)
    {
        case 'a':
                //print'';
                break;
        case 'b':
                //print'';
                break;
        default:
            break;
    }

}

How can I achieve this any key press information detection without if statement?

Body:
I've not used Unity, however, I understand your problem and I am a C# developer.

From a quick search I have found someone on Unity forums with a similar problem to you. Here is the thread https://answers.unity.com/questions/1520939/check-if-there-is-a-keyboard-input.html.

if (Input.anyKeyDown)
 {
     Event e = Event.current;
     if (e.isKey)
     {
         Debug.Log("Current Key is : " + e.keyCode.ToString());
     }
 }

The code above (from the Unity forum link) enables you to detect input.anyKeyDown (keyboard and mouse). Then you can filter the mouse detections by checking if the input was only a keyboard input  with e.isKey

Here is documentation for KeyCode. This also includes all the properties available to it (many keyboard related properties that you can potential check against).

For example (not tested):

Event e = Event.current;
if (e.isKey)
{
    Debug.Log("Current Key is : " + e.keyCode.ToString());

    if(e.keyCode == KeyCode.A) //checks if the keycode returned equals the 'A' key
    {
         // Do something
    }
}

EDIT: As mentioned by the other answer you can try Input.inputString. According to the documentation insputString contains "Only ASCII characters". So for example you could do something like this in the 'Update' method if letters was what you were only looking to check.

void Update()
{
    //get the input
    var input = Input.inputString;

    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
    {
        switch(input)
        {
            case 'a': break;
            case 'b': break;
        }
    }
}

Hope this can help.


问:
simplest possible test for output binding not working
I am testing a dead simple component with one button. When button is clicked it emits an (@output) event is emitted and then parent's callback (chatMessageFeedbackHandler) is called. Nothing out of ordinary.

But for some reason the following test is not working. I am just testing if  parent's chatMessageFeedbackHandler is called when child's button#test1 is clicked.

Note: If you comment either one of the following tests work successfully:

LINE: child 1.1 and child 1.2

LINE: parent 1.1 and parent 1.2

Test:

```<code>import {async, ComponentFixture, fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing';
import {Component, DebugElement} from "@angular/core";
import {AppComponent} from './app.component';
import {By} from '@angular/platform-browser';

function createHostComponent(): ComponentFixture<HostComponent> {
  const fixture = TestBed.createComponent(HostComponent);
  fixture.detectChanges();
  return fixture as ComponentFixture<HostComponent>;
}

fdescribe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<HostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HostComponent, AppComponent],
    })
    // .compileComponents();
  }));

  beforeEach(() => {
    // fixture = TestBed.createComponent(ChatFeedbackComponent);
    fixture = createHostComponent();

  });

  fit('should emit chatMessageFeedback$ true when clicked on like button', fakeAsync(() => {
    const appComponent = fixture.debugElement.query(By.directive(AppComponent)) as DebugElement;
    // spyOn(appComponent.componentInstance,'chatFeedbackClicked');//LINE: parent 1.1
    spyOn(fixture.componentInstance,'outputHandler'); //LINE: child 1.1
    fixture.debugElement.nativeElement.querySelector('#test1').click();
    tick(500);
    flushMicrotasks();
    fixture.detectChanges();
    // expect(appComponent.componentInstance.chatFeedbackClicked).toHaveBeenCalled();//LINE: parent 1.2
    expect(fixture.componentInstance.outputHandler).toHaveBeenCalledWith(true);//LINE: child 1.2
  }));

});

@Component({selector: 'host-for-test', template: `
    <app-root (chatMessageFeedback$)="outputHandler($event)"></app-root>
  `})
class HostComponent {

  outputHandler(data) {
    alert();
  }
}
</code>```

Child Component:

```<code>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button id="test1" (click)="chatFeedbackClicked(true)">Test</button>
  `,
})
export class AppComponent {
  @Output() chatMessageFeedback$ = new EventEmitter();

  chatFeedbackClicked(isFeedbackPositive: boolean) {
    this.chatMessageFeedback$.emit(isFeedbackPositive);
  }
}
</code>```

答:
To test the following parent host component, calls the actual function, when the child emits , i think that you're tackling the problem from the wrong end.

In your case you need to mock, the template component (the child, app-chat-feedback component), and triggers the event fire manually (not through the whole click process, that's the case for another unit test). Check the below, this should get you working.

This is the mock of the template component

@Component({
    template: '',
    selector: 'app-chat-feedback'
})
export class ChatFeedbackComponentMock {

    @Output() chatMessageFeedback$: EventEmitter<any> = new EventEmitter<any>();

    // This will be the function that triggers the emit
    emitFeedback(value: any) {
        this.chatMessageFeedback$.emit(value);
    }
}
```

<p>This is the component whose functionality you're testing, in this case, that the <code>chatFeedbackClicked</code> is called when the child emits an event. This is the real component.</p>

<pre class="lang-js prettyprint-override"><code>@Component({
    template:`
        // Your Logic here
        <app-chat-feedback (chatMessageFeedback$)="chatFeedbackClicked($event)"></app-chat-feedback>
    `
})
export class MyComponentUnderTest {
    chatFeedbackClicked() {
        // Your logic here
    }
}
</code>```

This is the test definition.

describe('MyComponentUnderTest', () => {

    let fixture: ComponentFixture<MyComponentUnderTest>;
    let component: MyComponentUnderTest;

    beforeEach(() => {
        // Register both the real component under test, and the mock component of the child
        TestBed.configureTestingModule({
            declarations: [ ChatFeedbackComponentMock, MyComponentUnderTest]
        });

        // Get a handle to the component fixture, and the component instancce
        fixture = TestBed.createComponent(MyComponentUnderTest);
        component = fixture.componentInstance;
    });

    // Important that you have the fakeAsync wrapper function, since the EventEmmiter behaves asynchronously
    it('Should call chatFeedbackClicked when the chatMessageFeedback$ event is fired', fakeAsync(() => {

        // Get a handle of the instance of the child mock component (the template component that you're mocking)
        let child: ChatFeedbackComponentMock = fixture.debugElement.query(By.css('app-chat-feedback')).componentInstance;

        // Spy on the function of the component under test, that will be asserted
        spyOn(component, 'chatFeedbackClicked');

        // Call emit feedback with some value, on the child component. This will trigger an emit call
        child.emitFeedback('value');

        // Since the calls are asynchronous, (EventEmmitter behaves like an observable), we need to simulate passing of time
        tick();

        // Assert that the function was called with the passed value
        expect(component.chatFeedbackClicked).toHaveBeenCalledWith('value');
    }));
});
```

Read more about testing asynchronous functions here and about fakeAsync wrapper function here

Body:
I am testing a dead simple component with one button. When button is clicked it emits an (@output) event is emitted and then parent's callback (chatMessageFeedbackHandler) is called. Nothing out of ordinary.

But for some reason the following test is not working. I am just testing if  parent's chatMessageFeedbackHandler is called when child's button#test1 is clicked.

Note: If you comment either one of the following tests work successfully:

LINE: child 1.1 and child 1.2

LINE: parent 1.1 and parent 1.2

Test:

import {async, ComponentFixture, fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing';
import {Component, DebugElement} from "@angular/core";
import {AppComponent} from './app.component';
import {By} from '@angular/platform-browser';

function createHostComponent(): ComponentFixture<HostComponent> {
  const fixture = TestBed.createComponent(HostComponent);
  fixture.detectChanges();
  return fixture as ComponentFixture<HostComponent>;
}

fdescribe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<HostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HostComponent, AppComponent],
    })
    // .compileComponents();
  }));

  beforeEach(() => {
    // fixture = TestBed.createComponent(ChatFeedbackComponent);
    fixture = createHostComponent();

  });

  fit('should emit chatMessageFeedback$ true when clicked on like button', fakeAsync(() => {
    const appComponent = fixture.debugElement.query(By.directive(AppComponent)) as DebugElement;
    // spyOn(appComponent.componentInstance,'chatFeedbackClicked');//LINE: parent 1.1
    spyOn(fixture.componentInstance,'outputHandler'); //LINE: child 1.1
    fixture.debugElement.nativeElement.querySelector('#test1').click();
    tick(500);
    flushMicrotasks();
    fixture.detectChanges();
    // expect(appComponent.componentInstance.chatFeedbackClicked).toHaveBeenCalled();//LINE: parent 1.2
    expect(fixture.componentInstance.outputHandler).toHaveBeenCalledWith(true);//LINE: child 1.2
  }));

});

@Component({selector: 'host-for-test', template: `
    <app-root (chatMessageFeedback$)="outputHandler($event)"></app-root>
  `})
class HostComponent {

  outputHandler(data) {
    alert();
  }
}

Child Component:

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button id="test1" (click)="chatFeedbackClicked(true)">Test</button>
  `,
})
export class AppComponent {
  @Output() chatMessageFeedback$ = new EventEmitter();

  chatFeedbackClicked(isFeedbackPositive: boolean) {
    this.chatMessageFeedback$.emit(isFeedbackPositive);
  }
}

Body:
To test the following parent host component, calls the actual function, when the child emits , i think that you're tackling the problem from the wrong end.

In your case you need to mock, the template component (the child, app-chat-feedback component), and triggers the event fire manually (not through the whole click process, that's the case for another unit test). Check the below, this should get you working.

This is the mock of the template component

@Component({
    template: '',
    selector: 'app-chat-feedback'
})
export class ChatFeedbackComponentMock {

    @Output() chatMessageFeedback$: EventEmitter<any> = new EventEmitter<any>();

    // This will be the function that triggers the emit
    emitFeedback(value: any) {
        this.chatMessageFeedback$.emit(value);
    }
}

This is the component whose functionality you're testing, in this case, that the chatFeedbackClicked is called when the child emits an event. This is the real component.

@Component({
    template:`
        // Your Logic here
        <app-chat-feedback (chatMessageFeedback$)="chatFeedbackClicked($event)"></app-chat-feedback>
    `
})
export class MyComponentUnderTest {
    chatFeedbackClicked() {
        // Your logic here
    }
}

This is the test definition.

describe('MyComponentUnderTest', () => {

    let fixture: ComponentFixture<MyComponentUnderTest>;
    let component: MyComponentUnderTest;

    beforeEach(() => {
        // Register both the real component under test, and the mock component of the child
        TestBed.configureTestingModule({
            declarations: [ ChatFeedbackComponentMock, MyComponentUnderTest]
        });

        // Get a handle to the component fixture, and the component instancce
        fixture = TestBed.createComponent(MyComponentUnderTest);
        component = fixture.componentInstance;
    });

    // Important that you have the fakeAsync wrapper function, since the EventEmmiter behaves asynchronously
    it('Should call chatFeedbackClicked when the chatMessageFeedback$ event is fired', fakeAsync(() => {

        // Get a handle of the instance of the child mock component (the template component that you're mocking)
        let child: ChatFeedbackComponentMock = fixture.debugElement.query(By.css('app-chat-feedback')).componentInstance;

        // Spy on the function of the component under test, that will be asserted
        spyOn(component, 'chatFeedbackClicked');

        // Call emit feedback with some value, on the child component. This will trigger an emit call
        child.emitFeedback('value');

        // Since the calls are asynchronous, (EventEmmitter behaves like an observable), we need to simulate passing of time
        tick();

        // Assert that the function was called with the passed value
        expect(component.chatFeedbackClicked).toHaveBeenCalledWith('value');
    }));
});

Read more about testing asynchronous functions here and about fakeAsync wrapper function here