问:
Trying to pass an array to a different class in Java
I'm creating a lottery program and trying linked lists for the first time. I'm passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".

There will be another class which will be made for the winning numbers but I'm trying to fix this issue first. I'm unsure how to fix this as I've been stuck for quite a while now.

Any help would be much appreciated.

This is the piece of code I'm having trouble with, this is in the Lottery class in the displayPlayers() method -

```<code>for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
</code>```

```<code>public class LOTTERY
{
    Scanner keyboard = new Scanner(System.in);

    private PLAYER pHead;

    public LOTTERY()
    {
        pHead = null;

    }

    public void displayPlayers() {
        PLAYER currentPlayer = pHead;
        System.out.println("Name: " + currentPlayer.getName());
        System.out.println("Age: " + currentPlayer.getAge());
        currentPlayer.randNum();
        System.out.println("Your Numbers: ");

        for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
        menu();
    }

    public void runProg() {

        displayPlayers();
    }

    public static void main(String[] args) {
        LOTTERY lottery = new LOTTERY();
        lottery.runProg();
    }
}

</code>```

答:
The method getNumbers() does not take an parameters but you are trying to pass it i.  Additionally, this method returns an array, so you want to get this before the loop iteration, then iterate through it.

You can do this easily using an enhanced for loop:

```<code>for (int currentNum : currentPlayer.getNumbers()) {
    System.out.println(currentNum);
}
</code>```

Or with a standard for loop:

```<code>int [] arr = currentPlayer.getNumbers();
for (int i = 0; i < arr.length; i++) {
     System.out.println(arr[i]);
}
</code>```

Body:
I'm creating a lottery program and trying linked lists for the first time. I'm passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".

There will be another class which will be made for the winning numbers but I'm trying to fix this issue first. I'm unsure how to fix this as I've been stuck for quite a while now.

Any help would be much appreciated.

This is the piece of code I'm having trouble with, this is in the Lottery class in the displayPlayers() method -

for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }

public class LOTTERY
{
    Scanner keyboard = new Scanner(System.in);

    private PLAYER pHead;

    public LOTTERY()
    {
        pHead = null;

    }

    public void displayPlayers() {
        PLAYER currentPlayer = pHead;
        System.out.println("Name: " + currentPlayer.getName());
        System.out.println("Age: " + currentPlayer.getAge());
        currentPlayer.randNum();
        System.out.println("Your Numbers: ");

        for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
        menu();
    }

    public void runProg() {

        displayPlayers();
    }

    public static void main(String[] args) {
        LOTTERY lottery = new LOTTERY();
        lottery.runProg();
    }
}

Body:
The method getNumbers() does not take an parameters but you are trying to pass it i.  Additionally, this method returns an array, so you want to get this before the loop iteration, then iterate through it.

You can do this easily using an enhanced for loop:

for (int currentNum : currentPlayer.getNumbers()) {
    System.out.println(currentNum);
}

Or with a standard for loop:

int [] arr = currentPlayer.getNumbers();
for (int i = 0; i < arr.length; i++) {
     System.out.println(arr[i]);
}


来源: stackexchange

问:
Column-specific processing in an sklearn pipeline
I have a situation where I need to do some column-specific processing in a pipeline, but because transformers return numpy arrays rather than pandas dataframes, I don't have column names to do my feature engineering.

Here's a simple, reproducible example where I have a function called engineer_feature that I want to use to create new data. I need to use it during/after the pipeline because it depends on one column becoming imputed, and I would like it to be able to be performed during k-fold cross-validation.

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

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(df):
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer()),
    ("engineer", FunctionTransformer(engineer_feature)),
    ("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)
</code>```

Which yields this error:

```<code>IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

Which makes sense because engineer_feature is trying to index columns as if though they are dataframes when they are just numpy arrays.

What's a strategy for getting around this? I don't want to hardcode column indices to access them via numpy, especially since my real dataframe has many more columns.

答:
For your toy example to work you need to:

```<code>def engineer_feature(X):
    return np.c_[X,X[:,0]/X[:,1]]

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer())
    ,("engineer", FunctionTransformer(engineer_feature))
    ,("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)
</code>```

FunctionTransformer() accepts numpy array, you cannot avoid hardcoding here.

ContentLicense: CC BY-SA 4.0

Body:
I have a situation where I need to do some column-specific processing in a pipeline, but because transformers return numpy arrays rather than pandas dataframes, I don't have column names to do my feature engineering.

Here's a simple, reproducible example where I have a function called engineer_feature that I want to use to create new data. I need to use it during/after the pipeline because it depends on one column becoming imputed, and I would like it to be able to be performed during k-fold cross-validation.

import numpy as np
import pandas as pd

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(df):
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer()),
    ("engineer", FunctionTransformer(engineer_feature)),
    ("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)

Which yields this error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Which makes sense because engineer_feature is trying to index columns as if though they are dataframes when they are just numpy arrays.

What's a strategy for getting around this? I don't want to hardcode column indices to access them via numpy, especially since my real dataframe has many more columns.

Body:
For your toy example to work you need to:

def engineer_feature(X):
    return np.c_[X,X[:,0]/X[:,1]]

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer())
    ,("engineer", FunctionTransformer(engineer_feature))
    ,("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)

FunctionTransformer() accepts numpy array, you cannot avoid hardcoding here.


问:
what is wrong in this sql syntax?
```<code>SELECT *
FROM ua_campus_report_campus (old)
WHERE article LIKE 'Ed %'
</code>```

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(old) WHERE article LIKE Ed % LIMIT 0, 25' at line 1

table names image

答:
Identifiers that contain spaces or special characters must be escaped. Normal MySQL pattern is to enclose identifier in backtick characters:

```<code>  SELECT t.*
    FROM `ua_campus_report_campus (old)` t
   WHERE t.article LIKE 'Ed %'
</code>```

Also note that best practice is qualify all column references with the table name or alias.

(It's also possible to escape identifiers by enclosing them in double quotes when sql_mode includes ANSI_QUOTES.)

Title: what is wrong in this sql syntax?

Body:
SELECT *
FROM ua_campus_report_campus (old)
WHERE article LIKE 'Ed %'

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(old) WHERE article LIKE Ed % LIMIT 0, 25' at line 1

table names image

Body:
Identifiers that contain spaces or special characters must be escaped. Normal MySQL pattern is to enclose identifier in backtick characters:

  SELECT t.*
    FROM `ua_campus_report_campus (old)` t
   WHERE t.article LIKE 'Ed %'

Also note that best practice is qualify all column references with the table name or alias.

(It's also possible to escape identifiers by enclosing them in double quotes when sql_mode includes ANSI_QUOTES.)


问:
Issue with installing yeoman
I am trying to install yeoman with node 4.8.7.

```<code>npm install -g yo
</code>```

This is the error I get :

C:\Users\thomas\AppData\Roaming\nvm\v4.8.7\node_modules\yo\node_modules\yeoman-doctor\lib\index.js:12
      (async () => {
             ^

    SyntaxError: Unexpected token (
        at exports.runInThisContext (vm.js:53:16)
        at Module._compile (module.js:373:25)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Module.require (module.js:353:17)
        at require (internal/module.js:12:17)
        at Object.<anonymous> (C:\Users\thomas\AppData\Roaming\nvm\v4.8.7\node_modules\yo\node_modules\yeoman-doctor\lib\cli.js:3:1)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
    npm ERR! Windows_NT 10.0.18362
    npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
"--global" "yo"
    npm ERR! node v4.8.7
    npm ERR! npm  v2.15.11
    npm ERR! code ELIFECYCLE

    npm ERR! yo@3.1.1 postinstall: `yodoctor`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the yo@3.1.1 postinstall script 'yodoctor'.
    npm ERR! This is most likely a problem with the yo package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR!     yodoctor
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR!     npm bugs yo
    npm ERR! Or if that isn't available, you can get their info via:
    npm ERR!
    npm ERR!     npm owner ls yo
    npm ERR! There is likely additional logging output above.

    npm ERR! Please include the following file with any support request:
    npm ERR!     C:\Users\thomas\dev\workspace\aprhtechvalley\npm-debug.log
```

any idea how to solve this issue?

thanks

答:
Please update your NodeJS to the latest version, which is 12: https://nodejs.org/en/download/

Or, if you need to install it via NVM: https://tecadmin.net/install-nodejs-with-nvm/

Title: Issue with installing yeoman

Body:
I am trying to install yeoman with node 4.8.7.

npm install -g yo

This is the error I get :

C:\Users\thomas\AppData\Roaming\nvm\v4.8.7\node_modules\yo\node_modules\yeoman-doctor\lib\index.js:12
      (async () => {
             ^

    SyntaxError: Unexpected token (
        at exports.runInThisContext (vm.js:53:16)
        at Module._compile (module.js:373:25)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Module.require (module.js:353:17)
        at require (internal/module.js:12:17)
        at Object.<anonymous> (C:\Users\thomas\AppData\Roaming\nvm\v4.8.7\node_modules\yo\node_modules\yeoman-doctor\lib\cli.js:3:1)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
    npm ERR! Windows_NT 10.0.18362
    npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
"--global" "yo"
    npm ERR! node v4.8.7
    npm ERR! npm  v2.15.11
    npm ERR! code ELIFECYCLE

    npm ERR! yo@3.1.1 postinstall: `yodoctor`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the yo@3.1.1 postinstall script 'yodoctor'.
    npm ERR! This is most likely a problem with the yo package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR!     yodoctor
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR!     npm bugs yo
    npm ERR! Or if that isn't available, you can get their info via:
    npm ERR!
    npm ERR!     npm owner ls yo
    npm ERR! There is likely additional logging output above.

    npm ERR! Please include the following file with any support request:
    npm ERR!     C:\Users\thomas\dev\workspace\aprhtechvalley\npm-debug.log

any idea how to solve this issue?

thanks


问:
Matlab change in symbolic notation of derivative
I've recently upgraded Matlab from 2013b to 2019a (yes, I know, a lot has changed....but not software costs). I have some "legacy code" which makes heavy use of the symbolic tool box. One thing that seems to be causing a big issue is the change in notation. I think this question is best presented through example:

2013

```<code>>> F(x) = sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

D(F)(1)
</code>```

2019

```<code>>> F(x) = str2sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

subs(diff(F(x), x), x, 1)
</code>```

In 2019, F(x) = sym('F(x)'); would not work and I was told to switch to F(x) = str2sym('F(x)'); which seems to perform the operation as intended, but the notation is killing my code.

Is there a way to salvage the old notation or do I have to rewrite my code?

EDIT

Good comment.....how is this breaking my code? I use the symbolic tools to solve equations then parse them based on their structure. For example, if an expression has a third derivative, I would put that in group A. If it has a 7 derivative, I would put that in group B. In 2013, it was easy to parse for high derivatives...a third derivative would look like this D(D(D(F)))(x) in 2019 it looks like this diff(F(x), x, x, x). I've also found that 2019 mixes its notation. For example

```<code>F(x) = str2sym('F(x+dx)')
F(x) =

F(dx + x)

>> diff(F,x,3)

ans(x) =

D(D(D(F)))(dx + x)
</code>```

At this point, I'm thinking this is just going to end up being one patch fix after another. Probably not the best idea to be parsing symbolic expressions if the notation is volatile. I was hoping there might be a "yeah, go to preferences and select..."

答:
If adding something like the +dx makes 2019 switch notation to D, maybe you can just do something like that always and then substitute out the extra stuff? I don't have the symbolic toolbox so can't experiment, but just a thought.

Example

change F(x) = str2sym('F(x)'); to

F(x) = str2sym('F(x+dx)');

then use

subs(diff(F,x),x + dx,1)

which returns D(F)(1) and has the same meaning as subs(diff(F(x), x), x, 1)

Body:
I've recently upgraded Matlab from 2013b to 2019a (yes, I know, a lot has changed....but not software costs). I have some "legacy code" which makes heavy use of the symbolic tool box. One thing that seems to be causing a big issue is the change in notation. I think this question is best presented through example:

2013

>> F(x) = sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

D(F)(1)

2019

>> F(x) = str2sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

subs(diff(F(x), x), x, 1)

In 2019, F(x) = sym('F(x)'); would not work and I was told to switch to F(x) = str2sym('F(x)'); which seems to perform the operation as intended, but the notation is killing my code.

Is there a way to salvage the old notation or do I have to rewrite my code?

EDIT

Good comment.....how is this breaking my code? I use the symbolic tools to solve equations then parse them based on their structure. For example, if an expression has a third derivative, I would put that in group A. If it has a 7 derivative, I would put that in group B. In 2013, it was easy to parse for high derivatives...a third derivative would look like this D(D(D(F)))(x) in 2019 it looks like this diff(F(x), x, x, x). I've also found that 2019 mixes its notation. For example

F(x) = str2sym('F(x+dx)')
F(x) =

F(dx + x)

>> diff(F,x,3)

ans(x) =

D(D(D(F)))(dx + x)

At this point, I'm thinking this is just going to end up being one patch fix after another. Probably not the best idea to be parsing symbolic expressions if the notation is volatile. I was hoping there might be a "yeah, go to preferences and select..."


问:
Write a database class in python
For a hobby project I'm doing at the moment I want to write an object oriented python program.But one of the first issue I'm running into is creating a class for my (MySQL) database.

I am trying to use as few packages as possible and I want to try to write the database class by using only pymysql.The problem is that there is an overwhelming amount of libraries and a lack of explanation on writing a good database class in python.

Any suggestions and especially examples would be much appreciated

答:
import sqlite3
"""singleton class to deal with db"""
'''same can be use for pymysql just replace the sqlite3 with pymysql'''

class DBConnection:
    instance = None

    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super().__new__(DBConnection)
            return cls.instance
        return cls.instance

    def __init__(self, db_name='you-db-name'):
        self.name = db_name
        # connect takes url, dbname, user-id, password
        self.conn = self.connect(db_name)
        self.cursor = self.conn.cursor()

    def connect(self):
        try:
            return sqlite3.connect(self.name)
        except sqlite3.Error as e:
            pass

    def __del__(self):
        self.cursor.close()
        self.conn.close()

  # write your function here for CRUD operations
```

ContentLicense: CC BY-SA 3.0

Title: Write a database class in python


问:
What is the Ideal way to return data from function without leaking memory?
In IPhone Development ObjC , I wonder what is the right approach for functions to return some values in Dictionaries or Arrays. I mean should they return autorelease objects, but wouldn't it be bad if I am using too many functions to return values, like getUserRecordsFromDB() function will return all the user records, so should they return me autorelease objects? also when I am calling them multiple times, suppose with a span of 4 seconds to get the newely updated data. Can somebody let me an ideal scanario of how to get data from a function called frequently in the flow of program, and not leaking the memory.</p>

答:
If the method is in same class use global variable, if it is in some other class make sure it is allocated only one time, reuse the same memory every time it call that method.

Also check NSAutoreleasePool


问:
There is always a default background on TextInputLayout in Android
I have TextInputLayout and TextInputEditText like this

```<code><com.google.android.material.textfield.TextInputLayout
            android:id="@+id/loginUsernameText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/text_input_margin_left_right"
            android:layout_marginRight="@dimen/text_input_margin_left_right"
            android:layout_marginTop="@dimen/text_input_margin_top_bottom"
            android:hint="@string/username"
            android:layout_below="@id/loginButtonLogin">

        <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/loginUsername"
                android:layout_width="match_parent"
                android:padding="5dp"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"/>

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/loginPasswordText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/text_input_margin_left_right"
            android:layout_marginRight="@dimen/text_input_margin_left_right"
            android:layout_marginTop="@dimen/text_input_margin_top_bottom"
            android:hint="@string/password"
            android:layout_below="@id/loginUsernameText">

        <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/loginPassword"
                android:layout_width="match_parent"
                android:padding="5dp"
                android:layout_height="wrap_content"
                android:inputType="textPassword"/>

    </com.google.android.material.textfield.TextInputLayout>
</code>```

This is my styles.xml file

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/white</item>
        <item name="android:textSize">14sp</item>
    </style>

</resources>
</code>```

So I am not using anything extra on TextInputLayout and they are appearing like this

This grey background is always there.
How do I remove this background and just get the default TextInputLayout. Thanks.

答:
For me it worked with app:boxBackgroundColor="@null", like this:

```<code>    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:boxBackgroundColor="@null"
        android:hint="@string/description">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine|textCapSentences" />

    </com.google.android.material.textfield.TextInputLayout>
</code>```

Body:
I have TextInputLayout and TextInputEditText like this

<com.google.android.material.textfield.TextInputLayout
            android:id="@+id/loginUsernameText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/text_input_margin_left_right"
            android:layout_marginRight="@dimen/text_input_margin_left_right"
            android:layout_marginTop="@dimen/text_input_margin_top_bottom"
            android:hint="@string/username"
            android:layout_below="@id/loginButtonLogin">

        <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/loginUsername"
                android:layout_width="match_parent"
                android:padding="5dp"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"/>

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/loginPasswordText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/text_input_margin_left_right"
            android:layout_marginRight="@dimen/text_input_margin_left_right"
            android:layout_marginTop="@dimen/text_input_margin_top_bottom"
            android:hint="@string/password"
            android:layout_below="@id/loginUsernameText">

        <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/loginPassword"
                android:layout_width="match_parent"
                android:padding="5dp"
                android:layout_height="wrap_content"
                android:inputType="textPassword"/>

    </com.google.android.material.textfield.TextInputLayout>

This is my styles.xml file

<resources>

</resources>

So I am not using anything extra on TextInputLayout and they are appearing like this

This grey background is always there.
How do I remove this background and just get the default TextInputLayout. Thanks.

Body:
For me it worked with app:boxBackgroundColor="@null", like this:

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:boxBackgroundColor="@null"
        android:hint="@string/description">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine|textCapSentences" />

    </com.google.android.material.textfield.TextInputLayout>


问:
Error in .local(object, ...) when try to write or plot raster
I have a randomForest model that I am trying to predict back over the study area. I am able to run the predict without errors, and I can see that it produces a raster, but when I try to run writeRaster() or plot(), I get the error Error in .local(.object, ...) without any more information. Here is the code (note that envStack is the raster stack of environmental predictors and rf.full is the randomForest model object):

```<code>library(here)
library(raster)
library(randomForest)
setwd(here("species", model_species, "outputs", "grids"))
fn <- paste0(model_run_name, "_raw_", Sys.Date(), ".tif")

outRas <- predict(object = envStack,
                  model = rf.full,
                  type = "prob",
                  index = 2,
                  na.rm = TRUE,
                  filename = fn,
                  format = "GTiff",
                  overwrite = TRUE,
                  progress = "text")
writeRaster(outRas, filename = fn, format = "GTiff", overwrite = TRUE)
</code>```

And, here is the error:

Error in .local(.Object, ...) :

The same thing happens if I try to plot the output raster:

```<code>plot(outRas)
</code>```

Error in .local(.Object, ...) :

I'm including a screenshot of the envStack and rf.full objects as well as the outRas raster product from the predict. To check if the issue was a file size issue, I used object.size(outRas), which returned 12832 bytes. I also checked the available space on the drive where I want to store the raster, and there are over 60 GB of free space:

I'm not sure why the min and max values are unknown for a lot of the rasters in the stack, but just to make sure the individual rasters weren't corrupt, I tried to plot one with missing min/max values (plot(envStack[[1]])), and it plotted just fine:

The model object (rf.full) was used successfully to compute various validation metrics, so as far as I know, there are no issues with it, and the folder where I want to save the output raster exists.

When I check the temporary file location with rasterTmpFile(), it returns a file that doesn't exist (although the containing folder does):

```<code>rasterTmpFile()
[1] "C:/Users/username/AppData/Local/Temp/Rtmpkxfn1t/raster/r_tmp_2020-02-17_152958_23480_67648.grd"
</code>```

I feel like I have encountered this issue before, but I can't remember how I resolved it (or if I resolved it). The related questions I have looked at on here point to file size and file location issues, which don't seem to by me problem. Some hint at issues with format type, but I have saved other rasters as GeoTiffs as recently as last week in earlier steps of this process using writeRaster() with format = "GTiff". Also, the fact that I get the same error when just trying to plot outRas within R makes it seem like there is an issue with the raster itself. Any help is appreciated.

UPDATE: The problem turned out to be that the writeRaster() statement was unnecessary. Taking it out solved the issue. See my answer below for more details.

答: I figured out what I was doing wrong. I had that code bit embedded in an if/else try statement, so it was trying to run the predict and write the raster as part of the same run. However, the writeRaster() line is unnecessary since the predict() function includes a filename= argument to save the file. By telling it to write the raster right after that confused R somehow and caused it to throw that error. Thus, I removed the writeRaster() statement, and it solved the problem.

Body:
I have a randomForest model that I am trying to predict back over the study area. I am able to run the predict without errors, and I can see that it produces a raster, but when I try to run writeRaster() or plot(), I get the error Error in .local(.object, ...) without any more information. Here is the code (note that envStack is the raster stack of environmental predictors and rf.full is the randomForest model object):

library(here)
library(raster)
library(randomForest)
setwd(here("species", model_species, "outputs", "grids"))
fn <- paste0(model_run_name, "_raw_", Sys.Date(), ".tif")

outRas <- predict(object = envStack,
                  model = rf.full,
                  type = "prob",
                  index = 2,
                  na.rm = TRUE,
                  filename = fn,
                  format = "GTiff",
                  overwrite = TRUE,
                  progress = "text")
writeRaster(outRas, filename = fn, format = "GTiff", overwrite = TRUE)

And, here is the error:

Error in .local(.Object, ...) :

The same thing happens if I try to plot the output raster:

plot(outRas)

Error in .local(.Object, ...) :

I'm including a screenshot of the envStack and rf.full objects as well as the outRas raster product from the predict. To check if the issue was a file size issue, I used object.size(outRas), which returned 12832 bytes. I also checked the available space on the drive where I want to store the raster, and there are over 60 GB of free space:

I'm not sure why the min and max values are unknown for a lot of the rasters in the stack, but just to make sure the individual rasters weren't corrupt, I tried to plot one with missing min/max values (plot(envStack[[1]])), and it plotted just fine:

The model object (rf.full) was used successfully to compute various validation metrics, so as far as I know, there are no issues with it, and the folder where I want to save the output raster exists.

When I check the temporary file location with rasterTmpFile(), it returns a file that doesn't exist (although the containing folder does):

rasterTmpFile()
[1] "C:/Users/username/AppData/Local/Temp/Rtmpkxfn1t/raster/r_tmp_2020-02-17_152958_23480_67648.grd"

I feel like I have encountered this issue before, but I can't remember how I resolved it (or if I resolved it). The related questions I have looked at on here point to file size and file location issues, which don't seem to by me problem. Some hint at issues with format type, but I have saved other rasters as GeoTiffs as recently as last week in earlier steps of this process using writeRaster() with format = "GTiff". Also, the fact that I get the same error when just trying to plot outRas within R makes it seem like there is an issue with the raster itself. Any help is appreciated.

UPDATE: The problem turned out to be that the writeRaster() statement was unnecessary. Taking it out solved the issue. See my answer below for more details.


问:
How can I remove leading and trailing quotes in SQL Server?
I have a table in a SQL Server database with an NTEXT column.  This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.

For example:

"this is a test message"

should become

this is a test message

I know of the LTRIM and RTRIM functions but these workl only for spaces.  Any suggestions on which functions I can use to achieve this.

答: You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test

ContentLicense: CC BY-SA 2.5


问:
Show the repeating values only once and only what changes in separated list under it
A query with select distinct of multiple columns, joins and where clause is returning records like the following:

```<code>ID  title   Date    other field
1   text 1  01-Jan-20   another value
1   text 1  07-Mar-20   another value
1   text 1  20-Sep-20   another value
1   text 1  30-Dec-20   another value
2   text 2  02-Feb-20   something else
2   text 2  12-Mar-20   something else
2   text 2  15-May-20   something else
2   text 2  17-Jul-20   something else

</code>```

How can I display all the repeated values once and only the dates that are changing like this:

```<code>1, text, another value
01-Jan-20
07-Mar-20
20-Sep-20
30-Dec-20

1, text, something else
02-Feb-20
12-Mar-20
15-May-20
17-Jul-20

</code>```

Should I change the oracle query or do something with map, reduce on the array of the results in the language that I am using?
Any example?

答:
Here is an example

let myObj = {};
`1   text 1  01-Jan-20   another value
1   text 1  07-Mar-20   another value
1   text 1  20-Sep-20   another value
1   text 1  30-Dec-20   another value
2   text 2  02-Feb-20   something else
2   text 2  12-Mar-20   something else
2   text 2  15-May-20   something else
2   text 2  17-Jul-20   something else`.split(/\n/)
.forEach(line => {
  let [_, num, title, date, val] = line.match(/(\d+)\s+(.*?)  (.*?)   (.*)/)
  // console.log("n",num,"t",title,"d", date, "v",val)
  if (!myObj[title]) myObj[title] = { num:num, val:val,dates:[] }
  myObj[title].dates.push(date)
})

console.log(myObj)```

Body:
A query with select distinct of multiple columns, joins and where clause is returning records like the following:

ID  title   Date    other field
1   text 1  01-Jan-20   another value
1   text 1  07-Mar-20   another value
1   text 1  20-Sep-20   another value
1   text 1  30-Dec-20   another value
2   text 2  02-Feb-20   something else
2   text 2  12-Mar-20   something else
2   text 2  15-May-20   something else
2   text 2  17-Jul-20   something else

How can I display all the repeated values once and only the dates that are changing like this:

1, text, another value
01-Jan-20
07-Mar-20
20-Sep-20
30-Dec-20

1, text, something else
02-Feb-20
12-Mar-20
15-May-20
17-Jul-20

Should I change the oracle query or do something with map, reduce on the array of the results in the language that I am using?
Any example?


问:
R: Why am I getting an extra column titled "X.1" in my dataframe after reading my .txt file?
I have got this .txt file outputed by a microscope to process.

```<code>#read the .txt file generated by microscope, skipping the first 9 lines of garbage information
df <- read.csv("Objects_Population - AllCells.txt", sep="\t", skip = 9,header=TRUE, fill = T)
</code>```

Then I started looking at the structure of the dataframe, everything seems fine except I now found an extra column in the end of the data frame named "x.1" and all rows of it are NA values. I don't see this column when I open the .txt file in excel. I suspect the problem has something to do with the column names generated by microscope, they contain quite some special characters

Below is the dataframe read by Excel(only showing the last 2 columns since I have 132 columns, and their names are disgustingly long):

```<code>AllCells - Cell Contact Area with Neighbors [%] AllCells - Nucleus Nearest Neighbor Distance [Âµm]
0                                               4.82083
21.9512                                         0
15.7895                                         0
29.4118                                         0.584611
0                                               4.21569
0                                               1.99599
0                                               3.50767
...
</code>```

This has happened to me before but I never took it too serious as I was always interested in a subset of my data frame. Now I'm looking at all columns then this starts to bothering me.

Is there any way I can read them correctly without R attaching that additional "X.1" column in the end? Preferably not manually delete or subset out the last column...

Cheers,
ML

答:
If all other column names are correct, you have probably a trailing \t in the text file. R tries to include it and gives it the generic column name X.1.

You could try and read the file first as 'plain text' and remove the trailing \t and only then use read.csv:

```<code>file_connection <- file("Objects_Population - AllCells.txt")
content <- readLines(file_connection )
close(file_connection)
</code>```

Now we try to get rid of these trailing \t (this might need some testing to fit your needs)

```<code>sanitized <- gsub("\\t$", "", content)
</code>```

And then we read this sanitized string as if it was a file (using the argument text)

```<code>df <- read.csv(text=paste0(sanitized, collapse="\n"), sep="\t", skip = 9,header=TRUE, fill = T)
</code>```

Body:
I have got this .txt file outputed by a microscope to process.

#read the .txt file generated by microscope, skipping the first 9 lines of garbage information
df <- read.csv("Objects_Population - AllCells.txt", sep="\t", skip = 9,header=TRUE, fill = T)

Then I started looking at the structure of the dataframe, everything seems fine except I now found an extra column in the end of the data frame named "x.1" and all rows of it are NA values. I don't see this column when I open the .txt file in excel. I suspect the problem has something to do with the column names generated by microscope, they contain quite some special characters

Below is the dataframe read by Excel(only showing the last 2 columns since I have 132 columns, and their names are disgustingly long):

AllCells - Cell Contact Area with Neighbors [%] AllCells - Nucleus Nearest Neighbor Distance [Âµm]
0                                               4.82083
21.9512                                         0
15.7895                                         0
29.4118                                         0.584611
0                                               4.21569
0                                               1.99599
0                                               3.50767
...

This has happened to me before but I never took it too serious as I was always interested in a subset of my data frame. Now I'm looking at all columns then this starts to bothering me.

Is there any way I can read them correctly without R attaching that additional "X.1" column in the end? Preferably not manually delete or subset out the last column...

Cheers,
ML

Body:
If all other column names are correct, you have probably a trailing \t in the text file. R tries to include it and gives it the generic column name X.1.

You could try and read the file first as 'plain text' and remove the trailing \t and only then use read.csv:

file_connection <- file("Objects_Population - AllCells.txt")
content <- readLines(file_connection )
close(file_connection)

Now we try to get rid of these trailing \t (this might need some testing to fit your needs)

sanitized <- gsub("\\t$", "", content)

And then we read this sanitized string as if it was a file (using the argument text)

df <- read.csv(text=paste0(sanitized, collapse="\n"), sep="\t", skip = 9,header=TRUE, fill = T)


问:
Android file management
i use the code below to write a file to the sd card and read the content of it:

```<code>try {
        if (root.canWrite())
        {
                File rootdir = Environment.getExternalStorageDirectory();
                File yourFile = new File(rootdir, "tomato50.txt");
                FileWriter filewriter = new FileWriter(file,true);
                BufferedWriter out = new BufferedWriter(filewriter);
            for (int k=0; k<assignArr.size(); k++)
            {
               out.write(assignArr.get(k) + "\n");
               Toast.makeText(MainActivity.this, "out: " + assignArr.get(k), Toast.LENGTH_LONG).show();
            }
            out.close();
          }
          } catch (IOException e) {
          Log.e("TAG", "Could not write file " + e.getMessage());

try {
       File rootdir = Environment.getExternalStorageDirectory();
       File yourFile = new File(rootdir, "tomato50.txt");
       FileReader filereader = new FileReader(yourFile);
       BufferedReader br = new BufferedReader(filereader);
       String line;
       while((line = br.readLine()) != null)
       {
           assignArrBe.add(line);
           Toast.makeText(MainActivity.this, "Read from file: " + line, Toast.LENGTH_LONG).show();
        }
      br.close();
       }
      catch (IOException e)
     {
        e.printStackTrace();
     }
</code>```

Question is: how can i write to the phone memory and read from it?

答:
First of all you have to put in your manifest file this line:

```<code>...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
</code>```

If it is not enough, can you explain the problem with more details?

Title: Android file management

Body:
i use the code below to write a file to the sd card and read the content of it:

try {
        if (root.canWrite())
        {
                File rootdir = Environment.getExternalStorageDirectory();
                File yourFile = new File(rootdir, "tomato50.txt");
                FileWriter filewriter = new FileWriter(file,true);
                BufferedWriter out = new BufferedWriter(filewriter);
            for (int k=0; k<assignArr.size(); k++)
            {
               out.write(assignArr.get(k) + "\n");
               Toast.makeText(MainActivity.this, "out: " + assignArr.get(k), Toast.LENGTH_LONG).show();
            }
            out.close();
          }
          } catch (IOException e) {
          Log.e("TAG", "Could not write file " + e.getMessage());

try {
       File rootdir = Environment.getExternalStorageDirectory();
       File yourFile = new File(rootdir, "tomato50.txt");
       FileReader filereader = new FileReader(yourFile);
       BufferedReader br = new BufferedReader(filereader);
       String line;
       while((line = br.readLine()) != null)
       {
           assignArrBe.add(line);
           Toast.makeText(MainActivity.this, "Read from file: " + line, Toast.LENGTH_LONG).show();
        }
      br.close();
       }
      catch (IOException e)
     {
        e.printStackTrace();
     }

Question is: how can i write to the phone memory and read from it?

Body:
First of all you have to put in your manifest file this line:

...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>

If it is not enough, can you explain the problem with more details?


问:
TKinter dealing with multiple monitors and image display
I have functioning code but there are a few things which I would like to change about it but don't know how to so thought i'd ask here. My code is as follows:

```<code>import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

#Define the target, source and output arrays. Source has to be completely white otherwise it kills everything
def initialize(x,y):
    xarr = np.zeros(x)
    yarr = np.zeros(y)
    target = np.meshgrid(xarr,yarr)
    target = target[0]
    source = np.meshgrid(xarr,yarr)
    source = source[0]
    output = np.meshgrid(xarr,yarr)
    output = output[0]
    for i in range(x):
        for n in range(y):
            source[n][i] = 1
    return target, source, output

# creates trap between XTrapMin-XTrapMax and YTrapMin-YTrapMax on Array
def trap(xtmi,xtma,xs,ytmi,ytma,ys,array):
    for i in range(xs):
        if xtmi < i < xtma:
            for n in range(ys):
                if ytmi < n < ytma:
                    array[n][i] = 255
    return

#Returns the amplitude of a complex number
def Amplitude(x):
    if isinstance(x, complex):
        return np.sqrt(x.real**2+x.imag**2)
    else:
        return np.abs(x)

#Returns the phase of a complex number
def Phase(z):
        return np.angle(z)

#Main GS algorithm implementation using numpy FFT package
#performs the GS algorithm to obtain a phase distribution for the plane, Source
#such that its Fourier transform would have the amplitude distribution of the plane, Target.
def GS(target,source):
    A = np.fft.ifft2(target)
    for i in range(5):
        B = Amplitude(source) * np.exp(1j * Phase(A))
        C = np.fft.fft2(B)
        D = Amplitude(target) * np.exp(1j * Phase(C))
        A = np.fft.ifft2(D)
    output = Phase(A)
    return output

#Make array into PIL Image
def mkPIL(array):
    im = Image.fromarray(np.uint8(array))
    return im

def up():
    global ytmi
    global ytma
    ytmi -= 10
    ytma -= 10
    return

def down():
    global ytmi
    global ytma
    ytmi += 10
    ytma += 10
    return

def right():
    global xtmi
    global xtma
    xtmi += 10
    xtma += 10
    return

def left():
    global xtmi
    global xtma
    xtmi -= 10
    xtma -= 10
    return

xtmi = 125
xtma = 130
xs = 1024
ytmi = 0
ytma = 5
ys = 768

root = tk.Tk()
root.attributes('-fullscreen', True)
def main():
    app = Lower(root)
    root.mainloop()

class Lower:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master).pack()
        self.displayimg = tk.Button(self.frame, text = 'Display', width = 25, command = self.plot)
        self.displayimg.pack()
        self.makewidg()
    def makewidg(self):
        self.fig = plt.figure(figsize=(100,100), frameon=False)  #changing figsize doesnt cange the size of the plot display
        self.fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
        self.fig.tight_layout()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_yticklabels([])
        self.ax.set_xticklabels([])
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)
        self.canvas.get_tk_widget().pack(expand=True)
        self.canvas.figure.tight_layout()
        self.canvas.draw()
        self.new_window()
    def new_window(self):
        self.newWindow = tk.Toplevel()
        self.app = Display(self.newWindow)
    def plot(self):
        global xtmi, xtma, xs, ytmi, ytma, ys, i
        target,source,output=initialize(xs,ys)
        trap(xtmi,xtma,xs,ytmi,ytma,ys,target)
        output = GS(target,source)
        self.ax.imshow(output, cmap='gray')
        self.ax.set_yticklabels([])
        self.ax.set_xticklabels([])
        self.canvas.draw()
        self.ax.clear()

    def kill(self):
        root.destroy()

class Display:

    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.frame.pack()
        self.up = tk.Button(self.frame, text = 'Up', width = 25, command = up)
        self.up.pack()
        self.down = tk.Button(self.frame, text = 'Down', width = 25, command = down)
        self.down.pack()
        self.right = tk.Button(self.frame, text =  'Right', width = 25, command = right)
        self.right.pack()
        self.left = tk.Button(self.frame, text = 'Left', width = 25, command = left)
        self.left.pack()
        self.kill = tk.Button(self.frame, text = 'Kill', width = 25, command = self.kill)
        self.kill.pack()
    def kill(self):
        root.destroy()
main()
</code>```

Currently the button displayimg from the class Lower is displayed above the image, is there a way in which I can have the display button on the Display class and still have it manipulate the image on the Lower screen? Also, I intend to display the window opened by Lower on a separate monitor, but can't drag it seeing as it is fullscreen, is there a way around that I can get it on my second monitor?

I try that as such:

```<code>self.displayimg = tk.Button(self.top, text = 'Display', width = 25, command = Lower.plot(Lower))
self.displayimg.pack()
</code>```

But this causes a misreference I think as I get an error code

AttributeError: type object 'Lower' has no attribute 'ax'

答:
Call to Lower.plot

You are using Lower.plot as your button command. It needs one argument, self which must be an instance of Lower - so Lower.plot(Lower) is passing a class where an instance is expected. Instead you need to use the app instance you've made, and call app.plot(). The arguement self is automatically the instance itself, this is fundamental to OOP in python. Calling the method on an instance passes self as the first arg, so it's missing from the call. Calling Lower.plot(...) is calling the method on the class Lower, so there is no instance, and you have to supply your own. I'd avoid calling methods without an instance like this in this situation, and use your app instance.

Command for the display button

Your button creation becomes something like:
self.displayimg = tk.Button(self.top, text = 'Display', width = 25, command = app.plot)
If you need to pass additional args to plot, you need to delay the function call so it happens on click, not on creation of the button. You can use lambda : app.plot("red", 10, whatever) to make a nameless function, taking no arguments, that when called will go on to call app.plot with the given args.

Positioning the window

You can control the position of the app window using wm_geometry:

```<code>app.wm_geometry("200x200+100+500")
</code>```

Will cause the app window to be 200px by 200px, positioned 100px left and 500px down from the origin, and on a windows machine, this is the top left corner of your primary monitor. You can keep the width and height the same and just move the window with eg

```<code>app.wm_geometry("+100+500")
</code>```

You can use more scripting to build the string +{xpos}+{ypos} with whichever values you like to match your desktop layout.

Body:
I have functioning code but there are a few things which I would like to change about it but don't know how to so thought i'd ask here. My code is as follows:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

#Define the target, source and output arrays. Source has to be completely white otherwise it kills everything
def initialize(x,y):
    xarr = np.zeros(x)
    yarr = np.zeros(y)
    target = np.meshgrid(xarr,yarr)
    target = target[0]
    source = np.meshgrid(xarr,yarr)
    source = source[0]
    output = np.meshgrid(xarr,yarr)
    output = output[0]
    for i in range(x):
        for n in range(y):
            source[n][i] = 1
    return target, source, output

# creates trap between XTrapMin-XTrapMax and YTrapMin-YTrapMax on Array
def trap(xtmi,xtma,xs,ytmi,ytma,ys,array):
    for i in range(xs):
        if xtmi < i < xtma:
            for n in range(ys):
                if ytmi < n < ytma:
                    array[n][i] = 255
    return

#Returns the amplitude of a complex number
def Amplitude(x):
    if isinstance(x, complex):
        return np.sqrt(x.real**2+x.imag**2)
    else:
        return np.abs(x)

#Returns the phase of a complex number
def Phase(z):
        return np.angle(z)

#Main GS algorithm implementation using numpy FFT package
#performs the GS algorithm to obtain a phase distribution for the plane, Source
#such that its Fourier transform would have the amplitude distribution of the plane, Target.
def GS(target,source):
    A = np.fft.ifft2(target)
    for i in range(5):
        B = Amplitude(source) * np.exp(1j * Phase(A))
        C = np.fft.fft2(B)
        D = Amplitude(target) * np.exp(1j * Phase(C))
        A = np.fft.ifft2(D)
    output = Phase(A)
    return output

#Make array into PIL Image
def mkPIL(array):
    im = Image.fromarray(np.uint8(array))
    return im

def up():
    global ytmi
    global ytma
    ytmi -= 10
    ytma -= 10
    return

def down():
    global ytmi
    global ytma
    ytmi += 10
    ytma += 10
    return

def right():
    global xtmi
    global xtma
    xtmi += 10
    xtma += 10
    return

def left():
    global xtmi
    global xtma
    xtmi -= 10
    xtma -= 10
    return

xtmi = 125
xtma = 130
xs = 1024
ytmi = 0
ytma = 5
ys = 768

root = tk.Tk()
root.attributes('-fullscreen', True)
def main():
    app = Lower(root)
    root.mainloop()

class Lower:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master).pack()
        self.displayimg = tk.Button(self.frame, text = 'Display', width = 25, command = self.plot)
        self.displayimg.pack()
        self.makewidg()
    def makewidg(self):
        self.fig = plt.figure(figsize=(100,100), frameon=False)  #changing figsize doesnt cange the size of the plot display
        self.fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
        self.fig.tight_layout()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_yticklabels([])
        self.ax.set_xticklabels([])
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)
        self.canvas.get_tk_widget().pack(expand=True)
        self.canvas.figure.tight_layout()
        self.canvas.draw()
        self.new_window()
    def new_window(self):
        self.newWindow = tk.Toplevel()
        self.app = Display(self.newWindow)
    def plot(self):
        global xtmi, xtma, xs, ytmi, ytma, ys, i
        target,source,output=initialize(xs,ys)
        trap(xtmi,xtma,xs,ytmi,ytma,ys,target)
        output = GS(target,source)
        self.ax.imshow(output, cmap='gray')
        self.ax.set_yticklabels([])
        self.ax.set_xticklabels([])
        self.canvas.draw()
        self.ax.clear()

    def kill(self):
        root.destroy()

class Display:

    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.frame.pack()
        self.up = tk.Button(self.frame, text = 'Up', width = 25, command = up)
        self.up.pack()
        self.down = tk.Button(self.frame, text = 'Down', width = 25, command = down)
        self.down.pack()
        self.right = tk.Button(self.frame, text =  'Right', width = 25, command = right)
        self.right.pack()
        self.left = tk.Button(self.frame, text = 'Left', width = 25, command = left)
        self.left.pack()
        self.kill = tk.Button(self.frame, text = 'Kill', width = 25, command = self.kill)
        self.kill.pack()
    def kill(self):
        root.destroy()
main()

Currently the button displayimg from the class Lower is displayed above the image, is there a way in which I can have the display button on the Display class and still have it manipulate the image on the Lower screen? Also, I intend to display the window opened by Lower on a separate monitor, but can't drag it seeing as it is fullscreen, is there a way around that I can get it on my second monitor?

I try that as such:

self.displayimg = tk.Button(self.top, text = 'Display', width = 25, command = Lower.plot(Lower))
self.displayimg.pack()

But this causes a misreference I think as I get an error code

AttributeError: type object 'Lower' has no attribute 'ax'

Body:
Call to Lower.plot

You are using Lower.plot as your button command. It needs one argument, self which must be an instance of Lower - so Lower.plot(Lower) is passing a class where an instance is expected. Instead you need to use the app instance you've made, and call app.plot(). The arguement self is automatically the instance itself, this is fundamental to OOP in python. Calling the method on an instance passes self as the first arg, so it's missing from the call. Calling Lower.plot(...) is calling the method on the class Lower, so there is no instance, and you have to supply your own. I'd avoid calling methods without an instance like this in this situation, and use your app instance.

Command for the display button

Your button creation becomes something like:
self.displayimg = tk.Button(self.top, text = 'Display', width = 25, command = app.plot)
If you need to pass additional args to plot, you need to delay the function call so it happens on click, not on creation of the button. You can use lambda : app.plot("red", 10, whatever) to make a nameless function, taking no arguments, that when called will go on to call app.plot with the given args.

Positioning the window

You can control the position of the app window using wm_geometry:

app.wm_geometry("200x200+100+500")

Will cause the app window to be 200px by 200px, positioned 100px left and 500px down from the origin, and on a windows machine, this is the top left corner of your primary monitor. You can keep the width and height the same and just move the window with eg

app.wm_geometry("+100+500")

You can use more scripting to build the string +{xpos}+{ypos} with whichever values you like to match your desktop layout.


问:
Food menu list automatically split into 2 columns
I want to achieve a food menu that looks like this (screenshot), split into 2 columns.

So the question is: Is there any possible way to automate it? A la just insert foods into one list and it automatically splits it into 2 columns.

Best Regards

答:
You can do it with flexbox or with the css property column-count.

Please check this(column-count): https://www.w3schools.com/cssref/css3_pr_column-count.asp

Or this(flexbox): https://flexbox.help/

Hope it helps!


问:
How can I make a TextView automatically scroll as I add more lines of text?
So, I have a TextView like so:

```<code><TextView
    android:layout_width="fill_parent"
    android:layout_height="140.7dp"
    android:id="@+id/terminalOutput"
    android:layout_marginBottom="0.0dp"
    android:scrollbars="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true"
    android:maxLines="8" />
</code>```

I use it as a sort of running log, displayed to the user so they can monitor progress of a task that takes about 3 minutes. However, once I go over 8 lines, the text goes off screen. This is unintuitive to the user because they have no way of knowing that it went off screen, other than to manually poll by trying scroll down.

How can I make it so that every time I add some text to this TextView I make it scroll down as low as it can go?

Also, this is in Xamarin Android, but I don't think it's relevant. It's easy to translate between it and Java

答:
In my case, nothing worked at first because I was apparently attempting to make changes to the UI (auto scrolling up after adding text that is out of view), outside of the UI thread.  The words would display but with no auto scroll.  Correction, setText would work but not append.

My call for auto scroll was not in a UI thread because I coded the call to be made in response to a socket onMessage call; which I run on its own thread.  So, I had to enclose my function call with the following code and everything worked.

```<code> runOnUiThread(new Runnable() {
                 @Override
                 public void run() {

                     // Stuff that updates the UI

                 }
             });
</code>```

I'm sure all of the methods would work in someway so long as you are running it on a UI thread. But, to achieve the autoscroll effect for a "chat room" i.e. new text at top of chat window but when amount of text is longer than the window - autoscroll up the new messages into view, i just used the ... fullScroll(View.FOCUS_DOWN) ... method.

Body:
So, I have a TextView like so:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="140.7dp"
    android:id="@+id/terminalOutput"
    android:layout_marginBottom="0.0dp"
    android:scrollbars="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true"
    android:maxLines="8" />

I use it as a sort of running log, displayed to the user so they can monitor progress of a task that takes about 3 minutes. However, once I go over 8 lines, the text goes off screen. This is unintuitive to the user because they have no way of knowing that it went off screen, other than to manually poll by trying scroll down.

How can I make it so that every time I add some text to this TextView I make it scroll down as low as it can go?

Also, this is in Xamarin Android, but I don't think it's relevant. It's easy to translate between it and Java

Body:
In my case, nothing worked at first because I was apparently attempting to make changes to the UI (auto scrolling up after adding text that is out of view), outside of the UI thread.  The words would display but with no auto scroll.  Correction, setText would work but not append.

My call for auto scroll was not in a UI thread because I coded the call to be made in response to a socket onMessage call; which I run on its own thread.  So, I had to enclose my function call with the following code and everything worked.

 runOnUiThread(new Runnable() {
                 @Override
                 public void run() {

                     // Stuff that updates the UI

                 }
             });

I'm sure all of the methods would work in someway so long as you are running it on a UI thread. But, to achieve the autoscroll effect for a "chat room" i.e. new text at top of chat window but when amount of text is longer than the window - autoscroll up the new messages into view, i just used the ... fullScroll(View.FOCUS_DOWN) ... method.


问:
Excluding member functions and inheritance, what are some of the most common programming patterns for adding functionality to a class?
There're likely no more than 2-4 widely used approaches to this problem.

I have a situation in which there's a common class I use all over the place, and (on occasion) I'd like to give it special abilities.  For arguments sake, let's say that type checking is not a requirement.

What are some means of giving functionality to a class without it being simply inheritance or member functions?

One way I've seen is the "decorator" pattern in which a sort of mutator wraps around the class, modifies it a bit, and spits out a version of it with more functions.

Another one I've read about but never used is for gaming. It has something to do with entities and power-ups/augments.  I'm not sure about the specifics, but I think they have a list of them.

???

I don't need specific code of a specific language so much as a general gist and some keywords.  I can implement from there.

答:
So as far as I understand, you're looking to extend an interface to allow client-specific implementations that may require additional functionality, and you want to do so in a way that doesn't clutter up the base class.

As you mentioned, for simple systems, the standard way is to use the Adaptor pattern: subclass the "special abilities", then call that particular subclass when you need it. This is definitely the best choice if the extent of the special abilities you'll need to add is known and reasonably small, i.e. you generally only use the base class, but for three-to-five places where additional functionality is needed.

But I can see why you'd want some other possible options, because rarely do we know upfront the full extent of the additional functionality that will be required of the subclasses (i.e. when implementing a Connection API or a Component Class, each of which could be extended almost without bound). Depending on how complex the client-specific implementations are, how much additional functionality is needed and how much it varies between the implementations, this could be solved in a variety of ways:

Decorator Pattern as you mentioned (useful in the case where the special entities are only ever expanding the pre-existing methods of the base class, without adding brand new ones)

```<code>class MyClass{};
DecoratedClass = decorate(MyClass);
</code>```

A combined AbstractFactory/Adaptor builder for the subclasses (useful for cases where there are groupings of functionality in the subclasses that may differ in their implementations)

```<code>    interface Button {
        void paint();
    }

    interface GUIFactory {
        Button createButton();
    }

    class WinFactory implements GUIFactory {
        public Button createButton() {
            return new WinButton();
        }
    }

    class OSXFactory implements GUIFactory {
        public Button createButton() {
            return new OSXButton();
        }
    }

    class WinButton implements Button {
        public void paint() {
            System.out.println("I'm a WinButton");
        }
    }

    class OSXButton implements Button {
        public void paint() {
            System.out.println("I'm an OSXButton");
        }
    }

    class Application {
        public Application(GUIFactory factory) {
            Button button = factory.createButton();
            button.paint();
        }
     }

    public class ApplicationRunner {
        public static void main(String[] args) {
            new Application(createOsSpecificFactory());
        }

    public static GUIFactory createOsSpecificFactory() {
        int sys = readFromConfigFile("OS_TYPE");
        if (sys == 0) return new WinFactory();
        else return new OSXFactory();
        }
    }
</code>```

The Strategy pattern could also work, depending on the use case. But that would be a heavier lift with the preexisting base class that you don't want to change, and depending on if it is a strategy that is changing between those subclasses. The Visitor Pattern could also fit, but would have the same problem and involve a major change to the architecture around the base class.

```<code>class MyClass{
  public sort() { Globals.getSortStrategy()() }
};
</code>```

Finally, if the "special abilities" needed are enough (or could eventually be enough) to justify a whole new interface, this may be a good time for the use of the Extension Objects Pattern. Though it does make your clients or subclasses far more complex, as they have to manage a lot more: checking that the specific extension object and it's required methods exist, etc.

```<code>class MyClass{
  public addExtension(addMe) {
    addMe.initialize(this);
  }
  public getExtension(getMe);
};
(new MyClass()).getExtension("wooper").doWoop();
</code>```

With all that being said, keep it as simple as possible, sometimes you just have to write the specific subclasses or a few adaptors and you're done, especially with a preexisting class in use in many other places. You also have to ask how much you want to leave the class open for further extension. It might be worthwhile to keep the tech debt low with an abstract factory, so less changes need to be made when you add more functionality down the road. Or maybe what you really want is to lock the class down to prevent further extension, for the sake of understand-ability and simplicity. You have to examine your use case, future plans, and existing architecture to decide on the path forward. More than likely, there are lots of right answers and only a couple very wrong ones, so weigh the options, pick one that feels right, then implement and push code.

Body:
So as far as I understand, you're looking to extend an interface to allow client-specific implementations that may require additional functionality, and you want to do so in a way that doesn't clutter up the base class.

As you mentioned, for simple systems, the standard way is to use the Adaptor pattern: subclass the "special abilities", then call that particular subclass when you need it. This is definitely the best choice if the extent of the special abilities you'll need to add is known and reasonably small, i.e. you generally only use the base class, but for three-to-five places where additional functionality is needed.

But I can see why you'd want some other possible options, because rarely do we know upfront the full extent of the additional functionality that will be required of the subclasses (i.e. when implementing a Connection API or a Component Class, each of which could be extended almost without bound). Depending on how complex the client-specific implementations are, how much additional functionality is needed and how much it varies between the implementations, this could be solved in a variety of ways:

Decorator Pattern as you mentioned (useful in the case where the special entities are only ever expanding the pre-existing methods of the base class, without adding brand new ones)

class MyClass{};
DecoratedClass = decorate(MyClass);

A combined AbstractFactory/Adaptor builder for the subclasses (useful for cases where there are groupings of functionality in the subclasses that may differ in their implementations)

    interface Button {
        void paint();
    }

    interface GUIFactory {
        Button createButton();
    }

    class WinFactory implements GUIFactory {
        public Button createButton() {
            return new WinButton();
        }
    }

    class OSXFactory implements GUIFactory {
        public Button createButton() {
            return new OSXButton();
        }
    }

    class WinButton implements Button {
        public void paint() {
            System.out.println("I'm a WinButton");
        }
    }

    class OSXButton implements Button {
        public void paint() {
            System.out.println("I'm an OSXButton");
        }
    }

    class Application {
        public Application(GUIFactory factory) {
            Button button = factory.createButton();
            button.paint();
        }
     }

    public class ApplicationRunner {
        public static void main(String[] args) {
            new Application(createOsSpecificFactory());
        }

    public static GUIFactory createOsSpecificFactory() {
        int sys = readFromConfigFile("OS_TYPE");
        if (sys == 0) return new WinFactory();
        else return new OSXFactory();
        }
    }

The Strategy pattern could also work, depending on the use case. But that would be a heavier lift with the preexisting base class that you don't want to change, and depending on if it is a strategy that is changing between those subclasses. The Visitor Pattern could also fit, but would have the same problem and involve a major change to the architecture around the base class.

class MyClass{
  public sort() { Globals.getSortStrategy()() }
};

Finally, if the "special abilities" needed are enough (or could eventually be enough) to justify a whole new interface, this may be a good time for the use of the Extension Objects Pattern. Though it does make your clients or subclasses far more complex, as they have to manage a lot more: checking that the specific extension object and it's required methods exist, etc.

class MyClass{
  public addExtension(addMe) {
    addMe.initialize(this);
  }
  public getExtension(getMe);
};
(new MyClass()).getExtension("wooper").doWoop();

With all that being said, keep it as simple as possible, sometimes you just have to write the specific subclasses or a few adaptors and you're done, especially with a preexisting class in use in many other places. You also have to ask how much you want to leave the class open for further extension. It might be worthwhile to keep the tech debt low with an abstract factory, so less changes need to be made when you add more functionality down the road. Or maybe what you really want is to lock the class down to prevent further extension, for the sake of understand-ability and simplicity. You have to examine your use case, future plans, and existing architecture to decide on the path forward. More than likely, there are lots of right answers and only a couple very wrong ones, so weigh the options, pick one that feels right, then implement and push code.


问:
ReactJS error on using hooks with react router dom v6
I'm using the react router dom v6(tests) to create routes.
In one of the delete routes I am not getting the result of an api because I have an error.
I'm not able to get through useParams () the parameters passed in the url to do the search in the api.
The error is

Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)

  2. You might be breaking the Rules of Hooks

  3. You might have more than one copy of React in the same app

  See for tips about how to debug and fix this problem.

  ▶ 2 stack frames were collapsed.

  useParams

  C:/wamp64/packages/react-router/modules/index.js:383

    380 |  * This is useful for components that need to know "active" state, e.g.

    381 |  * .

    382 |  */

  383 | export function useMatch(to) {

    384 |   let location = useLocation();

    385 |   let resolvedLocation = useResolvedLocation(to);

    386 |   // TODO: Try to match search + hash as well

  View compiled

  Delete.renderResult

  C:/wamp64/www/apirest-react/src/actions/Delete/index.js:18

    15 |

    16 |  renderResult = async () => {

    17 |

  18 |      const {id} = useParams();

       | ^  19 |      const response = await api.get(/users/delete/${id}/Gla123);

    20 |      this.setState({message: response.data.message});

MY CODE:

```<code>import React, { Component } from 'react';
import { useParams } from 'react-router-dom';
import api from '../../services/api';
import './styles.css';
export default class Delete extends Component {

    state = {
        message: "Deleting user...",
    }

    componentDidMount() {
        this.renderResult();
    }

    renderResult = async () => {

        const { id } = useParams();
        const response = await api.get(`/users/delete/${id}/Gla123`);
        this.setState({ message: response.data.message });
    }
    render() {
        return (
            <div className="userDeleted">
                <div className="message">{this.state.message}</div>
            </div>
        );
    }
}
</code>```

答: you are not able to use hooks inside class components. Instead you should use withRouter HOC and get params from match property.</p>

Body:
I'm using the react router dom v6(tests) to create routes.
In one of the delete routes I am not getting the result of an api because I have an error.
I'm not able to get through useParams () the parameters passed in the url to do the search in the api.
The error is

Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)

  2. You might be breaking the Rules of Hooks

  3. You might have more than one copy of React in the same app

  See for tips about how to debug and fix this problem.

  ▶ 2 stack frames were collapsed.

  useParams

  C:/wamp64/packages/react-router/modules/index.js:383

    380 |  * This is useful for components that need to know "active" state, e.g.

    381 |  * .

    382 |  */

  383 | export function useMatch(to) {

    384 |   let location = useLocation();

    385 |   let resolvedLocation = useResolvedLocation(to);

    386 |   // TODO: Try to match search + hash as well

  View compiled

  Delete.renderResult

  C:/wamp64/www/apirest-react/src/actions/Delete/index.js:18

    15 |

    16 |  renderResult = async () => {

    17 |

  18 |      const {id} = useParams();

       | ^  19 |      const response = await api.get(/users/delete/${id}/Gla123);

    20 |      this.setState({message: response.data.message});

MY CODE:

import React, { Component } from 'react';
import { useParams } from 'react-router-dom';
import api from '../../services/api';
import './styles.css';
export default class Delete extends Component {

    state = {
        message: "Deleting user...",
    }

    componentDidMount() {
        this.renderResult();
    }

    renderResult = async () => {

        const { id } = useParams();
        const response = await api.get(`/users/delete/${id}/Gla123`);
        this.setState({ message: response.data.message });
    }
    render() {
        return (

{this.state.message}

        );
    }
}


问:
Error in running jar file of spring boot application
When i create a jar file it will be created but when i run a jar file it will show error similar happened with docker file when i create a docker file it will be created but when i run a docker file it will show error.

```<code>
jar {
    baseName = "${project.jarName}"
    version = "${project.versionName}"
    enabled = true
    manifest {
        attributes 'Main-Class': 'com.exmaple.Application'
    }

}

task buildDocker(type: Docker, dependsOn: build) {
    push = false
    applicationName = jar.baseName
    tagVersion = jar.version
    dockerfile = file('src/main/docker/Dockerfile')
    doFirst {
        copy {
            from jar
            into stageDir
        }
        copy {
            from "${project.buildDir}/resources/main/run.sh"
            into stageDir
        }
    }
}
</code>```

ERROR.

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
    at com.example.Application.main(Application.java:19)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication

答:
Use the Shadow Jar library in build.gradle file to resolve this issue.</p>

```<code>apply plugin: 'com.github.johnrengelman.shadow'

classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1'

</code>```

Body:
When i create a jar file it will be created but when i run a jar file it will show error similar happened with docker file when i create a docker file it will be created but when i run a docker file it will show error.

jar {
    baseName = "${project.jarName}"
    version = "${project.versionName}"
    enabled = true
    manifest {
        attributes 'Main-Class': 'com.exmaple.Application'
    }

}

task buildDocker(type: Docker, dependsOn: build) {
    push = false
    applicationName = jar.baseName
    tagVersion = jar.version
    dockerfile = file('src/main/docker/Dockerfile')
    doFirst {
        copy {
            from jar
            into stageDir
        }
        copy {
            from "${project.buildDir}/resources/main/run.sh"
            into stageDir
        }
    }
}

ERROR.

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
    at com.example.Application.main(Application.java:19)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication

Body:
Use the Shadow Jar library in build.gradle file to resolve this issue.

apply plugin: 'com.github.johnrengelman.shadow'

classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1'


问:
Angular CLI - changing where my components get generated
Is there anyway to change the default location of my generated components in angular cli config?

I want to change where my angular CLI defaults its generated components to a specific components folder.  After upgrading to angular 9 I get the following error when trying to generate a component outside of the root folder, which I never used to get:

```<code>Could not find an NgModule. Use the skip-import option to skip importing in NgModule.
</code>```

I can only seem to generate components and services from the root/src folder and nowhere else.

Just upgraded my angular and angular cli.  Currently running:

```<code>@angular-devkit/architect         0.900.2
@angular-devkit/build-angular     0.900.2
@angular-devkit/build-optimizer   0.900.2
@angular-devkit/build-webpack     0.900.2
@angular-devkit/core              9.0.2
@angular-devkit/schematics        9.0.2
@angular/cli                      9.0.2
@ngtools/webpack                  9.0.2
@schematics/angular               9.0.2
@schematics/update                0.900.2
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2
</code>```

答:
You have to generate the component as follow:

```<code>ng g c componentName [folder] --skip-import
</code>```

e.g:

```<code>ng g c myComponent myComponentFolder --skip-import
</code>```

and then add the component in the declarations array of your app.module.ts file manually.

Body:
Is there anyway to change the default location of my generated components in angular cli config?

I want to change where my angular CLI defaults its generated components to a specific components folder.  After upgrading to angular 9 I get the following error when trying to generate a component outside of the root folder, which I never used to get:

Could not find an NgModule. Use the skip-import option to skip importing in NgModule.

I can only seem to generate components and services from the root/src folder and nowhere else.

Just upgraded my angular and angular cli.  Currently running:

@angular-devkit/architect         0.900.2
@angular-devkit/build-angular     0.900.2
@angular-devkit/build-optimizer   0.900.2
@angular-devkit/build-webpack     0.900.2
@angular-devkit/core              9.0.2
@angular-devkit/schematics        9.0.2
@angular/cli                      9.0.2
@ngtools/webpack                  9.0.2
@schematics/angular               9.0.2
@schematics/update                0.900.2
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2

Body:
You have to generate the component as follow:

ng g c componentName [folder] --skip-import

e.g:

ng g c myComponent myComponentFolder --skip-import

and then add the component in the declarations array of your app.module.ts file manually.


问:
Are Strapi lifecycle callbacks 'broken'?
I'm interested in using Strapi's lifecycle callbacks -- https://strapi.io/documentation/3.0.0-beta.x/concepts/models.html#lifecycle-callbacks -- and someone in a Strapi forum mentioned that they are broken at the moment.  I tried to add one to my model's create method and it seems to work.  What is the current state?  We are considering Strapi for a large project, but it's in beta, and I'm not sure if it's at a stable enough state for us to use it.

答:
Yes as of right now the lifecycle callbacks are considered broken, you can follow the tracking issue here: https://github.com/strapi/strapi/issues/1443

They do plan to be reviewed before Strapi goes stable in the next 2 months I believe.

Edit: If you want to perform any of the beforeX logic you can override the controllers. The afterX is where things become a bit more difficult...


问:
Sum a list of objects based on BigDecimal field in single line
Suppose we have:

```<code>class Foo {
   public BigDecimal field;
}
</code>```

and that we have a list of Foo instances, i.e. List<Foo> list.

How can we calculate the sum of the values of the field from the objects in the list in a single line?

I found examples of similar cases using streams but they handle simpler cases and do not work for this; such as calculating for List<Integer> or when the field is something easily "summable" (int, Integer...).

答:
```<code>list.stream().map(foo -> foo.field).reduce(BigDecimal.ZERO, (a, b) -> a.add(b));
</code>```

Body:
Suppose we have:

class Foo {
   public BigDecimal field;
}

and that we have a list of Foo instances, i.e. List<Foo> list.

How can we calculate the sum of the values of the field from the objects in the list in a single line?

I found examples of similar cases using streams but they handle simpler cases and do not work for this; such as calculating for List<Integer> or when the field is something easily "summable" (int, Integer...).


问:
Trying to pass an array to a different class in Java
I'm creating a lottery program and trying linked lists for the first time. I'm passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".

There will be another class which will be made for the winning numbers but I'm trying to fix this issue first. I'm unsure how to fix this as I've been stuck for quite a while now.

Any help would be much appreciated.

This is the piece of code I'm having trouble with, this is in the Lottery class in the displayPlayers() method -

```<code>for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
</code>```

```<code>public class LOTTERY
{
    Scanner keyboard = new Scanner(System.in);

    private PLAYER pHead;

    public LOTTERY()
    {
        pHead = null;

    }

    public void displayPlayers() {
        PLAYER currentPlayer = pHead;
        System.out.println("Name: " + currentPlayer.getName());
        System.out.println("Age: " + currentPlayer.getAge());
        currentPlayer.randNum();
        System.out.println("Your Numbers: ");

        for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
        menu();
    }

    public void runProg() {

        displayPlayers();
    }

    public static void main(String[] args) {
        LOTTERY lottery = new LOTTERY();
        lottery.runProg();
    }
}

</code>```

答: The error you are getting says it all, the method you wrote takes no parameters. When you call your getNumbers() method, you pass it the value of i, though java does not expect that, since you declared the method without any parameters.

Body:
I'm creating a lottery program and trying linked lists for the first time. I'm passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".

There will be another class which will be made for the winning numbers but I'm trying to fix this issue first. I'm unsure how to fix this as I've been stuck for quite a while now.

Any help would be much appreciated.

This is the piece of code I'm having trouble with, this is in the Lottery class in the displayPlayers() method -

for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }

public class LOTTERY
{
    Scanner keyboard = new Scanner(System.in);

    private PLAYER pHead;

    public LOTTERY()
    {
        pHead = null;

    }

    public void displayPlayers() {
        PLAYER currentPlayer = pHead;
        System.out.println("Name: " + currentPlayer.getName());
        System.out.println("Age: " + currentPlayer.getAge());
        currentPlayer.randNum();
        System.out.println("Your Numbers: ");

        for(int i = 0; i < 6; i++) {
            System.out.println(currentPlayer.getNumbers(i));
        }
        menu();
    }

    public void runProg() {

        displayPlayers();
    }

    public static void main(String[] args) {
        LOTTERY lottery = new LOTTERY();
        lottery.runProg();
    }
}


问:
Using ajax autocompleteextender control in asp.net
I am using ajax AutoCompleteExtender control and using .net 3.5. I add the dll successfully in my toolbox tab.

So first of all i create a website and then drag the script manager, textbox and AutoCompleteExtender control in my default.aspx page. Then i add webservice and define one web method i.e. GetSuggestions(). My program is executed successfully but i am not getting the correct output. When i put any text in textbox, it is not populating any suggestion. Please help me.

Here is my webservice code:

```<code>using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]
[System.ComponentModel.ToolboxItem(false)]

public class MyAutocompleteService : WebService
{
    [WebMethod]

    public string[] GetSuggestions(string prefixText, int count)
    {
        List<string> responses = new List<string>();

        for (int i = 0; i < count; i++)

            responses.Add(prefixText + (char)(i + 65));

        return responses.ToArray();

    }

}
</code>```

And Here is my default.aspx code:

```<code><%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services >
        <asp:ServiceReference Path="~/MyAutocompleteService.asmx" />
        </Services>
        </asp:ScriptManager>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />

        <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
            ServiceMethod="GetSuggestions" ServicePath="MyAutocompleteService.asmx"
            TargetControlID="TextBox1" MinimumPrefixLength ="1"
            CompletionSetCount ="12" EnableCaching="true">
        </asp:AutoCompleteExtender>
        <br />
        <br />

    </div>
    </form>
</body>
</html>
</code>```

So please help me where i am missing.

答:
Try to use path without "~" sign</p>

```<code><asp:ServiceReference Path="MyAutocompleteService.asmx" />
</code>```

Body:
I am using ajax AutoCompleteExtender control and using .net 3.5. I add the dll successfully in my toolbox tab.

So first of all i create a website and then drag the script manager, textbox and AutoCompleteExtender control in my default.aspx page. Then i add webservice and define one web method i.e. GetSuggestions(). My program is executed successfully but i am not getting the correct output. When i put any text in textbox, it is not populating any suggestion. Please help me.

Here is my webservice code:

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;

///
/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]
[System.ComponentModel.ToolboxItem(false)]

public class MyAutocompleteService : WebService
{
    [WebMethod]

    public string[] GetSuggestions(string prefixText, int count)
    {
        List<string> responses = new List<string>();

        for (int i = 0; i < count; i++)

            responses.Add(prefixText + (char)(i + 65));

        return responses.ToArray();

    }

}

And Here is my default.aspx code:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Untitled Page</title>

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services >
        <asp:ServiceReference Path="~/MyAutocompleteService.asmx" />
        </Services>
        </asp:ScriptManager>

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
            ServiceMethod="GetSuggestions" ServicePath="MyAutocompleteService.asmx"
            TargetControlID="TextBox1" MinimumPrefixLength ="1"
            CompletionSetCount ="12" EnableCaching="true">
        </asp:AutoCompleteExtender>

    </form>

So please help me where i am missing.

Body:
Try to use path without "~" sign

<asp:ServiceReference Path="MyAutocompleteService.asmx" />


问:
Azure function Python - error "binding type(s) 'blobTrigger' are not registered"
I am trying to run an Azure function locally on my Mac and getting the following error: The binding type(s) 'blobTrigger' are not registered. Please ensure the type is correct and the binding extension is installed.

I'm working with Python 3.6.8 and have installed azure-functions-core-tools using homebrew (brew tap azure/functions; brew install azure-functions-core-tools).

Setup my local.settings.json file with the expected configuration, so function should be listening to the correct storage container hosted in azure.

Im certain I have not changed any code or configuration files since it was working last week.

host.json file contains:

```<code>{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}
</code>```

function.json file contains:

```<code>{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "xmlblob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "<directory>/{name}",
      "connection": "AzureStorageAccountConnectionString"
    }
  ]
}
</code>```

requirements.txt file contains:

```<code>azure-cosmos==3.1.0
azure-functions-worker==1.0.0b6
azure-storage==0.36.0
azure-storage-blob==2.0.1
xmljson==0.2.0
xmlschema==1.0.11
</code>```

Then I run the following commands in my terminal:

```<code>1) pip install -r requirements.txt
2) source .env/bin/activate
3) func host start
</code>```

I then get the following error:

```<code><Application name>: The binding type(s) 'blobTrigger' are not registered. Please ensure the type is correct and the binding extension is installed.
</code>```

答:
You have done everything correct by the looks of it, but you need to have the dotnet core framework and runtime installed locally in order to execute the trigger.

For me on Ubuntu, I followed this guide. Once installed I was able to trigger a blob function locally.

For Mac, I would take a look here about installing dotnot core.

Body:
I am trying to run an Azure function locally on my Mac and getting the following error: The binding type(s) 'blobTrigger' are not registered. Please ensure the type is correct and the binding extension is installed.

I'm working with Python 3.6.8 and have installed azure-functions-core-tools using homebrew (brew tap azure/functions; brew install azure-functions-core-tools).

Setup my local.settings.json file with the expected configuration, so function should be listening to the correct storage container hosted in azure.

Im certain I have not changed any code or configuration files since it was working last week.

host.json file contains:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}

function.json file contains:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "xmlblob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "<directory>/{name}",
      "connection": "AzureStorageAccountConnectionString"
    }
  ]
}

requirements.txt file contains:

azure-cosmos==3.1.0
azure-functions-worker==1.0.0b6
azure-storage==0.36.0
azure-storage-blob==2.0.1
xmljson==0.2.0
xmlschema==1.0.11

Then I run the following commands in my terminal:

1) pip install -r requirements.txt
2) source .env/bin/activate
3) func host start

I then get the following error:

<Application name>: The binding type(s) 'blobTrigger' are not registered. Please ensure the type is correct and the binding extension is installed.