问:
How to convert Uint8List to C equivalent datatype using dart:ffi
I am trying to send an image to my Custom C++ code which I am planning to run using dart:ffi. I have successfully run the hello world problem where I send two integers and get the some of them as another intiger.

Now I want to send a whole image to it and process it on my C++ code. I am able to get Uint8List from the CameraImage using the below code

```<code>Future<ui.Image> convertCameraImageToUiImage(CameraImage image) async {
imglib.Image libImage = imglib.Image.fromBytes(
  image.width,
  image.height,
  image.planes[0].bytes,
  format: imglib.Format.bgra,
);
final c = Completer<ui.Image>();
ui.decodeImageFromPixels(
  libImage.getBytes(),
  image.width,
  image.height,
  ui.PixelFormat.rgba8888,
  c.complete,
);
return c.future;
</code>```

}

Then I converted it to Uint8List

```<code>ByteData data = await image.toByteData();
Uint8List bytes = data.buffer.asUint8List();
</code>```

My problem is, how should I define lookup function to send a Uint8List to the C++ code and get List<bool>, my function over C++ expects cv::mat (I can tweak it to receive array of integers) as a parameter and sends a Vector of boolean.

This is what I have tried

```<code>final List<bool> Function(Uint8List image) _imageToCode = nativeAddLib
.lookup<NativeFunction<List<bool> Function(List<Uint8List>)>>("imageToCode")
.asFunction();
</code>```

The problem is, the bool and Uint8List are not a type supported by C++ so the function doesn't recognize them. How should I send it over the channel.

答:
You have to allocate, and then copy the data into, a Pointer<something>. Your exported C function can then have a something* argument. You will also need to pass the length of the data. As the goal is to construct a cv::Mat you might want to pass the geometry instead, and infer the data length from that.

So, if your exported C function has a signature:

```<code>void process(int32_t width, int32_t height, uint8_t *bytes);
</code>```

your two Dart typedefs would be:

```<code>typedef process_func = Void Function(Int32 width, Int32 height, Pointer<Uint8> bytes);
typedef ProcessFunc = void Function(int width, int height, Pointer<Uint8> bytes);
</code>```

use those in the lookup

```<code>_process = nativeLib
    .lookup<NativeFunction<process_func>>('process')
    .asFunction();
</code>```

To allocate the buffer, first import 'package:ffi/ffi.dart'; and use allocate

```<code>var outBuf = allocate<Uint8>(count: outSize);
</code>```

then use a for loop to copy the data. Alternatively use asTypedData on outBuf to get a Uint8List and use setAll.

Remember to free the buffer after using it.

(As your pixels are rgba8888, they fit in unsigned 32 bit ints. You might want to pass Uint32s across in your pointer, and get them using data.buffer.asUint32List().)

You want to return a list of bool. bool isn't supported you you have to pass a list of, say, Int8 where you've set the values to 1 and 0 respectively. (If your list is bounded and reasonably sized, you could use a bitmap. For example, if you knew it was always 32 bits long, pack those bits into a Uint32 as 32 ones and zeroes.)

There are a couple of strategies for returning a list, where list in ffi is going to mean Pointer<something> of course.

If the list is bounded, you can allocate it on the Dart side, pass the pointer with the function and have the C function fill in the values, maybe returning an integer of the number it filled in.

If the list is unbounded you must allow C to malloc it, as only the C function knows how much space it needs. You now need to return 2 values: the pointer and the length. Since you can only return one value you need to do something like pass in a Pointer<Int32> and have the C function assign the length to that.

Body:
I am trying to send an image to my Custom C++ code which I am planning to run using dart:ffi. I have successfully run the hello world problem where I send two integers and get the some of them as another intiger.

Now I want to send a whole image to it and process it on my C++ code. I am able to get Uint8List from the CameraImage using the below code

Future<ui.Image> convertCameraImageToUiImage(CameraImage image) async {
imglib.Image libImage = imglib.Image.fromBytes(
  image.width,
  image.height,
  image.planes[0].bytes,
  format: imglib.Format.bgra,
);
final c = Completer<ui.Image>();
ui.decodeImageFromPixels(
  libImage.getBytes(),
  image.width,
  image.height,
  ui.PixelFormat.rgba8888,
  c.complete,
);
return c.future;

}

Then I converted it to Uint8List

ByteData data = await image.toByteData();
Uint8List bytes = data.buffer.asUint8List();

My problem is, how should I define lookup function to send a Uint8List to the C++ code and get List<bool>, my function over C++ expects cv::mat (I can tweak it to receive array of integers) as a parameter and sends a Vector of boolean.

This is what I have tried

final List<bool> Function(Uint8List image) _imageToCode = nativeAddLib
.lookup<NativeFunction<List<bool> Function(List<Uint8List>)>>("imageToCode")
.asFunction();

The problem is, the bool and Uint8List are not a type supported by C++ so the function doesn't recognize them. How should I send it over the channel.

Body:
You have to allocate, and then copy the data into, a Pointer<something>. Your exported C function can then have a something* argument. You will also need to pass the length of the data. As the goal is to construct a cv::Mat you might want to pass the geometry instead, and infer the data length from that.

So, if your exported C function has a signature:

void process(int32_t width, int32_t height, uint8_t *bytes);

your two Dart typedefs would be:

typedef process_func = Void Function(Int32 width, Int32 height, Pointer<Uint8> bytes);
typedef ProcessFunc = void Function(int width, int height, Pointer<Uint8> bytes);

use those in the lookup

_process = nativeLib
    .lookup<NativeFunction<process_func>>('process')
    .asFunction();

To allocate the buffer, first import 'package:ffi/ffi.dart'; and use allocate

var outBuf = allocate<Uint8>(count: outSize);

then use a for loop to copy the data. Alternatively use asTypedData on outBuf to get a Uint8List and use setAll.

Remember to free the buffer after using it.

(As your pixels are rgba8888, they fit in unsigned 32 bit ints. You might want to pass Uint32s across in your pointer, and get them using data.buffer.asUint32List().)

You want to return a list of bool. bool isn't supported you you have to pass a list of, say, Int8 where you've set the values to 1 and 0 respectively. (If your list is bounded and reasonably sized, you could use a bitmap. For example, if you knew it was always 32 bits long, pack those bits into a Uint32 as 32 ones and zeroes.)

There are a couple of strategies for returning a list, where list in ffi is going to mean Pointer<something> of course.

If the list is bounded, you can allocate it on the Dart side, pass the pointer with the function and have the C function fill in the values, maybe returning an integer of the number it filled in.

If the list is unbounded you must allow C to malloc it, as only the C function knows how much space it needs. You now need to return 2 values: the pointer and the length. Since you can only return one value you need to do something like pass in a Pointer<Int32> and have the C function assign the length to that.


来源: stackexchange

问:
How can I limit the colorbar?
I am trying to make a map with this code. But I don't know how to choose the range of the colorbar. I tried with set_clim(min,max) but it doesn't work with matplotlib 3.1.

```<code>    plt.figure(figsize=(12,6))
    ax = plt.axes(projection=ccrs.PlateCarree())
    cs=ax.contourf(lon, lat, bowenratio, 11, cmap=plt.cm.Spectral_r)
    ax.coastlines()
    cbar = plt.colorbar(cs, orientation='horizontal',shrink=0.7)
</code>```

答:
Be sure to put plt.clim(min,max) after your visualization.

You can include the number of bins, based on your range within the cmap function as outlined in this example which also has a -1 to 1 range specified within a plt.clim function: https://stackoverflow.com/a/61896135/9022112

ContentLicense: CC BY-SA 4.0

Title: How can I limit the colorbar?

Body:
I am trying to make a map with this code. But I don't know how to choose the range of the colorbar. I tried with set_clim(min,max) but it doesn't work with matplotlib 3.1.

    plt.figure(figsize=(12,6))
    ax = plt.axes(projection=ccrs.PlateCarree())
    cs=ax.contourf(lon, lat, bowenratio, 11, cmap=plt.cm.Spectral_r)
    ax.coastlines()
    cbar = plt.colorbar(cs, orientation='horizontal',shrink=0.7)


问:
How to add multiple rows with decreasing values into a series
I have a series of number:

```
5138
22498
42955
```

I would like add 3 numbers (decrease 1 each) to each number above:

```
5135
5136
5137
5138
22495
22496
22497
22498
42952
42953
42954
42955
```

How to do that? Thanks.

答:
Use list comprehension with flatten new values created by range:

```<code>s = pd.Series([5138,22498,42955])

N = 3
a = pd.Series([y for x in s for y in range(x-N, x+1)])
print (a)
0      5135
1      5136
2      5137
3      5138
4     22495
5     22496
6     22497
7     22498
8     42952
9     42953
10    42954
11    42955
dtype: int64
</code>```

Or is possible create ranges and flatten by Series.explode, last Series.reset_index is used for default index:

```<code>N = 3
a = s.apply(lambda x: range(x-N, x+1)).explode().reset_index(drop=True)
</code>```

Body:
I have a series of number:

5138
22498
42955

I would like add 3 numbers (decrease 1 each) to each number above:

5135
5136
5137
5138
22495
22496
22497
22498
42952
42953
42954
42955

How to do that? Thanks.

Body:
Use list comprehension with flatten new values created by range:

s = pd.Series([5138,22498,42955])

N = 3
a = pd.Series([y for x in s for y in range(x-N, x+1)])
print (a)
0      5135
1      5136
2      5137
3      5138
4     22495
5     22496
6     22497
7     22498
8     42952
9     42953
10    42954
11    42955
dtype: int64

Or is possible create ranges and flatten by Series.explode, last Series.reset_index is used for default index:

N = 3
a = s.apply(lambda x: range(x-N, x+1)).explode().reset_index(drop=True)


问:
Does setTimeout functions remove after it worked?
I want to add data on a div that comes from socket. And remove it after 5 seconds. (I am using socket.io client)

```<code>socket.on("data", (data) => {

    // add this data on div

    setTimeout(()=>{
      // remove data from div.
    }, 5000);

})
</code>```

But a setTimeout function added each time a message arrives. May this a performance issue after some times? Should I remove it?

答:
There's no need to worry about calling clearTimeout in your case. See this question.

If you are concerned about performance, here's a post about a promising alternative to setTimeout that could be helpful to you.

Body:
I want to add data on a div that comes from socket. And remove it after 5 seconds. (I am using socket.io client)

socket.on("data", (data) => {

    // add this data on div

    setTimeout(()=>{
      // remove data from div.
    }, 5000);

})

But a setTimeout function added each time a message arrives. May this a performance issue after some times? Should I remove it?


问:
How to set innodb_thread_concurrency in MYSQL
My MYSQL DB is very slow but when I change the innodb_thread_concurrency value from the default 33 to 0 selects per second rise from 30-40 to 600-700. I would like to set this value every time the DB starts. I usually change variables in my.ini. There are 3 my.ini files on my system but the one in use (listed in MYSQL Workbench) is in the programdata directory. I have tried adding the variable to all 3 but it makes no difference. I must be getting the syntax wrong but I've tried several variations:
    innodb_thread_concurrency=0
    set-variable=innodb_thread_concurrency=0
Neither seem to work. Whenever I look at the system variable (in MYSQL Workbench) the innodb_thread_concurrency is 33 until I start a session and enter :
    set global innodb_thread_concurrency=0;
On Unix systems they talk about my.cnf but no such file exists on my W10 system.

What do I need to do to have this variable correctly set at startup?

答:
The correct syntax is:

```<code>innodb_thread_concurrency=0
</code>```

Make sure you add it to the [mysqld] section of the file.

Body:
The correct syntax is:

innodb_thread_concurrency=0

Make sure you add it to the [mysqld] section of the file.


答:
Last state is:
for s in range(1, steps_count):
                data = {'t': block['t'] + (step_size * s)}  # get every interim step for time

```<code>            for m in motors:
                if 0 != motors_diff[m]:
                    data[m] = (block[m] + (motors_steps[m] * (s/2) * (1-cos((pi*s)/(steps_count)))))   # rise/fall
                if 0 == motors_diff[m]:
                    data[m] = (block[m] + (motors_steps[m] * s))  #equals
            # push data to file
            write_line(data)
</code>```

Result:

Not nice Sinus really nice sinus. But best of, I can make.

Title: Python-Script - Create square intermediate values

Body:
I create intermediate, linear values with a Python script,
For example:

input:

000000,0,0,0,0,0
000100,20,90,0,0
016100,20,90,0,0
020100,90,20,0,0
024100,20.90,0.0
028100,90,20,0,0
030 100.0.0.0.0

after script I get output:

RCOU, 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0
RCOU, 100000,1200,1900,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 200000,1200,1900,1000,1000,0,0,0,0,0,0,0,0,0,0,0
.................................................. ..........................................
RCOU, 16100000,1200,1900,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 16200000,1218,1882,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 16300000.1235.1865.1000.1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 16400000,1252,1848,1000,1000,0,0,0,0,0,0,0,0,0,0,0
.................................................. ..........................................
RCOU, 28600000,1675,1150,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 28700000,1630,1140,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 28800000.1585.11130.1000.1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 28900000,1540,1120,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29000000,1495,1110,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29100000.1450.1100.1000.1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29200000,1405,1090,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29300000.1360.1080.1000.1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29400000,1315,1070,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29500000,1270,1060,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29600000,1225,1050,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29700000,1180,1040,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29800000,1135,1030,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 29900000,1090,1020,1000,1000,0,0,0,0,0,0,0,0,0,0,0
RCOU, 30000000,1045,1010,1000,1000,0,0,0,0,0,0,0,0,0,0,0

i.e. 3rd b 4th columns go linear increase and decrease from 1200 to 1900

However, I would like to create a function changing - between input values - square or sin/cos, not linear. In a diagram - replace the triangles by sine.

#!/usr/bin/env python3

from optparse import OptionParser
from sys import argv
import os
from random import randint

def read(file_name):
    b = []
    with open(file_name) as input_file:
        for line in input_file.readlines():
            parts = line.strip().split(',')

            b.append(
                {
                    't': int(parts[0]),
                    'm1': int(parts[1]),
                    'm2': int(parts[2]),
                    'm3': int(parts[3]),
                    'm4': int(parts[4])
                }
            )
    return b

def handle_args():
    parser = OptionParser()
    parser.add_option('-i', '--input', dest='input', help='Input config file that will be read from')
    parser.add_option('-o', '--output', dest='output', help='Output config file that will be written to')
    (opts, args) = parser.parse_args()
    if not opts.input:
        parser.error('Input file not given. {0} -h for help'.format(argv[0]))
        parser.print_help()

    if not opts.output:
        parser.error('Output file not given. {0} -h for help'.format(argv[0]))
        parser.print_help()

    return opts

def write_line(values):
    """
    write a csv line in output file, out of a values dict
    :param values: dict with the data (as declared in read()
    :return: None
    """
    with open(OUTPUT_FILE_NAME, 'a') as out:

        out.write('RCOU,')
        out.write(str(values['t']*1000) +',')

        for _m in motors:
            out.write(str(round(values[_m])) + ',')
        out.write('0,0,0,0,0,0,0,0,0,0')
        out.write('\n')

if __name__ == '__main__':
    options = handle_args()  # handle arguments givenk

    step_size = 100  # ms
    motors = ('m1', 'm2', 'm3', 'm4')  # the motors. Only as field accessors
    OUTPUT_FILE_NAME = options.output  # the output file to write data to. (given in the args)
    INPUT_FILE_NAME = options.input  # the output file to read data from. (given in the args)

    print('reading from', INPUT_FILE_NAME)
    print('writing to', OUTPUT_FILE_NAME)

    blocks = read(options.input)  # read all lines

    # delete file if already exists
    if os.path.exists(OUTPUT_FILE_NAME):
        os.remove(OUTPUT_FILE_NAME)

    # if more than one line in file
    if len(blocks) > 1:

        with open(OUTPUT_FILE_NAME, 'a') as out:

            out.write('samp_rate=44100\nchannel=1\nsamp_size=16\ncodec=Audio/PCM\nbyte_order=QAudioFormat::LittleEndian\nsample_type=QAudioFormat::SignedInt\n')
            # out.write('channel=1\n')
            # out.write('samp_size=16\n')
            # out.write('codec=Audio/PCM\n')
            # out.write('byte_order=QAudioFormat::LittleEndian\n')
            # out.write('sample_type=QAudioFormat::SignedInt\n')
            # out.write('\n')

        write_line(blocks[0])  # write the first line of the input file directly to the output file !!!+1000

        for i in range(0, len(blocks) - 1):  # for every line except the last one
            block = blocks[i]  # the current values
            next_block = blocks[i + 1]  # the next values

            # calculate the step based on the current and next time value and the step_size
            steps_count = int((next_block['t'] - block['t']) / step_size)
            motors_steps = {}

            # get data of the motor fields
            for m in motors:
                # calculate the step of every motor based on the time value
                motors_steps[m] = float((next_block[m] - block[m]) / steps_count)

            for s in range(1, steps_count + 1):
                data = {'t': block['t'] + (step_size * s)}  # get every interim step for time

                for m in motors:
                # data[m] = randint(1250,1500) # get every step random value for every motor
                data[m] = (block[m] + (motors_steps[m] * s)) * 10 + 1000  # get every interim step for every motor
                # push data to file
                write_line(data)

        with open(OUTPUT_FILE_NAME, 'a') as out:
            out.write('RCOU,10100000,56797,56797,56797,56797,0,0,0,0,0,0,0,0,0,0')
    else:
        print('not enough data...')

I think I have to modify this line?

data[m] = (block[m] + (motors_steps[m] * s)) * 10 + 1000  # get every interim step for every motor

Body:
Last state is:
for s in range(1, steps_count):
                data = {'t': block['t'] + (step_size * s)}  # get every interim step for time

            for m in motors:
                if 0 != motors_diff[m]:
                    data[m] = (block[m] + (motors_steps[m] * (s/2) * (1-cos((pi*s)/(steps_count)))))   # rise/fall
                if 0 == motors_diff[m]:
                    data[m] = (block[m] + (motors_steps[m] * s))  #equals
            # push data to file
            write_line(data)

Result:

Not nice Sinus really nice sinus. But best of, I can make.


问:
How to remove the Begin forwarded message: part of an email body in a rails 3 app
I am receiving forwarded email into my rails 3 app and is working ok.

But in a forwarded email it includes the following message at the top for example :

```<code>Begin forwarded message:

From: roger rabbit <sales@mysite.com>
Date: 23 May 2011 13:52:08 GMT+01:00
To: sam@yoursite.com
Subject: Hi threre

Dear Mike

Yes please do the work for me!
</code>```

This format changes as to which email client sent the message.

I want to strip this out of the body so i can show just the forwarded message like so :

```<code>Dear Mike

Yes please do the work for me!
</code>```

What is the best way to do this as i know i can do it for this specific format but i need it to be more general / clever.

Is there some gem / lib i should be using ?

Any help would be great.

thanks Rick

答:
I haven't heard of a gem or library that would help for this, but my first crack at this would be:

Tackling the "Begin forwarded message:" that varies between clients could be the tricky one.

Tackling the email headers should be easier as they should be predictable.

For number 1:  I would take a guess that in most (hopefully all) cases, you'd want to discard any lines above the "From:" line.  So, find the line number that "From:" is on (via regex probably), delete all lines above that.  This would avoid having to get all variations of "Begin forwarded message:" that different email clients would come up with.

For number 2:  Have a regex that checks for the email header information.  Something that checks for "From: " or "To: " etc tied to the start of the line and then delete that line if it matches.

I would try to get as many test cases (example forwarded emails) as possible to make sure you're system is working correctly.  Once you have a few specific examples that you're stuck on, we may be able to help further.

ContentLicense: CC BY-SA 3.0

Body:
I am receiving forwarded email into my rails 3 app and is working ok.

But in a forwarded email it includes the following message at the top for example :

Begin forwarded message:

From: roger rabbit <sales@mysite.com>
Date: 23 May 2011 13:52:08 GMT+01:00
To: sam@yoursite.com
Subject: Hi threre

Dear Mike

Yes please do the work for me!

This format changes as to which email client sent the message.

I want to strip this out of the body so i can show just the forwarded message like so :

Dear Mike

Yes please do the work for me!

What is the best way to do this as i know i can do it for this specific format but i need it to be more general / clever.

Is there some gem / lib i should be using ?

Any help would be great.

thanks Rick


问:
add class not working with html5 video player using jquery
I have a simple video block, on video ended I am displaying certain gif,

Problem:

Now when a user pauses the video the gif also shows up, meaning When the video has ended the gifs shows up now when I play again the video and pause the video the gifs show again

To do

I want when a user pauses the video the gif should not display, meaning the gif should show up only on video ended

Here is my solution

HTML

```<code><div canplay id="video-block">
    <div id="video-container">
        <video id="videoplayer" playsinline muted autoplay>
            <source src="videos/good_job.mp4"></source>
        </video>
        <div id="interactive-layers">
        </div>

    </div>

    <div id="pause-play-button">
        <img id="play" src="images/play.png">
        <img id="pause" src="images/pause.png">
    </div>
</code>```

Js

```<code>$(document).ready(function(){
        $("#videoplayer")[0].addEventListener("ended", onVideoEnded);
});

function showGif(gifname) {
        $("#gif-data").remove();
        var gif = $("<div id='gif-data'><audio class='audio' id='gifaudio'  autoplay src='" + gifs[gifname].audio + "'></audio><img class='gif' id='animatedgif' src='" + gifs[gifname].gif + "?rand=" + Math.random() + "'></div>")
        $("#interactive-layers").append(gif);
}

function onVideoEnded(e) {

        showGif("ed22");

}

$("#pause-play-button").on("click", function () {
        clearTheTimeout();
        if ($("#video-block video")[0].paused == true) {
                $("#gif-data").addClass("hidegif");
                $("#video-block video")[0].play();
                $("#pause").css("display", 'block');
                $("#play").css("display", "none");
        } else {
                $("#video-block video")[0].pause();
                $("#audioplayer")[0].pause();
                $("#gif-data").removeClass("hidegif");
                $("#pause").css("display", 'none');
                $("#play").css("display", "block");
        }
});
</code>```

CSS

```<code>.hidegif{
    display: none;
}
</code>```

Unfortunately, still, my giffs shows up when I click pause video button,

What am I doing wrong?

答: It's a few months old post but in my experience addEventListener not works all the time with Jquery but the .on event works. so when you are listening the ended event, do it with .on and write the showGif function inside it.

Body:
I have a simple video block, on video ended I am displaying certain gif,

Problem:

Now when a user pauses the video the gif also shows up, meaning When the video has ended the gifs shows up now when I play again the video and pause the video the gifs show again

To do

I want when a user pauses the video the gif should not display, meaning the gif should show up only on video ended

Here is my solution

HTML

        <video id="videoplayer" playsinline muted autoplay>
            <source src="videos/good_job.mp4"></source>
        </video>

Js

$(document).ready(function(){
        $("#videoplayer")[0].addEventListener("ended", onVideoEnded);
});

function showGif(gifname) {
        $("#gif-data").remove();
        var gif = $("
<audio class='audio' id='gifaudio'  autoplay src='" + gifs[gifname].audio + "'></audio>
")
        $("#interactive-layers").append(gif);
}

function onVideoEnded(e) {

        showGif("ed22");

}

$("#pause-play-button").on("click", function () {
        clearTheTimeout();
        if ($("#video-block video")[0].paused == true) {
                $("#gif-data").addClass("hidegif");
                $("#video-block video")[0].play();
                $("#pause").css("display", 'block');
                $("#play").css("display", "none");
        } else {
                $("#video-block video")[0].pause();
                $("#audioplayer")[0].pause();
                $("#gif-data").removeClass("hidegif");
                $("#pause").css("display", 'none');
                $("#play").css("display", "block");
        }
});

CSS

.hidegif{
    display: none;
}

Unfortunately, still, my giffs shows up when I click pause video button,

What am I doing wrong?


问:
Android 11 Package Visibilty issue
I have a app that downloads an apk from server, but I am unable to launch it like other android versions even though I have queries tag in android manifest

Here is the intent code:-

```<code>private void callInstallProcess() {
        try
        {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File file = new File(pathname);
            Uri fileUri = Uri.fromFile(file);
//            if (Build.VERSION.SDK_INT >= 24) {
//                fileUri = FileProvider.getUriForFile(this, getPackageName(),
//                        file);
//            }
            if(Build.VERSION.SDK_INT>=24){
                try{
                    Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
                    m.invoke(null);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(fileUri , "application/vnd.android.package-archive");
            startActivityForResult(intent, PERMISSIONS_REQUEST);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
</code>```

Here is my manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="x.x.x">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:mimeType="application/vnd.android.package-archive" />
    </intent>
</queries>
    <application
        android:allowBackup="false"
        android:icon="@mipmap/appicon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/appicon"
        android:networkSecurityConfig="@xml/network_security_config"

        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Gradle file:-

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "30.0.0-rc4"

    defaultConfig {
        applicationId "x.x.x"
        minSdkVersion 22
        targetSdkVersion 'R'
        versionCode 3
        versionName "1.11"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

I have allowed to my app the permission to install unknown apps on android R preview 4 emulator.

Log:-

```<code>W/System.err: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/Android/data/x.x.x/files/ApkDownload/x.x.x.apk typ=application/vnd.android.package-archive flg=0x3 }
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2067)
W/System.err:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
        at android.app.Activity.startActivityForResult(Activity.java:5323)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:5281)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at x.x.x.MainActivity.callInstallProcess(MainActivity.java:126)
        at x.x.x.MainActivity.askPerm(MainActivity.java:98)
W/System.err:     at x.x.x.MainActivity.access$000(MainActivity.java:42)
        at x.x.x.MainActivity$1.onClick(MainActivity.java:79)
        at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
D/EGL_emulation: eglMakeCurrent: 0xe8ae0220: ver 2 0 (tinfo 0xe8e31210)
</code>```

I am using android studio 4 and gradleversion is 4.0.0
Is it just a bug or am I doing something wrong as chrome manages to intent apk install.

答:
Is it just a bug or am I doing something wrong

You are doing something wrong.

Uri.fromFile() has been banned, in effect, since Android 7.0. Normally, your attempt to us it with an Intent would crash with a FileUriExposedException. Rather than fixing the problem, you decided to try to bypass the check, through your disableDeathOnFileUriExposure hack. However, nobody else has to honor your file:/// Uri, because, again, that has been banned for years. Apparently, Android R's installer no longer supports file:///.

So, at minimum, you need to switch to using FileProvider on Android 7.0+. Uri.fromFile() is fine for Android 6.0 and older, and specifically for what you are trying to do (install an APK), you have no choice but to use Uri.fromFile() for those older devices.

Also note that using ACTION_VIEW for installing an APK has been deprecated on Android 10+. Temporarily it still works, but Google would like you to switch to the PackageInstaller API instead.

Title: Android 11 Package Visibilty issue

Body:
I have a app that downloads an apk from server, but I am unable to launch it like other android versions even though I have queries tag in android manifest

Here is the intent code:-

private void callInstallProcess() {
        try
        {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File file = new File(pathname);
            Uri fileUri = Uri.fromFile(file);
//            if (Build.VERSION.SDK_INT >= 24) {
//                fileUri = FileProvider.getUriForFile(this, getPackageName(),
//                        file);
//            }
            if(Build.VERSION.SDK_INT>=24){
                try{
                    Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
                    m.invoke(null);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(fileUri , "application/vnd.android.package-archive");
            startActivityForResult(intent, PERMISSIONS_REQUEST);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

Here is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="x.x.x">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:mimeType="application/vnd.android.package-archive" />
    </intent>
</queries>
    <application
        android:allowBackup="false"
        android:icon="@mipmap/appicon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/appicon"
        android:networkSecurityConfig="@xml/network_security_config"

        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Gradle file:-

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "30.0.0-rc4"

    defaultConfig {
        applicationId "x.x.x"
        minSdkVersion 22
        targetSdkVersion 'R'
        versionCode 3
        versionName "1.11"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

I have allowed to my app the permission to install unknown apps on android R preview 4 emulator.

Log:-

W/System.err: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/Android/data/x.x.x/files/ApkDownload/x.x.x.apk typ=application/vnd.android.package-archive flg=0x3 }
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2067)
W/System.err:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
        at android.app.Activity.startActivityForResult(Activity.java:5323)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:5281)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at x.x.x.MainActivity.callInstallProcess(MainActivity.java:126)
        at x.x.x.MainActivity.askPerm(MainActivity.java:98)
W/System.err:     at x.x.x.MainActivity.access$000(MainActivity.java:42)
        at x.x.x.MainActivity$1.onClick(MainActivity.java:79)
        at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
D/EGL_emulation: eglMakeCurrent: 0xe8ae0220: ver 2 0 (tinfo 0xe8e31210)

I am using android studio 4 and gradleversion is 4.0.0
Is it just a bug or am I doing something wrong as chrome manages to intent apk install.


问:
How to create a dictionary from 2 lists and other dictionary in Python?
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

```<code>POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

</code>```

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

```<code>gandalf_wins=0
saruman_wins=0
</code>```

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

```<code>gandalf_power=[]
saruman_power=[]
</code>```

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!

答:
I don't think you need a dictionary for this. You can try:</p>

```<code>for x in range(spells):
    gandalf_attack = POWER[gandalf[x]]
    saruman_attack = POWER[saruman[x]]
    if gandalf_attack>saruman_attack:
        # Do something
    elif gandalf_attack>saruman_attack:
        # Do something
    else:
        # Tie
</code>```

Body:
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

gandalf_wins=0
saruman_wins=0

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

gandalf_power=[]
saruman_power=[]

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!

Body:
I don't think you need a dictionary for this. You can try:

for x in range(spells):
    gandalf_attack = POWER[gandalf[x]]
    saruman_attack = POWER[saruman[x]]
    if gandalf_attack>saruman_attack:
        # Do something
    elif gandalf_attack>saruman_attack:
        # Do something
    else:
        # Tie


问:
Making all form inputs to be in readonly mode while clicking submit button
I have a form when the submit button is clicked form's all inputs needs to be in read-only mode and hide submit button and also displays submitting text. For this I coded:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('readonly', true); //Making all inputs to readonly

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}</code>```

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>```

When I click the submit button it hides the submit button and shows submitting text. But it doesn't change the input property to read-only mode.

答:
Readonly does not work on radio buttons, you can use disabled: true, however...

See this answer to understand the difference between disabled and readonly: What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").attr('disabled', true); //Making all inputs to readonly

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}</code>```

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>```

Body:
I have a form when the submit button is clicked form's all inputs needs to be in read-only mode and hide submit button and also displays submitting text. For this I coded:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('readonly', true); //Making all inputs to readonly

  });
});

.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>

When I click the submit button it hides the submit button and shows submitting text. But it doesn't change the input property to read-only mode.

Body:
Readonly does not work on radio buttons, you can use disabled: true, however...

See this answer to understand the difference between disabled and readonly: What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").attr('disabled', true); //Making all inputs to readonly

  });
});

.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="hiddenFrame" class="hiddenFramehideclass"></iframe>

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1
  <div class="question_container">
    <div class="question_div">
      <p>Question?</p>
      <input type="hidden" name="qid1" value="22">
      <div class="option_div">
        <input type="radio" name="radio1" id="checka1" value="A">
        <label for="checka1">
          <p>A</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkb1" value="B">
        <label for="checkb1">
          <p>B</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkc1" value="C">
        <label for="checkc1">
          <p>C</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkd1" value="D">
        <label for="checkd1">
          <p>D</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checke1" value="E">
        <label for="checke1">
          <p>None of the above</p>
        </label>
      </div>
    </div>
  </div>
  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  <span id="submit_text">Submitting please <b>do not</b> refresh!</span>
</form>


问:
getting null in get serviece call without error in Angular
i get null in the subscribe statemaent,
the Api returns the correct data,
but in angular its accepted as null.
what should be the problem?
here is my subscribe in ts:

```<code>this.service.getFlightId( this.addFlightForm.controls["date"].value, this.addFlightForm.controls["time"].value,
this.originId,
this.destinationId,
this.addFlightForm.controls["flightNum"].value)
   .subscribe(data=>{
  this.flight=data;
}, err=>{
  this.noFlightId=true;
});
</code>```

and this is my serviece:

```<code>getFlightId(date:Date,time:Time,originId:number,destinationId:number,flightNum:number):Observable<Flight>{
        return this._http.get<Flight>("/api/flight/"+date+"/"+time+"/"+originId+"/"+destinationId+"/"+flightNum);
    }
</code>```

答:
As your configurationUrl = "/api/flight/"+date+"/"+time+"/"+originId+"/"+destinationId+"/"+flightNum`. I hope you cannot have any api call with exact parmas like

```<code>/flight/23-06-2020/12:00/originId/DestinationId/filghtnumber
</code>```

can you check in your backend if you have an API request like this /api/flight/23-06-2020/12:00/Austria/germany/F121.

Generally we make http call like below,

```<code>this.httpClient.get<any>(url, { params: x });
</code>```

Or may be this Link or stakeoverflow link can help you.

Body:
i get null in the subscribe statemaent,
the Api returns the correct data,
but in angular its accepted as null.
what should be the problem?
here is my subscribe in ts:

this.service.getFlightId( this.addFlightForm.controls["date"].value, this.addFlightForm.controls["time"].value,
this.originId,
this.destinationId,
this.addFlightForm.controls["flightNum"].value)
   .subscribe(data=>{
  this.flight=data;
}, err=>{
  this.noFlightId=true;
});

and this is my serviece:

getFlightId(date:Date,time:Time,originId:number,destinationId:number,flightNum:number):Observable<Flight>{
        return this._http.get<Flight>("/api/flight/"+date+"/"+time+"/"+originId+"/"+destinationId+"/"+flightNum);
    }

Body:
As your configurationUrl = "/api/flight/"+date+"/"+time+"/"+originId+"/"+destinationId+"/"+flightNum`. I hope you cannot have any api call with exact parmas like

/flight/23-06-2020/12:00/originId/DestinationId/filghtnumber

can you check in your backend if you have an API request like this /api/flight/23-06-2020/12:00/Austria/germany/F121.

Generally we make http call like below,

this.httpClient.get<any>(url, { params: x });

Or may be this Link or stakeoverflow link can help you.


问:
Changing UITextField Placeholder font
I'm changing the placeholder text color with the following code, but when I try to add NSFontAttribute I get the compiler error "too many arguments to method call, expect 2 have 3"

```<code> UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color},@{NSFontAttributeName:@"Roboto-Bold"}];
</code>```

This Works Fine:

```<code> UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color}];
</code>```

答:
Update for Swift 4.2 +

```<code>let attributes = [NSAttributedString.Key.foregroundColor: UIColor.black,
                  .font: UIFont.systemFont(ofSize: 14)]

searchTextField.attributedPlaceholder = NSAttributedString(string: "Placeholder text",
                                                           attributes: attributes)
</code>```

Reference for more attribute Keys - NSAttributedString.Key

Title: Changing UITextField Placeholder font

Body:
I'm changing the placeholder text color with the following code, but when I try to add NSFontAttribute I get the compiler error "too many arguments to method call, expect 2 have 3"

 UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color},@{NSFontAttributeName:@"Roboto-Bold"}];

This Works Fine:

 UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color}];

Body:
Update for Swift 4.2 +

let attributes = [NSAttributedString.Key.foregroundColor: UIColor.black,
                  .font: UIFont.systemFont(ofSize: 14)]

searchTextField.attributedPlaceholder = NSAttributedString(string: "Placeholder text",
                                                           attributes: attributes)

Reference for more attribute Keys - NSAttributedString.Key


问:
How to avoid if statements which returns value based on the input in java 8
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

```<code>RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}
</code>```

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

答:
I am not sure if the RoleEnum is under your control or not.

But I don't understand what is represents

User's role

Validation required for a user's role

Both

I think it represents option 3, perhaps required in your use case. But it has more than one reason to change. Please consider segregating them.

If you do so, your function changes to accept a RoleEnum and return a RoleValidationEnum.

You can use a switch to decide which RoleEnum returns which RoleValidationEnum.

I hope this helps.

Body:
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.


问:
Select the value of an element by name
How to access the value of this input field that is checked by its name attribute using Javascript :

```<code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
</code>```

I write this :

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

but there is an error:

```<code>TypeError: document.querySelector(...) is null
</code>```

And I do not want to be checked any inputs by default

答:
You're missing quotes:</p>

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

Title: Select the value of an element by name

Body:
How to access the value of this input field that is checked by its name attribute using Javascript :

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">

I write this :

document.querySelector('input[name="rate"]:checked').value;

but there is an error:

TypeError: document.querySelector(...) is null

And I do not want to be checked any inputs by default

Body:
You're missing quotes:

document.querySelector('input[name="rate"]:checked').value;


问:
How to run a function only when data is received from an xmlhttp call?
How can run an init() function that sets an innerHTML on my dom only when my getData() functions returns the array?

I am pretty sure i will need to have some kind of async await function here, but i am learning closures
 at the same time and not sure how can i do this.

Code would like something like this:

```<code>const uiController = (function () {
  let data;

  const getData = async () => {
    const xml = new XMLHttpRequest();

    xml.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        data = getArray(JSON.parse(this.responseText));
      }
    };

    xml.open("GET", "data.json", true);
    xml.send();

  };

  getData();

  // I only want init to run when getData() is finished and my data variable is updated with the fetched data.

  // Something similar to react ComponentDidMount
  const init = () => {

  document.getElementById("article-grid").innerHTML = `<div>${data}</div>`

  }
</code>```

Thank you :)

答:
```<code>const uiController = (function () {
let data;
// Something similar to react ComponentDidMount
const init = () => {
  document.getElementById("article-grid").innerHTML = `<div>${data}</div>`
}
const getData = async () => {
  const xml = new XMLHttpRequest();

  xml.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      data = getArray(JSON.parse(this.responseText));
      init(); // call inside readyState === 4
    }
  };

  xml.open("GET", "data.json", true);
  xml.send();
};

getData();
</code>```

Body:
How can run an init() function that sets an innerHTML on my dom only when my getData() functions returns the array?

I am pretty sure i will need to have some kind of async await function here, but i am learning closures
 at the same time and not sure how can i do this.

Code would like something like this:

const uiController = (function () {
  let data;

  const getData = async () => {
    const xml = new XMLHttpRequest();

    xml.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        data = getArray(JSON.parse(this.responseText));
      }
    };

    xml.open("GET", "data.json", true);
    xml.send();

  };

  getData();

  // I only want init to run when getData() is finished and my data variable is updated with the fetched data.

  // Something similar to react ComponentDidMount
  const init = () => {

  document.getElementById("article-grid").innerHTML = `<div>${data}</div>`

  }

Thank you :)


问:
Remove entities in CoreData from Swift
I am very new to Swift and I would like to remove of the students I have in CoreData from Swift. I have coded this :

```<code>let fetchRequest: FetchRequest<Student> = FetchRequest(entity: Student.entity(), sortDescriptors: [])
var students: FetchedResults<Student> { fetchRequest.wrappedValue }
for student in students {
  do {
    try self.managedObjectContext.delete(student)
  } catch {
    print("error")
  }
}
</code>```

but it crashes at run-time saying that I have an EXC_BAD_INSTRUCTION on the line where I initialize the students variable. What can I do to make this program correct?

Thanks for your help,
Francois

答:
To perform delete from CoreData on FetchedResults of an NSManagedObject, here's the code:

@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
    entity: Student.entity(),
    sortDescriptors: []
) var students: FetchedResults<Student>

func deleteAllStudents() {
    for student in students {
        managedObjectContext.delete(student)
    }
    do {
        try managedObjectContext.save()
    } catch {
        // handle the Core Data error
    }
}
```

<p>If, you want to delete only a few entries then use this:</p>

<pre class="lang-swift prettyprint-override"><code>func removeStudents(at offsets: IndexSet) { // Could use [Student] instead too.
    for index in offsets {
        let student = students[index]
        managedObjectContext.delete(student)
    }
    // save context...
}
</code>```

Title: Remove entities in CoreData from Swift

Body:
I am very new to Swift and I would like to remove of the students I have in CoreData from Swift. I have coded this :

let fetchRequest: FetchRequest<Student> = FetchRequest(entity: Student.entity(), sortDescriptors: [])
var students: FetchedResults<Student> { fetchRequest.wrappedValue }
for student in students {
  do {
    try self.managedObjectContext.delete(student)
  } catch {
    print("error")
  }
}

but it crashes at run-time saying that I have an EXC_BAD_INSTRUCTION on the line where I initialize the students variable. What can I do to make this program correct?

Thanks for your help,
Francois

Body:
To perform delete from CoreData on FetchedResults of an NSManagedObject, here's the code:

@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
    entity: Student.entity(),
    sortDescriptors: []
) var students: FetchedResults<Student>

func deleteAllStudents() {
    for student in students {
        managedObjectContext.delete(student)
    }
    do {
        try managedObjectContext.save()
    } catch {
        // handle the Core Data error
    }
}

If, you want to delete only a few entries then use this:

func removeStudents(at offsets: IndexSet) { // Could use [Student] instead too.
    for index in offsets {
        let student = students[index]
        managedObjectContext.delete(student)
    }
    // save context...
}


问:
What's the right navigation structure for iOS Swift app with onboarding screens?
I'm creating an app that works as follows

Launch Screen

a. if "Getting Started" screens have been viewed and accepted then open main app

b. if not viewed/accepted then show "Getting started", then show main app once accepted

The "Getting Started" screens are quite self-contained so I've created a Storyboard for them, whereas the main app will be programatically created.

Where should the logic for (2) live? I was thinking about creating some sort of UINavigationController that would sit above both sets of screens and could decided what to show. Alternatively, I was going to just launch the main app VC and let the logic to show the "Getting Started" as a modal live there.

Any suggestions on best practise please?

答:
There is no definitive answer. However, you may try to anticipate your needs a little bit:

if the onboarding screen is the only thing you will ever display this way, then you can put some code in the AppDelegate or in your main view controller,

if you plan to display this kind of screen after some releases (to present new features for example), you can use some kind of modal mechanism that can display a full screen modal that can be dismissed.

Regardless of the solution you choose:

Try to keep your code in an appropriate class or struct: the logic to decide what screen to show and how to create the view controller must be in an appropriate class or struct. This logic does not belong either in the AppDelegate nor in your home view controller — by the way, this is how you end with huge and messy view controllers.

For your need — choosing between several entities of the same kind — you can take a look at the factory design pattern. It is a common structure that encapsulates logic to create entities. You can design it to choose between your controllers:

class RootViewControllerFactory {

  var rootViewController: UIViewController {
    if shouldDisplayOnboardingScreen() {
      return generateOnboardingScreen()
    } else {
      return generateHomeScreen()
    }
  }

  private func shouldDisplayOnboardingScreen() -> Bool {
    // Your logic to decide whether you should display it or not.
  }

  func generateOnboardingScreen() -> UIViewController {
    // Load it from your storyboard
  }

  func generateHomeScreen() -> UIViewController {
    // Load it programmatically
  }

}
```

<p>Then, your <code>AppDelegate</code> can use the proper view controller, but the code is not mixed up in the loading code. This makes reading much easier:</p>

<pre class="lang-swift prettyprint-override"><code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    self.window?.rootViewController = RootViewControllerFactory().rootViewController
    self.window?.makeKeyAndVisible()

    return true
}
</code>```

With this solution, when the onboarding view controller is dismissed, you can call the generateHomeScreen() function of your factory to get the home screen and switch to it.

Body:
There is no definitive answer. However, you may try to anticipate your needs a little bit:

if the onboarding screen is the only thing you will ever display this way, then you can put some code in the AppDelegate or in your main view controller,

if you plan to display this kind of screen after some releases (to present new features for example), you can use some kind of modal mechanism that can display a full screen modal that can be dismissed.

Regardless of the solution you choose:

Try to keep your code in an appropriate class or struct: the logic to decide what screen to show and how to create the view controller must be in an appropriate class or struct. This logic does not belong either in the AppDelegate nor in your home view controller — by the way, this is how you end with huge and messy view controllers.

For your need — choosing between several entities of the same kind — you can take a look at the factory design pattern. It is a common structure that encapsulates logic to create entities. You can design it to choose between your controllers:

class RootViewControllerFactory {

  var rootViewController: UIViewController {
    if shouldDisplayOnboardingScreen() {
      return generateOnboardingScreen()
    } else {
      return generateHomeScreen()
    }
  }

  private func shouldDisplayOnboardingScreen() -> Bool {
    // Your logic to decide whether you should display it or not.
  }

  func generateOnboardingScreen() -> UIViewController {
    // Load it from your storyboard
  }

  func generateHomeScreen() -> UIViewController {
    // Load it programmatically
  }

}

Then, your AppDelegate can use the proper view controller, but the code is not mixed up in the loading code. This makes reading much easier:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    self.window?.rootViewController = RootViewControllerFactory().rootViewController
    self.window?.makeKeyAndVisible()

    return true
}

With this solution, when the onboarding view controller is dismissed, you can call the generateHomeScreen() function of your factory to get the home screen and switch to it.


问:
XPath - Get node with no child of specific type
XML: /A/B or /A

I want to get all A nodes that do not have any B children.

I've tried

```<code>/A[not(B)]
/A[not(exists(B))]
</code>```

without success

I prefer a solution with the syntax /*[local-name()="A" and .... ], if possible. Any ideas that works?

Clarification. The xml looks like:

```<code><WhatEver>
  <A>
    <B></B>
  </A>
</WhatEver>
</code>```

or

```<code><WhatEver>
  <A></A>
</WhatEver>
</code>```

答: Try this "/A[not(.//B)]" or this "/A[not(./B)]".

Body:
XML: /A/B or /A

I want to get all A nodes that do not have any B children.

I've tried

/A[not(B)]
/A[not(exists(B))]

without success

I prefer a solution with the syntax /*[local-name()="A" and .... ], if possible. Any ideas that works?

Clarification. The xml looks like:

<WhatEver>

</WhatEver>

or

<WhatEver>

</WhatEver>


答:
```<code>SQL> with t(mydate, shift, mass) as
  2  (
  3   select '01-05-2020', 'A', 5 from dual union all
  4   select '01-05-2020', 'B', 3 from dual union all
  5   select '01-05-2020', 'B', 3 from dual union all
  6   select '02-05-2020', 'A', 11 from dual union all
  7   select '02-05-2020', 'A', 5 from dual union all
  8   select '02-05-2020', 'C', 12 from dual union all
  9   select '02-05-2020', 'C', 12 from dual union all
 10   select '02-05-2020', 'B', 5 from dual
 11  )
 12  SELECT mydate,shift,
 13         SUM(CASE WHEN mass >=3 AND
 14                       mass < 10 THEN 1 ELSE 0 END) AS "mass>=3",
 15         SUM(CASE WHEN mass >10 THEN 1 ELSE 0 END) AS "mass>10"
 16    FROM t
 17   GROUP BY mydate,shift
 18   ORDER BY mydate,shift;

MYDATE     S    mass>=3    mass>10
---------- - ---------- ----------
01-05-2020 A          1      0
01-05-2020 B          2      0
02-05-2020 A          1      1
02-05-2020 B          1      0
02-05-2020 C          0      2

SQL>
SQL>
</code>```

Title: How to Use Group By on the Basis of Column Value?

Body:
I am trying to use Group By but unable to achieve the output
I want to Group by with Date, shift and with Mass.

Data is like :

date     | shift | mass
---------+-------+------
01-05-20 | A     | 5
01-05-20 | B     | 3
01-05-20 | B     | 3
02-05-20 | A     | 11
02-05-20 | A     | 5
02-05-20 | C     | 12
02-05-20 | C     | 12
02-05-20 | B     | 5

OutPut which i want

date     | shift | mass>3 | mass>10
---------+-------+--------+--------
01-05-20 | A     | 1      | 0
01-05-20 | B     | 2      | 0
02-05-20 | A     | 1      | 1
02-05-20 | B     | 1      | 0
02-05-20 | C     | 0      | 2


问:
In Selenium maven project not able to lunch the chrome browser
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:847)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:134)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:35)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:159)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
    at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:123)
    at iotdatanormalization.Datanormalization.beforeClass(Datanormalization.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)</p>

答:
```<code>    enter code here
<dependency>
     <groupId>io.github.bonigarcia</groupId>
     <artifactId>webdrivermanager</artifactId>
     <version>2.2.5</version>
</dependency>
<dependency>
     <groupId>org.seleniumhq.selenium</groupId>
     <artifactId>selenium-chrome-driver</artifactId>
     <version>2.50.0</version>//Your chrome driver version
</dependency>

package example;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DepChrome  {
    @Test
    public void testBrowser() {
        WebDriver driver;
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.get("https://google.com");
        String title = driver.getTitle();
        System.out.println(title);
        driver.quit();
    }
}
</code>```


问:
You must feed a value for placeholder tensor 'Placeholder_2' with dtype double and shape [25,25]
I am trying to construct my own ELM  and i need to fetch the Beta weight initialized in my class object in python. However, I tried am=lmost all things that i could find on tensor guide or from the internet, but i guess it's a silly mistake of structuring the code.

My code looks like this

```<code>def __init__(self,input_nodes,hidden_nodes,output_nodes):
 ....
  self.__beta = tf.zeros((Hidden_nodes,Output_nodes),dtype=tf.dtypes.float64,name=None)

def seq_train_graph(self):
   ....
  UPDATE = tf.matmul(tf.matmul(K_inverse, HT), inverse_acti_y - tf.matmul(H, self.__beta))
  An = self.__beta + UPDATE
  self.__beta = An

def retrieve_beta(self):
    return self.__sess.run(self.__beta )
</code>```

according to this class' code. retrieve_beta function is used to get the value of a beta weight of the network.
When i run the code, i get the following error

```<code>InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype double and shape [25,25]
     [[node Placeholder_2 (defined at <ipython-input-17-8874f24bd69c>:18) ]]

</code>```

I tried feeding the network call by adding feed_dict

```<code>self.__sess.run(self.__beta ,feed_dict={An: self.An })
</code>```

but no luck. getting an error of

```<code>TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles. For reference, the tensor object was Tensor("add_248:0", shape=(25, 100), dtype=float64) which was passed to the feed with key Tensor("Placeholder_5:0", shape=(25, 100), dtype=float64).
</code>```

I believe it's supposed to get an nd array instead of a tensor object. But in my case, beta weight is only initialized by the value of An (  self.__beta = An)  as far as i can see. or if i am missing something, please help me out.

Thanks

答:
You need to initialize beta with tf.Variable instead of tf.placeholder.

The below code provides you the detail of the custom implementation of ELM.

```<code>import tensorflow as tf
import numpy as np

# CHECK : Constants
omega = 1.

class ELM(object):
  def __init__(self, sess, batch_size, input_len, hidden_num, output_len):
    '''
    Args:
      sess : TensorFlow session.
      batch_size : The batch size (N)
      input_len : The length of input. (L)
      hidden_num : The number of hidden node. (K)
      output_len : The length of output. (O)
    '''

    self._sess = sess
    self._batch_size = batch_size
    self._input_len = input_len
    self._hidden_num = hidden_num
    self._output_len = output_len

    # for train
    self._x0 = tf.placeholder(tf.float32, [self._batch_size, self._input_len])
    self._t0 = tf.placeholder(tf.float32, [self._batch_size, self._output_len])

    # for test
    self._x1 = tf.placeholder(tf.float32, [None, self._input_len])
    self._t1 = tf.placeholder(tf.float32, [None, self._output_len])

    self._W = tf.Variable(
      tf.random_normal([self._input_len, self._hidden_num]),
      trainable=False, dtype=tf.float32)
    self._b = tf.Variable(
      tf.random_normal([self._hidden_num]),
      trainable=False, dtype=tf.float32)
    self._beta = tf.Variable(
      tf.zeros([self._hidden_num, self._output_len]),
      trainable=False, dtype=tf.float32)
    self._var_list = [self._W, self._b, self._beta]

    self.H0 = tf.matmul(self._x0, self._W) + self._b # N x L
    self.H0_T = tf.transpose(self.H0)

    self.H1 = tf.matmul(self._x1, self._W) + self._b # N x L
    self.H1_T = tf.transpose(self.H1)

    # beta analytic solution : self._beta_s (K x O)
    if self._input_len < self._hidden_num: # L < K
      identity = tf.constant(np.identity(self._hidden_num), dtype=tf.float32)
      self._beta_s = tf.matmul(tf.matmul(tf.matrix_inverse(
        tf.matmul(self.H0_T, self.H0) + identity/omega),
        self.H0_T), self._t0)
      # _beta_s = (H_T*H + I/om)^(-1)*H_T*T
    else:
      identity = tf.constant(np.identity(self._batch_size), dtype=tf.float32)
      self._beta_s = tf.matmul(tf.matmul(self.H0_T, tf.matrix_inverse(
        tf.matmul(self.H0, self.H0_T)+identity/omega)), self._t0)
      # _beta_s = H_T*(H*H_T + I/om)^(-1)*T

    self._assign_beta = self._beta.assign(self._beta_s)
    self._fx0 = tf.matmul(self.H0, self._beta)
    self._fx1 = tf.matmul(self.H1, self._beta)

    self._cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self._fx0, labels=self._t0))

    self._init = False
    self._feed = False

    # for the mnist test
    self._correct_prediction = tf.equal(tf.argmax(self._fx1,1), tf.argmax(self._t1,1))
    self._accuracy = tf.reduce_mean(tf.cast(self._correct_prediction, tf.float32))

  def feed(self, x, t):
    '''
    Args :
      x : input array (N x L)
      t : label array (N x O)
    '''

    if not self._init : self.init()
    self._sess.run(self._assign_beta, {self._x0:x, self._t0:t})
    self._feed = True

  def init(self):
    self._sess.run(tf.initialize_variables(self._var_list))
    self._init = True

  def test(self, x, t=None):
    if not self._feed : exit("Not feed-forward trained")
    if t is not None :
      print("Accuracy: {:.9f}".format(self._sess.run(self._accuracy, {self._x1:x, self._t1:t})))
    else :
      return self._sess.run(self._fx1, {self._x1:x})
</code>```

Hope this answers your question, Happy Learning!

Body:
I am trying to construct my own ELM  and i need to fetch the Beta weight initialized in my class object in python. However, I tried am=lmost all things that i could find on tensor guide or from the internet, but i guess it's a silly mistake of structuring the code.

My code looks like this

def __init__(self,input_nodes,hidden_nodes,output_nodes):
 ....
  self.__beta = tf.zeros((Hidden_nodes,Output_nodes),dtype=tf.dtypes.float64,name=None)

def seq_train_graph(self):
   ....
  UPDATE = tf.matmul(tf.matmul(K_inverse, HT), inverse_acti_y - tf.matmul(H, self.__beta))
  An = self.__beta + UPDATE
  self.__beta = An

def retrieve_beta(self):
    return self.__sess.run(self.__beta )

according to this class' code. retrieve_beta function is used to get the value of a beta weight of the network.
When i run the code, i get the following error

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype double and shape [25,25]
     [[node Placeholder_2 (defined at <ipython-input-17-8874f24bd69c>:18) ]]

I tried feeding the network call by adding feed_dict

self.__sess.run(self.__beta ,feed_dict={An: self.An })

but no luck. getting an error of

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles. For reference, the tensor object was Tensor("add_248:0", shape=(25, 100), dtype=float64) which was passed to the feed with key Tensor("Placeholder_5:0", shape=(25, 100), dtype=float64).

I believe it's supposed to get an nd array instead of a tensor object. But in my case, beta weight is only initialized by the value of An (  self.__beta = An)  as far as i can see. or if i am missing something, please help me out.

Thanks

Body:
You need to initialize beta with tf.Variable instead of tf.placeholder.

The below code provides you the detail of the custom implementation of ELM.

import tensorflow as tf
import numpy as np

# CHECK : Constants
omega = 1.

class ELM(object):
  def __init__(self, sess, batch_size, input_len, hidden_num, output_len):
    '''
    Args:
      sess : TensorFlow session.
      batch_size : The batch size (N)
      input_len : The length of input. (L)
      hidden_num : The number of hidden node. (K)
      output_len : The length of output. (O)
    '''

    self._sess = sess
    self._batch_size = batch_size
    self._input_len = input_len
    self._hidden_num = hidden_num
    self._output_len = output_len

    # for train
    self._x0 = tf.placeholder(tf.float32, [self._batch_size, self._input_len])
    self._t0 = tf.placeholder(tf.float32, [self._batch_size, self._output_len])

    # for test
    self._x1 = tf.placeholder(tf.float32, [None, self._input_len])
    self._t1 = tf.placeholder(tf.float32, [None, self._output_len])

    self._W = tf.Variable(
      tf.random_normal([self._input_len, self._hidden_num]),
      trainable=False, dtype=tf.float32)
    self._b = tf.Variable(
      tf.random_normal([self._hidden_num]),
      trainable=False, dtype=tf.float32)
    self._beta = tf.Variable(
      tf.zeros([self._hidden_num, self._output_len]),
      trainable=False, dtype=tf.float32)
    self._var_list = [self._W, self._b, self._beta]

    self.H0 = tf.matmul(self._x0, self._W) + self._b # N x L
    self.H0_T = tf.transpose(self.H0)

    self.H1 = tf.matmul(self._x1, self._W) + self._b # N x L
    self.H1_T = tf.transpose(self.H1)

    # beta analytic solution : self._beta_s (K x O)
    if self._input_len < self._hidden_num: # L < K
      identity = tf.constant(np.identity(self._hidden_num), dtype=tf.float32)
      self._beta_s = tf.matmul(tf.matmul(tf.matrix_inverse(
        tf.matmul(self.H0_T, self.H0) + identity/omega),
        self.H0_T), self._t0)
      # _beta_s = (H_T*H + I/om)^(-1)*H_T*T
    else:
      identity = tf.constant(np.identity(self._batch_size), dtype=tf.float32)
      self._beta_s = tf.matmul(tf.matmul(self.H0_T, tf.matrix_inverse(
        tf.matmul(self.H0, self.H0_T)+identity/omega)), self._t0)
      # _beta_s = H_T*(H*H_T + I/om)^(-1)*T

    self._assign_beta = self._beta.assign(self._beta_s)
    self._fx0 = tf.matmul(self.H0, self._beta)
    self._fx1 = tf.matmul(self.H1, self._beta)

    self._cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self._fx0, labels=self._t0))

    self._init = False
    self._feed = False

    # for the mnist test
    self._correct_prediction = tf.equal(tf.argmax(self._fx1,1), tf.argmax(self._t1,1))
    self._accuracy = tf.reduce_mean(tf.cast(self._correct_prediction, tf.float32))

  def feed(self, x, t):
    '''
    Args :
      x : input array (N x L)
      t : label array (N x O)
    '''

    if not self._init : self.init()
    self._sess.run(self._assign_beta, {self._x0:x, self._t0:t})
    self._feed = True

  def init(self):
    self._sess.run(tf.initialize_variables(self._var_list))
    self._init = True

  def test(self, x, t=None):
    if not self._feed : exit("Not feed-forward trained")
    if t is not None :
      print("Accuracy: {:.9f}".format(self._sess.run(self._accuracy, {self._x1:x, self._t1:t})))
    else :
      return self._sess.run(self._fx1, {self._x1:x})

Hope this answers your question, Happy Learning!


问:
Display used coupons + specific message on WooCommerce order Emails
I'm trying to display used coupons on WooCommerce order emails + add specific messages based on the used coupons.

Displaying coupons is working based on

Add Applied Coupon Code in Admin New Order Email Template - WooCommerce

I'm trying to expand on it by checking if the string $coupon_codes contains specific words/specific coupons, in this case "grouppurchase", and then displaying a message.

It needs to be for $coupon_codes as it can (and will be) used with multiple coupons

I managed to make it work with following code

How do I check if a string contains a specific word?

The problem is (strpos) it displays the message whenever ANY coupon is used, doesn't matter that is written in the coupon, and I can't figure out why

I'm following the strpos logic behind this answer

// Display used Coupons on Emails and Add GroupPurchase Warning
add_action( 'woocommerce_email_after_order_table', 'display_applied_coupons', 10, 4 );
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for admins and when there at least 1 coupon in the order
    if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;

    foreach( $order->get_items('coupon') as $coupon ){
        $coupon_codes[] = $coupon->get_code();
    }

    // For one coupon
    if( count($coupon_codes) == 1 ){
        $coupon_code = reset($coupon_codes);
        echo '
'.__( 'Used Coupon: ').$coupon_code.'
';
    }

    // For multiple coupons
    else {
        $coupon_codes = implode( ', ', $coupon_codes);
        echo '
'.__( 'Used Coupons: ').$coupon_codes.'
';
    }

    if (strpos($coupon_codes, 'groupurchase') !== false) {
        echo '
' . 'With this coupon you are participating in a group purchase' . '
' ;
    }

}
```

答:
Give it a try this way

// The email function hooked that display the text
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for admins and when there at least 1 coupon in the order
    if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;

    foreach( $order->get_items('coupon') as $coupon ){
        $coupon_codes[] = $coupon->get_code();
    }

    // For one coupon
    if( count( $coupon_codes ) == 1 ){
        $coupon_code = reset( $coupon_codes );

        // Set variable output
        $output = '
' . __( 'Coupon Used: ', 'woocommerce' ) . $coupon_code . '
';

        // Extra
        if ( strpos( $coupon_code, 'groupurchase') !== false ) {
            // Append to
            $output .= '
' . __('With this coupon you are participating in a group purchase', 'woocommerce') . '
';
        }

        // Echo output
        echo $output;
    } else { // For multiple coupons
        // Loop
        foreach ( $coupon_codes as $coupon_code ) {
            // Set variable output
            $output = '
' . __( 'Coupon Used: ', 'woocommerce' ) . $coupon_code . '
';

            // Extra
            if ( strpos( $coupon_code, 'groupurchase') !== false ) {
                // Append to
                $output .= '
' . __('With this coupon you are participating in a group purchase', 'woocommerce') . '
';
            }

            // Echo output
            echo $output;
        }
    }
}
add_action( 'woocommerce_email_order_details', 'display_applied_coupons', 10, 4 );
```

Body:
Give it a try this way

// The email function hooked that display the text
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for admins and when there at least 1 coupon in the order
    if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;

    foreach( $order->get_items('coupon') as $coupon ){
        $coupon_codes[] = $coupon->get_code();
    }

    // For one coupon
    if( count( $coupon_codes ) == 1 ){
        $coupon_code = reset( $coupon_codes );

        // Set variable output
        $output = '<p>' . __( 'Coupon Used: ', 'woocommerce' ) . $coupon_code . '</p>';

        // Extra
        if ( strpos( $coupon_code, 'groupurchase') !== false ) {
            // Append to
            $output .= '<p>' . __('With this coupon you are participating in a group purchase', 'woocommerce') . '</p>';
        }

        // Echo output
        echo $output;
    } else { // For multiple coupons
        // Loop
        foreach ( $coupon_codes as $coupon_code ) {
            // Set variable output
            $output = '<p>' . __( 'Coupon Used: ', 'woocommerce' ) . $coupon_code . '</p>';

            // Extra
            if ( strpos( $coupon_code, 'groupurchase') !== false ) {
                // Append to
                $output .= '<p>' . __('With this coupon you are participating in a group purchase', 'woocommerce') . '</p>';
            }

            // Echo output
            echo $output;
        }
    }
}
add_action( 'woocommerce_email_order_details', 'display_applied_coupons', 10, 4 );


问:
Python: How to use __add__ special method to add instances of the same class that return another instance of that class
Writing a program for a card game is what motivated the question. Currently, the way I defined the __add__ special method, I can in fact do something like this:

```<code>deck_one = Deck()
deck_two = Deck()
decks = deck_one + deck_two
</code>```

The challenge is that decks is a list, and I'm curious if there exists a way to add deck_one + deck_two such that decks would instead also become type Deck?

One reason I'm trying to do this, is if I wanted a game to include multiple decks, it would be neat to have the ability to add them all together, and pass them into decks which would 'hold' some n number of decks.

Below is a snippet of my code. I could be completely off here, but would __repr__ play any type of role in this? self.cards is what actually gets referred to in later methods. from what I understand, __repr__ returns it's representation (and as a sideq; I believe __str__ would return the samething if not defined (though please correct me If im wrong), but my understanding is that if I were to only include one, its generally better practice to pick __repr__ , unless both should be included? In anycase:

```<code>import collections
import random

Card = collections.namedtuple('Card', ['value', 'suit'])

class Deck:

    values = [str(v) for v in range(2, 11)] + list('JQKA')
    suits = "Spades Diamonds Hearts Clubs".split()

    def __init__(self):
        self.cards = [Card(value, suit) for suit in self.suits for value in self.values]

    def __repr__(self):
        deck_cards = "Deck()\n"
        for card in self.cards:
            deck_cards += f"({card.value}-{card.suit})"
        return deck_cards

    def __len__(self):
        return len(self.cards)

    def __getitem__(self, position):
        return self.cards[position]

    def __add__(self, deck):
        return self.cards + deck.cards

    def shuffle(self):
        random.shuffle(self.cards)

    def draw_card(self):
        return self.cards.pop()
</code>```

答:
The proper approach is maybe to subclass Deck and create a subclass DoubleDeck that has double the number of Cards:

```<code>class DoubleDeck(Deck):

    values = Deck.values * 2

len(DoubleDeck())    # --> 104
</code>```

Implementing the addition operator is a little bit contrived in this case, but can work if you create a new Deck, and concatenate the two lists of Cards from each operand to it, and return it: (This is not my favorite approach to solve the problem)

```<code>    def __add__(self, other):
        assert isinstance(other, type(self)
        larger_deck = self.__class__()
        larger_deck.cards = self.cards[:] + other.cards[:]  # making a proper copy of the objects
        return larger_deck
</code>```

Body:
Writing a program for a card game is what motivated the question. Currently, the way I defined the __add__ special method, I can in fact do something like this:

deck_one = Deck()
deck_two = Deck()
decks = deck_one + deck_two

The challenge is that decks is a list, and I'm curious if there exists a way to add deck_one + deck_two such that decks would instead also become type Deck?

One reason I'm trying to do this, is if I wanted a game to include multiple decks, it would be neat to have the ability to add them all together, and pass them into decks which would 'hold' some n number of decks.

Below is a snippet of my code. I could be completely off here, but would __repr__ play any type of role in this? self.cards is what actually gets referred to in later methods. from what I understand, __repr__ returns it's representation (and as a sideq; I believe __str__ would return the samething if not defined (though please correct me If im wrong), but my understanding is that if I were to only include one, its generally better practice to pick __repr__ , unless both should be included? In anycase:

import collections
import random

Card = collections.namedtuple('Card', ['value', 'suit'])

class Deck:

    values = [str(v) for v in range(2, 11)] + list('JQKA')
    suits = "Spades Diamonds Hearts Clubs".split()

    def __init__(self):
        self.cards = [Card(value, suit) for suit in self.suits for value in self.values]

    def __repr__(self):
        deck_cards = "Deck()\n"
        for card in self.cards:
            deck_cards += f"({card.value}-{card.suit})"
        return deck_cards

    def __len__(self):
        return len(self.cards)

    def __getitem__(self, position):
        return self.cards[position]

    def __add__(self, deck):
        return self.cards + deck.cards

    def shuffle(self):
        random.shuffle(self.cards)

    def draw_card(self):
        return self.cards.pop()

Body:
The proper approach is maybe to subclass Deck and create a subclass DoubleDeck that has double the number of Cards:

class DoubleDeck(Deck):

    values = Deck.values * 2

len(DoubleDeck())    # --> 104

Implementing the addition operator is a little bit contrived in this case, but can work if you create a new Deck, and concatenate the two lists of Cards from each operand to it, and return it: (This is not my favorite approach to solve the problem)

    def __add__(self, other):
        assert isinstance(other, type(self)
        larger_deck = self.__class__()
        larger_deck.cards = self.cards[:] + other.cards[:]  # making a proper copy of the objects
        return larger_deck


问:
Test if an internet connection is present in python
I have the following code that checks if an internet connection is present.

```<code>import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False
</code>```

This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

答:
Efficient way to check internet availability (modified @andrebrait's answer).

import socket

def isConnected():
    try:
        # connect to the host -- tells us if the host is actually
        # reachable
        sock = socket.create_connection(("www.google.com", 80))
        if sock is not None:
            print('Clossing socket')
            sock.close
        return True
    except OSError:
        pass
    return False
```

Body:
I have the following code that checks if an internet connection is present.

import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False

This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.