问:
Unable to get the required key values with respect to different fields in python
I am crawling through a series of APIs and trying to get the price from the keys. Some APIs have the value " AVG_price", "Average_price" and the rest have " price_min, price_max".

```<code>WANTED_PRICES = ['average_Price', 'average_price', 'avg_price', 'avg_Price']
WANTED_avgPRICES = ['price_min', 'price_max']
</code>```

In order to get the prices, Average prices are required. So, the above two list of fields are treated differently.

If an api has "price_min" and price_max", the prices are calculated as the average of the two. And if the api has any field from "Wanted_Prices", then the price is just extracted as it is.

```<code>
     def parse_slugs(self, response, slug_id, crawled_url):
        summary = json.loads(response.body)
        results = summary.get('results', [])
        for result in results:
            for result_avg, result_mm in zip(WANTED_PRICES, WANTED_avgPRICES):
                price = None
               if result_avg in result:
                    price = Decimal(result[result_avg])

                elif result_mm in result:
                    minp = result['price_min']
                    maxp = result['price_max']
                    price = ((Decimal(minp + maxp)) / 2)
                if 'published_date' in result.keys():
                    date = result['published_date'].split(' ')[0]
                else:
                    date = result['published_Date'].split(' ')[0]

                print(slug_id,date,price)

</code>```

But I am getting errors:

The prices from the  APIs that have the fields from "WANTED_avgPRICES" are not getting extracted. Only the date and the Slug_Id is shown in the output(for example):

```<code>{'1234'} 08/25/2020 None
{'1234'} 08/25/2020 None
{'1234'} 08/25/2020 None
{'1234'} 08/25/2020 None
</code>```

It's giving out two outputs for each unique values.Duplicates

```<code>{'1053'} 07/01/2020 0.9137499999999999511501869165
{'1053'} 07/01/2020 0.9137499999999999511501869165
{'1053'} 06/25/2020 0.9137499999999999511501869165
{'1053'} 06/25/2020 0.9137499999999999511501869165
</code>```

答:
By default, zip() stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:

```<code>>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo')]
</code>```

This mean that you don't process ALL items from WANTED_PRICES list.

Body:
I am crawling through a series of APIs and trying to get the price from the keys. Some APIs have the value " AVG_price", "Average_price" and the rest have " price_min, price_max".

WANTED_PRICES = ['average_Price', 'average_price', 'avg_price', 'avg_Price']
WANTED_avgPRICES = ['price_min', 'price_max']

In order to get the prices, Average prices are required. So, the above two list of fields are treated differently.

If an api has "price_min" and price_max", the prices are calculated as the average of the two. And if the api has any field from "Wanted_Prices", then the price is just extracted as it is.

     def parse_slugs(self, response, slug_id, crawled_url):
        summary = json.loads(response.body)
        results = summary.get('results', [])
        for result in results:
            for result_avg, result_mm in zip(WANTED_PRICES, WANTED_avgPRICES):
                price = None
               if result_avg in result:
                    price = Decimal(result[result_avg])

                elif result_mm in result:
                    minp = result['price_min']
                    maxp = result['price_max']
                    price = ((Decimal(minp + maxp)) / 2)
                if 'published_date' in result.keys():
                    date = result['published_date'].split(' ')[0]
                else:
                    date = result['published_Date'].split(' ')[0]

                print(slug_id,date,price)

But I am getting errors:

The prices from the  APIs that have the fields from "WANTED_avgPRICES" are not getting extracted. Only the date and the Slug_Id is shown in the output(for example):

{'1234'} 08/25/2020 None
{'1234'} 08/25/2020 None
{'1234'} 08/25/2020 None
{'1234'} 08/25/2020 None

It's giving out two outputs for each unique values.Duplicates

{'1053'} 07/01/2020 0.9137499999999999511501869165
{'1053'} 07/01/2020 0.9137499999999999511501869165
{'1053'} 06/25/2020 0.9137499999999999511501869165
{'1053'} 06/25/2020 0.9137499999999999511501869165

Body:
By default, zip() stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:

>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo')]

This mean that you don't process ALL items from WANTED_PRICES list.


来源: stackexchange

问:
SuperController of Getx Package in Flutter causing a problem
I am facing a problem when I extends a class with SuperController of Getx PAckage in Flutter. Please go through my code and let me know the solution.

main.dart

```<code>import 'package:flutter/material.dart';
import 'package:flutter_app/user_status_controller.dart';
import 'package:get/get.dart';

void main() {
  Get.put(UserStatusController());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
          child: Text(
        'Hello',
        style: TextStyle(fontSize: 50),
      )),
    );
  }
}
</code>```

user_status_controller.dart

```<code>import 'package:get/get.dart';

class UserStatusController extends SuperController {
  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}
</code>```

The error thrown is:

```<code>E/flutter ( 3620): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 3620): #0      FullLifeCycleMixin.onInit (package:get/get_state_manager/src/simple/get_controllers.dart:90:28)
E/flutter ( 3620): #1      GetLifeCycleBase._onStart (package:get/get_instance/src/lifecycle.dart:66:5)
E/flutter ( 3620): #2      InternalFinalCallback.call (package:get/get_instance/src/lifecycle.dart:12:26)
E/flutter ( 3620): #3      GetInstance._startController (package:get/get_instance/src/get_instance.dart:253:16)
E/flutter ( 3620): #4      GetInstance._initDependencies (package:get/get_instance/src/get_instance.dart:204:11)
E/flutter ( 3620): #5      GetInstance.find (package:get/get_instance/src/get_instance.dart:301:17)
E/flutter ( 3620): #6      GetInstance.put (package:get/get_instance/src/get_instance.dart:86:12)
E/flutter ( 3620): #7      Inst.put (package:get/get_instance/src/extension_instance.dart:89:21)
E/flutter ( 3620): #8      main (package:flutter_app/main.dart:6:7)
E/flutter ( 3620): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:129:25)
E/flutter ( 3620): #10     _rootRun (dart:async/zone.dart:1428:13)
E/flutter ( 3620): #11     _CustomZone.run (dart:async/zone.dart:1328:19)
[GETX] Instance "UserStatusController" has been created
E/flutter ( 3620): #12     _runZoned (dart:async/zone.dart:1863:10)
E/flutter ( 3620): #13     runZonedGuarded (dart:async/zone.dart:1851:12)
E/flutter ( 3620): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:125:5)
E/flutter ( 3620): #15     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
E/flutter ( 3620): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
</code>```

Could anybody tell me what is throwing the error. Please help me. This is a simple code I'm unable to understand what is causing this.

答:
In order to use SuperController you need to call   WidgetsFlutterBinding.ensureInitialized(); on the main function of your app:

```<code>void main(){
     WidgetsFlutterBinding.ensureInitialized();

     runApp(YourApp());
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am facing a problem when I extends a class with SuperController of Getx PAckage in Flutter. Please go through my code and let me know the solution.

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_app/user_status_controller.dart';
import 'package:get/get.dart';

void main() {
  Get.put(UserStatusController());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
          child: Text(
        'Hello',
        style: TextStyle(fontSize: 50),
      )),
    );
  }
}

user_status_controller.dart

import 'package:get/get.dart';

class UserStatusController extends SuperController {
  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}

The error thrown is:

E/flutter ( 3620): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 3620): #0      FullLifeCycleMixin.onInit (package:get/get_state_manager/src/simple/get_controllers.dart:90:28)
E/flutter ( 3620): #1      GetLifeCycleBase._onStart (package:get/get_instance/src/lifecycle.dart:66:5)
E/flutter ( 3620): #2      InternalFinalCallback.call (package:get/get_instance/src/lifecycle.dart:12:26)
E/flutter ( 3620): #3      GetInstance._startController (package:get/get_instance/src/get_instance.dart:253:16)
E/flutter ( 3620): #4      GetInstance._initDependencies (package:get/get_instance/src/get_instance.dart:204:11)
E/flutter ( 3620): #5      GetInstance.find (package:get/get_instance/src/get_instance.dart:301:17)
E/flutter ( 3620): #6      GetInstance.put (package:get/get_instance/src/get_instance.dart:86:12)
E/flutter ( 3620): #7      Inst.put (package:get/get_instance/src/extension_instance.dart:89:21)
E/flutter ( 3620): #8      main (package:flutter_app/main.dart:6:7)
E/flutter ( 3620): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:129:25)
E/flutter ( 3620): #10     _rootRun (dart:async/zone.dart:1428:13)
E/flutter ( 3620): #11     _CustomZone.run (dart:async/zone.dart:1328:19)
[GETX] Instance "UserStatusController" has been created
E/flutter ( 3620): #12     _runZoned (dart:async/zone.dart:1863:10)
E/flutter ( 3620): #13     runZonedGuarded (dart:async/zone.dart:1851:12)
E/flutter ( 3620): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:125:5)
E/flutter ( 3620): #15     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
E/flutter ( 3620): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

Could anybody tell me what is throwing the error. Please help me. This is a simple code I'm unable to understand what is causing this.

Body:
In order to use SuperController you need to call   WidgetsFlutterBinding.ensureInitialized(); on the main function of your app:

void main(){
     WidgetsFlutterBinding.ensureInitialized();

     runApp(YourApp());
}


问:
Error: Not found wrapperScript: D:\a\1\s\gradlew
I'm creating an Azure Devops pipeline for my Android repository which is on Bitbucket. I have created a classic pipeline. I have setup continuous integration by following various steps following this blog post:
https://itnext.io/how-to-setup-ci-cd-pipelines-for-android-with-azure-devops-2a4ded0de0e7

Before proceeding with CD, I wanted to run the pipeline. So I ran the pipeline and faced the below Error:
Error: Not found wrapperScript: D:\a\1\s\gradlew

I'm adding the raw log file for your reference. I searched online for a solution and to my disappointment, I couldn't find a working solution. Please help. Find the log file below

2022-02-07T12:25:24.6666771Z ##[debug]Evaluating condition for step:
'gradlew buildRelease' 2022-02-07T12:25:24.6668643Z
##[debug]Evaluating: succeeded() 2022-02-07T12:25:24.6669141Z ##[debug]Evaluating succeeded: 2022-02-07T12:25:24.6670247Z ##[debug]=> True 2022-02-07T12:25:24.6670740Z ##[debug]Result: True 2022-02-07T12:25:24.6671294Z ##[section]Starting: gradlew buildRelease
2022-02-07T12:25:24.6783754Z
============================================================================== 2022-02-07T12:25:24.6784050Z Task         : Gradle
2022-02-07T12:25:24.6784257Z Description  : Build using a Gradle
wrapper script 2022-02-07T12:25:24.6784478Z Version      : 3.198.0
2022-02-07T12:25:24.6784667Z Author       : Microsoft Corporation
2022-02-07T12:25:24.6784956Z Help         :
https://learn.microsoft.com/azure/devops/pipelines/tasks/build/gradle
2022-02-07T12:25:24.6785279Z
============================================================================== 2022-02-07T12:25:24.7052847Z ##[debug]Using node path:
C:\agents\2.198.2\externals\node10\bin\node.exe
2022-02-07T12:25:24.8527724Z ##[debug]agent.TempDirectory=D:\a_temp
2022-02-07T12:25:24.8551469Z ##[debug]loading inputs and endpoints
2022-02-07T12:25:24.8568842Z ##[debug]loading
ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN
2022-02-07T12:25:24.8583719Z ##[debug]loading
ENDPOINT_AUTH_SCHEME_SYSTEMVSSCONNECTION 2022-02-07T12:25:24.8586465Z
##[debug]loading ENDPOINT_AUTH_SYSTEMVSSCONNECTION 2022-02-07T12:25:24.8588710Z ##[debug]loading
INPUT_CHECKSTYLEANALYSISENABLED 2022-02-07T12:25:24.8590512Z
##[debug]loading INPUT_CLASSFILESDIRECTORIES 2022-02-07T12:25:24.8592099Z ##[debug]loading INPUT_CODECOVERAGETOOL
2022-02-07T12:25:24.8593560Z ##[debug]loading INPUT_CWD
2022-02-07T12:25:24.8595038Z ##[debug]loading
INPUT_FAILIFCOVERAGEEMPTY 2022-02-07T12:25:24.8596499Z
##[debug]loading INPUT_FINDBUGSANALYSISENABLED 2022-02-07T12:25:24.8597942Z ##[debug]loading INPUT_GRADLE5XORHIGHER
2022-02-07T12:25:24.8599413Z ##[debug]loading INPUT_GRADLEOPTS
2022-02-07T12:25:24.8600881Z ##[debug]loading INPUT_JAVAHOMESELECTION
2022-02-07T12:25:24.8602279Z ##[debug]loading INPUT_JDKARCHITECTURE
2022-02-07T12:25:24.8603715Z ##[debug]loading INPUT_JDKVERSION
2022-02-07T12:25:24.8605152Z ##[debug]loading INPUT_PMDANALYSISENABLED
2022-02-07T12:25:24.8606525Z ##[debug]loading
INPUT_PUBLISHJUNITRESULTS 2022-02-07T12:25:24.8607917Z
##[debug]loading INPUT_SPOTBUGSANALYSISENABLED 2022-02-07T12:25:24.8609416Z ##[debug]loading
INPUT_SPOTBUGSGRADLEPLUGINVERSION 2022-02-07T12:25:24.8610867Z
##[debug]loading INPUT_SPOTBUGSGRADLEPLUGINVERSIONCHOICE 2022-02-07T12:25:24.8612211Z ##[debug]loading INPUT_SQANALYSISENABLED
2022-02-07T12:25:24.8613592Z ##[debug]loading
INPUT_SQGRADLEPLUGINVERSION 2022-02-07T12:25:24.8614946Z
##[debug]loading INPUT_SQGRADLEPLUGINVERSIONCHOICE 2022-02-07T12:25:24.8616200Z ##[debug]loading INPUT_TASKS
2022-02-07T12:25:24.8617526Z ##[debug]loading INPUT_TESTRESULTSFILES
2022-02-07T12:25:24.8618917Z ##[debug]loading INPUT_WRAPPERSCRIPT
2022-02-07T12:25:24.8625809Z ##[debug]loaded 25
2022-02-07T12:25:24.8705719Z ##[debug]Agent.ProxyUrl=undefined
2022-02-07T12:25:24.8707003Z ##[debug]Agent.CAInfo=undefined
2022-02-07T12:25:24.8707814Z ##[debug]Agent.ClientCert=undefined
2022-02-07T12:25:24.8708734Z
##[debug]Agent.SkipCertValidation=undefined 2022-02-07T12:25:25.0132101Z ##[debug]check path :
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0135127Z ##[debug]adding resource file:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0136145Z ##[debug]system.culture=en-US
2022-02-07T12:25:25.0177088Z ##[debug]Resource file has already set
to:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0183934Z ##[debug]Resource file has already set
to:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0191436Z ##[debug]Resource file has already set
to:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0206150Z ##[debug]Resource file has already set
to:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0213723Z ##[debug]Resource file has already set
to:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-codecoverage-tools\module.json 2022-02-07T12:25:25.0500114Z ##[debug]check path :
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-java-common\lib.json
2022-02-07T12:25:25.0501427Z ##[debug]adding resource file:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\node_modules\azure-pipelines-tasks-java-common\lib.json
2022-02-07T12:25:25.0502355Z ##[debug]system.culture=en-US
2022-02-07T12:25:25.0515301Z ##[debug]check path :
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\task.json
2022-02-07T12:25:25.0516298Z ##[debug]adding resource file:
D:\a_tasks\Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4\3.198.0\task.json
2022-02-07T12:25:25.0517122Z ##[debug]system.culture=en-US
2022-02-07T12:25:25.0534237Z ##[debug]wrapperScript=D:\a\1\s\gradlew
2022-02-07T12:25:25.0534980Z ##[debug]check path : D:\a\1\s\gradlew
2022-02-07T12:25:25.0538217Z ##[debug]task result: Failed
2022-02-07T12:25:25.0565952Z ##[error]Error: Not found wrapperScript:
D:\a\1\s\gradlew 2022-02-07T12:25:25.0575454Z ##[debug]Processed:
##vso[task.issue type=error;]Error: Not found wrapperScript: D:\a\1\s\gradlew 2022-02-07T12:25:25.0582600Z ##[debug]Processed:
##vso[task.complete result=Failed;]Error: Not found wrapperScript: D:\a\1\s\gradlew 2022-02-07T12:25:25.0620465Z ##[section]Finishing:
gradlew buildRelease

答:
Error: Not found wrapperScript: D:\a\1\s\gradlew

Based on the error message, the Gradle task couldn't find the gradlew file in the source folder.

You need to check the gradlew file path in your repo. Then you can modify the field:Gradle wrapper in Gradle  task.

For example:

gradlew file path:

Gradle task:

You can also select the file in the task with ... Option.

For example:


问:
How do Image Loading Libraries like Coil or Glide do memory management?
I am new to Android development. My app has use case where I want to download and display images from Internet. I am using Kotlin to build App and decided to use Coil library as Image loading library. While using my application, user's action my trigger download of multiple images. How do these image loading libraries make sure that memory/cache/disk space doesn't fill up? Do these libraries clear/delete images that were downloaded during last use?</p>

答:
The answer is going to depend on the particular library.  But in general, they download the images to a file, to serve as a disk cache.  That disk cache generally is kept to some limit in terms of size, with files being deleted on an LRU (least recently used) basis.  They may then do the same with in memory representations, keeping the last N megabytes worth of images cached in a pool, ejecting on an LRU basis when needed.  Ejecting them from the cache may or may not remove them from memory entirely-  it depends on if any other reference to the object is maintained by client code.  Some libraries allow configurable behavior on this, by either allowing client code to set size limits or provide entire cache implementations.

It's still possible for space to fill up.  Especially memory-  if you have too many bitmaps open and use up all available heap, then you're going OOM no matter what the loading library does.  What the loading library will do is prevent multiple network requests for the same image, and prevent you from having to do all the cache management by hand.


问:
Use 'import module' or 'from module import'?
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?

答:
The difference between import module and from module import foo is mainly subjective.  Pick the one you like best and be consistent in your use of it.  Here are some points to help you decide.

import module

Pros:

Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module

Cons:

Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

from module import foo

Pros:

Less typing to use foo

More control over which items of a module can be accessed

Cons:

To use a new item from the module you have to update your import statement

You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()

Either method is acceptable, but don't use from module import *.

For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed.  This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.

OwnerDisplayName: kRON

OwnerDisplayName: Mark Roddy

ContentLicense: CC BY-SA 3.0


问:
Trouble Centring divs after floating divs
In Google Chrome I'm having trouble centring my footer and text in the "what" div after the floating divs. You can see the page at this link:

It looks fine in Internet Explorer, but in Google Chrome they aren't centred :(

答: Adding margin:0; for the paragraph inside the footer fixes the issue ?


问:
How to prevent title bar from greyed out upon opening another form?
I am working on a custom context menu in an open-source text editor project I found on the internet. The custom context menu is made out of a Form. The problem is when I open the custom context menu, the text editor(main form) lost focus(becomes gray). I want it to look like this when the context menu opens, but not this. I have tried some solutions but they didn't work:

Solution 1: Caused the custom context menu to be on the back of the text editor once opened. It then stopped the custom context menu from working properly.

Solution 2: Caused my program to be crashed so it automatically closed.

Solution 3: I tried using either Control.Focus() or Control.Activate() to have focus on the text editor when invoking the custom context menu, but still didn't work.

Are there any other solutions I could try or am I missing something here?

Link(Head to: Branch -> v2.01) to the custom context menu project that I am working on. Please note that I have made it so that Control Key(CTRL) + Right mouse button(RMB) to invoke the custom context menu.

答:
I am not sure whether this is conventionally the correct way to do it, but it works for me.

However, another problem it poses is that the context menu item functions cannot be executed. It can be clicked but then the nothing happens.

```<code>//activated event handler for the context menu
private void ContextMenu_Activated(object sender, EventArgs e)
        {
            //solution A
            this.Activate(); //gives the main form the focus

            //solution B
            //this.Focus(); //gives the main form the focus

            contextMenuObj.Visible = true; //forces the context menu to be displayed

            //to maintain highlighted text in textbox in main form
            richTextBox1.HideSelection = false;

            //reset default flag once custom context menu opens
            ctrlIsDown = false;
            rmbIsUp = false;
        }
</code>```

This way, the main form is not greyed out when the context menu is displayed.

Body:
I am not sure whether this is conventionally the correct way to do it, but it works for me.

However, another problem it poses is that the context menu item functions cannot be executed. It can be clicked but then the nothing happens.

//activated event handler for the context menu
private void ContextMenu_Activated(object sender, EventArgs e)
        {
            //solution A
            this.Activate(); //gives the main form the focus

            //solution B
            //this.Focus(); //gives the main form the focus

            contextMenuObj.Visible = true; //forces the context menu to be displayed

            //to maintain highlighted text in textbox in main form
            richTextBox1.HideSelection = false;

            //reset default flag once custom context menu opens
            ctrlIsDown = false;
            rmbIsUp = false;
        }

This way, the main form is not greyed out when the context menu is displayed.


问:
exec() function in python not executing in django
Hope you all are fine.
I want to use the exec() function in django to execute my strings picked from the database.
The code I wrote is working in just python script but not working in Django views. Below is my code in python script which I'm running in notebook.

```<code>ticker = 'AAPL'
title = 'f"hey {ticker} is a really doing good."'
exec('title = ' + title)
print(title)
</code>```

But same code in Django views is not executing. Below is the code in views.py.

```<code>ticker = 'AAPL'
title = queryset.title #The title here is The {ticker} is not doing good.
exec('title = ' + title)
</code>```

It is not giving the write anwser, just returning the first title as shown below.

The {ticker} is not doing good. Thats is the {ticker} body.

If anyone have any solution, kindly help me to figure it out.

答:
I found the answer.
If you want to execute one variable, then use the upper code which is:

```<code>ticker = 'AAPL'
title = queryset.title.format(ticker=ticker)
</code>```

If you want to execute whole dictionary with alot of values. Then ** is a good option. For example

```<code>dictionary = {'ticker': 'Example', 'website': 'example.com'}
queryset.title.format(**dictionary)
</code>```

Body:
Hope you all are fine.
I want to use the exec() function in django to execute my strings picked from the database.
The code I wrote is working in just python script but not working in Django views. Below is my code in python script which I'm running in notebook.

ticker = 'AAPL'
title = 'f"hey {ticker} is a really doing good."'
exec('title = ' + title)
print(title)

But same code in Django views is not executing. Below is the code in views.py.

ticker = 'AAPL'
title = queryset.title #The title here is The {ticker} is not doing good.
exec('title = ' + title)

It is not giving the write anwser, just returning the first title as shown below.

The {ticker} is not doing good. Thats is the {ticker} body.

If anyone have any solution, kindly help me to figure it out.

Body:
I found the answer.
If you want to execute one variable, then use the upper code which is:

ticker = 'AAPL'
title = queryset.title.format(ticker=ticker)

If you want to execute whole dictionary with alot of values. Then ** is a good option. For example

dictionary = {'ticker': 'Example', 'website': 'example.com'}
queryset.title.format(**dictionary)


问:
Docker Compose: depends_on with condition -> invalid type, should be an array
I have the following compose file:

version: "3"

services:

  zookeeper:
    image: docker-dev.art.intern/wurstmeister/zookeeper:latest
    ports:
      - 2181:2181

  kafka:
    image: docker-dev.art.intern/wurstmeister/kafka:latest
    ports:
      - 9092:9092
    environment:
      - KAFKA_LISTENERS=PLAINTEXT://:9092
      - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092
      - KAFKA_ADVERTISED_HOST_NAME=kafka
      - KAFKA_ADVERTISED_PORT=9092
      - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
    depends_on:
      - zookeeper

  app:
    build:
      context: ./
      dockerfile: app/Dockerfile
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4020/actuator/health"]
      interval: 30s
      timeout: 10s
      retries: 5
    depends_on:
      - kafka
      - zookeeper

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      app:
        condition: service_healthy
```
<p>As you can see im implementing a healthcheck for the app and I use <code>service_healthy</code> condition.
But that leads to the error:</p>
```The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be an array
```
<p>Is there a way to fix that issue?</p>
<p>If I change to array sanytax:</p>
<pre class="lang-yaml prettyprint-override"><code>...

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      - app:
          condition: service_healthy

</code>```

The error changes to:

```<code>The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be a string
</code>```

答:
you can do that with a compose file version 2.1, but it was removed in compose file version 3.

There are several things to be aware of when using depends_on:

depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

yet, will advise you not to downgrade your compose file. but rather handle it appropriately with a wrapper script.

you might find wait-for-it, dockerize, and/or wait-for handy.

in compose version 3 you can use depends long syntax to specify a condition

condition: condition under which dependency is considered satisfied

service_started: is an equivalent of the short syntax described above

service_healthy: specifies that a dependency is expected to be “healthy” (as indicated by healthcheck) before starting a dependent service.

service_completed_successfully: specifies that a dependency is expected to run to successful completion before starting a dependent service.

e.g.

services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
  redis:
    image: redis
  db:
    image: postgres
```

Body:
I have the following compose file:

version: "3"

services:

  zookeeper:
    image: docker-dev.art.intern/wurstmeister/zookeeper:latest
    ports:
      - 2181:2181

  kafka:
    image: docker-dev.art.intern/wurstmeister/kafka:latest
    ports:
      - 9092:9092
    environment:
      - KAFKA_LISTENERS=PLAINTEXT://:9092
      - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092
      - KAFKA_ADVERTISED_HOST_NAME=kafka
      - KAFKA_ADVERTISED_PORT=9092
      - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
    depends_on:
      - zookeeper

  app:
    build:
      context: ./
      dockerfile: app/Dockerfile
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4020/actuator/health"]
      interval: 30s
      timeout: 10s
      retries: 5
    depends_on:
      - kafka
      - zookeeper

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      app:
        condition: service_healthy

As you can see im implementing a healthcheck for the app and I use service_healthy condition.
But that leads to the error:

The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be an array

Is there a way to fix that issue?

If I change to array sanytax:

...

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      - app:
          condition: service_healthy

The error changes to:

The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be a string


问:
CalendarViewDayItem event not firing
I'm trying to add a RightTapped event to each CalendarViewDayItem. DoubleTapped event works fine, but RightTapped is not raised despite of that it's created.

This is how I have created them:

```<code>private void calviewSun_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
{

    args.Item.DoubleTapped += CalendarViewDayItem_DoubleTapped;
    args.Item.RightTapped  += CalendarViewDayItem_RightTapped;
}
</code>```

I have tried setting breakpoints to check if they were raised but they had any other problems, but they are never raised. I have check that args.Item.IsRightTapEnbaled is set to true.

I don't know why is not raising the event.

答:
Please try to use UIElement.AddHandler() Method to add right tapped event for the CalendarViewDayItem.

The code looks like this:

```<code> private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
    {
        args.Item.IsRightTapEnabled = true;
        args.Item.DoubleTapped += Item_DoubleTapped;
       // args.Item.RightTapped += Item_RightTapped;

        args.Item.AddHandler(UIElement.RightTappedEvent, new RightTappedEventHandler(Item_RightTapped), true);
    }

    private void Item_RightTapped(object sender, RightTappedRoutedEventArgs e)
    {
        Debug.WriteLine("RightTapped");
    }
</code>```

Title: CalendarViewDayItem event not firing

Body:
I'm trying to add a RightTapped event to each CalendarViewDayItem. DoubleTapped event works fine, but RightTapped is not raised despite of that it's created.

This is how I have created them:

private void calviewSun_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
{

    args.Item.DoubleTapped += CalendarViewDayItem_DoubleTapped;
    args.Item.RightTapped  += CalendarViewDayItem_RightTapped;
}

I have tried setting breakpoints to check if they were raised but they had any other problems, but they are never raised. I have check that args.Item.IsRightTapEnbaled is set to true.

I don't know why is not raising the event.

Body:
Please try to use UIElement.AddHandler() Method to add right tapped event for the CalendarViewDayItem.

The code looks like this:

 private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
    {
        args.Item.IsRightTapEnabled = true;
        args.Item.DoubleTapped += Item_DoubleTapped;
       // args.Item.RightTapped += Item_RightTapped;

        args.Item.AddHandler(UIElement.RightTappedEvent, new RightTappedEventHandler(Item_RightTapped), true);
    }

    private void Item_RightTapped(object sender, RightTappedRoutedEventArgs e)
    {
        Debug.WriteLine("RightTapped");
    }


问:
Setting fill style of flex legend item not working
I have been trying (but to no avail) to set the background color of a legend item in Flex to a color of my choosing.

Unfortunately, it doesn't seem to be working.

I obtain a reference to the legendItem in question and then set the fill style like so:

```<code>var legendItem:LegendItem = event.item;
var legendItemColor:SolidColor = new SolidColor(0x00FF00, 0.5);
legendItem.setStyle("fill", legendItemColor);
</code>```

I am able to set other styles of the legend item but, for some reason, this isn't working.

Any help would be greatly appreciated.

Thanks in advance.

答:
Managed to get the effect I was looking for by setting the opaqueBackground property of the legendItem.

```<code>legendItem.opaqueBackground = 0x00FF00;
</code>```

Doesn't really make sense and I had even found an example where setStyle of fill was used and seemed to work for them.

Oh well, as long as it works!

Body:
I have been trying (but to no avail) to set the background color of a legend item in Flex to a color of my choosing.

Unfortunately, it doesn't seem to be working.

I obtain a reference to the legendItem in question and then set the fill style like so:

var legendItem:LegendItem = event.item;
var legendItemColor:SolidColor = new SolidColor(0x00FF00, 0.5);
legendItem.setStyle("fill", legendItemColor);

I am able to set other styles of the legend item but, for some reason, this isn't working.

Any help would be greatly appreciated.

Thanks in advance.

Body:
Managed to get the effect I was looking for by setting the opaqueBackground property of the legendItem.

legendItem.opaqueBackground = 0x00FF00;

Doesn't really make sense and I had even found an example where setStyle of fill was used and seemed to work for them.

Oh well, as long as it works!


问:
In VueJS how to print the v-for’s increment digit key as a suffix to a CSS class
I simply want to increment a CSS class based on the loop count using the index value as a suffix to a defined class "classname nb" to get "classname nb1", "classname nb2".

I'm able to print it as content using double curly brackets {{ index }} (in my example below) but I dont’t know what syntaxe to use within the Vue :class prop.

        <v-bind class="classname" :class="nb{ index }">
            classname nb{{ index }}
        </v-bind>

```
<p>I expect these CSS classes on <code><v-bing></code> :</p>
```1. classname nb1
2. classname nb2
3. classname nb3
```

答:
I got the answer from a colleague...

First wrap the classname to index within single quotes for class ( '…' ), for not conflicting with the :class="" double quotes, followed by the plus sign (+) then the index key.

<v-bind class="classname" :class="'nb' + index">
  {{ "nb" + index }}
</v-bind>
```
<p>Gives</p>
<pre class="lang-html prettyprint-override"><code><v-bind class="classname nb1"> nb1 </v-bind>
<v-bind class="classname nb2"> nb2 </v-bind>
<v-bind class="classname nb3"> nb3 </v-bind>
</code>```

Body:
I simply want to increment a CSS class based on the loop count using the index value as a suffix to a defined class "classname nb" to get "classname nb1", "classname nb2".

I'm able to print it as content using double curly brackets {{ index }} (in my example below) but I dont’t know what syntaxe to use within the Vue :class prop.

        <v-bind class="classname" :class="nb{ index }">
            classname nb{{ index }}
        </v-bind>

I expect these CSS classes on <v-bing> :

1. classname nb1
2. classname nb2
3. classname nb3

Body:
I got the answer from a colleague...

First wrap the classname to index within single quotes for class ( '…' ), for not conflicting with the :class="" double quotes, followed by the plus sign (+) then the index key.

<v-bind class="classname" :class="'nb' + index">
  {{ "nb" + index }}
</v-bind>

Gives

<v-bind class="classname nb1"> nb1 </v-bind>
<v-bind class="classname nb2"> nb2 </v-bind>
<v-bind class="classname nb3"> nb3 </v-bind>


问:
React Environmental Variables are undefined with Dotenv
I am using dotenv to create an environment variable to insert a base url into my API call using react, dotenv, and webpack.

When I call the variables in the code, I don't get any error other than them printing as undefined. What am I doing wrong?

Here is my webpack file

```<code>const webpack = require("webpack");
const Dotenv = require("dotenv");

dotenv.config();

module.exports = (env) => {
  return {
    plugins: [
      new Dotenv(),
      new webpack.ProvidePlugin({
        process: "process/browser",
      }),
      new webpack.DefinePlugin({
        'process.env': JSON.stringify(process.env)
     })
    ],
  };
};
</code>```

Here are what the variables look like in the .env file in the root of my project

```<code>API_URL=http://localhost:8000
BASE_URL=https://my-url.com
</code>```

And here is how I am accessing it in the code (with axios for auth)

```<code>  axiosAuth: axios.create({
    baseURL: `${process.env.BASE_URL}`,
    timeout: 5000,
  })
</code>```

答:
Like Shah already explain, the only thing that you need is add the prefix "REACT_APP" to your current variables..
Change this:

```<code>API_URL=http://localhost:8000
BASE_URL=https://my-url.com
</code>```

To this:

```<code>REACT_APP_API_URL=http://localhost:8000
REACT_APP_BASE_URL=https://my-url.com
</code>```

Body:
I am using dotenv to create an environment variable to insert a base url into my API call using react, dotenv, and webpack.

When I call the variables in the code, I don't get any error other than them printing as undefined. What am I doing wrong?

Here is my webpack file

const webpack = require("webpack");
const Dotenv = require("dotenv");

dotenv.config();

module.exports = (env) => {
  return {
    plugins: [
      new Dotenv(),
      new webpack.ProvidePlugin({
        process: "process/browser",
      }),
      new webpack.DefinePlugin({
        'process.env': JSON.stringify(process.env)
     })
    ],
  };
};

Here are what the variables look like in the .env file in the root of my project

API_URL=http://localhost:8000
BASE_URL=https://my-url.com

And here is how I am accessing it in the code (with axios for auth)

  axiosAuth: axios.create({
    baseURL: `${process.env.BASE_URL}`,
    timeout: 5000,
  })

Body:
Like Shah already explain, the only thing that you need is add the prefix "REACT_APP" to your current variables..
Change this:

API_URL=http://localhost:8000
BASE_URL=https://my-url.com

To this:

REACT_APP_API_URL=http://localhost:8000
REACT_APP_BASE_URL=https://my-url.com


问:
Removing a model in rails (reverse of "rails g model Title...")
```<code>rails g model Rating user_id:integer message:string value:integer
</code>```

How can I completely remove this model? Thanks

答:
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run

```<code>bundle exec rails db:rollback
rails destroy model <model_name>
</code>```

For rails versions before 5.0 and higher use rake instead of rails

```<code>bundle exec rake db:rollback
rails destroy model <model_name>
</code>```

Body:
rails g model Rating user_id:integer message:string value:integer

How can I completely remove this model? Thanks

Body:
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run

bundle exec rails db:rollback
rails destroy model <model_name>

For rails versions before 5.0 and higher use rake instead of rails

bundle exec rake db:rollback
rails destroy model <model_name>


问:
How can we find multiple used range addresses in one sheet?
How can we loop through all cells in a sheet and find multiple used range addresses on this one sheet? In this screen shot we have used ranges of B2:F17, I2:M17, Q2:U17, C19:M34, and Q19:U34. How can I identify these beginning and ending cell addresses of these five used ranges, and print them in an array of cells? I have some sample code that shows the total used range on a sheet.

```<code>Sub Vba_Used_Range()

Dim iCell As Range
Dim iRange As Range
Dim c As Long
Dim i As Long

Set iRange = ActiveSheet.UsedRange

For Each iCell In ActiveSheet.UsedRange
    c = c + 1
    If IsEmpty(iCell) = True Then
        i = i + 1
    End If
Next iCell

MsgBox "There are total " & c & _
" cell(s) in the range, and out of those " & _
i & " cell(s) are empty."

End Sub
</code>```

Again, how can I print cell addresses for multiple used ranges on one sheet?

答:
```<code>    Dim rArea As Range
    For Each rArea In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants+xlCellTypeFormulas).Areas
        Debug.Print rArea.Address
    Next rArea
</code>```

Body:
How can we loop through all cells in a sheet and find multiple used range addresses on this one sheet? In this screen shot we have used ranges of B2:F17, I2:M17, Q2:U17, C19:M34, and Q19:U34. How can I identify these beginning and ending cell addresses of these five used ranges, and print them in an array of cells? I have some sample code that shows the total used range on a sheet.

Sub Vba_Used_Range()

Dim iCell As Range
Dim iRange As Range
Dim c As Long
Dim i As Long

Set iRange = ActiveSheet.UsedRange

For Each iCell In ActiveSheet.UsedRange
    c = c + 1
    If IsEmpty(iCell) = True Then
        i = i + 1
    End If
Next iCell

MsgBox "There are total " & c & _
" cell(s) in the range, and out of those " & _
i & " cell(s) are empty."

End Sub

Again, how can I print cell addresses for multiple used ranges on one sheet?


问:
How to Git Ignore Contain "tiu" Word Files
the category like:

```<code>/Script/tiu_adfsfdfdsff.js
/Script/tiu_adfsfdfdsff.js
...
/CSS/tiu_adfsfdfdsff.css
/CSS/tiu_adfsfdfdsff.css
...
</code>```

i want to ignore contain "tiu" files

my .gitignore files is:

```<code>CSS/tiu*.css
Script/tiu*.js
</code>```

but it don't work?

答:
if you want to ignore all the tiu* files, use a global pattern (without specifying the directory at first):

```<code>tui*.css
</code>```

If this does not work, here are the rules for patterns:
http://git-scm.com/docs/gitignore

Body:
the category like:

/Script/tiu_adfsfdfdsff.js
/Script/tiu_adfsfdfdsff.js
...
/CSS/tiu_adfsfdfdsff.css
/CSS/tiu_adfsfdfdsff.css
...

i want to ignore contain "tiu" files

my .gitignore files is:

CSS/tiu*.css
Script/tiu*.js

but it don't work?

Body:
if you want to ignore all the tiu* files, use a global pattern (without specifying the directory at first):

tui*.css

If this does not work, here are the rules for patterns:
http://git-scm.com/docs/gitignore


问:
Can we use logical operations on signals when using the systemverilog bind construct?
can we use logical operations on signals when using the systemverilog bind construct?
i.e. is this legal?

```<code>bind RTLTOP clk_if clk_if_inst (.clock (rtlclk_A || rtlclk_B) )
</code>```

The base issue, is that I want to use the bind construct to create something like the image seen below.

The reason I am trying to hack my way ahead, is because I have a fixed RTLTOP (I can't modify that), and I have a highly re-usable interface clk_if that generates events of a particular nature and that can be accessed via easy-to-use methods, therefore I want to be able to use all this good additional infrastructure. However I want the event to be generated based on the OR of the two clocks.

答:
You can use any expression in a bind to connect port as long as it meets the rules for any module instance port connection. The LRM even has an example in section 23.11 Binding auxiliary code to scopes or instances of a input port connected to the result of a function call with an argument that is a concatenation of signal.

It's easy to drive input ports with expressions, but you are limited to concatenation expressions connecting output ports.

Body:
can we use logical operations on signals when using the systemverilog bind construct?
i.e. is this legal?

bind RTLTOP clk_if clk_if_inst (.clock (rtlclk_A || rtlclk_B) )

The base issue, is that I want to use the bind construct to create something like the image seen below.

The reason I am trying to hack my way ahead, is because I have a fixed RTLTOP (I can't modify that), and I have a highly re-usable interface clk_if that generates events of a particular nature and that can be accessed via easy-to-use methods, therefore I want to be able to use all this good additional infrastructure. However I want the event to be generated based on the OR of the two clocks.


问:
React Redux state is lost at page refresh
in my react app I have 3 components. from the 1st component by a button, I use Link to go to the 2nd component. at the 2nd I create a state (redux store), manipulate it and when manipulation is finished by submitting button I redirect to the 3rd component. at the 3rd component, I also see the state (by redux chrome tool) but here when I refresh the page (the webpack thing when a code is changed and saved), I lose the sate and get an empty Object.

this is the structure of my app.

index.js

```<code>const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);
</code>```

App.js

```<code>const App = ({ location }) => (
  <Container>
    <Route location={location} path="/" exact component={HomePage} />
    <Route location={location} path="/GameInit" exact component={GameInit} />
    <Route location={location} path="/Battle" exact component={Battle} />
  </Container>
);

App.propTypes = {
  location: PropTypes.shape({
    pathname: PropTypes.string.isRequired
  }).isRequired
};

export default App;
</code>```

Here at HomePage, I have a button that links to GameInit

```<code>const HomePage = () => (<Button color="blue" as={Link} to="/GameInit">START GAME</Button>);
export default HomePage;
</code>```

and the GameInit Page looks like

```<code>class GameInit extends Component {
  componentWillMount() {
    const { createNewPlayer} = this.props;
    createNewPlayer();
  }
/* state manipulation till it gets valid */
 palyerIsReady()=>{ history.push("/Battle");}

export default connect(mapStateToProps,{ createNewPlayer})(GameInit);
</code>```

and finally Battle component where I first see the state but lose on refresh

```<code>class Battle extends Component {
  render() {return (/*some stuff*/);}}

Battle.propTypes = {
  players: PropTypes.object.isRequired // eslint-disable-line
};
const mapStateToProps = state => ({
  players: state.players
});
export default connect(mapStateToProps,null)(Battle);
</code>```

答:
Everyone is recommending localStorage, but you can also just save to sessionStorage (which i've read is safer than localStorage) and check for the storage item on refresh.
You can set it on response success or wherever.

```<code>window.sessionStorage.setItem("sessionName",JSON.stringify(message.payload));

</code>```

Then can check in your componentDidUpdate or mount.

```<code>  if(!isLoggedIn && !isAuthenticated && window.sessionStorage.getItem('session-name')){
            saveWhatYouWant(JSON.parse(window.sessionStorage.getItem('sessionName')))

        }
</code>```

I found this works much faster and you're essentially repopulating the store w/out needing to write a lot of code.

Body:
in my react app I have 3 components. from the 1st component by a button, I use Link to go to the 2nd component. at the 2nd I create a state (redux store), manipulate it and when manipulation is finished by submitting button I redirect to the 3rd component. at the 3rd component, I also see the state (by redux chrome tool) but here when I refresh the page (the webpack thing when a code is changed and saved), I lose the sate and get an empty Object.

this is the structure of my app.

index.js

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);

App.js

const App = ({ location }) => (
  <Container>
    <Route location={location} path="/" exact component={HomePage} />
    <Route location={location} path="/GameInit" exact component={GameInit} />
    <Route location={location} path="/Battle" exact component={Battle} />
  </Container>
);

App.propTypes = {
  location: PropTypes.shape({
    pathname: PropTypes.string.isRequired
  }).isRequired
};

export default App;

Here at HomePage, I have a button that links to GameInit

const HomePage = () => (<Button color="blue" as={Link} to="/GameInit">START GAME</Button>);
export default HomePage;

and the GameInit Page looks like

class GameInit extends Component {
  componentWillMount() {
    const { createNewPlayer} = this.props;
    createNewPlayer();
  }
/* state manipulation till it gets valid */
 palyerIsReady()=>{ history.push("/Battle");}

export default connect(mapStateToProps,{ createNewPlayer})(GameInit);

and finally Battle component where I first see the state but lose on refresh

class Battle extends Component {
  render() {return (/*some stuff*/);}}

Battle.propTypes = {
  players: PropTypes.object.isRequired // eslint-disable-line
};
const mapStateToProps = state => ({
  players: state.players
});
export default connect(mapStateToProps,null)(Battle);

Body:
Everyone is recommending localStorage, but you can also just save to sessionStorage (which i've read is safer than localStorage) and check for the storage item on refresh.
You can set it on response success or wherever.

window.sessionStorage.setItem("sessionName",JSON.stringify(message.payload));

Then can check in your componentDidUpdate or mount.

  if(!isLoggedIn && !isAuthenticated && window.sessionStorage.getItem('session-name')){
            saveWhatYouWant(JSON.parse(window.sessionStorage.getItem('sessionName')))

        }

I found this works much faster and you're essentially repopulating the store w/out needing to write a lot of code.


问:
How can I Calculate the maximum and minimum salary of the employees?

import java.util.*;

class EmployeesDetails {
    System.out.println("Welcome Aboard!");
    Scanner emp = new Scanner(System.in);
    List<EmployeesDetails> employeesDetails = new ArrayList<>();
    Boolean empQuestion = true;

    while (empQuestion == true) {
        System.out.println("Do you want to enter the employee details? Yes or No");
        String inputString = emp.next();
        empQuestion = inputString.equalsIgnoreCase("Yes") ? true : false;

        if (empQuestion == false) {
            System.out.println("Come again Later!");
            break;
        }

        System.out.println("Enter the employee name: ");
        String empName = emp.next();

        System.out.println("Enter the employee ID");
        String empID = emp.next();

        System.out.println("Enter the employee Phone number");
        String empPhoneNumber = emp.next();

        System.out.println("Enter the employee Salary");
        Float empSalary = emp.nextFloat();

        EmployeesDetails employee = new EmployeesDetails(empName, empID, empPhoneNumber, empSalary);
        employeesDetails.add(employee);
        System.out.println(employeesDetails);
    }

    emp.close();
}
```

Hi everyone, So here I've written a program for adding the employee details.

I want to add the minimum and maximum wage for the employees, for example let's say if I have added 10 employees then I want to display the minimum salary of the employee who earns the least and display the salary of the employee who earns the highest.

My initial approach was to use Math.min() but then I realized that it is used for comparing between two values. Then my second approach was to Collections.min(); but I realized it's used the min value of the list.

Thank you and please go easy on me I've just started to learn coding.

答:
The following demonstrates 4 possible solutions. Note the comments:

```<code>import java.util.*;

public class Main{

    public static void main(String[] args) {

        //Hardcoded data to make it more of an mre
        List<EmployeesDetails> employeesDetails = new ArrayList<>();
        employeesDetails.add(new EmployeesDetails("Sara", 1000f));
        employeesDetails.add(new EmployeesDetails("Deby", 1400f));
        employeesDetails.add(new EmployeesDetails("Dan", 1200f));

        //solution 1
        //Iterate over the collection and keep the employee with the highest (you can also keep the lowest)
        EmployeesDetails highestSalary = employeesDetails.get(0);
        for(EmployeesDetails e :employeesDetails ){
            if(e.getEmpSalary() > highestSalary.getEmpSalary()){
                highestSalary = e;
            }
        }

        //solution 2 contributed by Charlie Armstrong
        //Use Collections.max ( Collections.min )
        EmployeesDetails empD = Collections.max(employeesDetails, (e1, e2) -> Float.compare(e1.getEmpSalary(), e2.getEmpSalary()));
        System.out.println("employee with highest salary is "+empD);

        //solution 3
        //Use a stream, sort by salary find first to get the lowest
        //sort by salary in reverse and find first to get the highest
        Optional<EmployeesDetails> opEmpD = employeesDetails.stream().sorted((e1, e2) -> Float.compare(e2.getEmpSalary(), e1.getEmpSalary())).findFirst();
        System.out.println( opEmpD == null ? "No solution found" : "employee with highest salary is "+opEmpD.get());
        System.out.println("employee with highest salary is "+ highestSalary);

        //solution 4
        //Sort the collection by salary the last one is the highest
        //(get the first one for the lowest)
        Collections.sort(employeesDetails, (e1, e2) -> Float.compare(e1.getEmpSalary(), e2.getEmpSalary()));
        System.out.println("employee with highest salary is "+ employeesDetails.get(employeesDetails.size()-1));

    }
}

//simplified for to make it more of an mre
class EmployeesDetails {

    private final String empName;
    private final Float empSalary;

    public EmployeesDetails(String empName, Float empSalary) {
        this.empName = empName;
        this.empSalary = empSalary;
    }

    @Override
    public String toString() {
        return "EmployeesDetails{" +
                "Name='" + empName + '\'' +
                ", Salary='" + empSalary+ '\'' +
                '}';
    }

    public String getEmpName() {
        return empName;
    }

    public Float getEmpSalary() {
        return empSalary;
    }
}
</code>```

See:
 https://stackoverflow.com/help/minimal-reproducible-example

Body:
import java.util.*;

class EmployeesDetails {
    System.out.println("Welcome Aboard!");
    Scanner emp = new Scanner(System.in);
    List<EmployeesDetails> employeesDetails = new ArrayList<>();
    Boolean empQuestion = true;

    while (empQuestion == true) {
        System.out.println("Do you want to enter the employee details? Yes or No");
        String inputString = emp.next();
        empQuestion = inputString.equalsIgnoreCase("Yes") ? true : false;

        if (empQuestion == false) {
            System.out.println("Come again Later!");
            break;
        }

        System.out.println("Enter the employee name: ");
        String empName = emp.next();

        System.out.println("Enter the employee ID");
        String empID = emp.next();

        System.out.println("Enter the employee Phone number");
        String empPhoneNumber = emp.next();

        System.out.println("Enter the employee Salary");
        Float empSalary = emp.nextFloat();

        EmployeesDetails employee = new EmployeesDetails(empName, empID, empPhoneNumber, empSalary);
        employeesDetails.add(employee);
        System.out.println(employeesDetails);
    }

    emp.close();
}

Hi everyone, So here I've written a program for adding the employee details.

I want to add the minimum and maximum wage for the employees, for example let's say if I have added 10 employees then I want to display the minimum salary of the employee who earns the least and display the salary of the employee who earns the highest.

My initial approach was to use Math.min() but then I realized that it is used for comparing between two values. Then my second approach was to Collections.min(); but I realized it's used the min value of the list.

Thank you and please go easy on me I've just started to learn coding.

Body:
The following demonstrates 4 possible solutions. Note the comments:

import java.util.*;

public class Main{

    public static void main(String[] args) {

        //Hardcoded data to make it more of an mre
        List<EmployeesDetails> employeesDetails = new ArrayList<>();
        employeesDetails.add(new EmployeesDetails("Sara", 1000f));
        employeesDetails.add(new EmployeesDetails("Deby", 1400f));
        employeesDetails.add(new EmployeesDetails("Dan", 1200f));

        //solution 1
        //Iterate over the collection and keep the employee with the highest (you can also keep the lowest)
        EmployeesDetails highestSalary = employeesDetails.get(0);
        for(EmployeesDetails e :employeesDetails ){
            if(e.getEmpSalary() > highestSalary.getEmpSalary()){
                highestSalary = e;
            }
        }

        //solution 2 contributed by Charlie Armstrong
        //Use Collections.max ( Collections.min )
        EmployeesDetails empD = Collections.max(employeesDetails, (e1, e2) -> Float.compare(e1.getEmpSalary(), e2.getEmpSalary()));
        System.out.println("employee with highest salary is "+empD);

        //solution 3
        //Use a stream, sort by salary find first to get the lowest
        //sort by salary in reverse and find first to get the highest
        Optional<EmployeesDetails> opEmpD = employeesDetails.stream().sorted((e1, e2) -> Float.compare(e2.getEmpSalary(), e1.getEmpSalary())).findFirst();
        System.out.println( opEmpD == null ? "No solution found" : "employee with highest salary is "+opEmpD.get());
        System.out.println("employee with highest salary is "+ highestSalary);

        //solution 4
        //Sort the collection by salary the last one is the highest
        //(get the first one for the lowest)
        Collections.sort(employeesDetails, (e1, e2) -> Float.compare(e1.getEmpSalary(), e2.getEmpSalary()));
        System.out.println("employee with highest salary is "+ employeesDetails.get(employeesDetails.size()-1));

    }
}

//simplified for to make it more of an mre
class EmployeesDetails {

    private final String empName;
    private final Float empSalary;

    public EmployeesDetails(String empName, Float empSalary) {
        this.empName = empName;
        this.empSalary = empSalary;
    }

    @Override
    public String toString() {
        return "EmployeesDetails{" +
                "Name='" + empName + '\'' +
                ", Salary='" + empSalary+ '\'' +
                '}';
    }

    public String getEmpName() {
        return empName;
    }

    public Float getEmpSalary() {
        return empSalary;
    }
}

See:
 https://stackoverflow.com/help/minimal-reproducible-example


问:
Data redundancy on csv file
Hi Good day everyone I'm sorry I'm new to python programming sorry if I'm asking this even this is basic or not. Someone can help me with this?  My problem is I want to write the data that capture's on my open cv Like for example "Name" "Reputation" or something else. And write it to my csv file. It writes But I has a redundancy like per capture it records The same name. I just want one Name that don't redundant Someone can Help me with this Please???

Here's the code to record data to csv:

def markattend(name, years, pos, tempe):
    with open('attendances.csv', 'r+') as f:
        datalist = f.readlines()
        nameList = []

        for line in datalist:
            entry = line.split(',')
            nameList.append(entry[0])

        if name and years and pos and tempe not in nameList:
            now = datetime.now()
            dtString = now.strftime('%I:%M:%a:%d:%b:%Y')
            f.writelines(f'\n{name},{years},{pos},{tempe},{dtString}')
        return datalist
```
<p>And here I call the function and assigning its Data: like "Name" "Position"</p>
<pre class="lang-py prettyprint-override"><code>if confidence>70:
    cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    cv2.putText(img, get_temp(ser), (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    markattend(datas,datas1,datas2,get_temp(ser))  # <== This temp is from my sensor data and datas, datas1, datas2   it correspond the "Name" "position" "Student"
</code>```

Someone can help me   plsss

Here's my csv file photo:here's the Image

答:
for line in datalist:
    entry = line.split(',')
    nameList.append(entry[0])
```
<p>Only the names are being added to the <code>namesList</code> say:</p>
<pre class="lang-py prettyprint-override"><code>namesList = ['NameA', 'NameB']
</code>```

The if statements used on your code does not work the way you think it does.

```<code>if 'NameC' and 'NameB' in namesList:
</code>```

is going to evaluate it true, as you can see in the below snippet:

```<code>>>> namesList = ['NameA', 'NameB']
>>> 'NameC' and 'NameB' in namesList
True
>>> 'NameC' in namesList and 'NameB' in namesList
False
</code>```

In your case, it is clear that tempe is not in the namesList, hence every entry is appended.

Title: Data redundancy on csv file

Body:
Hi Good day everyone I'm sorry I'm new to python programming sorry if I'm asking this even this is basic or not. Someone can help me with this?  My problem is I want to write the data that capture's on my open cv Like for example "Name" "Reputation" or something else. And write it to my csv file. It writes But I has a redundancy like per capture it records The same name. I just want one Name that don't redundant Someone can Help me with this Please???

Here's the code to record data to csv:

def markattend(name, years, pos, tempe):
    with open('attendances.csv', 'r+') as f:
        datalist = f.readlines()
        nameList = []

        for line in datalist:
            entry = line.split(',')
            nameList.append(entry[0])

        if name and years and pos and tempe not in nameList:
            now = datetime.now()
            dtString = now.strftime('%I:%M:%a:%d:%b:%Y')
            f.writelines(f'\n{name},{years},{pos},{tempe},{dtString}')
        return datalist

And here I call the function and assigning its Data: like "Name" "Position"

if confidence>70:
    cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    cv2.putText(img, get_temp(ser), (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
    markattend(datas,datas1,datas2,get_temp(ser))  # <== This temp is from my sensor data and datas, datas1, datas2   it correspond the "Name" "position" "Student"

Someone can help me   plsss

Here's my csv file photo:here's the Image

Body:
for line in datalist:
    entry = line.split(',')
    nameList.append(entry[0])

Only the names are being added to the namesList say:

namesList = ['NameA', 'NameB']

The if statements used on your code does not work the way you think it does.

if 'NameC' and 'NameB' in namesList:

is going to evaluate it true, as you can see in the below snippet:

>>> namesList = ['NameA', 'NameB']
>>> 'NameC' and 'NameB' in namesList
True
>>> 'NameC' in namesList and 'NameB' in namesList
False

In your case, it is clear that tempe is not in the namesList, hence every entry is appended.


问:
Javascript change event on input element fires on only losing focus
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

```<code><input type="text" id="name" onchange="checkLength(this.value)" />
</code>```

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

答:
You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.

```<code><input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />
</code>```

Body:
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

<input type="text" id="name" onchange="checkLength(this.value)" />

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

Body:
You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.

<input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />


问:
Left join two dateframes with date columns on a range of dates?
Here's an example that fulfills the criteria. Dataframe df1 and df2 both have id columns and date columns. In df1 the id column is unique while in df2 it is non-unique. I'd like to create a new dataframe where the join happens if df1.id == df2.id and some pair of dates in df2 is within 1 week of the date in df1

```<code>df1

| customer_id (unique) | 'purchase_date'|
| --------             | -------------- |
| 1                    | 2021-05-14     |
| 2                    | 2021-09-16     |

df2

| customer_id | 'visit_dates'  |
| --------    | -------------- |
| 1           | 2021-05-11     |
| 1           | 2021-05-16     |
| 1           | 2021-05-21     |
| 2           | 2021-07-14     |
| 2           | 2021-09-17     |

# New Df will only have 1 row.
# For customer 1 there is a date within the range(05-07 -> 05-14)
# and within the range(05-14 -> 05-21) with matching id.
# For customer 2, there are no dates within (09-09 -> 09-16) so it should be filtered

newdf

| customer_id (unique) | 'purchase_date'| begin_date_range | end_date_range
| --------             | -------------- | ---------------- | -------------
| 1                    | 2021-05-14     | 2021-05-11       | 2021-05-16

</code>```

I understand how to do this in SQL, but I don't know what functions allow similar date predicate filtering in Pandas.

To construct df1 and df2:

```<code>data1 = {'customer_id': [1, 2], 'purchase_date': ['2021-05-14', '2021-09-16']}

data2 = {'customer_id': [1, 1, 1, 2, 2],
         'visit_dates': ['2021-05-11', '2021-05-16', '2021-05-21', '2021-07-14', '2021-09-17']}
</code>```

答:
Building on @Raymond Kwok's excellent answer: We could merge twice, once to left merge df1 to df2 and then merge the "begin_date_range" part with the "end_date_range" part

```<code>merged = df1.merge(df2, on='customer_id', how='left')
merged['purchase_date'] = pd.to_datetime(merged['purchase_date'])
merged['visit_dates'] = pd.to_datetime(merged['visit_dates'])

day_diff = merged['purchase_date'].sub(merged['visit_dates']).dt.days
out = (merged[day_diff.between(0,6)]
       .merge(merged[day_diff.between(-6,0)], on=['customer_id','purchase_date'])
       .rename(columns={'visit_dates_x': 'begin_date_range', 'visit_dates_y': 'end_date_range'}))
</code>```

Output:

```<code>   customer_id purchase_date begin_date_range end_date_range
0            1    2021-05-14       2021-05-11     2021-05-16
</code>```

Body:
Here's an example that fulfills the criteria. Dataframe df1 and df2 both have id columns and date columns. In df1 the id column is unique while in df2 it is non-unique. I'd like to create a new dataframe where the join happens if df1.id == df2.id and some pair of dates in df2 is within 1 week of the date in df1

df1

| customer_id (unique) | 'purchase_date'|
| --------             | -------------- |
| 1                    | 2021-05-14     |
| 2                    | 2021-09-16     |

df2

| customer_id | 'visit_dates'  |
| --------    | -------------- |
| 1           | 2021-05-11     |
| 1           | 2021-05-16     |
| 1           | 2021-05-21     |
| 2           | 2021-07-14     |
| 2           | 2021-09-17     |

# New Df will only have 1 row.
# For customer 1 there is a date within the range(05-07 -> 05-14)
# and within the range(05-14 -> 05-21) with matching id.
# For customer 2, there are no dates within (09-09 -> 09-16) so it should be filtered

newdf

| customer_id (unique) | 'purchase_date'| begin_date_range | end_date_range
| --------             | -------------- | ---------------- | -------------
| 1                    | 2021-05-14     | 2021-05-11       | 2021-05-16

I understand how to do this in SQL, but I don't know what functions allow similar date predicate filtering in Pandas.

To construct df1 and df2:

data1 = {'customer_id': [1, 2], 'purchase_date': ['2021-05-14', '2021-09-16']}

data2 = {'customer_id': [1, 1, 1, 2, 2],
         'visit_dates': ['2021-05-11', '2021-05-16', '2021-05-21', '2021-07-14', '2021-09-17']}

Body:
Building on @Raymond Kwok's excellent answer: We could merge twice, once to left merge df1 to df2 and then merge the "begin_date_range" part with the "end_date_range" part

merged = df1.merge(df2, on='customer_id', how='left')
merged['purchase_date'] = pd.to_datetime(merged['purchase_date'])
merged['visit_dates'] = pd.to_datetime(merged['visit_dates'])

day_diff = merged['purchase_date'].sub(merged['visit_dates']).dt.days
out = (merged[day_diff.between(0,6)]
       .merge(merged[day_diff.between(-6,0)], on=['customer_id','purchase_date'])
       .rename(columns={'visit_dates_x': 'begin_date_range', 'visit_dates_y': 'end_date_range'}))

Output:

   customer_id purchase_date begin_date_range end_date_range
0            1    2021-05-14       2021-05-11     2021-05-16


问:
Are System.Generics.Collections TList<record> subject to memory fragmentation in Delphi?
In Delphi 10.4, I have a record that I use like this in a TList (System.Generics.Collections):

```<code>uses
    System.Generics.Collections;

type
    TSomething = record
        Name: String;
        Foo: String;
        Bar: String;
        Group: String;
        Flag1: Boolean;
        Flag2: Boolean;
        Flag3: Boolean;
        Flag4: Boolean;
        Flag5: Boolean;
    end;

    PTSomething = ^TSomething;

//Simplified code for readability...

var
    Something: TSomething;
    MyList := TList<TSomething>;
    lRecP: PTSomething;

MyList := TList<TSomething>.Create;

while ACondition do
begin
    Something.Name := 'Something';
    //Fill the rest of the record
    MyList.Add(Something); //Add is done in a while loop which result around 1000 items in MyList
end;

//Later...
for i := 0 to MyList.Count - 1 do
begin
    if ACondition then
    begin
        lRecP := @MyList.List[i];
        lRecP.Name := 'Modified'; //Items can be modified but never deleted
    end;
end;

//Later...
MyList.Free;
</code>```

Is my code prone to memory fragmentation? I have about 1000 records in my list that I will iterate through and maybe modify a string off the record once per record.

Would there be a better way to do what I want to do?

答:
Records lie in intrinsic dynamic array of TSomething. This array will be reallocated when you add new records and expanding is required. Memory manager cares about memory allocation, deallocation, it tries to minimize fragmentation. For list size of 1000 fragmentation should be negligible.
Dynamic array capacity changes rarely to avoid expensive operations of reallocation and to diminish fragmentation (more info in SilverWarior
comment)

You records contain strings. Strings are really pointers, and strings bodies are in another place of memory. Again - memory manager cares about string allocation/deallocation, it does this work well (applications with instant creation, treatment and deallocation of millions of strings work 24/7 many years).

So frequent changing of strings does not affect on the list body (intrinsic array) (until you add new records/ delete existing ones), and unlikely can cause memory fragmentation.

Body:
In Delphi 10.4, I have a record that I use like this in a TList (System.Generics.Collections):

uses
    System.Generics.Collections;

type
    TSomething = record
        Name: String;
        Foo: String;
        Bar: String;
        Group: String;
        Flag1: Boolean;
        Flag2: Boolean;
        Flag3: Boolean;
        Flag4: Boolean;
        Flag5: Boolean;
    end;

    PTSomething = ^TSomething;

//Simplified code for readability...

var
    Something: TSomething;
    MyList := TList<TSomething>;
    lRecP: PTSomething;

MyList := TList<TSomething>.Create;

while ACondition do
begin
    Something.Name := 'Something';
    //Fill the rest of the record
    MyList.Add(Something); //Add is done in a while loop which result around 1000 items in MyList
end;

//Later...
for i := 0 to MyList.Count - 1 do
begin
    if ACondition then
    begin
        lRecP := @MyList.List[i];
        lRecP.Name := 'Modified'; //Items can be modified but never deleted
    end;
end;

//Later...
MyList.Free;

Is my code prone to memory fragmentation? I have about 1000 records in my list that I will iterate through and maybe modify a string off the record once per record.

Would there be a better way to do what I want to do?


答:
Calculate maximum and minimum salary at the time of input, because you are taking input for only one time, so I think this solution will help you.</p>
```<code> import java.util.*;

class EmployeesDetails {
    System.out.println("Welcome Aboard!");
    Scanner emp = new Scanner(System.in);
    // add these parameters to hold min and max values for salary and employees
    float maxSalary = Float.MIN_VALUE;
    float minSalary = Float.MAX_VALUE;
    EmployeesDetails maxSalaryEmployee = null;
    EmployeesDetails minSalaryEmployee = null;
    List<EmployeesDetails> employeesDetails = new ArrayList<>();
    Boolean empQuestion = true;

    while (empQuestion == true) {
        System.out.println("Do you want to enter the employee details? Yes or No");
        String inputString = emp.next();
        empQuestion = inputString.equalsIgnoreCase("Yes") ? true : false;

        if (empQuestion == false) {
            System.out.println("Come again Later!");
            break;
        }

        System.out.println("Enter the employee name: ");
        String empName = emp.next();

        System.out.println("Enter the employee ID");
        String empID = emp.next();

        System.out.println("Enter the employee Phone number");
        String empPhoneNumber = emp.next();

        System.out.println("Enter the employee Salary");
        Float empSalary = emp.nextFloat();

        EmployeesDetails employee = new EmployeesDetails(empName, empID, empPhoneNumber, empSalary);
        employeesDetails.add(employee);
        // for max salary calculation
        if(employee.getEmpSalary() > maxSalary){
         maxSalary = employee.getEmpSalary();
         maxSalaryEmployee = employee;
        }
        // for min salary calculation
        if(employee.getEmpSalary() < minSalary){
         minSalary = employee.getEmpSalary();
         minSalaryEmployee = employee;
        }
        System.out.println(employeesDetails);
    }

        System.out.println("Max Salary Employee: " + maxSalaryEmployee);
        System.out.println("Min Salary Employee: " + minSalaryEmployee);
    emp.close();
}
</code>```

Title: How can I Calculate the maximum and minimum salary of the employees?

Body:
Calculate maximum and minimum salary at the time of input, because you are taking input for only one time, so I think this solution will help you.

 import java.util.*;

class EmployeesDetails {
    System.out.println("Welcome Aboard!");
    Scanner emp = new Scanner(System.in);
    // add these parameters to hold min and max values for salary and employees
    float maxSalary = Float.MIN_VALUE;
    float minSalary = Float.MAX_VALUE;
    EmployeesDetails maxSalaryEmployee = null;
    EmployeesDetails minSalaryEmployee = null;
    List<EmployeesDetails> employeesDetails = new ArrayList<>();
    Boolean empQuestion = true;

    while (empQuestion == true) {
        System.out.println("Do you want to enter the employee details? Yes or No");
        String inputString = emp.next();
        empQuestion = inputString.equalsIgnoreCase("Yes") ? true : false;

        if (empQuestion == false) {
            System.out.println("Come again Later!");
            break;
        }

        System.out.println("Enter the employee name: ");
        String empName = emp.next();

        System.out.println("Enter the employee ID");
        String empID = emp.next();

        System.out.println("Enter the employee Phone number");
        String empPhoneNumber = emp.next();

        System.out.println("Enter the employee Salary");
        Float empSalary = emp.nextFloat();

        EmployeesDetails employee = new EmployeesDetails(empName, empID, empPhoneNumber, empSalary);
        employeesDetails.add(employee);
        // for max salary calculation
        if(employee.getEmpSalary() > maxSalary){
         maxSalary = employee.getEmpSalary();
         maxSalaryEmployee = employee;
        }
        // for min salary calculation
        if(employee.getEmpSalary() < minSalary){
         minSalary = employee.getEmpSalary();
         minSalaryEmployee = employee;
        }
        System.out.println(employeesDetails);
    }

        System.out.println("Max Salary Employee: " + maxSalaryEmployee);
        System.out.println("Min Salary Employee: " + minSalaryEmployee);
    emp.close();
}


问:
iCal.Net events working fine in Gmail but not for Outlook
I am using iCal.Net to send meeting invitations. It's working fine on Gmail and it's showing me event like:

But on Outlook it's not showing me any invite like accept, tentative, and decline options. It's showing me like:

It should be shown like this:

Here is my code:

```<code>async Task<SendResponse> CreateCalendarEventAsync(
        CalendarNotificationModel calendarNotificationModel)
{
var attendees = calendarNotificationModel.Attendees.Select(x => new
Ical.Net.DataTypes.Attendee()
{
    CommonName = x.AttendeeName,
    ParticipationStatus = "REQ-PARTICIPANT",
    Rsvp = true,
    Role = "REQ-PARTICIPANT",
    Value = new Uri($"mailto:{x.AttendeeEmail}")
}).ToList();

var e = new CalendarEvent
{
    Summary = calendarNotificationModel.Name,
    IsAllDay = true,

    Organizer = new Organizer()
    {
        CommonName = "HRMatrix",
        Value = new Uri("mailto:xyz@zxy.com")
    },
    Attendees = attendees,
    Status = "Confirmed",
    Sequence = 0,
    Start = new CalDateTime(calendarNotificationModel.StartDateTime),
    End = new CalDateTime(calendarNotificationModel.EndDateTime),
    Transparency = TransparencyType.Opaque,
    Location = calendarNotificationModel.Location,
    Description = calendarNotificationModel.Description
};

var calendar = new Calendar();
calendar.AddProperty("X-MS-OLK-FORCEINSPECTOROPEN", "TRUE");
calendar.AddProperty("METHOD", "REQUEST");

calendar.Events.Add(e);

var serializer = new CalendarSerializer();
var serializedCalendar = serializer.SerializeToString(calendar);

var bytesCalendar = Encoding.ASCII.GetBytes(serializedCalendar);
MemoryStream ms = new MemoryStream(bytesCalendar);
using (ms)
{
    ms.Position = 0;

    SmtpClient smtp = new SmtpClient
    {
        //The address of the SMTP server (I'll take mailbox 126 as an example, which can
be set according to the specific mailbox you use)
        Host = "smtp.gmail.com",
        EnableSsl = true,
        Port = 587,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        //Enter the user name and password of your sending SMTP server here
        Credentials  = new NetworkCredential("xyz@xyz", "sdfsdfsdfsdf")
    };
    //Set default sending information
    Email.DefaultSender = new SmtpSender(smtp);
    var email = Email
        //Sender
        .From("xyz@xyz")
        //Addressee
        .To("denis@org.com")
        //Message title
        .Subject("Interview")
        //Email content
        .Body("You are invited.");
    //Determine whether the transmission is successful according to the transmission
 result

    var attachment = new FluentEmail.Core.Models.Attachment
    {
        Data = ms,
        ContentType = "text/calendar",
        Filename = "invite.ics",
    };
    email.Attach(attachment);

    var result = email.Send();
    //Or send it asynchronously
    //await email.SendAsync();

    return result;
}
</code>```

}

Here is my .ics file:

```<code> BEGIN:VCALENDAR
 METHOD:Request
 PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN
 VERSION:2.0
 X-MS-OLK-FORCEINSPECTOROPEN:TRUE
 BEGIN:VEVENT
 ATTENDEE;CN=XYZ;PARTSTAT=REQ-PARTICIPANT;RSVP=TRUE;ROLE=REQ-PARTICIPA
  NT:mailto:XYZ@hotmail.com
 DESCRIPTION:You are invited to give an interview
 DTEND:20220208T091006
 DTSTAMP:20220207T181006Z
 DTSTART:20220208T041006
 LOCATION:Pakistan
 ORGANIZER;CN=HRMatrix:mailto:xyz@gmail.com
 SEQUENCE:0
 STATUS:Confirmed
 SUMMARY:XYZ
 TRANSP:OPAQUE
 UID:b2ddc1ef-a2e4-4b0e-afa0-27d9689fbsdf
 END:VEVENT
 END:VCALENDAR
</code>```

PS: if I send the above .ics file from Gmail client it works but it does not work from my SMTP client.

答: Hi you can try adding attachment charset to "charset=UTF-8" when sending an email or 'mime' => 'text/calendar; method=REQUEST; charset=UTF-8'.</p>

Body:
I am using iCal.Net to send meeting invitations. It's working fine on Gmail and it's showing me event like:

But on Outlook it's not showing me any invite like accept, tentative, and decline options. It's showing me like:

It should be shown like this:

Here is my code:

async Task<SendResponse> CreateCalendarEventAsync(
        CalendarNotificationModel calendarNotificationModel)
{
var attendees = calendarNotificationModel.Attendees.Select(x => new
Ical.Net.DataTypes.Attendee()
{
    CommonName = x.AttendeeName,
    ParticipationStatus = "REQ-PARTICIPANT",
    Rsvp = true,
    Role = "REQ-PARTICIPANT",
    Value = new Uri($"mailto:{x.AttendeeEmail}")
}).ToList();

var e = new CalendarEvent
{
    Summary = calendarNotificationModel.Name,
    IsAllDay = true,

    Organizer = new Organizer()
    {
        CommonName = "HRMatrix",
        Value = new Uri("mailto:xyz@zxy.com")
    },
    Attendees = attendees,
    Status = "Confirmed",
    Sequence = 0,
    Start = new CalDateTime(calendarNotificationModel.StartDateTime),
    End = new CalDateTime(calendarNotificationModel.EndDateTime),
    Transparency = TransparencyType.Opaque,
    Location = calendarNotificationModel.Location,
    Description = calendarNotificationModel.Description
};

var calendar = new Calendar();
calendar.AddProperty("X-MS-OLK-FORCEINSPECTOROPEN", "TRUE");
calendar.AddProperty("METHOD", "REQUEST");

calendar.Events.Add(e);

var serializer = new CalendarSerializer();
var serializedCalendar = serializer.SerializeToString(calendar);

var bytesCalendar = Encoding.ASCII.GetBytes(serializedCalendar);
MemoryStream ms = new MemoryStream(bytesCalendar);
using (ms)
{
    ms.Position = 0;

    SmtpClient smtp = new SmtpClient
    {
        //The address of the SMTP server (I'll take mailbox 126 as an example, which can
be set according to the specific mailbox you use)
        Host = "smtp.gmail.com",
        EnableSsl = true,
        Port = 587,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        //Enter the user name and password of your sending SMTP server here
        Credentials  = new NetworkCredential("xyz@xyz", "sdfsdfsdfsdf")
    };
    //Set default sending information
    Email.DefaultSender = new SmtpSender(smtp);
    var email = Email
        //Sender
        .From("xyz@xyz")
        //Addressee
        .To("denis@org.com")
        //Message title
        .Subject("Interview")
        //Email content
        .Body("You are invited.");
    //Determine whether the transmission is successful according to the transmission
 result

    var attachment = new FluentEmail.Core.Models.Attachment
    {
        Data = ms,
        ContentType = "text/calendar",
        Filename = "invite.ics",
    };
    email.Attach(attachment);

    var result = email.Send();
    //Or send it asynchronously
    //await email.SendAsync();

    return result;
}

}

Here is my .ics file:

 BEGIN:VCALENDAR
 METHOD:Request
 PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN
 VERSION:2.0
 X-MS-OLK-FORCEINSPECTOROPEN:TRUE
 BEGIN:VEVENT
 ATTENDEE;CN=XYZ;PARTSTAT=REQ-PARTICIPANT;RSVP=TRUE;ROLE=REQ-PARTICIPA
  NT:mailto:XYZ@hotmail.com
 DESCRIPTION:You are invited to give an interview
 DTEND:20220208T091006
 DTSTAMP:20220207T181006Z
 DTSTART:20220208T041006
 LOCATION:Pakistan
 ORGANIZER;CN=HRMatrix:mailto:xyz@gmail.com
 SEQUENCE:0
 STATUS:Confirmed
 SUMMARY:XYZ
 TRANSP:OPAQUE
 UID:b2ddc1ef-a2e4-4b0e-afa0-27d9689fbsdf
 END:VEVENT
 END:VCALENDAR

PS: if I send the above .ics file from Gmail client it works but it does not work from my SMTP client.


问:
C# threads and backgroundworker problem
In my main thread I run Backgroundworker. His todo work is method that Invoke "Method" from main thread. When I wish to cancel my backgroundworker it stops running but "Method" invoked on mainthread still run what cause problems. Any idea how to solve it?</p>

答:
Besides checking for CancellationPending, you need set the Cancel property on the DoWorkEventArgs argument.

Then, in the RunWorkerCompleted event, you can query the RunWorkerCompletedEventArgs's Cancelled property that will reflect the value you set in DoWorkEventArgs.

Now you may ask why the BackgroundWorker does not set these properties by itself whenever the operation is cancelled externally. The reason is that it does not know if your DoWorkEventArgs actually checked if it was cancelled. DoWorkEventArgs could have missed it and completed successfully. This is important because it could have caused side effects (like a database update) and you may need to know if it was actually done or not.

Title: C# threads and backgroundworker problem


问:
WebSphere 9 ND node agent stopped and the applications are still working. How/why?
This is WebSphere 9 ND. I've stopped the node agent and the serverStatus.sh script reports that it is down:  ADMU0509I: The Node Agent "nodeagent" cannot be reached. Why are the applications still authenticating and appear to be working?</p>

答:
See this article explaining the basic concepts of IBM Websphere application server Network Deployment.

node agent

A node agent manages all managed processes on a WebSphere Application Server on a node by communicating with the Network Deployment Manager to coordinate and synchronize the configuration. A node agent performs management operations on behalf of the Network Deployment Manager. The node agent represents the node in the management cell. Node agents are installed with WebSphere Application Server base, but are not required until the node is added to a cell in a Network Deployment environment.

application server

The application server is the primary component of WebSphere. The server runs a Java™ virtual machine, providing the runtime environment for the application's code. The application server provides containers that specialize in enabling the execution of specific Java application components.

Apps are deployed into the Application server and not to the nodeagent. The role of the node agent is to perform management operations on behalf of Deployment Manager.

So, if the nodeagent is stopped, you will only loose the ability to manage the servers running under that node and it will not stop already running application
servers or applications deployed to servers in that node.

You can validate this by grepping the server name (eg:server1) from the list of all running processes:

```<code> ps -ef | grep java | grep servername
</code>```

Sample output (for an app server) is given below:

```<code>wasadmin  12345 98765  2 13:18 pts/0    00:04:57 /opt/ibm/WebSphere/AppServer/java/8.0/bin/java -Dosgi.install.area=/opt/ibm/WebSphere/AppServer <collapsed text> cellname nodename servername
</code>```

where:

wasadmin - is the os username running the application server on that
node

12345 - is the pid of the application server running on that node.

98765 - is the pid of the parent process (nodeagent). This will be
"1" if the nodeagent is stopped

Body:
See this article explaining the basic concepts of IBM Websphere application server Network Deployment.

node agent

A node agent manages all managed processes on a WebSphere Application Server on a node by communicating with the Network Deployment Manager to coordinate and synchronize the configuration. A node agent performs management operations on behalf of the Network Deployment Manager. The node agent represents the node in the management cell. Node agents are installed with WebSphere Application Server base, but are not required until the node is added to a cell in a Network Deployment environment.

application server

The application server is the primary component of WebSphere. The server runs a Java™ virtual machine, providing the runtime environment for the application's code. The application server provides containers that specialize in enabling the execution of specific Java application components.

Apps are deployed into the Application server and not to the nodeagent. The role of the node agent is to perform management operations on behalf of Deployment Manager.

So, if the nodeagent is stopped, you will only loose the ability to manage the servers running under that node and it will not stop already running application
servers or applications deployed to servers in that node.

You can validate this by grepping the server name (eg:server1) from the list of all running processes:

 ps -ef | grep java | grep servername

Sample output (for an app server) is given below:

wasadmin  12345 98765  2 13:18 pts/0    00:04:57 /opt/ibm/WebSphere/AppServer/java/8.0/bin/java -Dosgi.install.area=/opt/ibm/WebSphere/AppServer <collapsed text> cellname nodename servername

where:

wasadmin - is the os username running the application server on that
node

12345 - is the pid of the application server running on that node.

98765 - is the pid of the parent process (nodeagent). This will be
"1" if the nodeagent is stopped


问:
TypeScript: get a property from conditional types
I'm trying to get a value that either can exist or not on the property. So I have 2 types: EmptyUser and UserResponse.

EmptyUser interface only has one property.
UserResponse interface has a lot of properties AND id property that I need.

Then in my function I'm trying to use id, but I can't get it from the created types. Below is the example of code:

```<code>interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = EmptyUser | UserResponse;

interface State {
  users: UsersType,
}
</code>```

then in my code I'm trying to get property id from state.users:

```<code>const { id }: UsersType = state.users;
</code>```

and I receive an error: TS2339: Property 'id' does not exist on type 'UsersType'.

I would appreciate any help.

答:
With | you are saying that UsersType can be any one of EmptyUser or UserResponse. So id can not be guaranteed to be in UsersType.

If you do it individually, with either one of the types you will not have an issue. Link

```<code>interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = UserResponse;

interface State {
  users: UsersType,
}

let state : State = {
  users : {
    id : 2
  }
};

const { id }: UsersType = state.users;
</code>```

But if you want an item to have properties from both, you need & intersection type.

```<code>interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = EmptyUser & UserResponse;

interface State {
  users: UsersType,
}

let state : State = {
  users : {
    id : 2,
    unauthorized : false
  }
};

const { id }: UsersType = state.users;
</code>```

Playground Link

Body:
I'm trying to get a value that either can exist or not on the property. So I have 2 types: EmptyUser and UserResponse.

EmptyUser interface only has one property.
UserResponse interface has a lot of properties AND id property that I need.

Then in my function I'm trying to use id, but I can't get it from the created types. Below is the example of code:

interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = EmptyUser | UserResponse;

interface State {
  users: UsersType,
}

then in my code I'm trying to get property id from state.users:

const { id }: UsersType = state.users;

and I receive an error: TS2339: Property 'id' does not exist on type 'UsersType'.

I would appreciate any help.

Body:
With | you are saying that UsersType can be any one of EmptyUser or UserResponse. So id can not be guaranteed to be in UsersType.

If you do it individually, with either one of the types you will not have an issue. Link

interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = UserResponse;

interface State {
  users: UsersType,
}

let state : State = {
  users : {
    id : 2
  }
};

const { id }: UsersType = state.users;

But if you want an item to have properties from both, you need & intersection type.

interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = EmptyUser & UserResponse;

interface State {
  users: UsersType,
}

let state : State = {
  users : {
    id : 2,
    unauthorized : false
  }
};

const { id }: UsersType = state.users;

Playground Link