问:
Error running pod install - Automatically assigning platform `iOS` with version `8.0` on target `Runner`
Hello I am not able to solve this problem with Cocoapods anyone can help me is the first time I am using this import-  import 'package:flutter_vlc_player/flutter_vlc_player.Dart'; and not what might be wrong.

(I’m using android studio on mac)

ERROR:

Launching lib/main.dart on iPhone 11 in debug mode...
Running pod install...                                              1,3s
CocoaPods' output:
↳
      Preparing

```<code>Analyzing dependencies

Inspecting targets to integrate
  Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)

Fetching external sources
-> Fetching podspec for `Flutter` from `Flutter`
-> Fetching podspec for `flutter_vlc_player` from `.symlinks/plugins/flutter_vlc_player/ios`

Resolving dependencies of `Podfile`
  CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only perfomed in repo update
[!] CocoaPods could not find compatible versions for pod "flutter_vlc_player":
  In Podfile:
    flutter_vlc_player (from `.symlinks/plugins/flutter_vlc_player/ios`)

Specs satisfying the `flutter_vlc_player (from `.symlinks/plugins/flutter_vlc_player/ios`)` dependency were found, but they required a higher minimum deployment target.

/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:328:in `raise_error_unless_state'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:310:in `block in unwind_for_conflict'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `tap'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `unwind_for_conflict'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:684:in `attempt_to_activate'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:254:in `process_topmost_state'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:182:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolver.rb:43:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/resolver.rb:94:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:1065:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:1063:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:124:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:410:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:235:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:234:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:156:in `install!'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command/install.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `<main>'
</code>```

Error output from CocoaPods:
↳

```<code>[!] Automatically assigning platform `iOS` with version `8.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
</code>```

Error running pod install
Error launching application on iPhone 11.

答:
Open [YourProject]/ios/Podfile and remove the # sign from platform :ios, '9.0' and try flutter run.
If it doesn't work increase the version number for example to 10.0

Body:
Hello I am not able to solve this problem with Cocoapods anyone can help me is the first time I am using this import-  import 'package:flutter_vlc_player/flutter_vlc_player.Dart'; and not what might be wrong.

(I’m using android studio on mac)

ERROR:

Launching lib/main.dart on iPhone 11 in debug mode...
Running pod install...                                              1,3s
CocoaPods' output:
↳
      Preparing

Analyzing dependencies

Inspecting targets to integrate
  Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)

Fetching external sources
-> Fetching podspec for `Flutter` from `Flutter`
-> Fetching podspec for `flutter_vlc_player` from `.symlinks/plugins/flutter_vlc_player/ios`

Resolving dependencies of `Podfile`
  CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only perfomed in repo update
[!] CocoaPods could not find compatible versions for pod "flutter_vlc_player":
  In Podfile:
    flutter_vlc_player (from `.symlinks/plugins/flutter_vlc_player/ios`)

Specs satisfying the `flutter_vlc_player (from `.symlinks/plugins/flutter_vlc_player/ios`)` dependency were found, but they required a higher minimum deployment target.

/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:328:in `raise_error_unless_state'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:310:in `block in unwind_for_conflict'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `tap'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `unwind_for_conflict'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:684:in `attempt_to_activate'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:254:in `process_topmost_state'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:182:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolver.rb:43:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/resolver.rb:94:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:1065:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:1063:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:124:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:410:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:235:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:234:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:156:in `install!'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command/install.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `'

Error output from CocoaPods:
↳

[!] Automatically assigning platform `iOS` with version `8.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

Error running pod install
Error launching application on iPhone 11.


来源: stackexchange

问:
Overlay text using FFmpeg command in android programmatically
I need to know what is the issue with my FFmpeg command for overlaying text to a video in android.

```<code> command = new String[]{"ffmpeg", "-i",  original_path,  "-vf", "drawtext=text='SiteName.local': fontsize=18: fontcolor=white: x=10:y=h-th-10", "-acodec", "copy", "-y",  dest.getAbsolutePath()};
</code>```

I am trying to create a video with a text overlay. However, i'm getting an error

```<code> [NULL @ 0xea699600] Unable to find a suitable output format for 'ffmpeg'
    ffmpeg: Invalid argument
</code>```

I have tested for the input file and output file using different command for trimming videos and it worked. However, the FFmpeg command for overlaying text does not work. I kindly ask for help.

Besides, i also need to know how i can animate the text to scroll from left to right, bounce using FFmpeg commands in android etc

答:
Finally i managed solving the issue over a long search. Drawtext can't work without including the fontfile. So the below code is what managed to settle my scores</p>

```<code>command = new String[]{"-i",  original_path,  "-vf", "drawtext=fontfile=/system/fonts/DroidSans.ttf:text='SiteName hulluway':fontsize=40:fontcolor=black: x=w-(t-4.5)*(w+tw)/5.5:y=100", "-acodec", "copy", "-y",  dest.getAbsolutePath()};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to know what is the issue with my FFmpeg command for overlaying text to a video in android.

 command = new String[]{"ffmpeg", "-i",  original_path,  "-vf", "drawtext=text='SiteName.local': fontsize=18: fontcolor=white: x=10:y=h-th-10", "-acodec", "copy", "-y",  dest.getAbsolutePath()};

I am trying to create a video with a text overlay. However, i'm getting an error

 [NULL @ 0xea699600] Unable to find a suitable output format for 'ffmpeg'
    ffmpeg: Invalid argument

I have tested for the input file and output file using different command for trimming videos and it worked. However, the FFmpeg command for overlaying text does not work. I kindly ask for help.

Besides, i also need to know how i can animate the text to scroll from left to right, bounce using FFmpeg commands in android etc

Body:
Finally i managed solving the issue over a long search. Drawtext can't work without including the fontfile. So the below code is what managed to settle my scores

command = new String[]{"-i",  original_path,  "-vf", "drawtext=fontfile=/system/fonts/DroidSans.ttf:text='SiteName hulluway':fontsize=40:fontcolor=black: x=w-(t-4.5)*(w+tw)/5.5:y=100", "-acodec", "copy", "-y",  dest.getAbsolutePath()};


问:
Check if a string defines a color
I'm looking for a way to check if a string defines a color since my program relies on users inputting colors and it breaks when they enter a wrong color. How can I do this? Here are some examples:</p>

```<code>check_color("blue") > True
check_color("deep sky blue") > True
check_color("test") > False
check_color("#708090") > True
</code>```

答: in tkinter: widget.winfo_rgb('color')

ContentLicense: CC BY-SA 3.0

Title: Check if a string defines a color

Body:
I'm looking for a way to check if a string defines a color since my program relies on users inputting colors and it breaks when they enter a wrong color. How can I do this? Here are some examples:

check_color("blue") > True
check_color("deep sky blue") > True
check_color("test") > False
check_color("#708090") > True

Body: in tkinter: widget.winfo_rgb('color')


问:
Why is parameter to string.indexOf method is an int in Java
I am wondering why the parameter to indexOf method an int , when the description says a char.

public int indexOf(int ch)

```<code>Returns the index within this string of the first occurrence of the specified **character**
</code>```

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#indexOf%28int%29

```<code>Also, both of these compiles fine:
char c = 'p';
str.indexOf(2147483647);
str.indexOf(c);
</code>```

a]Basically, what I am confused about is int in java is 32bit , while unicode characters are 16 bits .

b]Why not use the character themselves rather than using int . Is this any performance optimization ?. Are chars difficult to represent than int ? How ?

I assume this should be simple reasoning for this and that makes me know about it even more !

Thanks!

答:
Java has a whole slew of implicit typecasting rules being carried out under the hood. For primitives, there are special rules, which are all outlined in the document Conversions and Promotions, part of Sun's Java documentation. For your specific question, the conversion of int to char is a "narrowing primitive conversion." See section 5.1.3 in the above document.

That being said, it's a common programming practice to interchange small positive integers and characters which are encoded as integers. This goes back to their use indistinguishable use in C, when ASCII was all that existed.

Body:
I am wondering why the parameter to indexOf method an int , when the description says a char.

public int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified **character**

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#indexOf%28int%29

Also, both of these compiles fine:
char c = 'p';
str.indexOf(2147483647);
str.indexOf(c);

a]Basically, what I am confused about is int in java is 32bit , while unicode characters are 16 bits .

b]Why not use the character themselves rather than using int . Is this any performance optimization ?. Are chars difficult to represent than int ? How ?

I assume this should be simple reasoning for this and that makes me know about it even more !

Thanks!


问:
how to turn a for loop with if statement working on datetime df into a list comprehension
I am trying to  turn the below for loop with if statement into a list comprehension.

```<code># Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1
</code>```

I tried

```<code>[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]
</code>```

but I keep getting a syntaxerror

答:
You can use a list comprehension (really, just a generator expression), but not in the way you are thinking. Build a generator of AMs and PMs, then use that to build a Counter instance.

```<code>from collections import Counter

trip_counts = Counter(("AM" if trip['start'].hour < 12 else "PM")
                       for trip in onebike_datetimes)
</code>```

A self-contained demonstration:

```<code>from collections import Counter
from types import SimpleNamespace

onebike_datetimes = [
    {'start': SimpleNamespace(hour=9)},
    {'start': SimpleNamespace(hour=3)},
    {'start': SimpleNamespace(hour=14)},
    {'start': SimpleNamespace(hour=19)},
    {'start': SimpleNamespace(hour=7)},
    ]

trip_counts = Counter(("AM" if trip['start'].hour < 12 else "PM")
                       for trip in onebike_datetimes)

assert trip_counts["AM"] == 3
assert trip_counts["PM"] == 2
</code>```

Body:
I am trying to  turn the below for loop with if statement into a list comprehension.

# Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1

I tried

[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]

but I keep getting a syntaxerror

Body:
You can use a list comprehension (really, just a generator expression), but not in the way you are thinking. Build a generator of AMs and PMs, then use that to build a Counter instance.

from collections import Counter

trip_counts = Counter(("AM" if trip['start'].hour < 12 else "PM")
                       for trip in onebike_datetimes)

A self-contained demonstration:

from collections import Counter
from types import SimpleNamespace

onebike_datetimes = [
    {'start': SimpleNamespace(hour=9)},
    {'start': SimpleNamespace(hour=3)},
    {'start': SimpleNamespace(hour=14)},
    {'start': SimpleNamespace(hour=19)},
    {'start': SimpleNamespace(hour=7)},
    ]

trip_counts = Counter(("AM" if trip['start'].hour < 12 else "PM")
                       for trip in onebike_datetimes)

assert trip_counts["AM"] == 3
assert trip_counts["PM"] == 2


问:
OpenCV resize substantially different results between python and javascript
I'm currently working on a project dealing with thermal imagery and am having to do some resizing of the resulting image. I'm currently resizing in javascript (after sending data from web server), and this works really well, unfortunately a new requirement means I'm having to move this resizing over to the web server, using python.

I've done this, but when i'm resizing i'm now getting a 'triple overlapping image', which I don't get in the javascript side (see screenshot)

Python (Working Version)

```<code>nparr = np.frombuffer(temps, dtype=np.float32)
temparr = np.copy(nparr)
temparr *= (1.0/temparr.max())
// array comes in single dimension, reshapre to (width,height)
temps = temparr.reshape(int(temp_frame["width"]), int(temp_frame["height"]))
 socketio.emit("thermal_image", {'data':b''+bytearray(temps),'width':temps.shape[0], 'height':temps.shape[1]}, broadcast=True)

</code>```

Javascript (Working Version)

```<code>let bytes = new Float32Array(msg.data);
let width = msg.width;
let height = msg.height;
var mat = cv.matFromArray(height, width, cv.CV_32FC1, bytes);
let dst_mat = new cv.Mat();
let dsize = new cv.Size(1000,1000);
cv.resize(mat, dst_mat, dsize,0,0,cv.INTER_AREA);
cv.imshow(canvas_name, dst_mat);
</code>```

And the new python code, alongside the javascript used to display
Python (Not working version)

```<code>nparr = np.frombuffer(temps, dtype=np.float32)
temparr = np.copy(nparr)
temparr *= (1.0/temparr.max())
temps = temparr.reshape(int(temp_frame["width"]), int(temp_frame["height"]))
resized_temps = np.zeros((1000,1000), np.float32)
cv2.resize(temps, dsize=(1000,1000), dst=resized_temps, fx=0, fy=0,interpolation=cv2.INTER_AREA)
socketio.emit("thermal_image", {'data':b''+bytearray(resized_temps),
   'width':resized_temps.shape[0],
   'height':resized_temps.shape[1]},
   broadcast=True)
</code>```

Javascript (Not Working Version)

```<code>let bytes = new Float32Array(msg.data);
let width = msg.width;
let height = msg.height;
var mat = cv.matFromArray(height, width, cv.CV_32FC1, bytes);
cv.imshow(canvas_name, dst_mat);
</code>```

As you can see the only difference is the resize being either in the javascript or the python, and yet the results are between really good, and pretty much useless.
I know this is something i'm doing wrong but can't for the life of me figure it out.

The images are of the same person, slightly different poses. The second image is using the python, movement can still be seen, and if positioned correctly the object in the scene can be seen.. 3 times.

EDIT: Changed images to clearer ones

答:
Silly bug but in case anyone else comes across it after a sleepless time like me i'll post the answer:

I was receiving in the data a flattened byte array, then reshaping to the shape (width, height). This worked fine when doing the resize in javascript as I sent again the flattened array to javascript and the resize was done (height,width). Which is how opencv takes its values.

When moving to python I forgot to change the reshape to (height, width) and instead was keeping (width,height). So when opencv did the resize we were interpolating in the wrong directions, resulting in the lines and the duplicate images.

So Solution,

change line
temps = temparr.reshape(int(temp_frame["width"]), int(temp_frame["height"]))
temps = temparr.reshape(int(temp_frame["height"]), int(temp_frame["width"]))

and voila, opencv plays nice

Body:
I'm currently working on a project dealing with thermal imagery and am having to do some resizing of the resulting image. I'm currently resizing in javascript (after sending data from web server), and this works really well, unfortunately a new requirement means I'm having to move this resizing over to the web server, using python.

I've done this, but when i'm resizing i'm now getting a 'triple overlapping image', which I don't get in the javascript side (see screenshot)

Python (Working Version)

nparr = np.frombuffer(temps, dtype=np.float32)
temparr = np.copy(nparr)
temparr *= (1.0/temparr.max())
// array comes in single dimension, reshapre to (width,height)
temps = temparr.reshape(int(temp_frame["width"]), int(temp_frame["height"]))
 socketio.emit("thermal_image", {'data':b''+bytearray(temps),'width':temps.shape[0], 'height':temps.shape[1]}, broadcast=True)

Javascript (Working Version)

let bytes = new Float32Array(msg.data);
let width = msg.width;
let height = msg.height;
var mat = cv.matFromArray(height, width, cv.CV_32FC1, bytes);
let dst_mat = new cv.Mat();
let dsize = new cv.Size(1000,1000);
cv.resize(mat, dst_mat, dsize,0,0,cv.INTER_AREA);
cv.imshow(canvas_name, dst_mat);

And the new python code, alongside the javascript used to display
Python (Not working version)

nparr = np.frombuffer(temps, dtype=np.float32)
temparr = np.copy(nparr)
temparr *= (1.0/temparr.max())
temps = temparr.reshape(int(temp_frame["width"]), int(temp_frame["height"]))
resized_temps = np.zeros((1000,1000), np.float32)
cv2.resize(temps, dsize=(1000,1000), dst=resized_temps, fx=0, fy=0,interpolation=cv2.INTER_AREA)
socketio.emit("thermal_image", {'data':b''+bytearray(resized_temps),
   'width':resized_temps.shape[0],
   'height':resized_temps.shape[1]},
   broadcast=True)

Javascript (Not Working Version)

let bytes = new Float32Array(msg.data);
let width = msg.width;
let height = msg.height;
var mat = cv.matFromArray(height, width, cv.CV_32FC1, bytes);
cv.imshow(canvas_name, dst_mat);

As you can see the only difference is the resize being either in the javascript or the python, and yet the results are between really good, and pretty much useless.
I know this is something i'm doing wrong but can't for the life of me figure it out.

The images are of the same person, slightly different poses. The second image is using the python, movement can still be seen, and if positioned correctly the object in the scene can be seen.. 3 times.

EDIT: Changed images to clearer ones


问:
Sum values in a list of lists of dictionaries using common key-value pairs
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

```<code>data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]
</code>```

Expected output:

```<code>op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]
</code>```

答:
This should work:

from collections import defaultdict

data_without_duplicates = []
for l in data:
    users_ratings = defaultdict(int)
    for d in l:
        users_ratings[d["user"]] += d["rating"]
    data_without_duplicates.append(
        [{"user": user, "rating": rating} for user, rating in users_ratings.items()]
    )
```

Body:
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

Expected output:

op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]


问:
How to read a text file from HDFS in Scala natively (without using Spark)?
I know I can read a local file in Scala like so:

```<code>import scala.io.Source

val filename = "laba01/ml-100k/u.data"

for(line <- Source.fromFile(filename).getLines){
    println(line)
}
</code>```

This code words fine and prints out the lines from the text file. I run it in JupyterHub with Apache Toree.

I know I can read from HDFS at this server, because when I run the next code in another cell:

```<code>import sys.process._
"hdfs dfs -ls /labs/laba01/ml-100k/u.data"!
</code>```

it works fine too, and I can see this output:

```<code>-rw-r--r--   3 hdfs hdfs    1979173 2020-04-20 17:56 /labs/laba01/ml-100k/u.data

lastException: Throwable = null
warning: there was one feature warning; re-run with -feature for details

0
</code>```

Now I want to read this same file kept in HDFS by running this:

```<code>import scala.io.Source

val filename = "hdfs:/labs/laba01/ml-100k/u.data"

for(line <- Source.fromFile(filename).getLines){
    println(line)
}
</code>```

but I get this output instead of the file's lines printed out:

```<code>lastException = null

Name: java.io.FileNotFoundException
Message: hdfs:/labs/laba01/ml-100k/u.data (No such file or directory)
StackTrace:   at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.<init>(FileInputStream.java:138)
  at scala.io.Source$.fromFile(Source.scala:91)
  at scala.io.Source$.fromFile(Source.scala:76)
  at scala.io.Source$.fromFile(Source.scala:54)
</code>```

So how do I read this text file from HDFS?

答:
scala.io will not able to find any file in HDFS. It's not for that. If I'm not wrong it can only read file that are in your local (file:///)

You need to use hadoop-common.jar to read the data from HDFS.

You can find code example here
https://stackoverflow.com/a/41616512/7857701

Body:
I know I can read a local file in Scala like so:

import scala.io.Source

val filename = "laba01/ml-100k/u.data"

for(line <- Source.fromFile(filename).getLines){
    println(line)
}

This code words fine and prints out the lines from the text file. I run it in JupyterHub with Apache Toree.

I know I can read from HDFS at this server, because when I run the next code in another cell:

import sys.process._
"hdfs dfs -ls /labs/laba01/ml-100k/u.data"!

it works fine too, and I can see this output:

-rw-r--r--   3 hdfs hdfs    1979173 2020-04-20 17:56 /labs/laba01/ml-100k/u.data

lastException: Throwable = null
warning: there was one feature warning; re-run with -feature for details

0

Now I want to read this same file kept in HDFS by running this:

import scala.io.Source

val filename = "hdfs:/labs/laba01/ml-100k/u.data"

for(line <- Source.fromFile(filename).getLines){
    println(line)
}

but I get this output instead of the file's lines printed out:

lastException = null

Name: java.io.FileNotFoundException
Message: hdfs:/labs/laba01/ml-100k/u.data (No such file or directory)
StackTrace:   at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.<init>(FileInputStream.java:138)
  at scala.io.Source$.fromFile(Source.scala:91)
  at scala.io.Source$.fromFile(Source.scala:76)
  at scala.io.Source$.fromFile(Source.scala:54)

So how do I read this text file from HDFS?


问:
How to generate filtered list using reselect redux based on static filtered values?
I am fetching news data from an API, in the app I need to show 3 lists. today news, yesterday news, article news.

I think I should use redux reselect. However, all the examples I am visiting has a dynamic filter value (state filter) while I need data to be fileted statically (no state changes these filters)

my state at the moment is

```<code>{news : [] }
</code>```

How can I generate something like below using reselect

```<code>{news: [], todayNews:[], yesterdayNews:[], articleNews: []}
</code>```

should I use reselect or I should just filter inside a component? I think reselect is memorized so I prefer to use reselect for performance

答:
You can do something like the following:

const { createSelector } = Reselect;
const state = {
  news: [
    { id: 1, name: 'one' },
    { id: 2, name: 'two' },
    { id: 3, name: 'three' },
  ],
};
const selectNews = (state) => state.news;
const selectOdds = createSelector(selectNews, (news) =>
  news.filter(({ id }) => id % 2 !== 0)
);
const selectEvens = createSelector(selectNews, (news) =>
  news.filter(({ id }) => id % 2 === 0)
);
const selectFilteredNews = createSelector(
  selectNews,
  selectEvens,
  selectOdds,
  (news, even, odd) => ({ news, even, odd })
);
const news = selectFilteredNews(state);
console.log('news:', JSON.stringify(news, undefined, 2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>

<div id="root"></div></code>```

You use selectors when you need to calculate values based on state such as the total of a list or filtered things from a list. This way you don't need to duplicate the data in your state.

Body:
I am fetching news data from an API, in the app I need to show 3 lists. today news, yesterday news, article news.

I think I should use redux reselect. However, all the examples I am visiting has a dynamic filter value (state filter) while I need data to be fileted statically (no state changes these filters)

my state at the moment is

{news : [] }

How can I generate something like below using reselect

{news: [], todayNews:[], yesterdayNews:[], articleNews: []}

should I use reselect or I should just filter inside a component? I think reselect is memorized so I prefer to use reselect for performance

Body:
You can do something like the following:

const { createSelector } = Reselect;
const state = {
  news: [
    { id: 1, name: 'one' },
    { id: 2, name: 'two' },
    { id: 3, name: 'three' },
  ],
};
const selectNews = (state) => state.news;
const selectOdds = createSelector(selectNews, (news) =>
  news.filter(({ id }) => id % 2 !== 0)
);
const selectEvens = createSelector(selectNews, (news) =>
  news.filter(({ id }) => id % 2 === 0)
);
const selectFilteredNews = createSelector(
  selectNews,
  selectEvens,
  selectOdds,
  (news, even, odd) => ({ news, even, odd })
);
const news = selectFilteredNews(state);
console.log('news:', JSON.stringify(news, undefined, 2));

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

<div id="root"></div>

You use selectors when you need to calculate values based on state such as the total of a list or filtered things from a list. This way you don't need to duplicate the data in your state.


问:
High CPU usage with Android emulator (qemu-system-i386.exe)
The emulator qemu-system-i386.exe cpu usage almost constantly running between 7~9

Android studio 2.1
Android SDK Tools: 25.1.3
Host Operating System: Windows 7 - i7 2630QM - 8GB Ram
Intel x86 Atom System Image installed

No matter what setting i change in the emulator like: emulated performance, multi-core CPU, x86-64 image, always the same thing

It is really annoying fan always on

Anyone had a fix for this issue?

答:
In my case it was Airplane mode, when turned ON the CPU usage jumped to 99%:

```<code>adb shell

$ top
</code>```

The issue was noticed on Android 10.0 x86.
If you turn Airplane Mode OFF then the CPU usage should return to normal.

Body:
In my case it was Airplane mode, when turned ON the CPU usage jumped to 99%:

adb shell

$ top

The issue was noticed on Android 10.0 x86.
If you turn Airplane Mode OFF then the CPU usage should return to normal.


问:
How can I download android 2.0 sdk now
How can I download android android 2.0 (not 2.1) sdk now?
I tried 'android sdk and avd manager', it does not have android 2.0 downloadable.

Thank you.

答: I just downloaded the 2.0 and 2.0.1 SDKs with the SDK and AVD manager. All you have to do is uncheck "Display updates only" in the "Available Packages" section and you'll see them. However as mentioned above they are labeled obsolete.</p>

ContentLicense: CC BY-SA 2.5

Title: How can I download android 2.0 sdk now


问:
Spyder not opening the webcam result window using opencv even code is running
Code image

As you can see the code is clean but still spyder is not opening the webcam even if my code is running

答:
You should call cv2.waitKey() every time you want to update the UI.

In your code you are trying to call cv2.imshow() many times in the internal loop, and cv2.waitKey() only once in the outside loop. As a rule of the thumb, there should be one cv2.waitKey() call for every cv2.imshow() call.


答:
You can try:

```<code>from itertools import groupby

result = []
for lst in data:
    sublist = sorted(lst, key=lambda d: d['user'])
    grouped = groupby(sublist, key=lambda d: d['user'])
    result.append([
        {'user': name, 'rating': sum([d['rating'] for d in group])}
        for name, group in grouped])

# Sort the `result` `rating` wise:
result = [sorted(sub, key=lambda d: d['rating']) for sub in result]

# %%timeit
# 7.54 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

UPDATE (A more efficient solution):

```<code>result = []
for lst in data:
    visited = {}
    for d in lst:
        if d['user'] in  visited:
            visited[d['user']]['rating'] += d['rating']
        else:
            visited[d['user']] = d

    result.append(sorted(visited.values(), key=lambda d: d['rating']))

# %% timeit
# 2.5 µs ± 54 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Result:

```<code># print(result)
[
    [
        {'user': 2, 'rating': 10},
        {'user': 3, 'rating': 10},
        {'user': 1, 'rating': 20}
    ],
    [
        {'user': 4, 'rating': 4},
        {'user': 1, 'rating': 30},
        {'user': 2, 'rating': 80}
    ]
]
</code>```

Title: Sum values in a list of lists of dictionaries using common key-value pairs

Body:
You can try:

from itertools import groupby

result = []
for lst in data:
    sublist = sorted(lst, key=lambda d: d['user'])
    grouped = groupby(sublist, key=lambda d: d['user'])
    result.append([
        {'user': name, 'rating': sum([d['rating'] for d in group])}
        for name, group in grouped])

# Sort the `result` `rating` wise:
result = [sorted(sub, key=lambda d: d['rating']) for sub in result]

# %%timeit
# 7.54 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

UPDATE (A more efficient solution):

result = []
for lst in data:
    visited = {}
    for d in lst:
        if d['user'] in  visited:
            visited[d['user']]['rating'] += d['rating']
        else:
            visited[d['user']] = d

    result.append(sorted(visited.values(), key=lambda d: d['rating']))

# %% timeit
# 2.5 µs ± 54 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Result:

# print(result)
[
    [
        {'user': 2, 'rating': 10},
        {'user': 3, 'rating': 10},
        {'user': 1, 'rating': 20}
    ],
    [
        {'user': 4, 'rating': 4},
        {'user': 1, 'rating': 30},
        {'user': 2, 'rating': 80}
    ]
]


问:
cocos2d coordinates system
```<code>        CCLabelTTF *label = [CCLabelTTF labelWithString:@"Score : #" fontName:@"Arial" fontSize:14];

        // ask director the the window size
        CGSize size = [[CCDirector sharedDirector] winSize];

        // position the label on the center of the screen
        label.position =  ccp( size.width + 0, size.height + 0 );

        // add the label as a child to this Layer
        [self addChild: label];

        label.position =  ccp( size.width + 0, size.height + 0 );
</code>```

how would i get that label in the bottom left corner. I do not understand the coordinates system very well. From what I understand Y is bottom. X is far left. so how come when I use that code, the position of the label is top right. My application is portrait.

Also would it better to have the label as a sprite, or just keep it like that. ( its to hold a score )

答: consider first answer for your first question, and for second question answer is, if label is for score, then it's better you use label, rather than sprites(because you'll need 1000s of them and it'll be heavy as well as complicated)</p>

Title: cocos2d coordinates system

Body:
        CCLabelTTF *label = [CCLabelTTF labelWithString:@"Score : #" fontName:@"Arial" fontSize:14];

        // ask director the the window size
        CGSize size = [[CCDirector sharedDirector] winSize];

        // position the label on the center of the screen
        label.position =  ccp( size.width + 0, size.height + 0 );

        // add the label as a child to this Layer
        [self addChild: label];

        label.position =  ccp( size.width + 0, size.height + 0 );

how would i get that label in the bottom left corner. I do not understand the coordinates system very well. From what I understand Y is bottom. X is far left. so how come when I use that code, the position of the label is top right. My application is portrait.

Also would it better to have the label as a sprite, or just keep it like that. ( its to hold a score )


问:
unable to apply two different conditions and also check password hash
Quick check on this one that I am trying to figure out. First of all I want to apologize if I hurt your eyes with my code, I just started two weeks ago with php and I am trying my best applying the logic :-D

So 2 factor was just implemented via user profile, meaning that if the feature is still not enable the user can still login successfully, after the 2 fact is enabled then he will be redirected to verify the code. with that said the login.php post will need to check the following:

If 2fac is not enabled then check credentials/ password hash then login.

If 2fac is enabled then check if password is still correct then redirect to 2factcode.php for code verification.

error if the password is incorrect in either 1 or 2.

'''

```<code>$email=mysqli_real_escape_string($db,$_POST['email']);{

$password=mysqli_real_escape_string($db,$_POST['password']);

$stmt = $db->prepare("SELECT password FROM users WHERE email  = ? AND isEmailConfirmed='1' AND is2facEnabled='0'");
$stmt->bind_param("s", $_POST['email']);

$stmt->execute();
$stmt->bind_result($hash);

//checking hash
if ($stmt->fetch() && password_verify($_POST['password'], $hash)) {

$_SESSION['email'] = $email;

header('location: prod.php');
</code>```

'''

So here is what I've been trying to tweak (not sure if makes sense), if the statement is not valid meaning no rows were found because is2facenabled value is '1', then I still check if password hash is  correct then go to verify 2fac code.*

If I remove the password check below then it works but it never checks if the password is correct, if I leave it how it is then if I put a wrong password the page refresh with no errors and goes back to enter credentials. I think it has an issue with the $_POST but not sure.

```<code>elseif (!$stmt->fetch() && password_verify($_POST['password'], $hash)) {

    header('location: login2factorverification.php');

}else {
array_push($errors, "Incorrect credentials or email needs verification");

enter code here
</code>```

my question is, how do I accomplish these checks and login properly, thank you in advance.

Regards,
MF

答:
This basically amounts to what I consider the first rule of programming: Break The Problem Down.

Rather than trying to write one piece of code that checks user existence, password, and 2fac status, do one at a time:

Select details from the database based on the provided email address. If no row is found, they're not registered, so you don't need to do anything else.

You could include the "is address confirmed" check in the SQL, or you could write it as a separate if statement before checking anything else.

Next, check the password provided is correct. If it's not, it doesn't matter if the user has 2fac enabled or not, because you're not going to let them log in.

Finally, check if the user has 2fac enabled. If they do, redirect to the 2fac step; if they don't, mark them as successfully logged in.

Body:
Quick check on this one that I am trying to figure out. First of all I want to apologize if I hurt your eyes with my code, I just started two weeks ago with php and I am trying my best applying the logic :-D

So 2 factor was just implemented via user profile, meaning that if the feature is still not enable the user can still login successfully, after the 2 fact is enabled then he will be redirected to verify the code. with that said the login.php post will need to check the following:

If 2fac is not enabled then check credentials/ password hash then login.

If 2fac is enabled then check if password is still correct then redirect to 2factcode.php for code verification.

error if the password is incorrect in either 1 or 2.

'''

$email=mysqli_real_escape_string($db,$_POST['email']);{

$password=mysqli_real_escape_string($db,$_POST['password']);

$stmt = $db->prepare("SELECT password FROM users WHERE email  = ? AND isEmailConfirmed='1' AND is2facEnabled='0'");
$stmt->bind_param("s", $_POST['email']);

$stmt->execute();
$stmt->bind_result($hash);

//checking hash
if ($stmt->fetch() && password_verify($_POST['password'], $hash)) {

$_SESSION['email'] = $email;

header('location: prod.php');

'''

So here is what I've been trying to tweak (not sure if makes sense), if the statement is not valid meaning no rows were found because is2facenabled value is '1', then I still check if password hash is  correct then go to verify 2fac code.*

If I remove the password check below then it works but it never checks if the password is correct, if I leave it how it is then if I put a wrong password the page refresh with no errors and goes back to enter credentials. I think it has an issue with the $_POST but not sure.

elseif (!$stmt->fetch() && password_verify($_POST['password'], $hash)) {

    header('location: login2factorverification.php');

}else {
array_push($errors, "Incorrect credentials or email needs verification");

enter code here

my question is, how do I accomplish these checks and login properly, thank you in advance.

Regards,
MF


问:
How do I use multiple Radiobuttons in python tkinter?
I've struggled here long enough. I need some direction.

I am trying to make a byte generator GUI. 95% works ok, but I cant keep the radio buttons on/off once I click them.

I created 64 buttons in a loop, assigned values to the variable, and created a callback function.

In the callback function the I click a button, it then calls update_array, which updates a list and a text byte array. The values toggle from 0 to 1 — back and forth. Works fine but the buttons won’t stay on/highlighted. I’m not even sure if I should be using another button type.

The end result is the array of buttons and the byte array should show the same pattern.

I’m also trying to get the identity of the button I click. (Btn_XY) I know when I click Btn_44, but how do I find that out from tkinter?

Running python3.8 on MacBook Pro  Version 10.15.5

GUI Tab 1 shows the buttons and the byte map.

Callback function is def btnCall(self)

Buttons are created at line 280 to 293. Functions def btnCall and def update_array sure seem to be working ok. Even though they are incomplete - the part that is there is working. I can save the list later to a global list.

Print statements throughout show process and debug.

Suggestions please????    Thanks in advance!

```<code>import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as msg

class CHAR_GEN():
def __init__(self):         # Initializer method
    # Create instance
    self.win = tk.Tk()

    # Add a title
    self.win.title("Character Generator GUI")
    self.create_widgets()

    #create the byte array for the byte map
    self.create_byte_array()

# Modified Button Click Function
def click_me(self):
    self.action.configure(text='Hello ' + self.name.get() + ' ' +
                     self.number_chosen.get())

# GUI Callback
def checkCallback(self, *ignored_args):
    # only enable one checkbutton
    if self.chVarUn.get(): self.check3.configure(state='disabled')
    else:                  self.check3.configure(state='normal')
    if self.chVarEn.get(): self.check2.configure(state='disabled')
    else:                  self.check2.configure(state='normal')

def create_byte_array(self):
    print('Create the array')
    self.byte_array = []
    for row in range(8):
        self.byte_array.append([])
        for col in range(8):
            self.byte_array[row].append(0)

    #############
    self.byte_box.insert(tk.END, '\n\n byte_array = { \n')
    print(self.byte_array)
    for row  in range(8):
        #self.byte_array[row].append(0)
        print(''.join(map(str, self.byte_array[row])))
        msg = ''.join(map(str, self.byte_array[row]))

        #############
        self.byte_box.insert(tk.END, '     ')
        self.byte_box.insert(tk.END, msg)
        self.byte_box.insert(tk.END, '\n')
    self.byte_box.insert(tk.END, '              }\n')

    #############
    #############
    return self.byte_array

########################################################
#   The byte_array is just a structure. We will print a
#   text representation of it in the text box and
#   refresh it every time the update or create fuction is called
########################################################

def update_array(self,row,col):
    print('in update array row and col passed == {} {}'.format(row,col))

    print('the variable self.byte_array[row][col] == {}'.format(self.byte_array[row][col]))

    print('in update_array this is where we toggle the bit in the list')

    if self.byte_array[row][col] == 0:
        self.byte_array[row][col] = 1
    else:
        self.byte_array[row][col] = 0

    #############
    #############
    #############
    print('ready to print to text box')
    print(self.byte_array)
    # delete the text in the box
    self.byte_box.delete('1.0',tk.END)
    #redraw
    self.byte_box.insert(tk.END, '\n\n byte_array = { \n')

    for row  in range(8):
        print(''.join(map(str, self.byte_array[row])))
        msg = ''.join(map(str, self.byte_array[row]))

        #############
        self.byte_box.insert(tk.END, '     ')
        self.byte_box.insert(tk.END, msg)
        self.byte_box.insert(tk.END, '\n')
    self.byte_box.insert(tk.END, '              }\n')
    #############
    #############
    #############
    #############

#####################################
#####################################
#    Build a list for all the radVars
#####################################
# Radiobutton Callback
def btnCall(self):
    print('entered btnCall')
    print('this is where we clicked the button')
    btnVar = self.radVar.get()

    print('in btnCall btnVar == {}'.format(btnVar))
    ###
    s = str(btnVar)
    #print(s)
    if len(s) == 1:
        xpos = str(0)
        ypos = s
    else:
        xpos = s[-2]
        ypos = s[-1]
    print('in btnCall xpos,ypos == {}{}'.format(xpos,ypos))

    print('leaving btnCall() and calling self.update_array')
    self.update_array(int(xpos),int(ypos))

#####################################
#####################################
#####################################
# reset the pixel map
def reset_map(self):
    #delete map
    #turn off all the radio buttons
    #create map
    pass

def invert_map(self):
    #delete map
    #toggle the bits in the map
    #create map
    pass

# Exit GUI cleanly
def _quit(self):
    self.win.quit()
    self.win.destroy()
    exit()

#####################################################################################
def create_widgets(self):
    tabControl = ttk.Notebook(self.win)          # Create Tab Control

    tab1 = ttk.Frame(tabControl)            # Add a second tab
    tabControl.add(tab1, text='Tab 1')      # Make second tab visible
    tab2 = ttk.Frame(tabControl)            # Create a tab
    tabControl.add(tab2, text='Tab 2')      # Add the tab

    tabControl.pack(expand=1, fill="both")  # Pack to make visible

    # Top of Tab Control 2 -------------------------------------------

    # We are creating a container frame to hold all other widgets -- Tab2
    self.pixmap = ttk.LabelFrame(tab1, text=' Pixels')
    self.pixmap.grid(column=0, row=0, padx=8, pady=4)

    self.map_frame = ttk.LabelFrame(self.pixmap, text=' Pixel Map ')
    self.map_frame.grid(column=0, row=2, sticky='W', columnspan=2)

    ## Add a textbox frame to hold the character array
    self.byte_frame = ttk.LabelFrame(tab1, text=' Bytes  ')
    self.byte_frame.grid(column=1, row=0, sticky='W', columnspan=2)

    # Creating three checkbuttons
    self.chVarDis = tk.IntVar()
    self.check1 = tk.Checkbutton(self.pixmap, text="Disabled", variable=self.chVarDis, state='disabled')
    self.check1.select()
    self.check1.grid(column=0, row=0, sticky=tk.W)
   #
    self.chVarUn = tk.IntVar()
    self.check2 = tk.Checkbutton(self.pixmap, text="Junk", variable=self.chVarUn)
    self.check2.deselect()
    self.check2.grid(column=1, row=0, sticky=tk.W)
   #
    self.chVarEn = tk.IntVar()
    self.check3 = tk.Checkbutton(self.pixmap, text="Save", variable=self.chVarEn)
    self.check3.deselect()
    self.check3.grid(column=2, row=0, sticky=tk.W)

    # trace the state of the two checkbuttons
    self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
    print('self.chVarUn == {}'.format(self.chVarUn))
    self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
    #print('self.chVarEn == {}'.format(self.chVarEn))

    #####################################################################
    #
    #         create a text box to hold the bytes
    #
    #####################################################################

    self. byte_box = tk.Text(self.byte_frame, height=12, width=20)
    self.byte_box.grid(column=0, row=0, sticky=tk.E)
    #self.byte_box.insert(tk.END, "Just a text Widget\nin two lines\n")
    #self.byte_box.insert(tk.END, '\n\n byte_array = { \n')

    # First, we change our Radiobutton global variables into a list

    # create three Radiobuttons using one variable
    self.radVar = tk.IntVar()

    # Next we are selecting a non-existing index value for radVar
    self.radVar.set(99)

    # Now we are creating all three Radiobutton widgets within one loop
    # create a temp dictionary to build the radio buttones ????????

    ##########################
    #          build a function to create 64 of these radio buttons.
    #          later !!!
    ##########################

    #####################################################################
    #
    #         create a text box to hold the bytes
    #
    #####################################################################

    self. byte_box = tk.Text(self.byte_frame, height=12, width=20)
    self.byte_box.grid(column=0, row=0, sticky=tk.E)
    #self.byte_box.insert(tk.END, "Just a text Widget\nin two lines\n")
    #self.byte_box.insert(tk.END, '\n\n byte_array = { \n')

    # create 64 Radiobuttons using one variable
    self.radVar = tk.IntVar()

    # Next we are selecting a non-existing index value for radVar
    self.radVar.set(99)

    # Now we are creating all three Radiobutton widgets within one loop
    # create a temp dictionary to build the radio buttones

    ##########################
    #          build a function to create 64 of these radio buttons.
    #          later !!!
    ##########################
    ##########################
    # here are all the radio buttons
    ##########################
    ##########################
    ##########################
    '''
         Here we will use a double loop to greate the radio buttons
         and later the variables. The numbers in the loop will
         be appended to Btn_XY where XY is the row and column.

         Also use the numbers for naming radVar for each button
         Also use the numbers for naming row and column
    '''
    ##########################
    ##########################
    bname = "Btn_"
    for x in range(8):
        for y in range(8):
            #print(x,y)
            #print(bname + str(x) + str(y))
            cr_name = bname + str(x) + str(y)

            print('in creation loop cr_name == {}'.format(cr_name))
            ######
            # need to create a simple SMALL box above eache of these
            # to toggle on and off

            self.cr_name = tk.Radiobutton(self.map_frame, variable=self.radVar, val = int(str(x)+str(y)), command=self.btnCall)
            self.cr_name.grid(column=y+1, row=x+1, sticky=tk.W)
    ##########################

   #  create another frame container
    ###############################################################
    ###############################################################

    # Create a container to hold misc buttons
    misc_buttons_frame = ttk.LabelFrame(self.pixmap, text=' Modify ')
    misc_buttons_frame.grid(column=0, row=3, sticky='W', columnspan=2)

    # create another frame container
    ###############################################################
    ###############################################################
    ###############################################################
    # Add Buttons for reset and invert commands
    ttk.Button(misc_buttons_frame, text=" Reset Map", command=self.reset_map).grid(column=0, row=0, sticky='W')
    ttk.Button(misc_buttons_frame, text=" Invert Map  ", command=self.invert_map).grid(column=1, row=0, sticky='W')
    #
    for child in misc_buttons_frame.winfo_children():
        child.grid_configure(padx=2, pady=2)
    #
    for child in self.pixmap.winfo_children():
        child.grid_configure(padx=8, pady=2)

    # Creating a Menu Bar
    menu_bar = Menu(self.win)
    self.win.config(menu=menu_bar)

    # Add menu items
    file_menu = Menu(menu_bar, tearoff=0)
    file_menu.add_command(label="New")
    file_menu.add_separator()
    file_menu.add_command(label="Exit", command=self._quit)
    menu_bar.add_cascade(label="File", menu=file_menu)

    # Display a Message Box

    # Add another Menu to the Menu Bar and an item
    help_menu = Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label="Help", menu=help_menu)

    # Change the main windows icon
    # self.win.iconbitmap('pyc.ico')

    self.check3.focus()

# Start GUI

oop = CHAR_GEN()
oop.win.mainloop(
</code>```

)

答:
The purpose of Radiobutton is to have only a single one selected in a group.
You should use Checkbutton for your program.

In your program you never use the cr_name that contains X/Y to identify the button.

An example of how you can save CheckButtons and then access their value later:

```<code>from tkinter import *

root = Tk()

bits = []
btn = []

for i in range(10): #Populates a list as a replacement for your actual inputs
    bits.append("btn"+str(i))

for i in range(len(bits)):
    #print text by referencing itself from the list where buttons are stored
    btn.append(Checkbutton(root, text=bits[i], command=lambda c=i: print(btn[c].cget("text"))))
    btn[i].pack() #pack the buttons

root.mainloop()
</code>```

Body:
I've struggled here long enough. I need some direction.

I am trying to make a byte generator GUI. 95% works ok, but I cant keep the radio buttons on/off once I click them.

I created 64 buttons in a loop, assigned values to the variable, and created a callback function.

In the callback function the I click a button, it then calls update_array, which updates a list and a text byte array. The values toggle from 0 to 1 — back and forth. Works fine but the buttons won’t stay on/highlighted. I’m not even sure if I should be using another button type.

The end result is the array of buttons and the byte array should show the same pattern.

I’m also trying to get the identity of the button I click. (Btn_XY) I know when I click Btn_44, but how do I find that out from tkinter?

Running python3.8 on MacBook Pro  Version 10.15.5

GUI Tab 1 shows the buttons and the byte map.

Callback function is def btnCall(self)

Buttons are created at line 280 to 293. Functions def btnCall and def update_array sure seem to be working ok. Even though they are incomplete - the part that is there is working. I can save the list later to a global list.

Print statements throughout show process and debug.

Suggestions please????    Thanks in advance!

import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as msg

class CHAR_GEN():
def __init__(self):         # Initializer method
    # Create instance
    self.win = tk.Tk()

    # Add a title
    self.win.title("Character Generator GUI")
    self.create_widgets()

    #create the byte array for the byte map
    self.create_byte_array()

# Modified Button Click Function
def click_me(self):
    self.action.configure(text='Hello ' + self.name.get() + ' ' +
                     self.number_chosen.get())

# GUI Callback
def checkCallback(self, *ignored_args):
    # only enable one checkbutton
    if self.chVarUn.get(): self.check3.configure(state='disabled')
    else:                  self.check3.configure(state='normal')
    if self.chVarEn.get(): self.check2.configure(state='disabled')
    else:                  self.check2.configure(state='normal')

def create_byte_array(self):
    print('Create the array')
    self.byte_array = []
    for row in range(8):
        self.byte_array.append([])
        for col in range(8):
            self.byte_array[row].append(0)

    #############
    self.byte_box.insert(tk.END, '\n\n byte_array = { \n')
    print(self.byte_array)
    for row  in range(8):
        #self.byte_array[row].append(0)
        print(''.join(map(str, self.byte_array[row])))
        msg = ''.join(map(str, self.byte_array[row]))

        #############
        self.byte_box.insert(tk.END, '     ')
        self.byte_box.insert(tk.END, msg)
        self.byte_box.insert(tk.END, '\n')
    self.byte_box.insert(tk.END, '              }\n')

    #############
    #############
    return self.byte_array

########################################################
#   The byte_array is just a structure. We will print a
#   text representation of it in the text box and
#   refresh it every time the update or create fuction is called
########################################################

def update_array(self,row,col):
    print('in update array row and col passed == {} {}'.format(row,col))

    print('the variable self.byte_array[row][col] == {}'.format(self.byte_array[row][col]))

    print('in update_array this is where we toggle the bit in the list')

    if self.byte_array[row][col] == 0:
        self.byte_array[row][col] = 1
    else:
        self.byte_array[row][col] = 0

    #############
    #############
    #############
    print('ready to print to text box')
    print(self.byte_array)
    # delete the text in the box
    self.byte_box.delete('1.0',tk.END)
    #redraw
    self.byte_box.insert(tk.END, '\n\n byte_array = { \n')

    for row  in range(8):
        print(''.join(map(str, self.byte_array[row])))
        msg = ''.join(map(str, self.byte_array[row]))

        #############
        self.byte_box.insert(tk.END, '     ')
        self.byte_box.insert(tk.END, msg)
        self.byte_box.insert(tk.END, '\n')
    self.byte_box.insert(tk.END, '              }\n')
    #############
    #############
    #############
    #############

#####################################
#####################################
#    Build a list for all the radVars
#####################################
# Radiobutton Callback
def btnCall(self):
    print('entered btnCall')
    print('this is where we clicked the button')
    btnVar = self.radVar.get()

    print('in btnCall btnVar == {}'.format(btnVar))
    ###
    s = str(btnVar)
    #print(s)
    if len(s) == 1:
        xpos = str(0)
        ypos = s
    else:
        xpos = s[-2]
        ypos = s[-1]
    print('in btnCall xpos,ypos == {}{}'.format(xpos,ypos))

    print('leaving btnCall() and calling self.update_array')
    self.update_array(int(xpos),int(ypos))

#####################################
#####################################
#####################################
# reset the pixel map
def reset_map(self):
    #delete map
    #turn off all the radio buttons
    #create map
    pass

def invert_map(self):
    #delete map
    #toggle the bits in the map
    #create map
    pass

# Exit GUI cleanly
def _quit(self):
    self.win.quit()
    self.win.destroy()
    exit()

#####################################################################################
def create_widgets(self):
    tabControl = ttk.Notebook(self.win)          # Create Tab Control

    tab1 = ttk.Frame(tabControl)            # Add a second tab
    tabControl.add(tab1, text='Tab 1')      # Make second tab visible
    tab2 = ttk.Frame(tabControl)            # Create a tab
    tabControl.add(tab2, text='Tab 2')      # Add the tab

    tabControl.pack(expand=1, fill="both")  # Pack to make visible

    # Top of Tab Control 2 -------------------------------------------

    # We are creating a container frame to hold all other widgets -- Tab2
    self.pixmap = ttk.LabelFrame(tab1, text=' Pixels')
    self.pixmap.grid(column=0, row=0, padx=8, pady=4)

    self.map_frame = ttk.LabelFrame(self.pixmap, text=' Pixel Map ')
    self.map_frame.grid(column=0, row=2, sticky='W', columnspan=2)

    ## Add a textbox frame to hold the character array
    self.byte_frame = ttk.LabelFrame(tab1, text=' Bytes  ')
    self.byte_frame.grid(column=1, row=0, sticky='W', columnspan=2)

    # Creating three checkbuttons
    self.chVarDis = tk.IntVar()
    self.check1 = tk.Checkbutton(self.pixmap, text="Disabled", variable=self.chVarDis, state='disabled')
    self.check1.select()
    self.check1.grid(column=0, row=0, sticky=tk.W)
   #
    self.chVarUn = tk.IntVar()
    self.check2 = tk.Checkbutton(self.pixmap, text="Junk", variable=self.chVarUn)
    self.check2.deselect()
    self.check2.grid(column=1, row=0, sticky=tk.W)
   #
    self.chVarEn = tk.IntVar()
    self.check3 = tk.Checkbutton(self.pixmap, text="Save", variable=self.chVarEn)
    self.check3.deselect()
    self.check3.grid(column=2, row=0, sticky=tk.W)

    # trace the state of the two checkbuttons
    self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
    print('self.chVarUn == {}'.format(self.chVarUn))
    self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
    #print('self.chVarEn == {}'.format(self.chVarEn))

    #####################################################################
    #
    #         create a text box to hold the bytes
    #
    #####################################################################

    self. byte_box = tk.Text(self.byte_frame, height=12, width=20)
    self.byte_box.grid(column=0, row=0, sticky=tk.E)
    #self.byte_box.insert(tk.END, "Just a text Widget\nin two lines\n")
    #self.byte_box.insert(tk.END, '\n\n byte_array = { \n')

    # First, we change our Radiobutton global variables into a list

    # create three Radiobuttons using one variable
    self.radVar = tk.IntVar()

    # Next we are selecting a non-existing index value for radVar
    self.radVar.set(99)

    # Now we are creating all three Radiobutton widgets within one loop
    # create a temp dictionary to build the radio buttones ????????

    ##########################
    #          build a function to create 64 of these radio buttons.
    #          later !!!
    ##########################

    #####################################################################
    #
    #         create a text box to hold the bytes
    #
    #####################################################################

    self. byte_box = tk.Text(self.byte_frame, height=12, width=20)
    self.byte_box.grid(column=0, row=0, sticky=tk.E)
    #self.byte_box.insert(tk.END, "Just a text Widget\nin two lines\n")
    #self.byte_box.insert(tk.END, '\n\n byte_array = { \n')

    # create 64 Radiobuttons using one variable
    self.radVar = tk.IntVar()

    # Next we are selecting a non-existing index value for radVar
    self.radVar.set(99)

    # Now we are creating all three Radiobutton widgets within one loop
    # create a temp dictionary to build the radio buttones

    ##########################
    #          build a function to create 64 of these radio buttons.
    #          later !!!
    ##########################
    ##########################
    # here are all the radio buttons
    ##########################
    ##########################
    ##########################
    '''
         Here we will use a double loop to greate the radio buttons
         and later the variables. The numbers in the loop will
         be appended to Btn_XY where XY is the row and column.

         Also use the numbers for naming radVar for each button
         Also use the numbers for naming row and column
    '''
    ##########################
    ##########################
    bname = "Btn_"
    for x in range(8):
        for y in range(8):
            #print(x,y)
            #print(bname + str(x) + str(y))
            cr_name = bname + str(x) + str(y)

            print('in creation loop cr_name == {}'.format(cr_name))
            ######
            # need to create a simple SMALL box above eache of these
            # to toggle on and off

            self.cr_name = tk.Radiobutton(self.map_frame, variable=self.radVar, val = int(str(x)+str(y)), command=self.btnCall)
            self.cr_name.grid(column=y+1, row=x+1, sticky=tk.W)
    ##########################

   #  create another frame container
    ###############################################################
    ###############################################################

    # Create a container to hold misc buttons
    misc_buttons_frame = ttk.LabelFrame(self.pixmap, text=' Modify ')
    misc_buttons_frame.grid(column=0, row=3, sticky='W', columnspan=2)

    # create another frame container
    ###############################################################
    ###############################################################
    ###############################################################
    # Add Buttons for reset and invert commands
    ttk.Button(misc_buttons_frame, text=" Reset Map", command=self.reset_map).grid(column=0, row=0, sticky='W')
    ttk.Button(misc_buttons_frame, text=" Invert Map  ", command=self.invert_map).grid(column=1, row=0, sticky='W')
    #
    for child in misc_buttons_frame.winfo_children():
        child.grid_configure(padx=2, pady=2)
    #
    for child in self.pixmap.winfo_children():
        child.grid_configure(padx=8, pady=2)

    # Creating a Menu Bar
    menu_bar = Menu(self.win)
    self.win.config(menu=menu_bar)

    # Add menu items
    file_menu = Menu(menu_bar, tearoff=0)
    file_menu.add_command(label="New")
    file_menu.add_separator()
    file_menu.add_command(label="Exit", command=self._quit)
    menu_bar.add_cascade(label="File", menu=file_menu)

    # Display a Message Box

    # Add another Menu to the Menu Bar and an item
    help_menu = Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label="Help", menu=help_menu)

    # Change the main windows icon
    # self.win.iconbitmap('pyc.ico')

    self.check3.focus()

# Start GUI

oop = CHAR_GEN()
oop.win.mainloop(

)

Body:
The purpose of Radiobutton is to have only a single one selected in a group.
You should use Checkbutton for your program.

In your program you never use the cr_name that contains X/Y to identify the button.

An example of how you can save CheckButtons and then access their value later:

from tkinter import *

root = Tk()

bits = []
btn = []

for i in range(10): #Populates a list as a replacement for your actual inputs
    bits.append("btn"+str(i))

for i in range(len(bits)):
    #print text by referencing itself from the list where buttons are stored
    btn.append(Checkbutton(root, text=bits[i], command=lambda c=i: print(btn[c].cget("text"))))
    btn[i].pack() #pack the buttons

root.mainloop()


问:
`$request->ajax()` does not detect ajax request when using Fetch API to pull data in Laravel
In my Laravel app, I am using Fetch API to load data on scroll. Below is my JS code in blade file

let route = '{{ route("load") }}' + '?q=' + encodeURI('{{ $para }}');
fetch(route)
.then(response => {
   if(!response.ok) {
       throw new Error('Network response was not ok');
   }
   return response.text();
})
.then(data => {
   console.log(data);
})
.catch((error) => {
   console.error('Error:', error);
})
```

<p>And in my controller</p>

<pre class="lang-php prettyprint-override"><code>public function loadData( Request $request )
{
    if( $request->ajax() ) {

       return $request->query('q');

     }
     return 'Not Ajax!';
}
</code>```

It always return 'Not Ajax!';

I am not sure why this is happening. It was not a problem with other libraries like jQuery or Axios

答: Please try  to use request()->ajax() function instead of $request->ajax(). I think the problem is you have imported the wrong Request at the top. It happens with me also because of Editor

Body:
In my Laravel app, I am using Fetch API to load data on scroll. Below is my JS code in blade file

let route = '{{ route("load") }}' + '?q=' + encodeURI('{{ $para }}');
fetch(route)
.then(response => {
   if(!response.ok) {
       throw new Error('Network response was not ok');
   }
   return response.text();
})
.then(data => {
   console.log(data);
})
.catch((error) => {
   console.error('Error:', error);
})

And in my controller

public function loadData( Request $request )
{
    if( $request->ajax() ) {

       return $request->query('q');

     }
     return 'Not Ajax!';
}

It always return 'Not Ajax!';

I am not sure why this is happening. It was not a problem with other libraries like jQuery or Axios


问:
autoconf: best practice for including `libftdi` in `configure.ac`
Hello everybody out there using GNU autoconf,

What is the best practice to look for libftdi and including it with autoconf for compiling a C program using it?

The following snippet from a configure.ac file works, but I'm not sure, whether it is best practice:

```<code>PKG_CHECK_MODULES([LIBFTDI], [libftdi])
#AC_CHECK_LIB([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_SEARCH_LIBS([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_CHECK_HEADERS([ftdi.h],[],[echo "error: missing libftdi header files" && exit 1])
LIBS="-lftdi $LIBS $LDFLAGS" # works, but is this the best way?
</code>```

I'm building the program with autoconf (GNU Autoconf) 2.69 and compiling it with gcc version 7.5.0 on Ubuntu 18.04.

答:
If libftdi uses pkg-config (and it appears to, given you said that snippet works), the PKG_CHECK_MODULES is what you want. The default for action-if-not-found is to error out, so if this is a required dependency, it's exactly what you want.

But you shouldn't use LIBS that way. First because LDFLAGS does not have the same semantics as LIBS, second because the pkg-config file might have provided you with further search paths that are required.

Instead you should add to your Makefile.am the flags as you need them:

```<code>mytarget_CFLAGS = $(LIBFTDI_CFLAGS)
mytarget_LDADD = $(LIBFTDI_LIBS)
</code>```

You can refer to my Autotools Mythbuster — Dependency Discovery for further details on how to use pkg-config for dependencies. You can see there how you would generally use AC_CHECK_LIB or AC_SEARCH_LIB, but seriously if pkg-config works, stick to that, as it's more reliable and consistent.

Body:
Hello everybody out there using GNU autoconf,

What is the best practice to look for libftdi and including it with autoconf for compiling a C program using it?

The following snippet from a configure.ac file works, but I'm not sure, whether it is best practice:

PKG_CHECK_MODULES([LIBFTDI], [libftdi])
#AC_CHECK_LIB([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_SEARCH_LIBS([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_CHECK_HEADERS([ftdi.h],[],[echo "error: missing libftdi header files" && exit 1])
LIBS="-lftdi $LIBS $LDFLAGS" # works, but is this the best way?

I'm building the program with autoconf (GNU Autoconf) 2.69 and compiling it with gcc version 7.5.0 on Ubuntu 18.04.

Body:
If libftdi uses pkg-config (and it appears to, given you said that snippet works), the PKG_CHECK_MODULES is what you want. The default for action-if-not-found is to error out, so if this is a required dependency, it's exactly what you want.

But you shouldn't use LIBS that way. First because LDFLAGS does not have the same semantics as LIBS, second because the pkg-config file might have provided you with further search paths that are required.

Instead you should add to your Makefile.am the flags as you need them:

mytarget_CFLAGS = $(LIBFTDI_CFLAGS)
mytarget_LDADD = $(LIBFTDI_LIBS)

You can refer to my Autotools Mythbuster — Dependency Discovery for further details on how to use pkg-config for dependencies. You can see there how you would generally use AC_CHECK_LIB or AC_SEARCH_LIB, but seriously if pkg-config works, stick to that, as it's more reliable and consistent.


问:
SQL server recovery mechanism
I have a service application in C# which queries data from one database and inserts it into another SQL database.

Sometimes, the MSSQLSERVER service crashed for unknown reason and my application will crash as well. I want to do a SQL recovery mechanism that where I check to make sure the sqlconnection state is fine before i write to the database but how i do that?

I tried stopping MSSQLSERVER service and sqlconnection.State is always open even when the MSSQLSERVER service is stopped.

答:
First: Fix your real problem. SQL Server should be very, very stable.

Second: consider using MSMQ (or SQL Service Broker) on both the client application and server to queue updates.

Title: SQL server recovery mechanism


问:
Iframe rendering error : <rect> attribute width: A negative value is not valid
I'm trying to integrate an iframe from Google Ngram Viewer into a page of my rails app. The app is currently in development and, curiously, sometimes the Ngram Iframe doesn't appear and throws an error :

ngram-viewer-deps.js:50 Error:  attribute width: A negative
  value is not valid. ("-152")

Here is the corresponding iframe URL : https://books.google.com/ngrams/interactive_chart?content=aspirateur&year_start=1700&year_end=2008&corpus=19&smoothing=3&direct_url=t1%3B%2Caspirateur%3B%2Cc0

Here is the iframe element rendered (I only copy/paste outer HTML here) :

```<code><iframe name="ngram_chart" src="https://books.google.com/ngrams/interactive_chart?content=aspirateur&year_start=1700&year_end=2008&corpus=19&smoothing=3&direct_url=t1%3B%2Caspirateur%3B%2Cc0" width="800" height="335" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no"></iframe>
</code>```

Any idea how to prevent this error from happening? Thanks.

答:
To be honest i don't now about google Ngram viewer, but i believe the error means that the iframe container width is getting too small. Probably there is a code in that viewer checking the actual width available for the iframe, when the width is extremely small or negative due to overflows from other elements, then it throws this error.

I would start by checking what width is available for the iframe on different screens, especially smaller screens.

A fast try might be a set a min width on the iframe and check if the error still persists.

Body:
I'm trying to integrate an iframe from Google Ngram Viewer into a page of my rails app. The app is currently in development and, curiously, sometimes the Ngram Iframe doesn't appear and throws an error :

ngram-viewer-deps.js:50 Error:  attribute width: A negative
  value is not valid. ("-152")

Here is the corresponding iframe URL : https://books.google.com/ngrams/interactive_chart?content=aspirateur&year_start=1700&year_end=2008&corpus=19&smoothing=3&direct_url=t1%3B%2Caspirateur%3B%2Cc0

Here is the iframe element rendered (I only copy/paste outer HTML here) :

Any idea how to prevent this error from happening? Thanks.


问:
angular: updateRenderer throws Cannot read property 'name' of undefined for string variable
I have a really strange problem with displaying a string variable. The error I'm getting is this:

```<code>ERROR TypeError: Cannot read property 'name' of undefined
at checkBindingNoChanges (core.js:9912)
at checkNoChangesNodeInline (core.js:13961)
at checkNoChangesNode (core.js:13935)
at debugCheckNoChangesNode (core.js:14764)
at debugCheckRenderNodeFn (core.js:14704)
at Object.eval [as updateRenderer] (MonitoringCriteriaComponent.html:93)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14686)
at checkNoChangesView (core.js:13775)
at callViewAction (core.js:14126)
at execEmbeddedViewsAction (core.js:14104)
</code>```

This is thrown while trying to display a string type variable like this:

```<code><span>{{daysCounter}}</span>
</code>```

The variable is declared and changed this way:

```<code>daysCounter = '';

public countTotalNumberOfDays() {
  this.daysCounter = '' + DateUtils.calculateNumberOfDays(this.dateFrom.datePickerTime.toDate(), this.dateTo.datePickerTime.toDate());
  console.log('daysCounter', this.daysCounter);
}
</code>```

The error is thrown after calculation is being made, as it's properly logged in the console log, however when it is being displayed in the html template, the above error is logged. Value of this variable is not accessed anywhere else. This is within one component, other variables are visible in the template.

I don't know what else might be relevant to this problem. I'm quite stumped...

答:
I kept digging and found out that the reason for the error was a way function used to set its value was called. It was called in a (changeListener) in another component higher up, and while it was reported in console log correctly the error was thrown because the higher component, I'm guessing, did not have access to that variable. Logging in this case was very confusing.

The solution was moving the function changing the value of the var from the function used in changeListener to another spot, used only in that component.

Body:
I have a really strange problem with displaying a string variable. The error I'm getting is this:

ERROR TypeError: Cannot read property 'name' of undefined
at checkBindingNoChanges (core.js:9912)
at checkNoChangesNodeInline (core.js:13961)
at checkNoChangesNode (core.js:13935)
at debugCheckNoChangesNode (core.js:14764)
at debugCheckRenderNodeFn (core.js:14704)
at Object.eval [as updateRenderer] (MonitoringCriteriaComponent.html:93)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14686)
at checkNoChangesView (core.js:13775)
at callViewAction (core.js:14126)
at execEmbeddedViewsAction (core.js:14104)

This is thrown while trying to display a string type variable like this:

{{daysCounter}}

The variable is declared and changed this way:

daysCounter = '';

public countTotalNumberOfDays() {
  this.daysCounter = '' + DateUtils.calculateNumberOfDays(this.dateFrom.datePickerTime.toDate(), this.dateTo.datePickerTime.toDate());
  console.log('daysCounter', this.daysCounter);
}

The error is thrown after calculation is being made, as it's properly logged in the console log, however when it is being displayed in the html template, the above error is logged. Value of this variable is not accessed anywhere else. This is within one component, other variables are visible in the template.

I don't know what else might be relevant to this problem. I'm quite stumped...


问:
HTTP method POST is not supported by this URL Java servlet
Can someone please tell me why i am getting error:HTTP Status 405 – Method Not Allowed ?
I am trying accomplish that after method doPost() ,user will be redirected to "/logout" controller ,where is invalidate session.
It's funny because method is called ,do everything what should do(update user in database), but after send to user error 405.Another  where i use doPost() (for example: LoginController)  working well ,but when i try compere and find bug ,i dont see any :<

```<code><div class="container">
    <div class="col-md-8 col-md-offset-2">
        <form method="post" action="account">
            <div class="form-group">
                <label for="email">Email address</label>
                <input name="email" type="email" class="form-control" id="email"
                       value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
                       placeholder="Enter email">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="password" placeholder="Password">
            </div>
            <div class="form-group">
                <label for="repeatPassword">Repeat Password</label>
                <input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="repeatPassword" placeholder="Password">
            </div>
            <input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
        </form>
    </div>
</div>

@WebServlet("/account")
public class AccountController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String repeatPassword = req.getParameter("repeatPassword");

        if (email == null || password == null || repeatPassword == null) {
            doGet(req, resp);
            return;
        }

        if (password.equals(repeatPassword)) {
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("loggedUser");
            user.setEmail(email);
            String sha1hexPassword = DigestUtils.sha1Hex(password);
            user.setPassword(sha1hexPassword);
            UserService service = new UserService();

            try {
                service.update(user);
            } catch (UpdateObjectException e) {
                e.printStackTrace();
            }
            req.getRequestDispatcher("/logout").forward(req, resp);
        } else {
            req.setAttribute("errorMessage", "Passwords not the same");
            req.setAttribute("fragment", "account");
            req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
        }
    }
}
</code>```

Thanks for any hint.

答: Your doGet() method call is inside the server doPost() code. You should redirect the response, doGet is for recieving a GET request and any query string.</p>

Body:
Can someone please tell me why i am getting error:HTTP Status 405 – Method Not Allowed ?
I am trying accomplish that after method doPost() ,user will be redirected to "/logout" controller ,where is invalidate session.
It's funny because method is called ,do everything what should do(update user in database), but after send to user error 405.Another  where i use doPost() (for example: LoginController)  working well ,but when i try compere and find bug ,i dont see any :<

        <form method="post" action="account">

                Email address
                <input name="email" type="email" class="form-control" id="email"
                       value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
                       placeholder="Enter email">

                Password
                <input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="password" placeholder="Password">

                Repeat Password
                <input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="repeatPassword" placeholder="Password">

            <input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
        </form>

@WebServlet("/account")
public class AccountController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String repeatPassword = req.getParameter("repeatPassword");

        if (email == null || password == null || repeatPassword == null) {
            doGet(req, resp);
            return;
        }

        if (password.equals(repeatPassword)) {
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("loggedUser");
            user.setEmail(email);
            String sha1hexPassword = DigestUtils.sha1Hex(password);
            user.setPassword(sha1hexPassword);
            UserService service = new UserService();

            try {
                service.update(user);
            } catch (UpdateObjectException e) {
                e.printStackTrace();
            }
            req.getRequestDispatcher("/logout").forward(req, resp);
        } else {
            req.setAttribute("errorMessage", "Passwords not the same");
            req.setAttribute("fragment", "account");
            req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
        }
    }
}

Thanks for any hint.


问:
discord.py: How to get the first letter of a user's name?
I want to make a "ticket-system" and want the channel it creates to have the name of the first letter of the user. So, I already have this:

@client.event
async def on_raw_reaction_add(reaction):
ticket = await guildbtv.create_text_channel(name=f'ticket', overwrites=overwrites, category=supportcat,
                                                    position=None, topic='Hier kannst du dein Anliegen äussern!',
                                           reason='Ticket')
```

答:
You can get the name of the user by using client.get_user(ID).display_name

Getting the first letter of the nickname of the user in the guild that reacted in:

@client.event
async def on_reaction_add(reaction, user):
    first_letter = user.display_name[0]
```

<p>Getting the first letter of the username of the user:</p>

<pre class="lang-py prettyprint-override"><code>@client.event
async def on_reaction_add(reaction, user):
    first_letter = client.get_user(user.id).display_name[0]
</code>```

Body:
You can get the name of the user by using client.get_user(ID).display_name

Getting the first letter of the nickname of the user in the guild that reacted in:

@client.event
async def on_reaction_add(reaction, user):
    first_letter = user.display_name[0]

Getting the first letter of the username of the user:

@client.event
async def on_reaction_add(reaction, user):
    first_letter = client.get_user(user.id).display_name[0]


问:
start activity without bringing application to foreground
I'm facing a problem with my android app. In my splashscreen after some verifications the app starts the homeactivity but if the user gets to another app, the homeactivity of my app will still get to the foreground of the device. Is there a way to start the homeactivity without bringing my app to front?
I tried this code but it did not work</p>

```<code>Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);
</code>```

答:
Instead of launching HomeActivity instantly just raise a flag and consume it next time your SplashScreen is in resumed state. For example you can use LiveData to store the flag and observe it:

```<code>// inside SplashScreen or its ViewModel if you have one
MutableLiveData<Boolean> isVerifiedLiveData = new MutableLiveData<>();

// inside SplashScreen
@Override
protected void onCreate(Bundle savedInstanceState) {

    /* ...... add this to onCreate .... */

    isVerifiedLiveData.observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean isVerified) {
            if(isVerified){
                Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
                startActivity(intent);
                finish();
            }
        }
    });
}
</code>```

Then to trigger activity change simply modify isVerifiedLiveData value:

```<code>isVerifiedLiveData.setValue(true);
</code>```

Body:
I'm facing a problem with my android app. In my splashscreen after some verifications the app starts the homeactivity but if the user gets to another app, the homeactivity of my app will still get to the foreground of the device. Is there a way to start the homeactivity without bringing my app to front?
I tried this code but it did not work

Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);

Body:
Instead of launching HomeActivity instantly just raise a flag and consume it next time your SplashScreen is in resumed state. For example you can use LiveData to store the flag and observe it:

// inside SplashScreen or its ViewModel if you have one
MutableLiveData<Boolean> isVerifiedLiveData = new MutableLiveData<>();

// inside SplashScreen
@Override
protected void onCreate(Bundle savedInstanceState) {

    /* ...... add this to onCreate .... */

    isVerifiedLiveData.observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean isVerified) {
            if(isVerified){
                Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
                startActivity(intent);
                finish();
            }
        }
    });
}

Then to trigger activity change simply modify isVerifiedLiveData value:

isVerifiedLiveData.setValue(true);


问:
How to change line chart data label to icon or image in chart.js
I want to change data label text to icon or image.

This chart show labels with months. I want to change this label text to icon or image

答:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images instead of tick labels directly on the canvas using CanvasRenderingContext2D.

You'll also have to instruct Chart.js not to display the default tick labels. This can be done through the following definition inside the chart options.

```<code>scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }],
</code>```

Further you need to define some padding at the bottom and right of the chart, otherwise you'll see only part of the images.

```<code>layout: {
  padding: {
    bottom: 30,
    right: 15
  }
},
</code>```

Please have a look at the runnable code snippet below.

const labels = ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
const values = [48, 56, 33, 44];

new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
        var x = xAxis.getPixelForTick(index);
        var image = new Image();
        image.src = images[index],
        ctx.drawImage(image, x - 12, yAxis.bottom + 10);
      });
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        bottom: 30,
        right: 15
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
          stepSize: 20
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        },
        ticks: {
          display: false
        }
      }],
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas></code>```

Body:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images instead of tick labels directly on the canvas using CanvasRenderingContext2D.

You'll also have to instruct Chart.js not to display the default tick labels. This can be done through the following definition inside the chart options.

scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }],

Further you need to define some padding at the bottom and right of the chart, otherwise you'll see only part of the images.

layout: {
  padding: {
    bottom: 30,
    right: 15
  }
},

Please have a look at the runnable code snippet below.

const labels = ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
const values = [48, 56, 33, 44];

new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
        var x = xAxis.getPixelForTick(index);
        var image = new Image();
        image.src = images[index],
        ctx.drawImage(image, x - 12, yAxis.bottom + 10);
      });
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        bottom: 30,
        right: 15
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
          stepSize: 20
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        },
        ticks: {
          display: false
        }
      }],
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>


问:
How can I delete a property from object returned by mongoose
I am querying users collection and I don't want to send back password. My main point is that if I can perform javascript operations on mongodb objects or not. Here is my code:

```<code>router.get("/:userId", async (req, res) => {
  try {
    const user = await User.findById(req.params.userId);
    delete user.password;
    if (user.parent !== undefined) {
      const referrer = await User.findOne({ _id: user.parent });
      return res.json({ user, referrer });
    }
    res.json(user);
  } catch (error) {
    res.status(400).json(error);
  }
});
</code>```

I am getting this output

```<code>{
    "is_deleted": false,
    "packages": [],
    "_id": "5ed102f3fefa080404db01df",
    "name": "parent",
    "email": "parent@parent.com",
    "gender": "m",
    "password": "$2b$10$HTGaoy.AVmoG/A0c/vkikO0NnEBte7f2tvwt2FQE94bZlNiYTeX8i",
    "__v": 0
}
</code>```

I tried to perform filter on a list of mongodb objects and that failed too.

答:
I would use findeOne with the projection on the end:

```<code>const user = await User.findOne({ _id: req.params.userId },{ password: 0 });
</code>```

You can exclude more fields with setting the value to 0

Body:
I am querying users collection and I don't want to send back password. My main point is that if I can perform javascript operations on mongodb objects or not. Here is my code:

router.get("/:userId", async (req, res) => {
  try {
    const user = await User.findById(req.params.userId);
    delete user.password;
    if (user.parent !== undefined) {
      const referrer = await User.findOne({ _id: user.parent });
      return res.json({ user, referrer });
    }
    res.json(user);
  } catch (error) {
    res.status(400).json(error);
  }
});

I am getting this output

{
    "is_deleted": false,
    "packages": [],
    "_id": "5ed102f3fefa080404db01df",
    "name": "parent",
    "email": "parent@parent.com",
    "gender": "m",
    "password": "$2b$10$HTGaoy.AVmoG/A0c/vkikO0NnEBte7f2tvwt2FQE94bZlNiYTeX8i",
    "__v": 0
}

I tried to perform filter on a list of mongodb objects and that failed too.

Body:
I would use findeOne with the projection on the end:

const user = await User.findOne({ _id: req.params.userId },{ password: 0 });

You can exclude more fields with setting the value to 0