问:
Using a lambda function for pandas.DataFrame boolean indexing reports TypeError
I have a list of words called sowpods and I need to verify which combination of letters exist either as a word or within a word.

For example, if my letters are ['r', 't', 'e', 'f'], one of the possible combinations is 're' which is within 'red', therefore the word 'red' should be kept.

I already have some code that can figure out all of the possible combinations, but now I want to find how to add all of the words that fit the requirements to a list.

I have done the following:

import pandas as pd

sowpods = pd.read_csv('sowpods.csv', names=['Word'])

possible_combination = 'RE'
possible_words = pd.DataFrame([], columns=['Word'])

comb_in_word = lambda _: True if (possible_combination in _) else False # ------ line 8

sowpods_bool = sowpods['Word'].apply(comb_in_word) # --------------------------- line 10
possible_words.append(sowpods.loc[sowpods_bool, 'Word'])
```

<p>But then I get:</p>

<pre class="lang-py prettyprint-override"><code> File "c:\tests.py", line 10, in <module>
    sowpods_bool = sowpods['Word'].apply(comb_in_word)
  File "C:\Python38-32\lib\site-packages\pandas\core\series.py", line 3848, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas\_libs\lib.pyx", line 2329, in pandas._libs.lib.map_infer
  File "c:\Users\lenovo\OneDrive\Prog\Projects\Scrabble\tests.py", line 8, in <lambda>
    comb_in_word = lambda _: True if possible_combination in _ else False
TypeError: argument of type 'float' is not iterable
</code>```

I tested my lambda function in a more controlled environment and it worked fine, so I'm confident that the error's not coming from there.

I don't understand why I get this error when I'm not iterating through anything myself. I get that pandas is iterating through the DataFrame's column, but it shouldn't do an error where it's using floats instead of integers.

Edit:

[In]
print(sowpods.head())
[Out]
      Word
0      AA
1     AAH
2   AAHED
3  AAHING
4    AAHS
```

<pre class="lang-py prettyprint-override"><code>[In]
print(sowpods.dtypes)
[Out]
Word    object
dtype: object
</code>```

答:
In the list of words there were 'NA' and 'NULL', which Pandas represented as NaNs. I had to specify keep_default_na=False:

```<code>sowpods = pd.read_csv('projects/scrabble/sowpods_en.csv', names=['Word'], keep_default_na=False)

</code>```

Body:
I have a list of words called sowpods and I need to verify which combination of letters exist either as a word or within a word.

For example, if my letters are ['r', 't', 'e', 'f'], one of the possible combinations is 're' which is within 'red', therefore the word 'red' should be kept.

I already have some code that can figure out all of the possible combinations, but now I want to find how to add all of the words that fit the requirements to a list.

I have done the following:

import pandas as pd

sowpods = pd.read_csv('sowpods.csv', names=['Word'])

possible_combination = 'RE'
possible_words = pd.DataFrame([], columns=['Word'])

comb_in_word = lambda _: True if (possible_combination in _) else False # ------ line 8

sowpods_bool = sowpods['Word'].apply(comb_in_word) # --------------------------- line 10
possible_words.append(sowpods.loc[sowpods_bool, 'Word'])

But then I get:

 File "c:\tests.py", line 10, in <module>
    sowpods_bool = sowpods['Word'].apply(comb_in_word)
  File "C:\Python38-32\lib\site-packages\pandas\core\series.py", line 3848, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas\_libs\lib.pyx", line 2329, in pandas._libs.lib.map_infer
  File "c:\Users\lenovo\OneDrive\Prog\Projects\Scrabble\tests.py", line 8, in <lambda>
    comb_in_word = lambda _: True if possible_combination in _ else False
TypeError: argument of type 'float' is not iterable

I tested my lambda function in a more controlled environment and it worked fine, so I'm confident that the error's not coming from there.

I don't understand why I get this error when I'm not iterating through anything myself. I get that pandas is iterating through the DataFrame's column, but it shouldn't do an error where it's using floats instead of integers.

Edit:

[In]
print(sowpods.head())
[Out]
      Word
0      AA
1     AAH
2   AAHED
3  AAHING
4    AAHS

[In]
print(sowpods.dtypes)
[Out]
Word    object
dtype: object

Body:
In the list of words there were 'NA' and 'NULL', which Pandas represented as NaNs. I had to specify keep_default_na=False:

sowpods = pd.read_csv('projects/scrabble/sowpods_en.csv', names=['Word'], keep_default_na=False)


来源: stackexchange

问:
Subscription to MQTT broker and get the data being passed
I am generating data with a node.js simulator and passing this data to a http route /simulator/data

In the application I am listening broker with MQTT mqtthandler.js file which I share below.

```<code>//This is mqtthandler.js file

const mqtt = require("mqtt");

class MqttHandler {
  constructor() {
    this.mqttClient = null;
    this.host = "mqtt://localhost:1883";
    this.username = "YOUR_USER"; // mqtt credentials if these are needed to connect
    this.password = "YOUR_PASSWORD";
  }

  connect() {
    // Connect mqtt with credentials (in case of needed, otherwise we can omit 2nd param)
    this.mqttClient = mqtt.connect(this.host, {
      username: this.username,
      password: this.password,
    });

    // Mqtt error calback
    this.mqttClient.on("error", (err) => {
      console.log(err);
      this.mqttClient.end();
    });

    // Connection callback
    this.mqttClient.on("connect", () => {
      console.log(`mqtt client connected`);
    });

    // mqtt subscriptions
    this.mqttClient.subscribe("value", { qos: 0 });

    // When a message arrives, console.log it
    this.mqttClient.on("message", function (topic, message) {
      console.log(message.toString());
    });

    this.mqttClient.on("close", () => {
      console.log(`mqtt client disconnected`);
    });
  }

  // Sends a mqtt message to topic: mytopic
  sendMessage(message) {
    this.mqttClient.publish("value", message);
  }
}

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

When simulator sending the data to the /simulator/data route, I am getting the value and sending the broker with value topic. I share the post request code and output of simulator below.

```<code>var mqttHandler = require("../mqtthandler");

module.exports = function (app) {
  app.get("/simulator", function (req, res) {
    res.render("iot/simulator");
  });

  // route to display all the data that is generated
  app.get("/simulator/data", require("./controllers/data").all);

  var mqttClient = new mqttHandler();
  mqttClient.connect();

  // route to write data to the database
  app.post(
    "/simulator/data",
    require("./controllers/data").write,
    (req, res) => {
      mqttClient.sendMessage(req.body.value);
      res.status(200).send("Message sent to mqtt");
    }
  );

  // delete the data when the stream is stopped or when the app is closed
  app.get("/simulator/data/delete", require("./controllers/data").delete);
};
</code>```

When I send get request to /simulator/data I am able to see generated data, however this data is not being sent to broker.

```<code>//This is output of simulator

    [
        {
            "_id": "5ecfadc13cb66f10e4d9d39b",
            "value": "1.886768240197795",
            "__v": 0,
            "categories": []
        },
        {
            "_id": "5ecfadc23cb66f10e4d9d39c",
            "value": "7.351404601932272",
            "__v": 0,
            "categories": []
        }
    ]
</code>```

PS: Broker is created via node-red

I would like to pass this data to broker and see the result with MQTT subscription. However I can not find where am I making mistake.

答:
Your solution is to fix your development process. Rather than working from failure debugging 2 subsystems (your publisher / simulator and your subscriber), work from success:

1) use publishers that you KNOW work, eg. mosquitto_pub, any simulator that works, etc.

2) use subscribers that you KNOW work, eg. mosquitto_sub

This will solve your problem in minutes, rather than hours or days, and let you focus on the code that you REALLY want to develop.

ContentLicense: CC BY-SA 4.0

Body:
I am generating data with a node.js simulator and passing this data to a http route /simulator/data

In the application I am listening broker with MQTT mqtthandler.js file which I share below.

//This is mqtthandler.js file

const mqtt = require("mqtt");

class MqttHandler {
  constructor() {
    this.mqttClient = null;
    this.host = "mqtt://localhost:1883";
    this.username = "YOUR_USER"; // mqtt credentials if these are needed to connect
    this.password = "YOUR_PASSWORD";
  }

  connect() {
    // Connect mqtt with credentials (in case of needed, otherwise we can omit 2nd param)
    this.mqttClient = mqtt.connect(this.host, {
      username: this.username,
      password: this.password,
    });

    // Mqtt error calback
    this.mqttClient.on("error", (err) => {
      console.log(err);
      this.mqttClient.end();
    });

    // Connection callback
    this.mqttClient.on("connect", () => {
      console.log(`mqtt client connected`);
    });

    // mqtt subscriptions
    this.mqttClient.subscribe("value", { qos: 0 });

    // When a message arrives, console.log it
    this.mqttClient.on("message", function (topic, message) {
      console.log(message.toString());
    });

    this.mqttClient.on("close", () => {
      console.log(`mqtt client disconnected`);
    });
  }

  // Sends a mqtt message to topic: mytopic
  sendMessage(message) {
    this.mqttClient.publish("value", message);
  }
}

module.exports = MqttHandler;

When simulator sending the data to the /simulator/data route, I am getting the value and sending the broker with value topic. I share the post request code and output of simulator below.

var mqttHandler = require("../mqtthandler");

module.exports = function (app) {
  app.get("/simulator", function (req, res) {
    res.render("iot/simulator");
  });

  // route to display all the data that is generated
  app.get("/simulator/data", require("./controllers/data").all);

  var mqttClient = new mqttHandler();
  mqttClient.connect();

  // route to write data to the database
  app.post(
    "/simulator/data",
    require("./controllers/data").write,
    (req, res) => {
      mqttClient.sendMessage(req.body.value);
      res.status(200).send("Message sent to mqtt");
    }
  );

  // delete the data when the stream is stopped or when the app is closed
  app.get("/simulator/data/delete", require("./controllers/data").delete);
};

When I send get request to /simulator/data I am able to see generated data, however this data is not being sent to broker.

//This is output of simulator

    [
        {
            "_id": "5ecfadc13cb66f10e4d9d39b",
            "value": "1.886768240197795",
            "__v": 0,
            "categories": []
        },
        {
            "_id": "5ecfadc23cb66f10e4d9d39c",
            "value": "7.351404601932272",
            "__v": 0,
            "categories": []
        }
    ]

PS: Broker is created via node-red

I would like to pass this data to broker and see the result with MQTT subscription. However I can not find where am I making mistake.


问:
How to check from which onResume the user is coming
I have a problem. The following Picture visualises my issue. We start in App 1 and press the button. Now we either get to see the screen of app2 or the setting screen. Now when i press the back button (marked as the red circle in app2 and settings) and we get back to the app1 screen. But what i wanna know is from what screen we get back to the app1 screen.

```<code>    @Override
        protected void onResume() {
            super.onResume();

        // if(from setting) {
            // do this
           }

            NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
            NfcAdapter adapter = manager.getDefaultAdapter();
            if (adapter != null && adapter.isEnabled()) {
                   Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
                    startActivity(userHomeScreen);

            }
        }

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc_setting);

        NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
        NfcAdapter adapter = manager.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled()) {
            FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
            if (currentUser != null){
                Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
                startActivity(userHomeScreen);
            }else{
                Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(loginScreen);
            }
        }
        else {
            btn_nfc_navigate_setting = findViewById(R.id.btn_nfc_navigate_setting);

            btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
                }
            });
        }
</code>```

答:
If you want to know the result of an Intent (in this case settings or app2), you can use

startActivityForResult(intent, requestCode)

instead of

startActivity(intent).

Where request code should be unique for different intents (in this case settings and app2).

To handle the result you have to override the onActivityResult() in the actvity.

So your required code will be

```<code>    @Override
    protected void onResume() {
        super.onResume();

    // if(from setting) {
        // do this
        // }

        NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
        NfcAdapter adapter = manager.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled()) {
               Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
                startActivityForResult(userHomeScreen,1);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
        //    Activity returned from userHomeScreen
        }
        else if (requestCode ==2) {
        //    Activity returned from Settings
        }
    }
</code>```

UPDATE:

To add to that above if you want to access any Settings FEATURE you can use SETTINGS Constants as intent parameters.

Settings Documentation

For example, if you want to access NFC settings:

```<code>// Look into the constants in the documentation to know which constants to use in intent
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivityForResult(intent, 2);
</code>```

Body:
I have a problem. The following Picture visualises my issue. We start in App 1 and press the button. Now we either get to see the screen of app2 or the setting screen. Now when i press the back button (marked as the red circle in app2 and settings) and we get back to the app1 screen. But what i wanna know is from what screen we get back to the app1 screen.

    @Override
        protected void onResume() {
            super.onResume();

        // if(from setting) {
            // do this
           }

            NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
            NfcAdapter adapter = manager.getDefaultAdapter();
            if (adapter != null && adapter.isEnabled()) {
                   Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
                    startActivity(userHomeScreen);

            }
        }

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc_setting);

        NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
        NfcAdapter adapter = manager.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled()) {
            FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
            if (currentUser != null){
                Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
                startActivity(userHomeScreen);
            }else{
                Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(loginScreen);
            }
        }
        else {
            btn_nfc_navigate_setting = findViewById(R.id.btn_nfc_navigate_setting);

            btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
                }
            });
        }

Body:
If you want to know the result of an Intent (in this case settings or app2), you can use

startActivityForResult(intent, requestCode)

instead of

startActivity(intent).

Where request code should be unique for different intents (in this case settings and app2).

To handle the result you have to override the onActivityResult() in the actvity.

So your required code will be

    @Override
    protected void onResume() {
        super.onResume();

    // if(from setting) {
        // do this
        // }

        NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
        NfcAdapter adapter = manager.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled()) {
               Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
                startActivityForResult(userHomeScreen,1);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
        //    Activity returned from userHomeScreen
        }
        else if (requestCode ==2) {
        //    Activity returned from Settings
        }
    }

UPDATE:

To add to that above if you want to access any Settings FEATURE you can use SETTINGS Constants as intent parameters.

Settings Documentation

For example, if you want to access NFC settings:

// Look into the constants in the documentation to know which constants to use in intent
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivityForResult(intent, 2);


问:
What does {} means in services section of docker-compose.yml
I want to backup my wordpress container with a simple tar command but I struggle to understand where the db folder is located.

I have the following docker-compose.yml :

version: '2.0'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: ***
       MYSQL_DATABASE: ***
       MYSQL_USER: ***
       MYSQL_PASSWORD: ***

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
       - "8001:443"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: ***
       WORDPRESS_DB_PASSWORD: ***
       WORDPRESS_DB_NAME: ***
volumes:
    db_data: {}
```

The db_data volume is declared with this {}, on the dokcer-compose documentation I don't find any information : https://docs.docker.com/compose/compose-file/compose-file-v2/#volumes

I suppose it's not binded to the host filesystem

答:
In yaml a map can be represented with a JSON-like form: {fee: fie, foe: foo}.
So {} is simply an empty map - i.e. there are no volumes mounted.

See the spec here

Body:
I want to backup my wordpress container with a simple tar command but I struggle to understand where the db folder is located.

I have the following docker-compose.yml :

version: '2.0'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: ***
       MYSQL_DATABASE: ***
       MYSQL_USER: ***
       MYSQL_PASSWORD: ***

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
       - "8001:443"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: ***
       WORDPRESS_DB_PASSWORD: ***
       WORDPRESS_DB_NAME: ***
volumes:
    db_data: {}

The db_data volume is declared with this {}, on the dokcer-compose documentation I don't find any information : https://docs.docker.com/compose/compose-file/compose-file-v2/#volumes

I suppose it's not binded to the host filesystem


问:
Does the night mode need sqlite?
I just want to know if the night mode in Android needs sqlite?
or there's another way to save the mode in it
when the user close the app and reopen it again it will save the mode
pls help

If there's another way please share it with me
Thanks

答:
You can just save a variable in the SharedPreferences of the app for the preferred user settings and set theme on launch.
Go through the documentation to know more .SharedPreferences</p>

Title: Does the night mode need sqlite?


问:
Produce mapfile with CMAKE_CXX_FLAGS and MSVC14
I'am trying to generate a Mapfile with CMake (Clion)

```<code>cmake_minimum_required(VERSION 3.13)
project(cmake_testapp)
set(CMAKE_CXX_STANDARD 14)
MESSAGE("TEST_HELLO")
set(MSVC_COVERAGE_COMPILE_FLAGS "/Fm${PROJECT_SOURCE_DIR}/file.map")

set(CMAKE_CXX_FLAGS "${MSVC_COVERAGE_COMPILE_FLAGS} ${CMAKE_CXX_FLAGS}" )
MESSAGE(${CMAKE_CXX_FLAGS})
MESSAGE(${CMAKE_CXX_COMPILER})
add_executable(cmake_testapp loaderstack.cpp)
</code>```

Output:

```<code>"C:\Program Files\JetBrains\CLion 2020.1.1\bin\cmake\win\bin\cmake.exe" -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - NMake Makefiles" C:\Users\remi\Desktop\OK
TEST_HELLO
/FmC:/Users/remi/Desktop/OK/file.map /DWIN32 /D_WINDOWS /W3 /GR /EHsc
C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.26.28801/bin/Hostx86/x86/cl.exe
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/remi/Desktop/OK/cmake-build-debug

[Finished]
</code>```

But no file.map is produced even if the CMAKE_CXX_FLAGS contains the flag.

答:
The map file is generated by the linker, and is typically disabled by default. To enable generation of a map file, the /MAP linker option must be provided. When I tested with /MAP, the compiler flag /Fm specifying the map file path name was ignored, and the map file was generated with a default name next to the binary.

However, you can also specify the map file name by appending it to the /MAP linker option. In CMake, you can specify link options for a specific target using target_link_options:

```<code>cmake_minimum_required(VERSION 3.13)
project(cmake_testapp)
set(CMAKE_CXX_STANDARD 14)
MESSAGE("TEST_HELLO")

MESSAGE(${CMAKE_CXX_COMPILER})
add_executable(cmake_testapp loaderstack.cpp)

# Set the coverage flags for the cmake_testapp executable only.
target_link_options(cmake_testapp PRIVATE "/MAP:${PROJECT_SOURCE_DIR}/file.map")
</code>```

Body:
I'am trying to generate a Mapfile with CMake (Clion)

cmake_minimum_required(VERSION 3.13)
project(cmake_testapp)
set(CMAKE_CXX_STANDARD 14)
MESSAGE("TEST_HELLO")
set(MSVC_COVERAGE_COMPILE_FLAGS "/Fm${PROJECT_SOURCE_DIR}/file.map")

set(CMAKE_CXX_FLAGS "${MSVC_COVERAGE_COMPILE_FLAGS} ${CMAKE_CXX_FLAGS}" )
MESSAGE(${CMAKE_CXX_FLAGS})
MESSAGE(${CMAKE_CXX_COMPILER})
add_executable(cmake_testapp loaderstack.cpp)

Output:

"C:\Program Files\JetBrains\CLion 2020.1.1\bin\cmake\win\bin\cmake.exe" -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - NMake Makefiles" C:\Users\remi\Desktop\OK
TEST_HELLO
/FmC:/Users/remi/Desktop/OK/file.map /DWIN32 /D_WINDOWS /W3 /GR /EHsc
C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.26.28801/bin/Hostx86/x86/cl.exe
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/remi/Desktop/OK/cmake-build-debug

[Finished]

But no file.map is produced even if the CMAKE_CXX_FLAGS contains the flag.

Body:
The map file is generated by the linker, and is typically disabled by default. To enable generation of a map file, the /MAP linker option must be provided. When I tested with /MAP, the compiler flag /Fm specifying the map file path name was ignored, and the map file was generated with a default name next to the binary.

However, you can also specify the map file name by appending it to the /MAP linker option. In CMake, you can specify link options for a specific target using target_link_options:

cmake_minimum_required(VERSION 3.13)
project(cmake_testapp)
set(CMAKE_CXX_STANDARD 14)
MESSAGE("TEST_HELLO")

MESSAGE(${CMAKE_CXX_COMPILER})
add_executable(cmake_testapp loaderstack.cpp)

# Set the coverage flags for the cmake_testapp executable only.
target_link_options(cmake_testapp PRIVATE "/MAP:${PROJECT_SOURCE_DIR}/file.map")


问:
Project Reactor conditional execution of independent verification step
I can't figure it out, how to do this method without the if/else:

```<code>public Mono<Token> doAuthorization(InputDto dto) {
    if (isXStepNeeded(dto)) {
        return doXStep(dto)
            .then(doYStep(dto.getRfid()));
    } else {
        return doYStep(dto.getRfid());
    }
}

private boolean isXStepNeeded(InputDto  dto) {
    //simple non blocking check on the dto
}
private Mono<OtherDto> doXStep(InputDto  dto) {
    //checking something and returning Mono.error() if it fails
}
private Mono<Token> doYStep(String tokenUid) {
    //...
}
</code>```

As you can see, the X and Y steps are independent of each other. Is there a nice, readable way of writing doAuthorization that does not use if/else and I only have to write down doYStep() once?

答:
There is no way to do this without an if else while keeping it readable. Some options to do while keeping it readable include using "ternary operator" and new "switch case" introduced in Java 14.

Reduce it to one line using ternary operator:

```<code>return isXStepNeeded(dto) ? doXStep(dto).then(doYStep(dto.getRfid())) : doYStep(dto.getRfid());
</code>```

Or use the new switch case:

```<code>return switch (Boolean.toString(isXStepNeeded(dto))) {
    case "true" -> doXStep(dto).then(doYStep(dto.getRfid()));
    default -> doYStep(dto.getRfid());
};
</code>```

EDIT:

Since you don't want to write doYStep twice, you can do:

```<code>return Mono.just(isXStepNeeded(dto))
        .filter(b -> b)
        .flatMap(b -> doXStep(dto))
        .then(doYStep(dto.getRfid()));
</code>```

Body:
I can't figure it out, how to do this method without the if/else:

public Mono<Token> doAuthorization(InputDto dto) {
    if (isXStepNeeded(dto)) {
        return doXStep(dto)
            .then(doYStep(dto.getRfid()));
    } else {
        return doYStep(dto.getRfid());
    }
}

private boolean isXStepNeeded(InputDto  dto) {
    //simple non blocking check on the dto
}
private Mono<OtherDto> doXStep(InputDto  dto) {
    //checking something and returning Mono.error() if it fails
}
private Mono<Token> doYStep(String tokenUid) {
    //...
}

As you can see, the X and Y steps are independent of each other. Is there a nice, readable way of writing doAuthorization that does not use if/else and I only have to write down doYStep() once?

Body:
There is no way to do this without an if else while keeping it readable. Some options to do while keeping it readable include using "ternary operator" and new "switch case" introduced in Java 14.

Reduce it to one line using ternary operator:

return isXStepNeeded(dto) ? doXStep(dto).then(doYStep(dto.getRfid())) : doYStep(dto.getRfid());

Or use the new switch case:

return switch (Boolean.toString(isXStepNeeded(dto))) {
    case "true" -> doXStep(dto).then(doYStep(dto.getRfid()));
    default -> doYStep(dto.getRfid());
};

EDIT:

Since you don't want to write doYStep twice, you can do:

return Mono.just(isXStepNeeded(dto))
        .filter(b -> b)
        .flatMap(b -> doXStep(dto))
        .then(doYStep(dto.getRfid()));


问:
Pass bash variables to a list of commands stored as a separate "commands.txt"
I have the following PBS script:

```<code>#!/bin/bash -l
#PBS -l walltime=12:00:00,nodes=1:ppn=24,pmem=2580mb

((start=24))
((n_jobs_procimg=8))

cd $PBS_O_WORKDIR
conda activate msi_sip_37

module load parallel
parallel -u -j 3 < commands.txt
wait
</code>```

And the contents of commands.txt are:

```<code>python runs/process_img.py --n_jobs $n_jobs_procimg --msi_test True --idx_min $start+0 --idx_max $start+8
python runs/process_img.py --n_jobs $n_jobs_procimg --msi_test True --idx_min $start+8 --idx_max $start+16
python runs/process_img.py --n_jobs $n_jobs_procimg --msi_test True --idx_min $start+16 --idx_max $start+24
</code>```

I [incorrectly] expect that $start and $n_jobs_procimg should be available to the commands in commands.txt, but when I run this job, I get the following error for each command in commands.txt:

```<code>usage: process_img.py [-h] [-n N_JOBS] [-m MSI_TEST] [-i IDX_MIN] [-d IDX_MAX]
process_img.py: error: argument -n/--n_jobs: expected one argument
</code>```

How do I modify the parallel command in the PBS script so that $start and $n_jobs_procimg are passed to commands.txt?

In this case, $start should be an integer equal to 24 and $n_jobs_procimg should be an integer equal to 8.

It's not relevant to my question, but for context the process_img.py script uses a multiprocessing pool that takes the number of processing cores and as an argument (--n_jobs), and I want to have control over that based on the total number of processing cores I have available.

答:
export the variables:

```<code>#!/bin/bash -l
#PBS -l walltime=12:00:00,nodes=1:ppn=24,pmem=2580mb

start=24
n_jobs_procimg=8
export start
export n_jobs_procimg

cd $PBS_O_WORKDIR
conda activate msi_sip_37

module load parallel
parallel -u -j 3 < commands.txt
</code>```

Body:
I have the following PBS script:

#!/bin/bash -l
#PBS -l walltime=12:00:00,nodes=1:ppn=24,pmem=2580mb

((start=24))
((n_jobs_procimg=8))

cd $PBS_O_WORKDIR
conda activate msi_sip_37

module load parallel
parallel -u -j 3 < commands.txt
wait

And the contents of commands.txt are:

python runs/process_img.py --n_jobs $n_jobs_procimg --msi_test True --idx_min $start+0 --idx_max $start+8
python runs/process_img.py --n_jobs $n_jobs_procimg --msi_test True --idx_min $start+8 --idx_max $start+16
python runs/process_img.py --n_jobs $n_jobs_procimg --msi_test True --idx_min $start+16 --idx_max $start+24

I [incorrectly] expect that $start and $n_jobs_procimg should be available to the commands in commands.txt, but when I run this job, I get the following error for each command in commands.txt:

usage: process_img.py [-h] [-n N_JOBS] [-m MSI_TEST] [-i IDX_MIN] [-d IDX_MAX]
process_img.py: error: argument -n/--n_jobs: expected one argument

How do I modify the parallel command in the PBS script so that $start and $n_jobs_procimg are passed to commands.txt?

In this case, $start should be an integer equal to 24 and $n_jobs_procimg should be an integer equal to 8.

It's not relevant to my question, but for context the process_img.py script uses a multiprocessing pool that takes the number of processing cores and as an argument (--n_jobs), and I want to have control over that based on the total number of processing cores I have available.

Body:
export the variables:

#!/bin/bash -l
#PBS -l walltime=12:00:00,nodes=1:ppn=24,pmem=2580mb

start=24
n_jobs_procimg=8
export start
export n_jobs_procimg

cd $PBS_O_WORKDIR
conda activate msi_sip_37

module load parallel
parallel -u -j 3 < commands.txt


问:
How can I inspect the window object for mobile safari?
How can I inspect the window object for mobile safari?

Or more specifically window.navigator - trying to convert to string doesn't work and I can't explore it within the console either.

Thanks!

EDIT:

console.log(window.navigator);

console.log(String(window.navigator));

console.log(JSON.stringify(window.navigator));

console.log(window.navigator.serialize());

Also tried sending all these variations over the socket to the server and logging them there.

Output is either [object Navigator], "{}", or nothing

答:
I like jsconsole.com.

Also, you can use the json2.js library (https://github.com/douglascrockford/JSON-js), which will give you JSON.stringify() function.

```<code>console.log(JSON.stringify({a:'a',b:'b'});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I like jsconsole.com.

Also, you can use the json2.js library (https://github.com/douglascrockford/JSON-js), which will give you JSON.stringify() function.

console.log(JSON.stringify({a:'a',b:'b'});


问:
Laravel custom auth based on json data
I am trying to make auth based on third party api in laravel. not storing or using data from my local db. Here I am keeping api response data as an array just for visualization . It shows error Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, string given, called in vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php . How can I fix that. I also made R&D on it. Thanks in advance

```<code>    $user = [
        'status' => '200',
        'token' => 'aWsIpvOEZfv4sfSRUGS2dDeGw7',
        'id' => '12454545412',
        'user' => [
            'name' => 'xyz',
            'email' => 'xyz@gmail.com',
            'phone' => '12344787',
        ],
    ];

    $user = json_encode($user);
    Auth::login($user);
    return redirect( '/home' );
</code>```

答:
You should create User class as a dummy model if you prefer.

```<code>namespace App\Helpers; // depends on you

use Illuminate\Foundation\Auth\User as Authenticatable;

class AuthUser extends Authenticatable
{
    protected $guarded = [];
}
</code>```

And you can use like this:

```<code>$user = [
    'id' => '12454545412',
    'name' => 'xyz',
    'email' => 'xyz@gmail.com',
    'phone' => 1234564897,
    'token' => 'aWsIpvOEZfv4sfSRUGS2dDeGw7' // if you need in your user Object
];
$user = new AuthUser($user);
Auth::login($user);
dd(auth()->user());
</code>```

Title: Laravel custom auth based on json data

Body:
I am trying to make auth based on third party api in laravel. not storing or using data from my local db. Here I am keeping api response data as an array just for visualization . It shows error Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, string given, called in vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php . How can I fix that. I also made R&D on it. Thanks in advance

    $user = [
        'status' => '200',
        'token' => 'aWsIpvOEZfv4sfSRUGS2dDeGw7',
        'id' => '12454545412',
        'user' => [
            'name' => 'xyz',
            'email' => 'xyz@gmail.com',
            'phone' => '12344787',
        ],
    ];

    $user = json_encode($user);
    Auth::login($user);
    return redirect( '/home' );

Body:
You should create User class as a dummy model if you prefer.

namespace App\Helpers; // depends on you

use Illuminate\Foundation\Auth\User as Authenticatable;

class AuthUser extends Authenticatable
{
    protected $guarded = [];
}

And you can use like this:

$user = [
    'id' => '12454545412',
    'name' => 'xyz',
    'email' => 'xyz@gmail.com',
    'phone' => 1234564897,
    'token' => 'aWsIpvOEZfv4sfSRUGS2dDeGw7' // if you need in your user Object
];
$user = new AuthUser($user);
Auth::login($user);
dd(auth()->user());


问:
ggplot2: geom_area() blank gaps
I want to use geom_area to show the percentage of cohort's contribution over time.
Below is a reproducible dataset, apologize as it requires some external libraries.

```<code>library(BTYDplus)
library(tidyverse)
custFirstTxn <- BTYDplus::groceryElog %>% group_by(cust) %>% arrange(cust, date)  %>%
  filter(row_number()==1)
custFirstTxn$cohort <- tsibble::yearmonth(custFirstTxn$date)

custFirstTxn %>% group_by(cohort) %>% summarise(n()) %>% ungroup()

custFirstTxn <- custFirstTxn %>% ungroup() %>% dplyr::select(-date)

</code>```

```<code>BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
mutate(yearweek = tsibble::yearweek(date)) %>% group_by(cohort, yearweek) %>%
  summarise(txn_count = n()) %>%
  group_by(yearweek) %>%
  mutate(txn_per = (txn_count / sum(txn_count))*100) %>% arrange(yearweek) %>%
  ggplot(aes(x=yearweek, y=txn_per, fill=factor(cohort))) + geom_area(stat = 'identity') +
  theme_classic() + labs(fill = "Cohort")
</code>```

```<code>BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
  mutate(yearmonth = tsibble::yearmonth(date)) %>% group_by(cohort, yearmonth) %>%
  summarise(txn_count = n()) %>%
  group_by(yearmonth) %>%
  mutate(txn_per = (txn_count / sum(txn_count))*100) %>% arrange(yearmonth) %>%
  ggplot(aes(x=yearmonth, y=txn_per, fill=factor(cohort))) + geom_area(stat = 'identity') +
  theme_classic() + labs(fill = "Cohort")

</code>```

Notice that the charts have 'gaps' (white areas) in the early dates.
How can I ensure that the white areas are effectively flattened?
For example below, we don't see the white areas anymore

How can I also easily switch between percentage and raw count?

答:
Not the most elegant answer I have, but it works in principle

```<code># create all combinations of cohort and yearmonth
master <- BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
  mutate(yearmonth = tsibble::yearmonth(date)) %>% dplyr::select(cohort, yearmonth) %>% distinct() %>%
  expand(cohort, yearmonth)

# calculate the cohort yearmonth percentage
slave <- BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
  mutate(yearmonth = tsibble::yearmonth(date)) %>% group_by(cohort, yearmonth) %>%
  summarise(txn_count = n()) %>%
  group_by(yearmonth) %>%
  mutate(txn_per = (txn_count / sum(txn_count))*100) %>% arrange(yearmonth) %>% dplyr::select(-txn_count)

# join to the master table
master_slave <- master %>% left_join(slave)
# set those combinations with no amount to 0
master_slave$txn_per[is.na(master_slave$txn_per)] <- 0

# plot
master_slave %>%
  ggplot(aes(x=yearmonth, y=txn_per, fill=factor(cohort))) + geom_area(stat = 'identity') +
  theme_classic() + labs(fill = "Cohort")
</code>```

Title: ggplot2: geom_area() blank gaps

Body:
I want to use geom_area to show the percentage of cohort's contribution over time.
Below is a reproducible dataset, apologize as it requires some external libraries.

library(BTYDplus)
library(tidyverse)
custFirstTxn <- BTYDplus::groceryElog %>% group_by(cust) %>% arrange(cust, date)  %>%
  filter(row_number()==1)
custFirstTxn$cohort <- tsibble::yearmonth(custFirstTxn$date)

custFirstTxn %>% group_by(cohort) %>% summarise(n()) %>% ungroup()

custFirstTxn <- custFirstTxn %>% ungroup() %>% dplyr::select(-date)

BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
mutate(yearweek = tsibble::yearweek(date)) %>% group_by(cohort, yearweek) %>%
  summarise(txn_count = n()) %>%
  group_by(yearweek) %>%
  mutate(txn_per = (txn_count / sum(txn_count))*100) %>% arrange(yearweek) %>%
  ggplot(aes(x=yearweek, y=txn_per, fill=factor(cohort))) + geom_area(stat = 'identity') +
  theme_classic() + labs(fill = "Cohort")

BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
  mutate(yearmonth = tsibble::yearmonth(date)) %>% group_by(cohort, yearmonth) %>%
  summarise(txn_count = n()) %>%
  group_by(yearmonth) %>%
  mutate(txn_per = (txn_count / sum(txn_count))*100) %>% arrange(yearmonth) %>%
  ggplot(aes(x=yearmonth, y=txn_per, fill=factor(cohort))) + geom_area(stat = 'identity') +
  theme_classic() + labs(fill = "Cohort")

Notice that the charts have 'gaps' (white areas) in the early dates.
How can I ensure that the white areas are effectively flattened?
For example below, we don't see the white areas anymore

How can I also easily switch between percentage and raw count?

Body:
Not the most elegant answer I have, but it works in principle

# create all combinations of cohort and yearmonth
master <- BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
  mutate(yearmonth = tsibble::yearmonth(date)) %>% dplyr::select(cohort, yearmonth) %>% distinct() %>%
  expand(cohort, yearmonth)

# calculate the cohort yearmonth percentage
slave <- BTYDplus::groceryElog %>% left_join(custFirstTxn) %>%
  mutate(yearmonth = tsibble::yearmonth(date)) %>% group_by(cohort, yearmonth) %>%
  summarise(txn_count = n()) %>%
  group_by(yearmonth) %>%
  mutate(txn_per = (txn_count / sum(txn_count))*100) %>% arrange(yearmonth) %>% dplyr::select(-txn_count)

# join to the master table
master_slave <- master %>% left_join(slave)
# set those combinations with no amount to 0
master_slave$txn_per[is.na(master_slave$txn_per)] <- 0

# plot
master_slave %>%
  ggplot(aes(x=yearmonth, y=txn_per, fill=factor(cohort))) + geom_area(stat = 'identity') +
  theme_classic() + labs(fill = "Cohort")


问:
Jenkins Confluence Publisher - wiki markup plain text to add data in a new row
How can we append/add new row/new cell at the top of the table, to act as the first row, below the headers using wiki mark up tokens. ?

I use Jenkins confluence publisher to send values from Jenkins build to a cell in a table in the confluence page. As I run the job daily, I need the Jenkins job to append the new details at the first row and eventually the yesterday's job details will be pushed down to the second row.

before21 token returns results that should come under the column H1 while before 31 values under column H2. I tried to create a cell within the existing cell using |cell| and {{!}}, but none of them works for me as these tokens are inside the table. As shown in the screenshot below, the values are getting added to the same cell instead of new cell.

I am unsure if I can create a row for  before21 and use the same new row for before31. The values for these tokens are passed as plain text option from the  Jenkins confluence publisher, which will eventually be in the new rows. The plain text supports wiki markup format.
https://www.jenkins.io/doc/pipeline/steps/confluence-publisher/

Can you guys please direct me where am I doing wrong and how can I achieve this?

I use confluence 7X. In Edit mode the page looks like

This is post update

答: This is achieved by posting content in HTML format. </p>


问:
Adding options to apostrophe-images-widgets directly
I've improved several image widgets by extending 'apostrophe-images-widgets' directly. That may not be the best practice, but I used this since the beginning I've started to code with apostrophe-cms and It worked good. My slide widget for example only uses this lines in index.js:

module.exports = {
  extend: 'apostrophe-images-widgets',
  piecesModuleName: 'apostrophe-images',
  label: 'Slider Widget'
};
```

<p>Now my widget.html is the following:</p>

<pre class="lang-html prettyprint-override"><code><div class="slider fullscreen">
  <ul class="slides">

    {% block items %}

      {% for entry in data.widget._pieces %}
        {% set image = entry.item or entry %}
        {% set relationship = entry.relationship %}

        <li>
          <img
            data-image src="{{ apos.attachments.url(image.attachment, { size: data.options.size or 'full', crop: relationship }) }}"
            srcset="{{ apos.images.srcset(image.attachment) }}"
            sizes="{{ data.options.sizesAttr or '100vw' }}"
            alt="{{ image.title }}"
          >

          <div class="caption {{ image.align }}">

            {% block title %}
              <h3 class="accent-color truncate hide-on-small-only"
                {% if image.titleColor %}
                  style="color:{{ image.titleColor }}"
                {% endif %}
              >
                {{ image.title }}
              </h3>
            {% endblock %}

            {% block description %}
              {% if image.description %}
                <p class="flow-text"
                  {% if image.descriptionColor %}
                    style="color:{{ image.descriptionColor }}"
                  {% endif %}
                >
                  {{ image.description | nlbr }}
                </p>
              {% endif %}
            {% endblock %}

          </div>

          {% block credit %}
            {% if image.credit %}
              <div class="credit">
                {% if image.creditUrl %}

                {% endif %}
                      <span>{{ image.credit }}</span>
                {% if image.creditUrl %}

                {% endif %}
            </div>
            {% endif %}
          {% endblock %}

        </li>

      {% endfor %}
    {% endblock %}

  </ul>
</div>
</code>```

Now my question is how can I add options like sizesAttr and focalPoint: true etc to my Slider widget?

As i told above if its possible I don't want to add additional fields like you explained here:

  addFields: [
    {
      name: '_image',
      type: 'joinByOne',
      withType: 'apostrophe-image',
      label: 'Image',
      required: true,
      idField: 'imageId',
      filters: {
        projection: {
          attachment: true,
          description: true,
          title: true
        }
      }
    }
  ]
```

<p>It would be necessary to rewrite the widget to extend: <code>apostrope-pieces-widgets</code> instead <code>apostrope-images-widgets</code> and so on. So my idea is to add the desired options directly with <code>beforeConstruct</code> unfortunately that hasen't worked so I'm stuck there:</p>

<pre class="lang-js prettyprint-override"><code>module.exports = {
  extend: 'apostrophe-images-widgets',
  piecesModuleName: 'apostrophe-images',
  label: 'Slider Widget',
  beforeConstruct: function(self, options) {
    if (options.focalPoint === undefined) {
      options.focalPoint = true;
    }
  }
};
</code>```

Do you have maybe an hint, how I can do this? Maybe there is some example in you code how you added options with beforeConstruct or even in html with nujucks with some variables like that {%- set data.widget.options ... -%} ?

答:
You are dealing with two different types of options there, but they are both declared in the same place. focalPoint is a built-in option, enabling the focal point UI (which then lets you get focal point information back later) and sizesAttr is an example from the documentation of a custom option that you might create for your specific needs.

In both cases, they are passed into the area's widget options in the page or piece show page template. So this might be in default.html for a "default" page or show.html for a piece type's show page like so:

```<code>{{ apos.area(data.page, 'content', {
  widgets: {
    'image': {
      sizesAttr: '(min-width: 1024px) 50vw, 100vw',
      focalPoint: true
    }
  }
}) }}
</code>```

(data.page would be specific to a page, but would be data.piece for a piece's show page)

Then in the widget templates (your widget.html) they're referenced as properties on data.options as you can see with sizesAttr in your example. You could similarly add any random option like foo: 'bar' in the area's widget config, then reference it as data.options.foo in the widget template.

focalPoint is not as useful to reference directly. As a built-in option, it enables special functionality for the focal point, which is then referenced in templates using methods like apos.attachments.hasFocalPoint(). The documentation has more on that.

Body:
I've improved several image widgets by extending 'apostrophe-images-widgets' directly. That may not be the best practice, but I used this since the beginning I've started to code with apostrophe-cms and It worked good. My slide widget for example only uses this lines in index.js:

module.exports = {
  extend: 'apostrophe-images-widgets',
  piecesModuleName: 'apostrophe-images',
  label: 'Slider Widget'
};

Now my widget.html is the following:

    {% block items %}

      {% for entry in data.widget._pieces %}
        {% set image = entry.item or entry %}
        {% set relationship = entry.relationship %}

            {% block title %}

                {{ image.title }}

            {% endblock %}

            {% block description %}
              {% if image.description %}

                  {{ image.description | nlbr }}

              {% endif %}
            {% endblock %}

          {% block credit %}
            {% if image.credit %}

                {% if image.creditUrl %}

                {% endif %}
                      {{ image.credit }}
                {% if image.creditUrl %}

                {% endif %}

            {% endif %}
          {% endblock %}

      {% endfor %}
    {% endblock %}

Now my question is how can I add options like sizesAttr and focalPoint: true etc to my Slider widget?

As i told above if its possible I don't want to add additional fields like you explained here:

  addFields: [
    {
      name: '_image',
      type: 'joinByOne',
      withType: 'apostrophe-image',
      label: 'Image',
      required: true,
      idField: 'imageId',
      filters: {
        projection: {
          attachment: true,
          description: true,
          title: true
        }
      }
    }
  ]

It would be necessary to rewrite the widget to extend: apostrope-pieces-widgets instead apostrope-images-widgets and so on. So my idea is to add the desired options directly with beforeConstruct unfortunately that hasen't worked so I'm stuck there:

module.exports = {
  extend: 'apostrophe-images-widgets',
  piecesModuleName: 'apostrophe-images',
  label: 'Slider Widget',
  beforeConstruct: function(self, options) {
    if (options.focalPoint === undefined) {
      options.focalPoint = true;
    }
  }
};

Do you have maybe an hint, how I can do this? Maybe there is some example in you code how you added options with beforeConstruct or even in html with nujucks with some variables like that {%- set data.widget.options ... -%} ?

Body:
You are dealing with two different types of options there, but they are both declared in the same place. focalPoint is a built-in option, enabling the focal point UI (which then lets you get focal point information back later) and sizesAttr is an example from the documentation of a custom option that you might create for your specific needs.

In both cases, they are passed into the area's widget options in the page or piece show page template. So this might be in default.html for a "default" page or show.html for a piece type's show page like so:

{{ apos.area(data.page, 'content', {
  widgets: {
    'image': {
      sizesAttr: '(min-width: 1024px) 50vw, 100vw',
      focalPoint: true
    }
  }
}) }}

(data.page would be specific to a page, but would be data.piece for a piece's show page)

Then in the widget templates (your widget.html) they're referenced as properties on data.options as you can see with sizesAttr in your example. You could similarly add any random option like foo: 'bar' in the area's widget config, then reference it as data.options.foo in the widget template.

focalPoint is not as useful to reference directly. As a built-in option, it enables special functionality for the focal point, which is then referenced in templates using methods like apos.attachments.hasFocalPoint(). The documentation has more on that.


问:
t sql records that contain part of another record
Using SQL Server 2014.  Is there a way to select records where the string value partially exists in another field?

e.g.:

```<code>RowID   Field1     Field2
1       ABC        ABC DEF
2       XYZ        WERQ
3       MNB        MNB RTW
</code>```

From the above, I would want Rows 1 and 3 as they have ABC and MNB that matches.

```<code>SELECT RowID FROM MY TABLE
WHERE CONTAINS(Field1, Field2);
</code>```

I have tried the above, however, this does not work as you cannot specify a 2nd field name in the CONTAINS function.

What am I missing?

答:
I think you're looking for</p>

```<code>SELECT *
FROM
(
  VALUES
  (1,       'ABC',        'ABC DEF'),
  (2,       'XYZ',        'WERQ'),
  (3,       'MNB',        'MNB RTW'),
  -- for col2 like col1
  (4,       'HI MNB RTW S',        'MNB RTW')
) T(Id, Col1, Col2)
WHERE  CONCAT(' ', Col1, ' ') LIKE CONCAT('% ', Col2, ' %')
       OR
       CONCAT(' ', Col2, ' ') LIKE CONCAT('% ', Col1, ' %');
</code>```

Body:
Using SQL Server 2014.  Is there a way to select records where the string value partially exists in another field?

e.g.:

RowID   Field1     Field2
1       ABC        ABC DEF
2       XYZ        WERQ
3       MNB        MNB RTW

From the above, I would want Rows 1 and 3 as they have ABC and MNB that matches.

SELECT RowID FROM MY TABLE
WHERE CONTAINS(Field1, Field2);

I have tried the above, however, this does not work as you cannot specify a 2nd field name in the CONTAINS function.

What am I missing?

Body:
I think you're looking for

SELECT *
FROM
(
  VALUES
  (1,       'ABC',        'ABC DEF'),
  (2,       'XYZ',        'WERQ'),
  (3,       'MNB',        'MNB RTW'),
  -- for col2 like col1
  (4,       'HI MNB RTW S',        'MNB RTW')
) T(Id, Col1, Col2)
WHERE  CONCAT(' ', Col1, ' ') LIKE CONCAT('% ', Col2, ' %')
       OR
       CONCAT(' ', Col2, ' ') LIKE CONCAT('% ', Col1, ' %');


问:
Pass generic parameter optionally?
I have the following NetworkUseCase interface which processes a network request. P is the type of requestData and R the type of responseData.

```<code>interface NetworkUseCase<in P, out R> {
    fun process(requestData: P) : R
}
</code>```

The way it is normally used is the following:

```<code>class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(requestData)
</code>```

However, there are some use cases where there are no requestData needed. In that case, there should be no requestData argument passed. But I am not sure how to achieve that.

```<code>val responseData = ConcreteUseCase().process()
</code>```

What I have done so far is to set the type of requestData to Unit but then I still need to pass Unit as a parameter:

```<code>class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(Unit)
</code>```

Is there a way to achieve not being forced to always pass an argument in process()?

答:
You could write an extension function to overload it so any concrete version that uses Unit for the first type would automatically have access to this simpler overload:

```<code>fun <T> NetworkUseCase<Unit, T>.process() = process(Unit)
</code>```

But if the number of arguments for the function are not always the same, why put this function in an interface at all?  You wouldn't be able to use it in an abstract way.

Title: Pass generic parameter optionally?

Body:
I have the following NetworkUseCase interface which processes a network request. P is the type of requestData and R the type of responseData.

interface NetworkUseCase<in P, out R> {
    fun process(requestData: P) : R
}

The way it is normally used is the following:

class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(requestData)

However, there are some use cases where there are no requestData needed. In that case, there should be no requestData argument passed. But I am not sure how to achieve that.

val responseData = ConcreteUseCase().process()

What I have done so far is to set the type of requestData to Unit but then I still need to pass Unit as a parameter:

class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(Unit)

Is there a way to achieve not being forced to always pass an argument in process()?

Body:
You could write an extension function to overload it so any concrete version that uses Unit for the first type would automatically have access to this simpler overload:

fun <T> NetworkUseCase<Unit, T>.process() = process(Unit)

But if the number of arguments for the function are not always the same, why put this function in an interface at all?  You wouldn't be able to use it in an abstract way.


问:
Pandas : select columns that ends with another column
I am working on a dirty dataset where two columnns that I need to match are not properly formatted :

"id" is a string often made of digits, that potentially starts with zero

"parent_id" represents the id of the parent of the row, but it has been formatted to an int, and so the starting zeros are gone.

I want to find for which rows "id" is the same as "parent_id".  However, I cannot manage to match it like this :

```<code>df["is_the_same"] = (df["id"]==df["parent_id"])
</code>```

cause some of them would not match  (for example, the id "01004" has "1004" as parent_id, and would not match in this case)

How can I select columns that have "id" equal to "parent_id" once potential zeroes have been removed ?

I also tried :

```<code>df["is_the_same"] = df["id"].str.endswith(df["parent_id"])
</code>```

But it seems .str.endswith  only work with constant strings (another column)

答:
Use list comprehension with endswith:

```<code>df = pd.DataFrame({'id':['01004','1004','54620'], 'parent_id':['1004','203','20']})

df["is_the_same"] = [x.endswith(y) for x, y in df[["id","parent_id"]].values]
#alternative
#df["is_the_same"] = df.apply(lambda x: x["id"].endswith(x["parent_id"]), axis=1)
print (df)
      id parent_id  is_the_same
0  01004      1004         True
1   1004       203        False
2  54620        20         True
</code>```

If difference only leading zeros and numbers compare converted values to integers:

```<code>df["is_the_same"] = df["id"].astype(int) == df["parent_id"].astype(int)
print (df)
      id parent_id  is_the_same
0  01004      1004         True
1   1004       203        False
2  54620        20        False
</code>```

Body:
I am working on a dirty dataset where two columnns that I need to match are not properly formatted :

"id" is a string often made of digits, that potentially starts with zero

"parent_id" represents the id of the parent of the row, but it has been formatted to an int, and so the starting zeros are gone.

I want to find for which rows "id" is the same as "parent_id".  However, I cannot manage to match it like this :

df["is_the_same"] = (df["id"]==df["parent_id"])

cause some of them would not match  (for example, the id "01004" has "1004" as parent_id, and would not match in this case)

How can I select columns that have "id" equal to "parent_id" once potential zeroes have been removed ?

I also tried :

df["is_the_same"] = df["id"].str.endswith(df["parent_id"])

But it seems .str.endswith  only work with constant strings (another column)

Body:
Use list comprehension with endswith:

df = pd.DataFrame({'id':['01004','1004','54620'], 'parent_id':['1004','203','20']})

df["is_the_same"] = [x.endswith(y) for x, y in df[["id","parent_id"]].values]
#alternative
#df["is_the_same"] = df.apply(lambda x: x["id"].endswith(x["parent_id"]), axis=1)
print (df)
      id parent_id  is_the_same
0  01004      1004         True
1   1004       203        False
2  54620        20         True

If difference only leading zeros and numbers compare converted values to integers:

df["is_the_same"] = df["id"].astype(int) == df["parent_id"].astype(int)
print (df)
      id parent_id  is_the_same
0  01004      1004         True
1   1004       203        False
2  54620        20        False


答:
Please, check Shared Preferences. This is key-value storage and it's exactly suited for such needs.

As general practice - create some SharedPrefManager and move all logic with shared preferences there. Like in this answer.

Title: Does the night mode need sqlite?

Body:
I just want to know if the night mode in Android needs sqlite?
or there's another way to save the mode in it
when the user close the app and reopen it again it will save the mode
pls help

If there's another way please share it with me
Thanks


问:
R - Remove Empty Category in Summary
I'm working on cleaning a dataset I plan to use for analysis. Some records were coded as '' instead of NA's, so I'm converting all these records to be NA and then dropping them from my dataset.

After dropping these records, the '' factor group is still showing up in the summary of the data. Is there anyway to fix this?

Example Code:

```<code>surgery$gender[surgery$gender == ""] <- NA
surgery = surgery %>% drop_na(gender)
surgery$gender = as.factor(surgery$gender)

summary(surgery)
</code>```

Example Summary Output:

答:
```<code>surgery$gender = droplevels(surgery$gender)
</code>```

Title: R - Remove Empty Category in Summary

Body:
I'm working on cleaning a dataset I plan to use for analysis. Some records were coded as '' instead of NA's, so I'm converting all these records to be NA and then dropping them from my dataset.

After dropping these records, the '' factor group is still showing up in the summary of the data. Is there anyway to fix this?

Example Code:

surgery$gender[surgery$gender == ""] <- NA
surgery = surgery %>% drop_na(gender)
surgery$gender = as.factor(surgery$gender)

summary(surgery)

Example Summary Output:


问:
How to remove the first character of a variable
HI All,

In my js file i am getting an array of records (negetive values ) like this

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });
</code>```

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

答:
```<code>    var deletedDetailIds = $.map(eformDetailIds,
       function(item) { return item < 0 ? -item : null; }
    );
</code>```

Body:
HI All,

In my js file i am getting an array of records (negetive values ) like this

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this


问:
Get GCC's list of versions from ftp://ftp.gnu.org using ruby
Today I would like to make ruby script to parse this gcc download link: ftp://ftp.gnu.org/gnu/gcc/

I would like my code parse this page and give me list of all gcc version (include gcc text).

I would like to have into array:
["gcc-10.1.0","gcc-2.95"] ...etc. In one word, all gcc dir's name. Or is it possible without parsing?

答:
That "download page" is not a normal website, it is an FTP directory (that's why the URL starts with ftp://). Your web browser makes it look like a website, but FTP is essentially a network directory that you read files from.

Ruby's stdlib has a Net::FTP class that you should be able to use to list the files you want.


问:
SQL Server: How to add a specific date to date range query
I have a query that currently searches for records that have a payment date year within the current year.

I need to modify the query so that it searches records starting from November 15th of the previous year, in this case 2019 to anything within the current year 2020.

How can I add this date range?

This is my current query:

```<code>SELECT
    RECORD_ID
,   RECORD_TYPE
,   PERMIT_TYPE
,   RECORD_STATUS
,   PURCHASE_DATE
,   PURCHASE_TIME
,   PERMIT_YEAR
,   CONTACT_ADDRESS
,   CONTACT_NAME
FROM
    PERMIT_VIEW PV
INNER JOIN PERMIT BP
    ON PV.RECORD_ID = BP.RECORD_ID
INNER JOIN PAYMENT P
    ON BP.SERV_PROV_CODE = P.SERV_PROV_CODE
WHERE
    RECORD_TYPE IN ('Annual')
    AND YEAR(PURCHASED_DATE) = YEAR(GETDATE())  - This is the part I need to change.
    AND PV.RECORD_ID NOT LIKE 'DLY%'
    AND RECORD_STATUS NOT IN ('Void')
</code>```

Thank you for your help,

Erasmo

答:
You can use the condition:</p>

```<code>purchased_date >= datefromparts(year(getdate()) - 1, 11, 15)
</code>```

Body:
I have a query that currently searches for records that have a payment date year within the current year.

I need to modify the query so that it searches records starting from November 15th of the previous year, in this case 2019 to anything within the current year 2020.

How can I add this date range?

This is my current query:

SELECT
    RECORD_ID
,   RECORD_TYPE
,   PERMIT_TYPE
,   RECORD_STATUS
,   PURCHASE_DATE
,   PURCHASE_TIME
,   PERMIT_YEAR
,   CONTACT_ADDRESS
,   CONTACT_NAME
FROM
    PERMIT_VIEW PV
INNER JOIN PERMIT BP
    ON PV.RECORD_ID = BP.RECORD_ID
INNER JOIN PAYMENT P
    ON BP.SERV_PROV_CODE = P.SERV_PROV_CODE
WHERE
    RECORD_TYPE IN ('Annual')
    AND YEAR(PURCHASED_DATE) = YEAR(GETDATE())  - This is the part I need to change.
    AND PV.RECORD_ID NOT LIKE 'DLY%'
    AND RECORD_STATUS NOT IN ('Void')

Thank you for your help,

Erasmo

Body:
You can use the condition:

purchased_date >= datefromparts(year(getdate()) - 1, 11, 15)


问:
Is tf.compat.v1.layers.AveragePooling2D the same than tf.keras.layers.GlobalAveragePooling2D?
I'm just started to learn Tensorflow and I have found an example in Tensorflow 1.x that I think it is very difficult to migrate to Tensorflow 2.x, so I have decided to use it in its original version.

You can find the code on this github: Omniglot Character Set Classification Using Prototypical Network

I want to change the Flatten layer with a Global average pooling layer to this code:

```<code>def get_embeddings(support_set, h_dim, z_dim, reuse=False):

    net = convolution_block(support_set, h_dim)
    net = convolution_block(net, h_dim)
    net = convolution_block(net, h_dim)
    net = convolution_block(net, z_dim)
    net = tf.compat.v1.layers.flatten(net)

    return net
</code>```

On Tensorflow 2.x, I know that the function I want to use is GlobalAveragePooling2D, but I can't find a function with the same name on Tensorflow 1.x. I have found this AveragePooling2D.

Is AveragePooling2D the same a GlobalAveragePooling2D?

答:
if you can't access to GlobalAveragePooling2D, remember that you can do it simply defining your own lambda layer to do the same operation</p>

```<code>x = np.random.uniform(0,1, (2,224,224,3)).astype('float32')

GlobalAveragePooling2D()(x)
# the same as
Lambda(lambda x: tf.reduce_mean(x, axis=[1,2]))(x)
</code>```

Body:
I'm just started to learn Tensorflow and I have found an example in Tensorflow 1.x that I think it is very difficult to migrate to Tensorflow 2.x, so I have decided to use it in its original version.

You can find the code on this github: Omniglot Character Set Classification Using Prototypical Network

I want to change the Flatten layer with a Global average pooling layer to this code:

def get_embeddings(support_set, h_dim, z_dim, reuse=False):

    net = convolution_block(support_set, h_dim)
    net = convolution_block(net, h_dim)
    net = convolution_block(net, h_dim)
    net = convolution_block(net, z_dim)
    net = tf.compat.v1.layers.flatten(net)

    return net

On Tensorflow 2.x, I know that the function I want to use is GlobalAveragePooling2D, but I can't find a function with the same name on Tensorflow 1.x. I have found this AveragePooling2D.

Is AveragePooling2D the same a GlobalAveragePooling2D?

Body:
if you can't access to GlobalAveragePooling2D, remember that you can do it simply defining your own lambda layer to do the same operation

x = np.random.uniform(0,1, (2,224,224,3)).astype('float32')

GlobalAveragePooling2D()(x)
# the same as
Lambda(lambda x: tf.reduce_mean(x, axis=[1,2]))(x)


问:
How to get the pid of the process started by subprocess.run and kill it
I'm using Windows 10 and Python 3.7.

I ran the following command.

```<code>import subprocess
exeFilePath = "C:/Users/test/test.exe"
subprocess.run(exeFilePath)
</code>```

The .exe file launched with this command, I want to force-quit when the button is clicked or when the function is executed.

Looking at a past question, it has been indicated that the way to force quit is to get a PID and do an OS.kill as follows.

```<code>import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)
</code>```

However, I don't know how to get the PID of the process started in subprocess.run.

What should I do?

答:
Assign a variable to your subprocess

import os
import signal
import subprocess

exeFilePath = "C:/Users/test/test.exe"
p = subprocess.Popen(exeFilePath)
print(p.pid) # the pid
os.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL
```

<p>In same cases the process has children
processes. You need to kill all processes to terminate it. In that case you can use <code>psutil</code> </p>

<pre class="lang-py prettyprint-override"><code>#python -m pip install —user psutil

import psutil

#remember to assign subprocess to a variable

def kills(pid):
    '''Kills all process'''
    parent = psutil.Process(pid)
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()

#assumes variable p
kills(p.pid)
</code>```

This will kill all processes in that PID

Body:
I'm using Windows 10 and Python 3.7.

I ran the following command.

import subprocess
exeFilePath = "C:/Users/test/test.exe"
subprocess.run(exeFilePath)

The .exe file launched with this command, I want to force-quit when the button is clicked or when the function is executed.

Looking at a past question, it has been indicated that the way to force quit is to get a PID and do an OS.kill as follows.

import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)

However, I don't know how to get the PID of the process started in subprocess.run.

What should I do?

Body:
Assign a variable to your subprocess

import os
import signal
import subprocess

exeFilePath = "C:/Users/test/test.exe"
p = subprocess.Popen(exeFilePath)
print(p.pid) # the pid
os.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL

In same cases the process has children
processes. You need to kill all processes to terminate it. In that case you can use psutil

#python -m pip install —user psutil

import psutil

#remember to assign subprocess to a variable

def kills(pid):
    '''Kills all process'''
    parent = psutil.Process(pid)
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()

#assumes variable p
kills(p.pid)

This will kill all processes in that PID


问:
LibvclSharp winforms Go to specific Time
I am putting together a winforms app using libvclsharp wrapper.
It is a basic app that hosts 4 x VideoView windows and plays 4 different mp4 videos.

It plays ok and seems stable mostly, but the lib has some odd quirks that i cant seem to find an answer to

I need to click a button on the form and sent all the videos to a specific time, they are all the same length at the moment

using

```<code>  _mediaPlayer1 = new MediaPlayer(_libVLC1);
  _mediaPlayer2 = new MediaPlayer(_libVLC1);
  _mediaPlayer3 = new MediaPlayer(_libVLC1);
  _mediaPlayer4 = new MediaPlayer(_libVLC1);

  media1 = new Media(_libVLC1, @"D:Video.mp4", FromType.FromPath);
  media2 = new Media(_libVLC1, @"D:Video2.mp4", FromType.FromPath);
  media3 = new Media(_libVLC1, @"D:Video3.mp4", FromType.FromPath);
  media4 = new Media(_libVLC1, @"D:Video4.mp4", FromType.FromPath);

 _mediaPlayer1.Media = media1;
 _mediaPlayer2.Media = media2;
 _mediaPlayer3.Media = media3;
 _mediaPlayer4.Media = media4;

 videoView1.MediaPlayer = _mediaPlayer1;
 videoView2.MediaPlayer = _mediaPlayer2;
 videoView3.MediaPlayer = _mediaPlayer3;
 videoView4.MediaPlayer = _mediaPlayer4;

so to send all 4 to same time i use

foreach (var player in _PlayersCollection)
       {
        player.Time = 12000);
       }

</code>```

the problem is when click button the if the videos are playing it moves straight to the new time location.

if the videos are paused the videos twitch like they are moving just one frame, then you if click again they jump to the right time location.

this is very annoying and i cant see a reason why.

I saw a tip online to suggest setting the output renderer for the lib to D3d9 instead of D3d11 but i cant find any examples of how to change that for this lib.

Does anyone have any suggestions please who is familiar with lib on winforms.

thanks

答:
I also noticed this problem in vlc.dotnet

Looks like the player does not like it's time too be changed to fast.
My solution was to limit the update rate of my tracker.
Some thing similar may work for you.

```<code>long lngLastScrollTimeStamp=0;

private void trkVideo_Scroll(object sender, EventArgs e)
  {
  if (((Stopwatch.GetTimestamp() / TimeSpan.TicksPerMillisecond) - lngLastScrollTimeStamp) > 250)
    {
    vlcControl1.Time = trkVideo.Value;
    lngLastScrollTimeStamp = Stopwatch.GetTimestamp() / TimeSpan.TicksPerMillisecond;
    }
  }
</code>```

Body:
I am putting together a winforms app using libvclsharp wrapper.
It is a basic app that hosts 4 x VideoView windows and plays 4 different mp4 videos.

It plays ok and seems stable mostly, but the lib has some odd quirks that i cant seem to find an answer to

I need to click a button on the form and sent all the videos to a specific time, they are all the same length at the moment

using

  _mediaPlayer1 = new MediaPlayer(_libVLC1);
  _mediaPlayer2 = new MediaPlayer(_libVLC1);
  _mediaPlayer3 = new MediaPlayer(_libVLC1);
  _mediaPlayer4 = new MediaPlayer(_libVLC1);

  media1 = new Media(_libVLC1, @"D:Video.mp4", FromType.FromPath);
  media2 = new Media(_libVLC1, @"D:Video2.mp4", FromType.FromPath);
  media3 = new Media(_libVLC1, @"D:Video3.mp4", FromType.FromPath);
  media4 = new Media(_libVLC1, @"D:Video4.mp4", FromType.FromPath);

 _mediaPlayer1.Media = media1;
 _mediaPlayer2.Media = media2;
 _mediaPlayer3.Media = media3;
 _mediaPlayer4.Media = media4;

 videoView1.MediaPlayer = _mediaPlayer1;
 videoView2.MediaPlayer = _mediaPlayer2;
 videoView3.MediaPlayer = _mediaPlayer3;
 videoView4.MediaPlayer = _mediaPlayer4;

so to send all 4 to same time i use

foreach (var player in _PlayersCollection)
       {
        player.Time = 12000);
       }

the problem is when click button the if the videos are playing it moves straight to the new time location.

if the videos are paused the videos twitch like they are moving just one frame, then you if click again they jump to the right time location.

this is very annoying and i cant see a reason why.

I saw a tip online to suggest setting the output renderer for the lib to D3d9 instead of D3d11 but i cant find any examples of how to change that for this lib.

Does anyone have any suggestions please who is familiar with lib on winforms.

thanks

Body:
I also noticed this problem in vlc.dotnet

Looks like the player does not like it's time too be changed to fast.
My solution was to limit the update rate of my tracker.
Some thing similar may work for you.

long lngLastScrollTimeStamp=0;

private void trkVideo_Scroll(object sender, EventArgs e)
  {
  if (((Stopwatch.GetTimestamp() / TimeSpan.TicksPerMillisecond) - lngLastScrollTimeStamp) > 250)
    {
    vlcControl1.Time = trkVideo.Value;
    lngLastScrollTimeStamp = Stopwatch.GetTimestamp() / TimeSpan.TicksPerMillisecond;
    }
  }


问:
REACT TypeError: Class extends value undefined is not a constructor or null
I'm new to React and I'm trying to build a static web page to practice.
When I try to open the web page I get this error referring to the App.js file in src folder.

Error1-Image

App.js code below:

```<code>import React from 'react';
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];

class App extends React.Component() {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;
</code>```

If I try to import React, {Component} from 'react'
and I use "extends Component" instead of "extends React.Component" I get this error:

Error2-Image

Thank you for your help!

答:
you are extending React.Component() not React.Component

see the working code below

```<code>import React from 'react';
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];

class App extends React.Component {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;
</code>```

Body:
I'm new to React and I'm trying to build a static web page to practice.
When I try to open the web page I get this error referring to the App.js file in src folder.

Error1-Image

App.js code below:

import React from 'react';
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];

class App extends React.Component() {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;

If I try to import React, {Component} from 'react'
and I use "extends Component" instead of "extends React.Component" I get this error:

Error2-Image

Thank you for your help!

Body:
you are extending React.Component() not React.Component

see the working code below

import React from 'react';
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];

class App extends React.Component {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;


问:
Div get overflow scroll when using css-grid
I´m using css-grid and haven´t hade a problem whit it until now. I´m usually pretty good whit css but can´t figure out what the problem is.

```<code><div class="the_grid">
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
  <div>Some content</div>
</div>

...

.the_grid {
   display: grid;
   grid-template-rows: auto;
   grid-gap: 2%;
   grid-template-columns: 1fr 1fr;
}
</code>```

The last part in the grid is not showen if I don´t scroll, I can add some padding at the bottom and the scroll is removed but that´s not a solution that I think is going to work in the long run because the content differ from person to person. The content in the div´s are different length but I haven´t hade the same problem before and have been using grid in a few projects now. I tried adding 100% height, and same on the surrounding div´s as well but it dosen´t make any difference.

EDIT:

I got the answer below, it was the %, I changed it to rem and i worked.

答:
Issue with grid-gap: 2%; precisely the percentage value.

According to the spec

percentages resolve against zero for determining intrinsic size contributions, but resolve against the box’s content box when laying out the box’s contents.

Which means percentages will wait until the content has been laid out, get the width/height of the parent, calculate then add the space between grid items, Which causes overflow.

Demo

body * {
  padding: 10px;
  border: 1px solid;
}

.the_grid {
  background: red;
  /* inline for side-by-side comparison */
  display: inline-grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
}

/* same for grid-columns-gap, for the sake of this demo i only used row */
.gap {
  grid-row-gap: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="the_grid">
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
</div>

<div class="the_grid gap">
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
</div></code>```

Solution

Don't use percentage values.

body * {
  padding: 10px;
  border: 1px solid;
}

.the_grid {
  border: 1px solid;
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  grid-gap: 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="the_grid">
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
</div></code>```

You should simply avoid using percentages in grid as they are unpredictable, Good Read

Body:
I´m using css-grid and haven´t hade a problem whit it until now. I´m usually pretty good whit css but can´t figure out what the problem is.

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

...

.the_grid {
   display: grid;
   grid-template-rows: auto;
   grid-gap: 2%;
   grid-template-columns: 1fr 1fr;
}

The last part in the grid is not showen if I don´t scroll, I can add some padding at the bottom and the scroll is removed but that´s not a solution that I think is going to work in the long run because the content differ from person to person. The content in the div´s are different length but I haven´t hade the same problem before and have been using grid in a few projects now. I tried adding 100% height, and same on the surrounding div´s as well but it dosen´t make any difference.

EDIT:

I got the answer below, it was the %, I changed it to rem and i worked.

Body:
Issue with grid-gap: 2%; precisely the percentage value.

According to the spec

percentages resolve against zero for determining intrinsic size contributions, but resolve against the box’s content box when laying out the box’s contents.

Which means percentages will wait until the content has been laid out, get the width/height of the parent, calculate then add the space between grid items, Which causes overflow.

Demo

body * {
  padding: 10px;
  border: 1px solid;
}

.the_grid {
  background: red;
  /* inline for side-by-side comparison */
  display: inline-grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
}

/* same for grid-columns-gap, for the sake of this demo i only used row */
.gap {
  grid-row-gap: 10%;
}

<div class="the_grid">
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
</div>

<div class="the_grid gap">
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
</div>

Solution

Don't use percentage values.

body * {
  padding: 10px;
  border: 1px solid;
}

.the_grid {
  border: 1px solid;
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  grid-gap: 2px;
}

<div class="the_grid">
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
  <div>Some</div>
</div>

You should simply avoid using percentages in grid as they are unpredictable, Good Read


问:
Is it possible to involve a search bar on a DataFrame in Pandas?
I have a DataFrame in Pandas which collects some data from an Excel document. I created a GUI with PyQt5 in order to make it look more interesting but here is the thing.

Is it possbile to make a dynamic search bar in order to search through that DataFrame? For example, my DataFrame has over 3k+ rows and I wanna search for John Doe, then the results will come up on the GUI. As far as I know, QLineEdit is used for this but I can't seem to implement it on my code.

Is it me that is doing wrong or it is not possible to do it on a DataFrame? And if anyone wanna help me, just let me know, I would be so grateful and thankful, I guess it'll only take 10-15 minutes. I can also post the code here, but talking on Discord and explaining you in detail and also sharing screens would be a lot easier.

答:
This can be done by subclassing QAbstractTableModel to create a custom table model that uses the underlying dataframe for supplying data to a QTableView. This custom model can then be combined with a QProxyFilterSortModel to filter the data in the table. To create a custom non-editable model from QAbstractTableModel you need to implement rowCount, columnCount, data, and headerData at the very least. In this case, minimal implemetation could be something like this:

```<code>class DataFrameModel(QtCore.QAbstractTableModel):
    def __init__(self, data_frame, parent = None):
        super().__init__(parent)
        self.data_frame = data_frame

    def rowCount(self, index):
        if index.isValid():
            return 0
        return self.data_frame.shape[0]

    def columnCount(self, index):
        if index.isValid():
            return 0
        return self.data_frame.shape[1]

    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return None
        return str(self.data_frame.iloc[index.row(), index.column()])

    def headerData(self, section, orientation, role=None):
        if role != QtCore.Qt.DisplayRole:
            return None
        if orientation == QtCore.Qt.Vertical:
            return self.data_frame.index[section]
        else:
            return self.data_frame.columns[section]
</code>```

To show and filter the data in a table you could do something like this:

```<code>class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.table_view = QtWidgets.QTableView()

        self.proxy_model = QtCore.QSortFilterProxyModel()
        # by default, the QSortFilterProxyModel will search for keys in the first column only
        # setting QSortFilterProxyModel.filterKeyColumn to -1 will match values in all columns
        self.proxy_model.setFilterKeyColumn(-1)
        self.table_view.setModel(self.proxy_model)

        # line edit for entering (part of) the key that should be searched for
        self.line_edit = QtWidgets.QLineEdit()
        self.line_edit.textChanged.connect(self.filter_text)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.line_edit)
        vlayout.addWidget(self.table_view)

    def filter_text(self, text):
        self.proxy_model.setFilterFixedString(text)

    def set_data(self, data):
        self.model = DataFrameModel(pd.DataFrame(data))
        self.proxy_model.setSourceModel(self.model)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    win = MyWidget()
    win.set_data({'a':['apple', 'banana', 'cherry'], 'b':[4,5,6], 'c':['green', 'yellow', 'red']})
    win.show()
    app.exec()
</code>```

Of course this is a very basic implementation but I might help you get started.

Body:
This can be done by subclassing QAbstractTableModel to create a custom table model that uses the underlying dataframe for supplying data to a QTableView. This custom model can then be combined with a QProxyFilterSortModel to filter the data in the table. To create a custom non-editable model from QAbstractTableModel you need to implement rowCount, columnCount, data, and headerData at the very least. In this case, minimal implemetation could be something like this:

class DataFrameModel(QtCore.QAbstractTableModel):
    def __init__(self, data_frame, parent = None):
        super().__init__(parent)
        self.data_frame = data_frame

    def rowCount(self, index):
        if index.isValid():
            return 0
        return self.data_frame.shape[0]

    def columnCount(self, index):
        if index.isValid():
            return 0
        return self.data_frame.shape[1]

    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return None
        return str(self.data_frame.iloc[index.row(), index.column()])

    def headerData(self, section, orientation, role=None):
        if role != QtCore.Qt.DisplayRole:
            return None
        if orientation == QtCore.Qt.Vertical:
            return self.data_frame.index[section]
        else:
            return self.data_frame.columns[section]

To show and filter the data in a table you could do something like this:

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.table_view = QtWidgets.QTableView()

        self.proxy_model = QtCore.QSortFilterProxyModel()
        # by default, the QSortFilterProxyModel will search for keys in the first column only
        # setting QSortFilterProxyModel.filterKeyColumn to -1 will match values in all columns
        self.proxy_model.setFilterKeyColumn(-1)
        self.table_view.setModel(self.proxy_model)

        # line edit for entering (part of) the key that should be searched for
        self.line_edit = QtWidgets.QLineEdit()
        self.line_edit.textChanged.connect(self.filter_text)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.line_edit)
        vlayout.addWidget(self.table_view)

    def filter_text(self, text):
        self.proxy_model.setFilterFixedString(text)

    def set_data(self, data):
        self.model = DataFrameModel(pd.DataFrame(data))
        self.proxy_model.setSourceModel(self.model)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    win = MyWidget()
    win.set_data({'a':['apple', 'banana', 'cherry'], 'b':[4,5,6], 'c':['green', 'yellow', 'red']})
    win.show()
    app.exec()

Of course this is a very basic implementation but I might help you get started.


问:
What's the meaning of some sort of custom binary file?
In Head First C book, there is a "there are no dumb questions" section.

Are bitfields really just used to save space?

No, They're important if you need to read low-level binary information

Such as?

If you're reading or writing some sort of custom binary file.

What is that mean?

答:
Here's an example of how most people think bitfields should work - picture your typical IEEE 754 single-precision float:

```<code>+-+--------+-----------------------+
| |        |                       |
+-+--------+-----------------------+
 ^ ^        ^
 | |        |
 | |        +----------------------- significand
 | +-------------------------------- exponent
 +---------------------------------- sign bit
</code>```

You could create a struct type with bitfields to represent this format:

```<code>struct ieee_754_s {
  unsigned    sign_bit :  1;
  unsigned    exponent :  8;
  unsigned significand : 23;
};
</code>```

This could be a useful abstraction for learning and understanding how floating point formats work, and what operations need to be performed on each field in order to do floating point arithmetic, etc.

However, there also tends to be a naive expectation that this type would map directly onto a float and you could do all kinds of clever bit manipulations on float objects.

Except it doesn't.  At least, it's not guaranteed to.  On a little-endian system like x86 the fields don't map correctly.  To make it work on my Macbook, I had to define the type as

```<code>struct ieee_754_le {
  unsigned sig_3 : 8; // lowest-order bits of the significand
  unsigned sig_2 : 8;
  unsigned sig_1 : 7; // highest-order bits of the significand
  unsigned sign  : 1;
  unsigned exp   : 8;
};
</code>```

and then I could get it to map correctly.  But again, it's still not guaranteed.  Bit fields do not have to be laid out contiguously, and the order in which they're allocated within a storage unit is implementation-defined.  The layout above just happens to map cleanly onto a sequence of storage units, and the compiler was nice enough to order the bit fields as I expected within each storage unit.  It could have flipped the ordering of the sign and sig_1 fields.

Bit fields are a way to deal with objects whose sizes are not an integral number of storage units without having to do a bunch of bit masking.  They are not a good way to represent and interact with low-level binary formats.

Body:
Here's an example of how most people think bitfields should work - picture your typical IEEE 754 single-precision float:

+-+--------+-----------------------+
| |        |                       |
+-+--------+-----------------------+
 ^ ^        ^
 | |        |
 | |        +----------------------- significand
 | +-------------------------------- exponent
 +---------------------------------- sign bit

You could create a struct type with bitfields to represent this format:

struct ieee_754_s {
  unsigned    sign_bit :  1;
  unsigned    exponent :  8;
  unsigned significand : 23;
};

This could be a useful abstraction for learning and understanding how floating point formats work, and what operations need to be performed on each field in order to do floating point arithmetic, etc.

However, there also tends to be a naive expectation that this type would map directly onto a float and you could do all kinds of clever bit manipulations on float objects.

Except it doesn't.  At least, it's not guaranteed to.  On a little-endian system like x86 the fields don't map correctly.  To make it work on my Macbook, I had to define the type as

struct ieee_754_le {
  unsigned sig_3 : 8; // lowest-order bits of the significand
  unsigned sig_2 : 8;
  unsigned sig_1 : 7; // highest-order bits of the significand
  unsigned sign  : 1;
  unsigned exp   : 8;
};

and then I could get it to map correctly.  But again, it's still not guaranteed.  Bit fields do not have to be laid out contiguously, and the order in which they're allocated within a storage unit is implementation-defined.  The layout above just happens to map cleanly onto a sequence of storage units, and the compiler was nice enough to order the bit fields as I expected within each storage unit.  It could have flipped the ordering of the sign and sig_1 fields.

Bit fields are a way to deal with objects whose sizes are not an integral number of storage units without having to do a bunch of bit masking.  They are not a good way to represent and interact with low-level binary formats.