问:
Unable to Locate Textbox Element using selenium
I am having trouble to send text to textbox present in the given image as I have tried by passing the xpath of that textbox but its generates an error mentioned below. Anyone that can help me out of that.

```<code>from selenium import webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

</code>```
```<code>import time
path=r"path to your chrome driver.exe"
driver =  webdriver.Chrome(path)
driver.get("https://www4.sii.cl/mapasui/internet/#/contenido/index.html")

try:
    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="ng-app"]/body/div[5]/div/div/div[3]/div/button'))
         )
    element.click()
    print("prints its working fine now ..")

    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH,'//*[@id="titulo"]/div[8]/i'))
         )
    element.click()

    search =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[1]/input').click()
    search.send_keys("somehting in text")
    search.send_keys(Keys.RETURN)
    time.sleep(3)
    search_1 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[2]/input')
    search_1.send_keys("somehting in text")
    search_1.send_keys(Keys.RETURN)

    search_2 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[3]/input')
    search_2.send_keys("somehting in text")
    search_2.send_keys(Keys.RETURN)

    print("Its also working now ......")

    time.sleep(3)
except Exception as e:
    print(e)
    driver.quit()

</code>```

答:
For the Comuna input, there are some rules, since it has autocomplete functionality.

1 You have to define some specific value, which present in the list.

Some random text will not work!

2 You have to confirm the input with Keys.ENTER(Keys.RETURN on Mac).

# explicit wait for visibility (max timeout - 60 seconds)
search = WebDriverWait(driver, 60).until(
    EC.visibility_of_element_located((By.XPATH, '//*[@id="rolsearch"]/div[2]/div[1]/input'))
)
search.send_keys("EL MONTE" + Keys.ENTER)
time.sleep(3)
search_1 = driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[2]/input')
search_1.send_keys("somehting in text")

search_2 = driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[3]/input')
search_2.send_keys("somehting in text")

print("Its also working now ......")

time.sleep(3)

```

For other inputs, any text will be applied with send_keys without extra actions.

Body:
I am having trouble to send text to textbox present in the given image as I have tried by passing the xpath of that textbox but its generates an error mentioned below. Anyone that can help me out of that.

from selenium import webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

import time
path=r"path to your chrome driver.exe"
driver =  webdriver.Chrome(path)
driver.get("https://www4.sii.cl/mapasui/internet/#/contenido/index.html")

try:
    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="ng-app"]/body/div[5]/div/div/div[3]/div/button'))
         )
    element.click()
    print("prints its working fine now ..")

    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH,'//*[@id="titulo"]/div[8]/i'))
         )
    element.click()

    search =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[1]/input').click()
    search.send_keys("somehting in text")
    search.send_keys(Keys.RETURN)
    time.sleep(3)
    search_1 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[2]/input')
    search_1.send_keys("somehting in text")
    search_1.send_keys(Keys.RETURN)

    search_2 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[3]/input')
    search_2.send_keys("somehting in text")
    search_2.send_keys(Keys.RETURN)

    print("Its also working now ......")

    time.sleep(3)
except Exception as e:
    print(e)
    driver.quit()

Body:
For the Comuna input, there are some rules, since it has autocomplete functionality.

1 You have to define some specific value, which present in the list.

Some random text will not work!

2 You have to confirm the input with Keys.ENTER(Keys.RETURN on Mac).

# explicit wait for visibility (max timeout - 60 seconds)
search = WebDriverWait(driver, 60).until(
    EC.visibility_of_element_located((By.XPATH, '//*[@id="rolsearch"]/div[2]/div[1]/input'))
)
search.send_keys("EL MONTE" + Keys.ENTER)
time.sleep(3)
search_1 = driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[2]/input')
search_1.send_keys("somehting in text")

search_2 = driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[3]/input')
search_2.send_keys("somehting in text")

print("Its also working now ......")

time.sleep(3)

For other inputs, any text will be applied with send_keys without extra actions.


来源: stackexchange

问:
ERROR:flutter/lib/ui/ui_dart_state.cc(199) Unhandled Exception: Null check operator used on a null value
I am trying to generate through injectable, I done flutter clean also it won't work, I am using stable version flutter 2.2.2, I am facing null check error on this line of code

this code is throwing error

```<code>SharedPreferences.getInstance();
</code>```

also this code

```<code>   @module
    abstract class ThemeModule {
      @preResolve
      Future<SharedPreferences> get prefs async =>
           await SharedPreferences.getInstance();
    }
</code>```

Error Stack

E/flutter (27063): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (27063): #0      MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
E/flutter (27063): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
E/flutter (27063): #2      MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
E/flutter (27063): #3      MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
E/flutter (27063): #4      MethodChannelSharedPreferencesStore.getAll
package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44
E/flutter (27063): #5      SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart:180
E/flutter (27063): #6      SharedPreferences.getInstance
package:shared_preferences/shared_preferences.dart:56
E/flutter (27063): #7      main
package:financial/main.dart:12
E/flutter (27063): #8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (27063): #9      _rootRun (dart:async/zone.dart:1354:13)
E/flutter (27063): #10     _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (27063): #11     _runZoned (dart:async/zone.dart:1789:10)
E/flutter (27063): #12     runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (27063): #13     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (27063): #14     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (27063): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
```

答:
Instead of this

```<code>void main() {

  // qrCode.make();
  SharedPreferences.getInstance();
 Firebase.initializeApp();
  // FirebaseApp defaultApp = Firebase.app();
  runApp(const MyApp());
}
</code>```

Add like this

You must add WidgetsFlutterBinding.ensureInitialized(); starting of main method

```<code>    Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // qrCode.make();

  FirebaseApp app = await Firebase.initializeApp();
  // FirebaseApp defaultApp = Firebase.app();
  runApp(const MyApp());
}
</code>```

Reason: This library depends on the native library(android ,ios etc platofrm). Make sure that you have an instance of the WidgetsBinding, which is required to use platform channels to call the native code.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to generate through injectable, I done flutter clean also it won't work, I am using stable version flutter 2.2.2, I am facing null check error on this line of code

this code is throwing error

SharedPreferences.getInstance();

also this code

   @module
    abstract class ThemeModule {
      @preResolve
      Future<SharedPreferences> get prefs async =>
           await SharedPreferences.getInstance();
    }

Error Stack

E/flutter (27063): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (27063): #0      MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
E/flutter (27063): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
E/flutter (27063): #2      MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
E/flutter (27063): #3      MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
E/flutter (27063): #4      MethodChannelSharedPreferencesStore.getAll
package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44
E/flutter (27063): #5      SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart:180
E/flutter (27063): #6      SharedPreferences.getInstance
package:shared_preferences/shared_preferences.dart:56
E/flutter (27063): #7      main
package:financial/main.dart:12
E/flutter (27063): #8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (27063): #9      _rootRun (dart:async/zone.dart:1354:13)
E/flutter (27063): #10     _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (27063): #11     _runZoned (dart:async/zone.dart:1789:10)
E/flutter (27063): #12     runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (27063): #13     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (27063): #14     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (27063): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Body:
Instead of this

void main() {

  // qrCode.make();
  SharedPreferences.getInstance();
 Firebase.initializeApp();
  // FirebaseApp defaultApp = Firebase.app();
  runApp(const MyApp());
}

Add like this

You must add WidgetsFlutterBinding.ensureInitialized(); starting of main method

    Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // qrCode.make();

  FirebaseApp app = await Firebase.initializeApp();
  // FirebaseApp defaultApp = Firebase.app();
  runApp(const MyApp());
}

Reason: This library depends on the native library(android ,ios etc platofrm). Make sure that you have an instance of the WidgetsBinding, which is required to use platform channels to call the native code.


问:
With Azure should i store my static shared JS and images files in the package release or in a blob?
Speed and cost in mind.
Say I have a few JS and images files shared for multiple websites. that is not huge images files, this is only few static files like PNG sprites and common JS files.
I'm kind of lost on the choice :
- Should i keep it in my webpackage to release in Azure ?
- Or should i put these in blobs ?

The things I don't know is if i have a lot of hits on the blob solution, it might cost more than the hits on the IIS level of the package ?
Right, wrong ?

Edit : I realize storing JS files on the blob won't deliver it gziped ?

答: No need for the blobs that I can see.  The database round trip isn't adding value.  I'd just put the static content on the web server and let it serve it up.  Let the web server handle compressing the bytes on the wire for those cases where the client indicates that they can handle GZIP compression.</p>

ContentLicense: CC BY-SA 3.0


问:
how do i make FlxAsyncLoop work for making a progress bar in HaxeFlixel?
so, i tried to make an async loop for my game (to make a progress bar) and the game crashes when the state loads...

i tried to change the loops position so they don't collide and all of the code is from the FlxAsyncLoop demo but with other variables and some other changes.

here's the code:

```<code>import flixel.FlxCamera;
import flixel.FlxG;
import flixel.FlxObject;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.addons.util.FlxAsyncLoop;
import flixel.group.FlxGroup;
import flixel.math.FlxPoint;
import flixel.math.FlxVelocity;
import flixel.text.FlxText;
import flixel.ui.FlxBar;
import flixel.util.FlxColor;

class PlayState extends FlxState
{
public static var player:FlxSprite;

var ground:FlxSprite;
var axe:FlxSprite;
var wood:FlxSprite;
var base:FlxSprite;
var txt:FlxText;

var playerPos:FlxPoint;

var enemy:FlxSprite;

var move = false;

var progressR:FlxGroup;
var progressE:FlxGroup;

var resourceGroup:FlxGroup;
var enemyGroup:FlxGroup;

var maxItems:Int = 100;

var bar1:FlxBar;
var bartxt1:FlxText;
var bar2:FlxBar;
var bartxt2:FlxText;

var loopR:FlxAsyncLoop;
var loopE:FlxAsyncLoop;

public function addR()
{
    var wood = new FlxSprite(FlxG.random.int(100, 2500), FlxG.random.int(100, 1800));
    wood.makeGraphic(40, 100, FlxColor.BROWN);
    add(wood);

    bar1.value = (resourceGroup.members.length / maxItems) * 100;
    bartxt1.text = "Loading resources... " + resourceGroup.members.length + " / " + maxItems;
    bartxt1.screenCenter();
}

public function addE()
{
    var enemy = new FlxSprite(FlxG.random.int(300, 2500), FlxG.random.int(300, 1800));
    enemy.makeGraphic(32, 32, FlxColor.RED);
    add(enemy);

    bar2.value = (enemyGroup.members.length / maxItems) * 100;
    bartxt2.text = "Loading enemys... " + enemyGroup.members.length + " / " + maxItems;
    bartxt2.screenCenter();
}

override public function create()
{
    super.create();

    resourceGroup = new FlxGroup(maxItems);
    enemyGroup = new FlxGroup(maxItems);

    loopR = new FlxAsyncLoop(maxItems, addR);
    loopE = new FlxAsyncLoop(maxItems, addE);

    FlxG.camera.zoom = 0.5;

    playerPos = FlxPoint.get();

    ground = new FlxSprite(0, 0);
    ground.makeGraphic(2500, 1800, FlxColor.GREEN);
    add(ground);

    player = new FlxSprite(100, 100);
    player.loadGraphic(AssetPaths.n1__png);

    axe = new FlxSprite(player.x + 60, player.y);
    axe.loadGraphic(AssetPaths.axeR__png);

    camera = new FlxCamera(0, 0, 2500, 1800);
    camera.bgColor = FlxColor.TRANSPARENT;
    camera.setScrollBoundsRect(0, 0, ground.width, ground.height);
    FlxG.cameras.reset(camera);
    camera.target = player;

    if (FlxG.collide(wood, player))
        FlxObject.separate(wood, player);

    if (FlxG.collide(wood, enemy))
        FlxObject.separate(wood, enemy);

    if (FlxG.collide(enemy, player))
        FlxObject.separate(enemy, player);

    progressR = new FlxGroup();

    bar1 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
    bar1.value = 0;
    bar1.screenCenter();
    progressR.add(bar1);

    bartxt1 = new FlxText(0, 0, FlxG.width, "Loading resources... 0 / " + maxItems);
    bartxt1.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
    bartxt1.screenCenter();
    progressR.add(bartxt1);

    progressE = new FlxGroup();

    bar2 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
    bar2.value = 0;
    bar2.screenCenter();
    progressE.add(bar2);

    bartxt2 = new FlxText(0, 0, FlxG.width, "Loading enemys... 0 / " + maxItems);
    bartxt2.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
    bartxt2.screenCenter();
    progressE.add(bartxt2);

    resourceGroup.visible = false;
    resourceGroup.active = false;
    enemyGroup.visible = false;
    enemyGroup.active = false;

    add(progressR);
    add(progressE);
    add(resourceGroup);
    add(enemyGroup);
    add(loopR);
}

override public function update(elapsed:Float)
{
    super.update(elapsed);

    if (FlxG.keys.pressed.LEFT && move)
    {
        player.x -= 5;
        axe.loadGraphic(AssetPaths.axeL__png);
    }

    if (FlxG.keys.pressed.RIGHT && move)
    {
        player.x += 5;
        axe.loadGraphic(AssetPaths.axeR__png);
    }

    if (FlxG.keys.pressed.UP && move)
    {
        player.y -= 5;
    }

    if (FlxG.keys.pressed.DOWN && move)
    {
        player.y += 5;
    }

    axe.x = player.x + 60;
    axe.y = player.y;

    playerPos = FlxPoint.get();
    playerPos = player.getMidpoint();

    FlxVelocity.moveTowardsPoint(enemy, playerPos, 70);

    if (!loopR.started)
    {
        loopR.start();
    }
    else
    {
        if (loopR.finished)
        {
            resourceGroup.visible = true;
            progressR.visible = false;
            resourceGroup.active = true;
            progressR.active = false;

            loopR.kill();
            loopR.destroy();

            add(loopE);
            loopE.start();
        }
    }

    if (loopE.finished)
    {
        move = true;
        add(player);
        add(axe);

        enemyGroup.visible = true;
        progressE.visible = false;
        enemyGroup.active = true;
        progressE.active = false;

        loopE.kill();
        loopE.destroy();
    }
}
</code>```

}

i'm showing everything because of the functions and other things that can make this problem

(my english is bad sorry if i miss something...)

答:
Without knowing the exact error, I suspect that the problem is when you call

```<code>if (FlxG.collide(wood, player))
    FlxObject.separate(wood, player);

if (FlxG.collide(wood, enemy))
    FlxObject.separate(wood, enemy);

if (FlxG.collide(enemy, player))
    FlxObject.separate(enemy, player);
</code>```

Inside your create function - wood and enemy are declared in other functions and do not exist there.

There are a couple of things I would do differently here:

(Note: I didn't TEST this code, so there may still be problems, but this might help get you pointed in the right direction...)

```<code>class PlayState extends FlxState
{
    public static var player:FlxSprite;

    var ground:FlxSprite;
    var axe:FlxSprite;

    var base:FlxSprite;
    var txt:FlxText;

    var playerPos:FlxPoint;

    var move:Bool = false;

    var progressR:FlxGroup;
    var progressE:FlxGroup;

    var resourceGroup:FlxTypedGroup<FlxSprite>;
    var enemyGroup:FlxTypedGroup<FlxSprite>;

    var maxItems:Int = 100;

    var bar1:FlxBar;
    var bartxt1:FlxText;
    var bar2:FlxBar;
    var bartxt2:FlxText;

    var loopR:FlxAsyncLoop;
    var loopE:FlxAsyncLoop;

    public function addR()
    {
        var wood = new FlxSprite(FlxG.random.int(100, 2500), FlxG.random.int(100, 1800));
        wood.makeGraphic(40, 100, FlxColor.BROWN);
        resourceGroup.add(wood);

        bar1.value = (resourceGroup.members.length / maxItems) * 100;
        bartxt1.text = "Loading resources... " + resourceGroup.members.length + " / " + maxItems;
        bartxt1.screenCenter();

        FlxG.collide(player, resourceGroup) // should not need to call `seperate` - it's automatic when using `collide` vs `overlap`
    }

    public function addE()
    {
        var enemy = new FlxSprite(FlxG.random.int(300, 2500), FlxG.random.int(300, 1800));
        enemy.makeGraphic(32, 32, FlxColor.RED);
        enemyGroup.add(enemy);

        FlxG.collide(enemyGroup, resourceGroup)

        FlxG.collide(player, resourceGroup)

        bar2.value = (enemyGroup.members.length / maxItems) * 100;
        bartxt2.text = "Loading enemys... " + enemyGroup.members.length + " / " + maxItems;
        bartxt2.screenCenter();
    }

    override public function create()
    {
        super.create();

        resourceGroup = new FlxTypedGroup<FlxSprite>(maxItems);
        enemyGroup = new FlxTypedGroup<FlxSprite>(maxItems);

        loopR = new FlxAsyncLoop(maxItems, addR);
        loopE = new FlxAsyncLoop(maxItems, addE);

        FlxG.camera.zoom = 0.5;

        playerPos = FlxPoint.get();

        ground = new FlxSprite(0, 0);
        ground.makeGraphic(2500, 1800, FlxColor.GREEN);
        add(ground);

        player = new FlxSprite(100, 100);
        player.loadGraphic(AssetPaths.n1__png);

        axe = new FlxSprite(player.x + 60, player.y);
        axe.loadGraphic(AssetPaths.axeR__png);

        camera = new FlxCamera(0, 0, 2500, 1800);
        camera.bgColor = FlxColor.TRANSPARENT;
        camera.setScrollBoundsRect(0, 0, ground.width, ground.height);
        FlxG.cameras.reset(camera);
        camera.target = player;

        progressR = new FlxGroup();

        bar1 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
        bar1.value = 0;
        bar1.screenCenter();
        progressR.add(bar1);

        bartxt1 = new FlxText(0, 0, FlxG.width, "Loading resources... 0 / " + maxItems);
        bartxt1.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
        bartxt1.screenCenter();
        progressR.add(bartxt1);

        progressE = new FlxGroup();

        bar2 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
        bar2.value = 0;
        bar2.screenCenter();
        progressE.add(bar2);

        bartxt2 = new FlxText(0, 0, FlxG.width, "Loading enemys... 0 / " + maxItems);
        bartxt2.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
        bartxt2.screenCenter();
        progressE.add(bartxt2);

        resourceGroup.visible = false;
        resourceGroup.active = false;
        enemyGroup.visible = false;
        enemyGroup.active = false;

        add(progressR);
        add(progressE);
        add(resourceGroup);
        add(enemyGroup);
        add(loopR);
    }

    public function gamePlay(elapsed:Float):Void
    {
        if (FlxG.keys.pressed.LEFT && move)
        {
            player.x -= 5; // why +/- position and not .velocity?

            // THIS is probably not right - you want to use a sprite sheet with animations and call axe.play("left") or something...
            axe.loadGraphic(AssetPaths.axeL__png);
        }

        if (FlxG.keys.pressed.RIGHT && move)
        {
            player.x += 5;
            axe.loadGraphic(AssetPaths.axeR__png);
        }

        if (FlxG.keys.pressed.UP && move)
        {
            player.y -= 5;
        }

        if (FlxG.keys.pressed.DOWN && move)
        {
            player.y += 5;
        }

        axe.x = player.x + 60;
        axe.y = player.y;

        playerPos = FlxPoint.get();
        playerPos = player.getMidpoint();

        for (e in enemyGroup)
        {
            FlxVelocity.moveTowardsPoint(e, playerPos, 70);
        }
    }

    public function loading(elapsed:Float):Void
    {
        if (!loopR.started)
        {
            loopR.start();
        }
        else if (loopR.finished)
        {
            resourceGroup.visible = true;
            progressR.visible = false;
            resourceGroup.active = true;
            progressR.active = false;

            loopR.kill();
            loopR.destroy();

            add(loopE);
            loopE.start();
        }
        else if (loopE.finished)
        {
            move = true;
            add(player);
            add(axe);

            enemyGroup.visible = true;
            progressE.visible = false;
            enemyGroup.active = true;
            progressE.active = false;

            loopE.kill();
            loopE.destroy();
        }
    }

    override public function update(elapsed:Float)
    {
        super.update(elapsed);

        if (!move)
        {
            loading(elapsed);
        }
        else
        {
            gamePlay(elapsed);
        }
    }
}
</code>```

Body:
so, i tried to make an async loop for my game (to make a progress bar) and the game crashes when the state loads...

i tried to change the loops position so they don't collide and all of the code is from the FlxAsyncLoop demo but with other variables and some other changes.

here's the code:

import flixel.FlxCamera;
import flixel.FlxG;
import flixel.FlxObject;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.addons.util.FlxAsyncLoop;
import flixel.group.FlxGroup;
import flixel.math.FlxPoint;
import flixel.math.FlxVelocity;
import flixel.text.FlxText;
import flixel.ui.FlxBar;
import flixel.util.FlxColor;

class PlayState extends FlxState
{
public static var player:FlxSprite;

var ground:FlxSprite;
var axe:FlxSprite;
var wood:FlxSprite;
var base:FlxSprite;
var txt:FlxText;

var playerPos:FlxPoint;

var enemy:FlxSprite;

var move = false;

var progressR:FlxGroup;
var progressE:FlxGroup;

var resourceGroup:FlxGroup;
var enemyGroup:FlxGroup;

var maxItems:Int = 100;

var bar1:FlxBar;
var bartxt1:FlxText;
var bar2:FlxBar;
var bartxt2:FlxText;

var loopR:FlxAsyncLoop;
var loopE:FlxAsyncLoop;

public function addR()
{
    var wood = new FlxSprite(FlxG.random.int(100, 2500), FlxG.random.int(100, 1800));
    wood.makeGraphic(40, 100, FlxColor.BROWN);
    add(wood);

    bar1.value = (resourceGroup.members.length / maxItems) * 100;
    bartxt1.text = "Loading resources... " + resourceGroup.members.length + " / " + maxItems;
    bartxt1.screenCenter();
}

public function addE()
{
    var enemy = new FlxSprite(FlxG.random.int(300, 2500), FlxG.random.int(300, 1800));
    enemy.makeGraphic(32, 32, FlxColor.RED);
    add(enemy);

    bar2.value = (enemyGroup.members.length / maxItems) * 100;
    bartxt2.text = "Loading enemys... " + enemyGroup.members.length + " / " + maxItems;
    bartxt2.screenCenter();
}

override public function create()
{
    super.create();

    resourceGroup = new FlxGroup(maxItems);
    enemyGroup = new FlxGroup(maxItems);

    loopR = new FlxAsyncLoop(maxItems, addR);
    loopE = new FlxAsyncLoop(maxItems, addE);

    FlxG.camera.zoom = 0.5;

    playerPos = FlxPoint.get();

    ground = new FlxSprite(0, 0);
    ground.makeGraphic(2500, 1800, FlxColor.GREEN);
    add(ground);

    player = new FlxSprite(100, 100);
    player.loadGraphic(AssetPaths.n1__png);

    axe = new FlxSprite(player.x + 60, player.y);
    axe.loadGraphic(AssetPaths.axeR__png);

    camera = new FlxCamera(0, 0, 2500, 1800);
    camera.bgColor = FlxColor.TRANSPARENT;
    camera.setScrollBoundsRect(0, 0, ground.width, ground.height);
    FlxG.cameras.reset(camera);
    camera.target = player;

    if (FlxG.collide(wood, player))
        FlxObject.separate(wood, player);

    if (FlxG.collide(wood, enemy))
        FlxObject.separate(wood, enemy);

    if (FlxG.collide(enemy, player))
        FlxObject.separate(enemy, player);

    progressR = new FlxGroup();

    bar1 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
    bar1.value = 0;
    bar1.screenCenter();
    progressR.add(bar1);

    bartxt1 = new FlxText(0, 0, FlxG.width, "Loading resources... 0 / " + maxItems);
    bartxt1.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
    bartxt1.screenCenter();
    progressR.add(bartxt1);

    progressE = new FlxGroup();

    bar2 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
    bar2.value = 0;
    bar2.screenCenter();
    progressE.add(bar2);

    bartxt2 = new FlxText(0, 0, FlxG.width, "Loading enemys... 0 / " + maxItems);
    bartxt2.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
    bartxt2.screenCenter();
    progressE.add(bartxt2);

    resourceGroup.visible = false;
    resourceGroup.active = false;
    enemyGroup.visible = false;
    enemyGroup.active = false;

    add(progressR);
    add(progressE);
    add(resourceGroup);
    add(enemyGroup);
    add(loopR);
}

override public function update(elapsed:Float)
{
    super.update(elapsed);

    if (FlxG.keys.pressed.LEFT && move)
    {
        player.x -= 5;
        axe.loadGraphic(AssetPaths.axeL__png);
    }

    if (FlxG.keys.pressed.RIGHT && move)
    {
        player.x += 5;
        axe.loadGraphic(AssetPaths.axeR__png);
    }

    if (FlxG.keys.pressed.UP && move)
    {
        player.y -= 5;
    }

    if (FlxG.keys.pressed.DOWN && move)
    {
        player.y += 5;
    }

    axe.x = player.x + 60;
    axe.y = player.y;

    playerPos = FlxPoint.get();
    playerPos = player.getMidpoint();

    FlxVelocity.moveTowardsPoint(enemy, playerPos, 70);

    if (!loopR.started)
    {
        loopR.start();
    }
    else
    {
        if (loopR.finished)
        {
            resourceGroup.visible = true;
            progressR.visible = false;
            resourceGroup.active = true;
            progressR.active = false;

            loopR.kill();
            loopR.destroy();

            add(loopE);
            loopE.start();
        }
    }

    if (loopE.finished)
    {
        move = true;
        add(player);
        add(axe);

        enemyGroup.visible = true;
        progressE.visible = false;
        enemyGroup.active = true;
        progressE.active = false;

        loopE.kill();
        loopE.destroy();
    }
}

}

i'm showing everything because of the functions and other things that can make this problem

(my english is bad sorry if i miss something...)

Body:
Without knowing the exact error, I suspect that the problem is when you call

if (FlxG.collide(wood, player))
    FlxObject.separate(wood, player);

if (FlxG.collide(wood, enemy))
    FlxObject.separate(wood, enemy);

if (FlxG.collide(enemy, player))
    FlxObject.separate(enemy, player);

Inside your create function - wood and enemy are declared in other functions and do not exist there.

There are a couple of things I would do differently here:

(Note: I didn't TEST this code, so there may still be problems, but this might help get you pointed in the right direction...)

class PlayState extends FlxState
{
    public static var player:FlxSprite;

    var ground:FlxSprite;
    var axe:FlxSprite;

    var base:FlxSprite;
    var txt:FlxText;

    var playerPos:FlxPoint;

    var move:Bool = false;

    var progressR:FlxGroup;
    var progressE:FlxGroup;

    var resourceGroup:FlxTypedGroup<FlxSprite>;
    var enemyGroup:FlxTypedGroup<FlxSprite>;

    var maxItems:Int = 100;

    var bar1:FlxBar;
    var bartxt1:FlxText;
    var bar2:FlxBar;
    var bartxt2:FlxText;

    var loopR:FlxAsyncLoop;
    var loopE:FlxAsyncLoop;

    public function addR()
    {
        var wood = new FlxSprite(FlxG.random.int(100, 2500), FlxG.random.int(100, 1800));
        wood.makeGraphic(40, 100, FlxColor.BROWN);
        resourceGroup.add(wood);

        bar1.value = (resourceGroup.members.length / maxItems) * 100;
        bartxt1.text = "Loading resources... " + resourceGroup.members.length + " / " + maxItems;
        bartxt1.screenCenter();

        FlxG.collide(player, resourceGroup) // should not need to call `seperate` - it's automatic when using `collide` vs `overlap`
    }

    public function addE()
    {
        var enemy = new FlxSprite(FlxG.random.int(300, 2500), FlxG.random.int(300, 1800));
        enemy.makeGraphic(32, 32, FlxColor.RED);
        enemyGroup.add(enemy);

        FlxG.collide(enemyGroup, resourceGroup)

        FlxG.collide(player, resourceGroup)

        bar2.value = (enemyGroup.members.length / maxItems) * 100;
        bartxt2.text = "Loading enemys... " + enemyGroup.members.length + " / " + maxItems;
        bartxt2.screenCenter();
    }

    override public function create()
    {
        super.create();

        resourceGroup = new FlxTypedGroup<FlxSprite>(maxItems);
        enemyGroup = new FlxTypedGroup<FlxSprite>(maxItems);

        loopR = new FlxAsyncLoop(maxItems, addR);
        loopE = new FlxAsyncLoop(maxItems, addE);

        FlxG.camera.zoom = 0.5;

        playerPos = FlxPoint.get();

        ground = new FlxSprite(0, 0);
        ground.makeGraphic(2500, 1800, FlxColor.GREEN);
        add(ground);

        player = new FlxSprite(100, 100);
        player.loadGraphic(AssetPaths.n1__png);

        axe = new FlxSprite(player.x + 60, player.y);
        axe.loadGraphic(AssetPaths.axeR__png);

        camera = new FlxCamera(0, 0, 2500, 1800);
        camera.bgColor = FlxColor.TRANSPARENT;
        camera.setScrollBoundsRect(0, 0, ground.width, ground.height);
        FlxG.cameras.reset(camera);
        camera.target = player;

        progressR = new FlxGroup();

        bar1 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
        bar1.value = 0;
        bar1.screenCenter();
        progressR.add(bar1);

        bartxt1 = new FlxText(0, 0, FlxG.width, "Loading resources... 0 / " + maxItems);
        bartxt1.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
        bartxt1.screenCenter();
        progressR.add(bartxt1);

        progressE = new FlxGroup();

        bar2 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
        bar2.value = 0;
        bar2.screenCenter();
        progressE.add(bar2);

        bartxt2 = new FlxText(0, 0, FlxG.width, "Loading enemys... 0 / " + maxItems);
        bartxt2.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
        bartxt2.screenCenter();
        progressE.add(bartxt2);

        resourceGroup.visible = false;
        resourceGroup.active = false;
        enemyGroup.visible = false;
        enemyGroup.active = false;

        add(progressR);
        add(progressE);
        add(resourceGroup);
        add(enemyGroup);
        add(loopR);
    }

    public function gamePlay(elapsed:Float):Void
    {
        if (FlxG.keys.pressed.LEFT && move)
        {
            player.x -= 5; // why +/- position and not .velocity?

            // THIS is probably not right - you want to use a sprite sheet with animations and call axe.play("left") or something...
            axe.loadGraphic(AssetPaths.axeL__png);
        }

        if (FlxG.keys.pressed.RIGHT && move)
        {
            player.x += 5;
            axe.loadGraphic(AssetPaths.axeR__png);
        }

        if (FlxG.keys.pressed.UP && move)
        {
            player.y -= 5;
        }

        if (FlxG.keys.pressed.DOWN && move)
        {
            player.y += 5;
        }

        axe.x = player.x + 60;
        axe.y = player.y;

        playerPos = FlxPoint.get();
        playerPos = player.getMidpoint();

        for (e in enemyGroup)
        {
            FlxVelocity.moveTowardsPoint(e, playerPos, 70);
        }
    }

    public function loading(elapsed:Float):Void
    {
        if (!loopR.started)
        {
            loopR.start();
        }
        else if (loopR.finished)
        {
            resourceGroup.visible = true;
            progressR.visible = false;
            resourceGroup.active = true;
            progressR.active = false;

            loopR.kill();
            loopR.destroy();

            add(loopE);
            loopE.start();
        }
        else if (loopE.finished)
        {
            move = true;
            add(player);
            add(axe);

            enemyGroup.visible = true;
            progressE.visible = false;
            enemyGroup.active = true;
            progressE.active = false;

            loopE.kill();
            loopE.destroy();
        }
    }

    override public function update(elapsed:Float)
    {
        super.update(elapsed);

        if (!move)
        {
            loading(elapsed);
        }
        else
        {
            gamePlay(elapsed);
        }
    }
}


问:
MySql: Insert data from one table to another
```<code>Table A:
+----+-------+--------+-------+
| id | Tag   | Name   | Size  |
+----+-------+--------+-------+
|  1 | One   | Bob    | 14.29 |
|  2 | Two   | Charles| 28.56 |
|  3 | Three | Frank  | 76.95 |
+----+-------+--------+-------+
Table B:
+----+-------+--------+-------+
| id | Tag   | Name   | Size  |
+----+-------+--------+-------+
|  55| Two   | Charles|     0 |
|  68| Three | Frank  |     0 |
+----+-------+--------+-------+
</code>```

What I want: Size from Table A in Table B

Closest query:

```<code>  INSERT INTO B (Size)
  SELECT Size FROM A
  WHERE A.Tag = B.Tag
  AND A.Name = B.Name;
</code>```

Resulting in error:
ERROR 1054 (42S22): Unknown column 'B.Tag' in 'where clause'.

```<code>I am newbie to MySql and guess this is a standard database task.

</code>```

答:
What you need is to update the table B and not insert new rows.

Use a join in the UPDATE statement:

```<code>UPDATE B
INNER JOIN A ON A.Tag = B.Tag AND A.Name = B.Name
SET B.Size = A.Size;
</code>```

Body:
Table A:
+----+-------+--------+-------+
| id | Tag   | Name   | Size  |
+----+-------+--------+-------+
|  1 | One   | Bob    | 14.29 |
|  2 | Two   | Charles| 28.56 |
|  3 | Three | Frank  | 76.95 |
+----+-------+--------+-------+
Table B:
+----+-------+--------+-------+
| id | Tag   | Name   | Size  |
+----+-------+--------+-------+
|  55| Two   | Charles|     0 |
|  68| Three | Frank  |     0 |
+----+-------+--------+-------+

What I want: Size from Table A in Table B

Closest query:

  INSERT INTO B (Size)
  SELECT Size FROM A
  WHERE A.Tag = B.Tag
  AND A.Name = B.Name;

Resulting in error:
ERROR 1054 (42S22): Unknown column 'B.Tag' in 'where clause'.

I am newbie to MySql and guess this is a standard database task.

Body:
What you need is to update the table B and not insert new rows.

Use a join in the UPDATE statement:

UPDATE B
INNER JOIN A ON A.Tag = B.Tag AND A.Name = B.Name
SET B.Size = A.Size;


问:
How to speed up pandas apply?
I have a large DataFrame of 3.14 million rows and I need to group them using 1 column then calculate the std dev and mean by groups. I have done the following and it works as expected, but it is very slow (20000 rows alone take 1min+). I am pretty sure there are much faster ways but I could not find any when I tried to google.

```<code>def gen_time_feats(df):
    feats = df.loc[:, 'f_0':'f_299']
    for col in feats.columns:
        df[f'{col}_avg'] = np.mean(feats[col].values)
        df[f'{col}_std'] = np.std(feats[col].values)
    return df

df_grouped = df.groupby('group_id')
df_with_time_feat = df_grouped.apply(gen_time_feats)
</code>```

The DataFrame has 300 columns and I want to append the std dev and mean for each column as additional columns, so in the end it will become 900 columns.

答:
Use filter to select the f_xxx columns then groupby group_id column then use a list of functions to apply to each columns. Finally, flat your column index.

```<code>out = df.filter(regex='f_\d+').groupby(df['group_id']).agg(['mean', 'std'])
out.columns = out.columns.to_flat_index().str.join('_')
out = df.set_index('group_id').join(out).sort_index(axis=1).reset_index()
print(out)

# Output:
  group_id  f_100  f_100_mean  f_100_std  f_200  f_200_mean  f_200_std
0        A      1         3.0   2.828427      5         7.0   2.828427
1        A      5         3.0   2.828427      9         7.0   2.828427
2        B      2         3.0   1.414214      6         7.0   1.414214
3        B      4         3.0   1.414214      8         7.0   1.414214
</code>```

Setup:

```<code>df = pd.DataFrame({'group_id': list('ABBA'), 'f_100': [1, 2, 4, 5], 'f_200': [5, 6, 8, 9]})
print(df)

# Output
  group_id  f_100  f_200
0        A      1      5
1        B      2      6
2        B      4      8
3        A      5      9
</code>```

Note if you want to have the name '_avg' instead of '_mean', use the modified version of agg: .agg([('avg', 'mean'), 'std'])

Title: How to speed up pandas apply?

Body:
I have a large DataFrame of 3.14 million rows and I need to group them using 1 column then calculate the std dev and mean by groups. I have done the following and it works as expected, but it is very slow (20000 rows alone take 1min+). I am pretty sure there are much faster ways but I could not find any when I tried to google.

def gen_time_feats(df):
    feats = df.loc[:, 'f_0':'f_299']
    for col in feats.columns:
        df[f'{col}_avg'] = np.mean(feats[col].values)
        df[f'{col}_std'] = np.std(feats[col].values)
    return df

df_grouped = df.groupby('group_id')
df_with_time_feat = df_grouped.apply(gen_time_feats)

The DataFrame has 300 columns and I want to append the std dev and mean for each column as additional columns, so in the end it will become 900 columns.

Body:
Use filter to select the f_xxx columns then groupby group_id column then use a list of functions to apply to each columns. Finally, flat your column index.

out = df.filter(regex='f_\d+').groupby(df['group_id']).agg(['mean', 'std'])
out.columns = out.columns.to_flat_index().str.join('_')
out = df.set_index('group_id').join(out).sort_index(axis=1).reset_index()
print(out)

# Output:
  group_id  f_100  f_100_mean  f_100_std  f_200  f_200_mean  f_200_std
0        A      1         3.0   2.828427      5         7.0   2.828427
1        A      5         3.0   2.828427      9         7.0   2.828427
2        B      2         3.0   1.414214      6         7.0   1.414214
3        B      4         3.0   1.414214      8         7.0   1.414214

Setup:

df = pd.DataFrame({'group_id': list('ABBA'), 'f_100': [1, 2, 4, 5], 'f_200': [5, 6, 8, 9]})
print(df)

# Output
  group_id  f_100  f_200
0        A      1      5
1        B      2      6
2        B      4      8
3        A      5      9

Note if you want to have the name '_avg' instead of '_mean', use the modified version of agg: .agg([('avg', 'mean'), 'std'])


问:
Run MATLAB program with Web Server inputs
I have a MATLAB application that I want to execute on a linux box with inputs from a web server. Requests to the server would all be from the local network.

Searching for different solutions, I've seen recommendations to host a Django server that serves an HTML form where users could input all the various data needed by the application. When a user fills out the form and submits it, the data would be sent through an API to the MATLAB application, which would serve up the report in a network shared drive.

Would this work well? Is there a different/easier solution available?

答:
Need more details to know if this would "work well". But in terms of the general outline you presented, seems feasible.

When you say "the data would be sent through an API to the MATLAB application", what exactly do you mean here? What API are we talking about? And what is "the Matlab application"? Do you mean just installing regular Matlab on this server machine, and then having the Django or other web application server run the matlab command to run a Matlab program, running as a distinct process (corresponding to a single matlab -batch execution, probably?) that services that? Two issues here: One, Matlab is a large program with a slow startup time. Matlab Production Server and similar solutions handle this by maintaining a pool of already-running "warmed up" Matlab worker processes to service incoming requests. Two, licensing: the "regular" Matlab licenses are aimed towards interactive use by humans; running Matlab like that on the server side to handle requests for a web app used by multiple humans may not be covered. Talk to your organization's lawyer or IT licensing expert before doing this.

@Will is right here: The Matlab Production Server is the product or "solution" that MathWorks provides for this scenario. And it's relatively easy to use. But ain't cheap. (On the other hand, when you're talking about Matlab, what is?)

If you have someone who can do a bit of system programming for you, there's a more affordable alternative: use the Matlab Compiler to build your Matlab code into a "CTF" DLL, and write a thin custom server wrapper on top of that, which can accept service calls for the particular Matlab things you need done, and dispatches them to your code. (Running that in a pool of multiple processes, if you want to be able to service multiple concurrent clients.) "Compiled" Matlab libraries that run against the Matlab Runtime do not require any additional licenses for their runtime execution.

Big questions here are: Do you want this to Go Fast? How many clients are you going to have, and how often are they going to be sending requests? What kind of data will be contained in the inputs and outputs to this Matlab code?

Have a look at the -batch option to the matlab command. Have a look at the various deployment options supported by the Matlab Compiler. And talk to your organization's lawyer.

If you decide to go the matlab -batch route, you probably do not want to pass the inputs to your Matlab code as command-line arguments. Command lines and environment variables only pass simple strings, and parsing those sucks, especially once you get in to nontrivial numerics. Bundle up all your inputs as JSON files, MAT files, or something similar, and then pass just a reference to those files (or SQL blobs, or similar) on the command line.

Also, depending on what your Matlab code is like, GNU Octave (https://gnu.org/software/octave/index) may be an option for you. Octave is many years behind Matlab in terms of functionality and stability, and doesn't have equivalents of all the Matlab Toolboxes, so it isn't a drop-in replacement in general terms. But for simple stuff, it works. And it is unencumbered by licensing, and has faster startup times in command-line mode.


问:
On running default app, Flutter throws "log reader stopped unexpectedly" after switching to Master
```<code>PS D:\flutterApp\myapp> flutter run
Running Gradle task 'assembleDebug'...

Running Gradle task 'assembleDebug'... Done                       203.1s (!)
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...                         7.7s
Error waiting for a debug connection: The log reader stopped unexpectedly
Error launching application on Redmi Note 4.
</code>```

Earlier it was Error waiting for a debug connection: Bad state: No element, I switched to master from stable and now it is throwing this error on run. App is getting installed but crashing by throwing this error.

答:
My current device is Redmi 9 prime

Android version: 11

MIUI version: 12.5.2

Even I faced a similar problem while debugging the app and then I disabled the USB debugging (security settings) and Revoke USB  debugging authorizations  in the developer option

The above method resolved my problem.

Body:
PS D:\flutterApp\myapp> flutter run
Running Gradle task 'assembleDebug'...

Running Gradle task 'assembleDebug'... Done                       203.1s (!)
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...                         7.7s
Error waiting for a debug connection: The log reader stopped unexpectedly
Error launching application on Redmi Note 4.

Earlier it was Error waiting for a debug connection: Bad state: No element, I switched to master from stable and now it is throwing this error on run. App is getting installed but crashing by throwing this error.


问:
serving pytorch model using flask
If multiple clients make a request to one server(pytorch model), how does the problem arise in the multithread of the flask or elsewhere?

As far as I know, if running the pytorch model with multithreading using flask, the data will get tangled. If I’m wrong, please correct it.

答:
Use a multithreaded approach for Flask as well, the request will get throttled if you just initiate a single threaded usual Flask server.

Use Gunicorn: https://gunicorn.org/ to start your Flask server, with a good number of threads, passed as a parameter value to Gunicorn.

Title: serving pytorch model using flask


问:
R Script to rearrange the elements of a vector by interleaving it
How to write an R-script to initialize a vector with integers, rearrange the elements by interleaving the
first half elements with the second half elements and store in the same vector without using pre-defined function and display the updated vector.</p>

答:
Another way is to use rbind on the 2 halves of the vector, which creates a matrix with two rows. Then, we can then turn the matrix into a vector, which will go through column by column (i.e., 1, 11, 2, 12...). However, this will only work for even vectors.

```<code>vec <- 1:20

c(rbind(vec[1:10], vec[11:20]))

# [1]  1 11  2 12  3 13  4 14  5 15  6 16  7 17  8 18  9 19 10 20
</code>```

So, for uneven vectors, we can use order, which will return the indices of the numbers in the two seq_along vectors.

```<code>vec2 <- 1:21

order(c(seq_along(vec2[1:10]),seq_along(vec2[11:21])))

# [1]  1 11  2 12  3 13  4 14  5 15  6 16  7 17  8 18  9 19 10 20 21
</code>```

Body:
Another way is to use rbind on the 2 halves of the vector, which creates a matrix with two rows. Then, we can then turn the matrix into a vector, which will go through column by column (i.e., 1, 11, 2, 12...). However, this will only work for even vectors.

vec <- 1:20

c(rbind(vec[1:10], vec[11:20]))

# [1]  1 11  2 12  3 13  4 14  5 15  6 16  7 17  8 18  9 19 10 20

So, for uneven vectors, we can use order, which will return the indices of the numbers in the two seq_along vectors.

vec2 <- 1:21

order(c(seq_along(vec2[1:10]),seq_along(vec2[11:21])))

# [1]  1 11  2 12  3 13  4 14  5 15  6 16  7 17  8 18  9 19 10 20 21


问:
When is it the right time to use C# class library (.dll)?
I'm a programmer who has never really used .dll files.
Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code.

Also, it seems like you can use .dll for a lot of different things, so I'd like the topic to concentrate on C#.

Right now I am working on a sanitizing library(?) (I think that is the correct term), which will be full of relevant methods that can sanitize variables in all sorts of different ways.

What I want to know is:

would there be any advantage to:

1) Write the methods to class library -> compile/build it -> add the library as a reference to the program - which would need to sanitize some variables ?

Or would it be exactly the same if I where to:

2) Create a new SanitizeClass in the program -> add all the sanitize methods -> call the methods from the SanitizeClass in the different classes in the program that needs to sanitize variables

In general, I also want to know when it is an advantage to use compiled class libraries.
I'm thinking of speed, security, all of it.

Could anyone enlightenment me? :)

答:
Using libraries is useful when you want to share code between multiple programs.

If you think you will need your classes to sanitize data in more than one program, this is a good idea to put them in a library.

It is also a good idea to put layers of your application in different libraries (check n-tier architecture)

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Martin


问:
How to delete uri directory(Folder) after user picks folder?
I have a notepad app that restores notes and backs them up. When manually backing up, it usually on android 10 would delete the folder then create it again with new files. Now with saf i cant figure out how to delete a chosen tree folder.
Heres my code but it doesnt work.</p>
```<code>try {
muri = t.getString("muri", "");
Uri uri = Uri.parse(muri);
DocumentsContract.deleteDocument
(getApplicationContext().getContentResolver(), uri);
}  catch (Exception e) {}
</code>```

答:
Figured it out</p>
```<code>try {
muri = t.getString("muri", "");
Uri uri = Uri.parse(muri);
DocumentFile dir = DocumentFile.fromTreeUri(this, uri);
DocumentFile dir2 = dir.findFile("Godisgood");
dir2.delete();
}  catch (Exception e) {}
</code>```

Body:
I have a notepad app that restores notes and backs them up. When manually backing up, it usually on android 10 would delete the folder then create it again with new files. Now with saf i cant figure out how to delete a chosen tree folder.
Heres my code but it doesnt work.

try {
muri = t.getString("muri", "");
Uri uri = Uri.parse(muri);
DocumentsContract.deleteDocument
(getApplicationContext().getContentResolver(), uri);
}  catch (Exception e) {}

Body:
Figured it out

try {
muri = t.getString("muri", "");
Uri uri = Uri.parse(muri);
DocumentFile dir = DocumentFile.fromTreeUri(this, uri);
DocumentFile dir2 = dir.findFile("Godisgood");
dir2.delete();
}  catch (Exception e) {}


问:
for-loop confusion
I'm supposed to write a code that will ask the user to input their names and the number of times they want it printed but I'm facing challenges. Kindly find my code below.</p>
```<code>name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = input(int())
for times in answer:
    print(name)
</code>```

答:
The statement answer = input(int()), as mentioned above should be answer = int(input()) instead.

Also, the statement for times in answer should be changed to for times in range(answer) as python would expect an iterable object after in (ie, an object over which python can iterate and get values). Here, answer will not be an iterable because it is an integer and not a list of objects that it can iterate over. range(answer) would tell python to iterate over the list of numbers starting from 0 to answer-1 (and hence, the loop will be carried answer number of times, anyways).

Please note that for times in answer will result in a TypeError due to the above mentioned reason.

So your final code would be:

name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = int(input())
for times in range(answer):
    print(name)
```

Title: for-loop confusion

Body:
I'm supposed to write a code that will ask the user to input their names and the number of times they want it printed but I'm facing challenges. Kindly find my code below.

name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = input(int())
for times in answer:
    print(name)


问:
Addition on HashSet of KeyValuePair
I have a list of entries. Each entry contains a string and a numerical value. The same string  can appear one or more times in a list and it can have a different numerical value. be I am looking for an elegant way to process the list. The end result should be a list of unique pairs of string and (sum of values for the string). Each unique string should be associated with the sum of all numerical values for the string. I consider creating a HashSet<KeyValuePair<string, double>> and to add each string to the HashSet. But I am not sure how to add all values together in a single loop. The code below works, but it is inefficient.</p>
```<code>        SortedSet<string> symbols = new SortedSet<string>();
        HashSet<KeyValuePair<string, double>> results = new HashSet<KeyValuePair<string, double>>();
        string file = openFileDialog1.FileName;
        string[] lines = File.ReadAllLines(file);

        foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            symbols.Add(symbol);
        }

        foreach(string uniqueSymbol in symbols) {
            double value = 0;
            foreach(string line in lines) {
                string[] values = line.Split('\t');
                string symbol = values[0].Trim();
                string sProfit = values[7].Trim();
                double fProfit = Convert.ToDouble(sProfit);

                if(symbol == uniqueSymbol) {
                    value += fProfit;
                }
            }

            results.Add(new KeyValuePair<string, double>(uniqueSymbol, value));
        }
</code>```

答:
As several others here, I agree that a Dictionary sounds like what suits your needs best. If using Linq is an option, here is an apporach that should work:

```<code>Dictionary<string, double> results = lines
    .Select(line => line.Split('\t'))
    .Select(lineEntries => (
        Symbol: lineEntries[0].Trim(),
        Value: Convert.ToDouble(lineEntries[7].Trim()))) // Some validation should be done here
    .GroupBy(symbolAndValue => symbolAndValue.Symbol)
    .ToDictionary(
        gr => gr.Key,
        gr => gr.Select(symbolAndValue => symbolAndValue.Value).Sum());
</code>```

I'm creating a tuple (string Symbol, double Value) for each line, then grouping them by Symbol, then creating a dictionary using Symbol as the Key and the sum of values connected to Symbol as the Value for each dictionary entry.

A slightly more concise approach would be merging the two Select statements together by performing line.Split('\t') twice:

```<code>.Select(line => (
    Symbol: line.Split('\t')[0].Trim(),
    Value: Convert.ToDouble(line.Split('\t')[7].Trim())))
</code>```

Title: Addition on HashSet of KeyValuePair

Body:
I have a list of entries. Each entry contains a string and a numerical value. The same string  can appear one or more times in a list and it can have a different numerical value. be I am looking for an elegant way to process the list. The end result should be a list of unique pairs of string and (sum of values for the string). Each unique string should be associated with the sum of all numerical values for the string. I consider creating a HashSet<KeyValuePair<string, double>> and to add each string to the HashSet. But I am not sure how to add all values together in a single loop. The code below works, but it is inefficient.

        SortedSet<string> symbols = new SortedSet<string>();
        HashSet<KeyValuePair<string, double>> results = new HashSet<KeyValuePair<string, double>>();
        string file = openFileDialog1.FileName;
        string[] lines = File.ReadAllLines(file);

        foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            symbols.Add(symbol);
        }

        foreach(string uniqueSymbol in symbols) {
            double value = 0;
            foreach(string line in lines) {
                string[] values = line.Split('\t');
                string symbol = values[0].Trim();
                string sProfit = values[7].Trim();
                double fProfit = Convert.ToDouble(sProfit);

                if(symbol == uniqueSymbol) {
                    value += fProfit;
                }
            }

            results.Add(new KeyValuePair<string, double>(uniqueSymbol, value));
        }

Body:
As several others here, I agree that a Dictionary sounds like what suits your needs best. If using Linq is an option, here is an apporach that should work:

Dictionary<string, double> results = lines
    .Select(line => line.Split('\t'))
    .Select(lineEntries => (
        Symbol: lineEntries[0].Trim(),
        Value: Convert.ToDouble(lineEntries[7].Trim()))) // Some validation should be done here
    .GroupBy(symbolAndValue => symbolAndValue.Symbol)
    .ToDictionary(
        gr => gr.Key,
        gr => gr.Select(symbolAndValue => symbolAndValue.Value).Sum());

I'm creating a tuple (string Symbol, double Value) for each line, then grouping them by Symbol, then creating a dictionary using Symbol as the Key and the sum of values connected to Symbol as the Value for each dictionary entry.

A slightly more concise approach would be merging the two Select statements together by performing line.Split('\t') twice:

.Select(line => (
    Symbol: line.Split('\t')[0].Trim(),
    Value: Convert.ToDouble(line.Split('\t')[7].Trim())))


问:
Jmeter: how to construct JSON Path using field names from csv file to compare data from API response with data from DB
I have an API which returns following response:

```<code> {
    "data": {
        "response": {
            "employee":
                {
                   "firstName": "Frank",
                   "lastName": "Porter",
                   "employeeNumber": "11102"
                }
            }
        }
}
</code>```

In JMeter, I need to do the following:

Query the DB and fetch data from the tables. Store it in a variable to compare with API response.

Write assertion which will compare the data from the DB with the API response. For this I need the assertion to read names of fields to compare from a CSV file.

I am able to construct a csv which has the list of fields - firstName,lastName,employeeNumber
In my assertion, I am parsing the API response using JSONSlurper and then trying to compare the data.
If I hardcode the field names, the comparison works ok - so something like below works ok:

```<code>import groovy.json.JsonSlurper;
def failureMessage = "";
def jsonResponse = null;
JsonSlurper JSON = new JsonSlurper ();

//compare data from db with API response

if (!jsonResponse.data.response.employee.firstName.equals(vars.getObject("datafromDB").get(0).get("firstName")))
{
          failureMessage += "firstName does not match \n\n";
}

if (failureMessage?.trim()) {
              AssertionResult.setFailureMessage(failureMessage);
     AssertionResult.setFailure(true);
}
// Print error messages if any
if (failureMessage?.trim()) {
    failureMessage += "URL: " + SampleResult.getURL() + "\n\n";
    failureMessage += "JSON RESPONSE: " + jsonResponse + "\n\n";
    AssertionResult.setFailureMessage(failureMessage);
    AssertionResult.setFailure(true);
}
</code>```

But I am not able to find a way to use the field names from the csv file. I have tried below but it does not work.

```<code>        String[] basefields = vars.getObject("getEmployeeFields").split(',');
        for(String t : basefields) {
            log.info("validating "+t);

        for (int i; i < vars.getObject("dataFromDB").size(); i++) {
            if (!jsonResponse.data.GetClientById.t.equals(vars.getObject("datafromDB").get(0).get("t"))) //--this is where i need to construct the path using the value from csv. Field names are same between API response and DB. So, I am using t in both places
                {
                    failureMessage += "Cli_no does not match \n\n";
                }
            }
</code>```

Can anyone guide me as to how to achieve this? I am using JSR 223 Assertion with groovy

答:
Try something like:

```<code>data.response.employee.get('t')
</code>```

as these JSON Objects are translated to Groovy's LazyMap

More information:

Apache Groovy - Parsing and producing JSON

Apache Groovy - Why and How You Should Use It

Body:
I have an API which returns following response:

 {
    "data": {
        "response": {
            "employee":
                {
                   "firstName": "Frank",
                   "lastName": "Porter",
                   "employeeNumber": "11102"
                }
            }
        }
}

In JMeter, I need to do the following:

Query the DB and fetch data from the tables. Store it in a variable to compare with API response.

Write assertion which will compare the data from the DB with the API response. For this I need the assertion to read names of fields to compare from a CSV file.

I am able to construct a csv which has the list of fields - firstName,lastName,employeeNumber
In my assertion, I am parsing the API response using JSONSlurper and then trying to compare the data.
If I hardcode the field names, the comparison works ok - so something like below works ok:

import groovy.json.JsonSlurper;
def failureMessage = "";
def jsonResponse = null;
JsonSlurper JSON = new JsonSlurper ();

//compare data from db with API response

if (!jsonResponse.data.response.employee.firstName.equals(vars.getObject("datafromDB").get(0).get("firstName")))
{
          failureMessage += "firstName does not match \n\n";
}

if (failureMessage?.trim()) {
              AssertionResult.setFailureMessage(failureMessage);
     AssertionResult.setFailure(true);
}
// Print error messages if any
if (failureMessage?.trim()) {
    failureMessage += "URL: " + SampleResult.getURL() + "\n\n";
    failureMessage += "JSON RESPONSE: " + jsonResponse + "\n\n";
    AssertionResult.setFailureMessage(failureMessage);
    AssertionResult.setFailure(true);
}

But I am not able to find a way to use the field names from the csv file. I have tried below but it does not work.

        String[] basefields = vars.getObject("getEmployeeFields").split(',');
        for(String t : basefields) {
            log.info("validating "+t);

        for (int i; i < vars.getObject("dataFromDB").size(); i++) {
            if (!jsonResponse.data.GetClientById.t.equals(vars.getObject("datafromDB").get(0).get("t"))) //--this is where i need to construct the path using the value from csv. Field names are same between API response and DB. So, I am using t in both places
                {
                    failureMessage += "Cli_no does not match \n\n";
                }
            }

Can anyone guide me as to how to achieve this? I am using JSR 223 Assertion with groovy

Body:
Try something like:

data.response.employee.get('t')

as these JSON Objects are translated to Groovy's LazyMap

More information:

Apache Groovy - Parsing and producing JSON

Apache Groovy - Why and How You Should Use It


问:
Try to get variable type on python3 on macOS and it show the below error
Traceback (most recent call last): File "/Users/kane/study/python/basicDataStructure/liner_data_structure.py", line 2, in <module> from turtle import clear File "/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 107, in <module> import tkinter as TK File "/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 37, in <module> import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter'

Note Please note that, I didn't use anything regarding tkinter. I only created a variable and checked its type.

I have found the answer at the link
brew install python-tk

答:
You will have to firstly import it on the os device!
Run these in your terminal

python3 get-pip.py

Pip install turtle
Pip install tkinter


问:
Sum for array with While loop JS
I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I've also tried to do (array.length) (array.length --) (array.length>numbers)
But nothing I tried worked... any suggestions? :)</p>
```<code>function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum += numbers;

      console.log(sum);
    }
  }
}
</code>```

答:
You can try this:</p>
```<code>function sum(arr, sum) {
    arr = [1, 5, 4, 6, 7];
    sum = 0;
    while (arr.length > 0) {
        sum += arr.pop();
    }
    return sum;
}
console.log(sum());
</code>```

Title: Sum for array with While loop JS

Body:
I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I've also tried to do (array.length) (array.length --) (array.length>numbers)
But nothing I tried worked... any suggestions? :)

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum += numbers;

      console.log(sum);
    }
  }
}

Body:
You can try this:

function sum(arr, sum) {
    arr = [1, 5, 4, 6, 7];
    sum = 0;
    while (arr.length > 0) {
        sum += arr.pop();
    }
    return sum;
}
console.log(sum());


问:
Pattern attribute not working as expected?
So I'm trying to make a form for my assignment, and I am using the pattern attribute in html so only certain characters are required to be typed on the text box. But for some reason, the form is saying using that I'm using an incorrect format even though I made my pattern attribute that way.

Here's an example of the code and a picture of the problem.

<form>
  Mobile Number:
  <input type="text" required id="mnumber" pattern="[0-9]">

  <input type="submit" value="submit">
</form>```

答:
You did write:

pattern="[0-9]"

You are asking for only one number. You just forget to add '+' to accept more than one number. I guess what you are searching for is this:

pattern="[0-9]+"


问:
Is there a way to allocate an Objective-C NSArray with objects contained in a C-style macro?
What I'd like to do is something like this:

```<code>NSArray *someArray = [[NSArray alloc] initWithObjects: C_MACRO, nil];
</code>```

With the C_MACRO part being an outlying file that uses a #define to list some number of NSStrings, so when I need to change the string objects that populate the array I can conveniently do in one file. So far, it seems this is impossible. But then again, I'm a novice.

Anyone care to enlighten me?

答:
No problem doing this... A macro is just text-replacement.

```<code>/* foo.h */
#define C_MACRO @"foo", @"bar"

/* bar.m */
#import "foo.h"
NSArray * someArray = [ [ NSArray alloc ] initWithObjects: C_MACRO, nil ];
</code>```

Note you can use macros inside another macro. So

```<code>#define FOO_STR @"foo"
#define BAR_STR @"bar"
#define STR_LIST FOO_STR, BAR_STR
</code>```

Another way is to have your strings allocated in a .m file, and declared as extern in a public header file. Handy if unique instances of the same object has to be shared.

```<code>/* foo.h */
extern NSString * const fooStr;
extern NSString * const barStr;

/* foo.m */
NSString * const fooStr = @"foo";
NSString * const BarStr = @"bar";
</code>```

Body:
What I'd like to do is something like this:

NSArray *someArray = [[NSArray alloc] initWithObjects: C_MACRO, nil];

With the C_MACRO part being an outlying file that uses a #define to list some number of NSStrings, so when I need to change the string objects that populate the array I can conveniently do in one file. So far, it seems this is impossible. But then again, I'm a novice.

Anyone care to enlighten me?

Body:
No problem doing this... A macro is just text-replacement.

/* foo.h */
#define C_MACRO @"foo", @"bar"

/* bar.m */
#import "foo.h"
NSArray * someArray = [ [ NSArray alloc ] initWithObjects: C_MACRO, nil ];

Note you can use macros inside another macro. So

#define FOO_STR @"foo"
#define BAR_STR @"bar"
#define STR_LIST FOO_STR, BAR_STR

Another way is to have your strings allocated in a .m file, and declared as extern in a public header file. Handy if unique instances of the same object has to be shared.

/* foo.h */
extern NSString * const fooStr;
extern NSString * const barStr;

/* foo.m */
NSString * const fooStr = @"foo";
NSString * const BarStr = @"bar";


问:
How can I stop React page to re-render?
I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working

```<code>  const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }

  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

  useEffect(() => {
     setLoad(false);
  }, [fetchPicth]);
</code>```

答:
This can be solved using 2 approaches

Pass state in dependency array of useEffect

```<code>
const [picth, setPicth] = useState([]);   // Initial state

 useEffect(() => {
    if (picth && picth.length !== 0) {   // Checks if data exists and length
                                         //is greater than 0
      setLoad(false);                    // Set Loading to false
    }
  }, [picth]);

const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };
</code>```

Check for the length, display Progress if there is no data. Display if data is present.

```<code>
{picth.length === 0 && <div>Progress</div>}
      {picth.length > 0 && (
        <div>
          {picth.map((book, index) => {
            return (
              <YourComponent></YourComponent>
            );
          })}
</code>```

Title: How can I stop React page to re-render?

Body:
I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working

  const [load, setLoad] = useState(false);

 if (load) {
    return
Progress
;
  }

  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

  useEffect(() => {
     setLoad(false);
  }, [fetchPicth]);

Body:
This can be solved using 2 approaches

Pass state in dependency array of useEffect

const [picth, setPicth] = useState([]);   // Initial state

 useEffect(() => {
    if (picth && picth.length !== 0) {   // Checks if data exists and length
                                         //is greater than 0
      setLoad(false);                    // Set Loading to false
    }
  }, [picth]);

const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

Check for the length, display Progress if there is no data. Display if data is present.

{picth.length === 0 && <div>Progress</div>}
      {picth.length > 0 && (
        <div>
          {picth.map((book, index) => {
            return (
              <YourComponent></YourComponent>
            );
          })}


问:
Why is my data not rendering from this.state?
I've been trying to get an array to come over into react and then display it on the browser. The data is coming over, but for some reason I cannot display it.

ReactJs:

```<code>import React, { Component } from "react";

export default class RegisterPage extends Component {
    constructor(props){
        super(props);
        this.state = {

        };

        this.getPlayers();
    }

    getPlayers() {
        fetch('/draft/get-players')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                players: data,
            });
        });
    }

    render(){
        return (<h1>{this.state.players[0].name}</h1>)
    }
}
</code>```

I initially was trying to .map this into multiple lines of HTML, but through troubleshooting learned that I'm not even able to get a single element out of the array.

JSON from /draft/get-players:

```<code>[
    {
        "id": 1,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 2,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 3,
        "name": "Kayvon Thidobeaux",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Oregon",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 4,
        "name": "Kyle Hamilton",
        "position": "S",
        "EstimatedRound": 1,
        "college": "Notre Dame",
        "age": "JR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 5,
        "name": "Ikem Ekwonu",
        "position": "OL",
        "EstimatedRound": 1,
        "college": "NC State",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    }
]
</code>```

答:
//you have not declared the array players just initialize the array first it will work</p>
```<code> this.state = {
              players:[]
           }
</code>```

Body:
I've been trying to get an array to come over into react and then display it on the browser. The data is coming over, but for some reason I cannot display it.

ReactJs:

import React, { Component } from "react";

export default class RegisterPage extends Component {
    constructor(props){
        super(props);
        this.state = {

        };

        this.getPlayers();
    }

    getPlayers() {
        fetch('/draft/get-players')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                players: data,
            });
        });
    }

    render(){
        return (
{this.state.players[0].name}
)
    }
}

I initially was trying to .map this into multiple lines of HTML, but through troubleshooting learned that I'm not even able to get a single element out of the array.

JSON from /draft/get-players:

[
    {
        "id": 1,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 2,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 3,
        "name": "Kayvon Thidobeaux",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Oregon",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 4,
        "name": "Kyle Hamilton",
        "position": "S",
        "EstimatedRound": 1,
        "college": "Notre Dame",
        "age": "JR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 5,
        "name": "Ikem Ekwonu",
        "position": "OL",
        "EstimatedRound": 1,
        "college": "NC State",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    }
]

Body:
//you have not declared the array players just initialize the array first it will work

 this.state = {
              players:[]
           }


问:
c++ class constructor breaking program and cout?
I have a program where just having cout statements works, however, adding in a class and calling its constructor completely breaks the program. I need help figuring out what the issue is.

This code produces no output:

#include <iostream>
#include <string>

using namespace std;

#define WORDCOUNTER_DATA_LENGTH 262144
struct WordCounterDataPair{
    string Word;
    unsigned int Count;
    unsigned int Position;
};
class WordCounter{
    public:
        WordCounter(){
            cout << "constructor\n";
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = "";
                Counts[i] = 0;
            }
        };
        WordCounter(string words[WORDCOUNTER_DATA_LENGTH], unsigned int counts[WORDCOUNTER_DATA_LENGTH]){
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = words[i];
                Counts[i] = counts[i];
            }
        };
        void IncrementWord(string word){
            WordCounterDataPair search = ValueOf(word);
            if(search.Count == 0){
                Words[search.Position] = word;
                Counts[search.Position] = 1;
                Length++;
            }else{
                Counts[search.Position]++;
            }
        };
        WordCounterDataPair at(unsigned int value){
            WordCounterDataPair res;
            res.Word = Words[value];
            res.Count = Counts[value];
            res.Position = value;
            return res;
        };
    protected:
        string Words[WORDCOUNTER_DATA_LENGTH];
        unsigned int Counts[WORDCOUNTER_DATA_LENGTH];
        unsigned int Length = 0;
        WordCounterDataPair ValueOf(string word){
            for(unsigned int i = 0; i < Length; i++){
                if(Words[i] == word){
                    WordCounterDataPair res;
                    res.Word = word;
                    res.Count = Counts[i];
                    res.Position = i;
                    return res;
                }
            }
            WordCounterDataPair res;
            res.Word = "";
            res.Count = 0;
            res.Position = Length;
            return res;
        };
};

int main(){
    cout << "before\n";
    WordCounter WCTest;
    cout << "after\n";
    return 0;
}
```
<p>And this code</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>

using namespace std;

#define WORDCOUNTER_DATA_LENGTH 262144
struct WordCounterDataPair{
    string Word;
    unsigned int Count;
    unsigned int Position;
};
class WordCounter{
    public:
        WordCounter(){
            cout << "constructor\n";
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = "";
                Counts[i] = 0;
            }
        };
        WordCounter(string words[WORDCOUNTER_DATA_LENGTH], unsigned int counts[WORDCOUNTER_DATA_LENGTH]){
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = words[i];
                Counts[i] = counts[i];
            }
        };
        void IncrementWord(string word){
            WordCounterDataPair search = ValueOf(word);
            if(search.Count == 0){
                Words[search.Position] = word;
                Counts[search.Position] = 1;
                Length++;
            }else{
                Counts[search.Position]++;
            }
        };
        WordCounterDataPair at(unsigned int value){
            WordCounterDataPair res;
            res.Word = Words[value];
            res.Count = Counts[value];
            res.Position = value;
            return res;
        };
    protected:
        string Words[WORDCOUNTER_DATA_LENGTH];
        unsigned int Counts[WORDCOUNTER_DATA_LENGTH];
        unsigned int Length = 0;
        WordCounterDataPair ValueOf(string word){
            for(unsigned int i = 0; i < Length; i++){
                if(Words[i] == word){
                    WordCounterDataPair res;
                    res.Word = word;
                    res.Count = Counts[i];
                    res.Position = i;
                    return res;
                }
            }
            WordCounterDataPair res;
            res.Word = "";
            res.Count = 0;
            res.Position = Length;
            return res;
        };
};

int main(){
    cout << "before\n";
    cout << "after\n";
    return 0;
}
</code>```

produces the output:

```<code>before
after
</code>```

What is going on here? How can a class constructor even cause this? I am using g++ to compile, and I'm compiling with g++ main.cpp -o program.exe. The compiler successfully creates a program for both files above and generates no errors or even warnings.

Thanks for your help in advance.

答:
#define WORDCOUNTER_DATA_LENGTH 262144

Issue is with the value of WORDCOUNTER_DATA_LENGTH. If you take a smaller value or do not iterate even for once, i.e. do not call the constructor(as done in second program) your program will run well. To iterate over a big value takes a lot of time and causes the program to end with no output. Try taking a smaller value and it will execute fine.

Body:
I have a program where just having cout statements works, however, adding in a class and calling its constructor completely breaks the program. I need help figuring out what the issue is.

This code produces no output:

#include <iostream>
#include <string>

using namespace std;

#define WORDCOUNTER_DATA_LENGTH 262144
struct WordCounterDataPair{
    string Word;
    unsigned int Count;
    unsigned int Position;
};
class WordCounter{
    public:
        WordCounter(){
            cout << "constructor\n";
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = "";
                Counts[i] = 0;
            }
        };
        WordCounter(string words[WORDCOUNTER_DATA_LENGTH], unsigned int counts[WORDCOUNTER_DATA_LENGTH]){
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = words[i];
                Counts[i] = counts[i];
            }
        };
        void IncrementWord(string word){
            WordCounterDataPair search = ValueOf(word);
            if(search.Count == 0){
                Words[search.Position] = word;
                Counts[search.Position] = 1;
                Length++;
            }else{
                Counts[search.Position]++;
            }
        };
        WordCounterDataPair at(unsigned int value){
            WordCounterDataPair res;
            res.Word = Words[value];
            res.Count = Counts[value];
            res.Position = value;
            return res;
        };
    protected:
        string Words[WORDCOUNTER_DATA_LENGTH];
        unsigned int Counts[WORDCOUNTER_DATA_LENGTH];
        unsigned int Length = 0;
        WordCounterDataPair ValueOf(string word){
            for(unsigned int i = 0; i < Length; i++){
                if(Words[i] == word){
                    WordCounterDataPair res;
                    res.Word = word;
                    res.Count = Counts[i];
                    res.Position = i;
                    return res;
                }
            }
            WordCounterDataPair res;
            res.Word = "";
            res.Count = 0;
            res.Position = Length;
            return res;
        };
};

int main(){
    cout << "before\n";
    WordCounter WCTest;
    cout << "after\n";
    return 0;
}

And this code

#include <iostream>
#include <string>

using namespace std;

#define WORDCOUNTER_DATA_LENGTH 262144
struct WordCounterDataPair{
    string Word;
    unsigned int Count;
    unsigned int Position;
};
class WordCounter{
    public:
        WordCounter(){
            cout << "constructor\n";
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = "";
                Counts[i] = 0;
            }
        };
        WordCounter(string words[WORDCOUNTER_DATA_LENGTH], unsigned int counts[WORDCOUNTER_DATA_LENGTH]){
            for(unsigned int i = 0; i < WORDCOUNTER_DATA_LENGTH; i++){
                Words[i] = words[i];
                Counts[i] = counts[i];
            }
        };
        void IncrementWord(string word){
            WordCounterDataPair search = ValueOf(word);
            if(search.Count == 0){
                Words[search.Position] = word;
                Counts[search.Position] = 1;
                Length++;
            }else{
                Counts[search.Position]++;
            }
        };
        WordCounterDataPair at(unsigned int value){
            WordCounterDataPair res;
            res.Word = Words[value];
            res.Count = Counts[value];
            res.Position = value;
            return res;
        };
    protected:
        string Words[WORDCOUNTER_DATA_LENGTH];
        unsigned int Counts[WORDCOUNTER_DATA_LENGTH];
        unsigned int Length = 0;
        WordCounterDataPair ValueOf(string word){
            for(unsigned int i = 0; i < Length; i++){
                if(Words[i] == word){
                    WordCounterDataPair res;
                    res.Word = word;
                    res.Count = Counts[i];
                    res.Position = i;
                    return res;
                }
            }
            WordCounterDataPair res;
            res.Word = "";
            res.Count = 0;
            res.Position = Length;
            return res;
        };
};

int main(){
    cout << "before\n";
    cout << "after\n";
    return 0;
}

produces the output:

before
after

What is going on here? How can a class constructor even cause this? I am using g++ to compile, and I'm compiling with g++ main.cpp -o program.exe. The compiler successfully creates a program for both files above and generates no errors or even warnings.

Thanks for your help in advance.


问:
Remove item from array according to condition
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

```
<pre class="lang-js prettyprint-override"><code>var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

</code>```

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

```

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance

答:
You just need to create a custom implementation of the filter

const files = ["foo.js", "foo2.js", "foo2.css", "foo.min.js", "bar.css","bar.min.css"];

const result = files.filter((file) => {
  const miniPart = '.min.';
  if (file.includes(miniPart)) return true;

  const [name, extension] = file.split('.');
  const miniFile = `${name}${miniPart}${extension}`;

  return !files.includes(miniFile);
});

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

Body:
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance

Body:
You just need to create a custom implementation of the filter

const files = ["foo.js", "foo2.js", "foo2.css", "foo.min.js", "bar.css","bar.min.css"];

const result = files.filter((file) => {
  const miniPart = '.min.';
  if (file.includes(miniPart)) return true;

  const [name, extension] = file.split('.');
  const miniFile = `${name}${miniPart}${extension}`;

  return !files.includes(miniFile);
});

console.log(result);

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


问:
Is there a glitch in discord.ext
```<code>import discord
from discord.ext import commands
import random
import praw

cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
                    client_secret = "",
                    username = "",
                    password = "",
                    user_agent = "")
@cl.event
async def on_ready():
  print("Bot is ready, get ready to do wutever u want with it")

@cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
 all_submission = []
 subreddit = reddit.subreddit("subr")
 subs = subreddit.filter(limit = amount)
 for submission in subs:
   all_submission.append(submission)
 random_sub = random.choice(all_submission)
 name = random_sub.title
 url = random_sub.url
 em = discord.embed(title = name)
 em.set_image = url
 await ctx.send(embed=em)
 print("embed sent")

cl.run("")
</code>```

when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing

```<code>It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 20, in meme
    subs = subreddit.filter(limit = amount)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
    self._fetch()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
    data = self._fetch_data()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
    return self._reddit.request("GET", path, params)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
    return self._core.request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
    return self._request_with_retries(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
    response, saved_exception = self._make_request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
    response = self._rate_limiter.call(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
    kwargs["headers"] = set_header_callback()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
    self._authorizer.refresh()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
    self._request_token(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
    raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request
</code>```

This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed

答: The problem is that, unlike the Bot.event decorator, the Bot.command decarator is a function that has to be called, so replace @cl.command with @cl.command()

Title: Is there a glitch in discord.ext

Body:
import discord
from discord.ext import commands
import random
import praw

cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
                    client_secret = "",
                    username = "",
                    password = "",
                    user_agent = "")
@cl.event
async def on_ready():
  print("Bot is ready, get ready to do wutever u want with it")

@cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
 all_submission = []
 subreddit = reddit.subreddit("subr")
 subs = subreddit.filter(limit = amount)
 for submission in subs:
   all_submission.append(submission)
 random_sub = random.choice(all_submission)
 name = random_sub.title
 url = random_sub.url
 em = discord.embed(title = name)
 em.set_image = url
 await ctx.send(embed=em)
 print("embed sent")

cl.run("")

when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing

It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 20, in meme
    subs = subreddit.filter(limit = amount)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
    self._fetch()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
    data = self._fetch_data()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
    return self._reddit.request("GET", path, params)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
    return self._core.request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
    return self._request_with_retries(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
    response, saved_exception = self._make_request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
    response = self._rate_limiter.call(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
    kwargs["headers"] = set_header_callback()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
    self._authorizer.refresh()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
    self._request_token(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
    raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request

This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed