问:
WinForms ComboBox - Event when Text Input is Clicked Into
I have a feature request that when a ComboBox is 'clicked into' that it clears the text so that the user can start entering in new data to search.  Does anyone know of a way to hook into this?  The 'click' event is raised on when the text is clicked as well as when the drop down arrow is also clicked (which opens up the drop down with items).  I only want it to happen on the first, not the latter.

Right now I'm capturing the click event and filtering on the DroppedDown property like so:

```<code>if(!comboBox.DroppedDown)
{
    // clear selection
}
</code>```

This seems to work most of the time, but bugs out frequently as well... so its not 100%.

If anyone knows of a proper way to do this I would appreciate!

答: Try the "Enter" event. It happens when a control gains focus on the form.</p>

Body:
I have a feature request that when a ComboBox is 'clicked into' that it clears the text so that the user can start entering in new data to search.  Does anyone know of a way to hook into this?  The 'click' event is raised on when the text is clicked as well as when the drop down arrow is also clicked (which opens up the drop down with items).  I only want it to happen on the first, not the latter.

Right now I'm capturing the click event and filtering on the DroppedDown property like so:

if(!comboBox.DroppedDown)
{
    // clear selection
}

This seems to work most of the time, but bugs out frequently as well... so its not 100%.

If anyone knows of a proper way to do this I would appreciate!


来源: stackexchange

问:
How to implement Recursive Paginated Network Call using RxSwift
I have an endpoint that returns the items of the current page. Also, if you want to get next page's items, you have to construct a URL with the next page's hash. This hash returns as property in the response of the previous request. As you understand, we need a recursive network call.

When a request finishes, a new request will begin until hash returns null through the response.

Then, I need to bind all collected data into an array.

How can I build something like that in RxSwift? I would appreciate if you describe that concept.

答:
You need something like this: https://gist.github.com/danielt1263/ec1032375498eb95aa260239b289d263

```<code>/**
 Calls `producer` with `seed` then emits result and also passes it to `pred`. Will continue to call `producer` with new values as long as `pred` returns values.
 - parameter seed: The starting value needed for the first producer call.
 - parameter pred: This closure determines what the next value pass into producer should be or returns nil if no more calls are necessary.
 - parameter producer: The function that produces the Single result.
 - returns: An observable that emits each producer's value.
 */
func emitWhile<T, U>(seed: U, pred: @escaping (T) -> U?, producer: @escaping (U) -> Single<T>) -> Observable<T>
</code>```

The seed is the hash for the first page. The pred takes the result of a network request, extracts the hash for the next page and returns it (or returns nil if there is no next page.) The producer takes the hash and returns an observable that will make the request for the page when it is subscribed to.

You will likely want to collect all the elements using either scan or reduce to emit all of the pages as a single array.

ContentLicense: CC BY-SA 4.0

Body:
You need something like this: https://gist.github.com/danielt1263/ec1032375498eb95aa260239b289d263

/**
 Calls `producer` with `seed` then emits result and also passes it to `pred`. Will continue to call `producer` with new values as long as `pred` returns values.
 - parameter seed: The starting value needed for the first producer call.
 - parameter pred: This closure determines what the next value pass into producer should be or returns nil if no more calls are necessary.
 - parameter producer: The function that produces the Single result.
 - returns: An observable that emits each producer's value.
 */
func emitWhile<T, U>(seed: U, pred: @escaping (T) -> U?, producer: @escaping (U) -> Single<T>) -> Observable<T>

The seed is the hash for the first page. The pred takes the result of a network request, extracts the hash for the next page and returns it (or returns nil if there is no next page.) The producer takes the hash and returns an observable that will make the request for the page when it is subscribed to.

You will likely want to collect all the elements using either scan or reduce to emit all of the pages as a single array.


问:
Hanging in View method
I've been recently learning python through a course. Everything works smoothly except when I use view method. Anybody having this problem as well?

I even used a sample code in https://pythonhosted.org/scikit-fuzzy/auto_examples/plot_tipping_problem_newapi.html#example-plot-tipping-problem-newapi-py. (link updated)

```<code>import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

quality.automf(3)
service.automf(3)

tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])

# HERE COMES MY PROBLEM
quality['average'].view()
</code>```

Whenever I get to view query part, all I get is a little square box that should show me the graph but it just keeps on loading. Any advice is greatly appreciated. Thank you!

答:
This is the complete example running:

```<code>import matplotlib.pyplot as plt
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

quality.automf(3)
service.automf(3)

tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])
</code>```

Here is my problem

```<code>quality['average'].view()

service.view()

tip.view()

rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low'])
rule2 = ctrl.Rule(service['average'], tip['medium'])
rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high'])

rule1.view()

tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])

tipping = ctrl.ControlSystemSimulation(tipping_ctrl)
</code>```

Pass inputs to the ControlSystem using Antecedent labels with Pythonic API

```<code># Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
tipping.input['quality'] = 6.5
tipping.input['service'] = 9.8

# Crunch the numbers
tipping.compute()
print (tip)
tip.view(sim=tipping)

plt.show()
</code>```

Title: Hanging in View method

Body:
I've been recently learning python through a course. Everything works smoothly except when I use view method. Anybody having this problem as well?

I even used a sample code in https://pythonhosted.org/scikit-fuzzy/auto_examples/plot_tipping_problem_newapi.html#example-plot-tipping-problem-newapi-py. (link updated)

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

quality.automf(3)
service.automf(3)

tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])

# HERE COMES MY PROBLEM
quality['average'].view()

Whenever I get to view query part, all I get is a little square box that should show me the graph but it just keeps on loading. Any advice is greatly appreciated. Thank you!

Body:
This is the complete example running:

import matplotlib.pyplot as plt
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

quality.automf(3)
service.automf(3)

tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])

Here is my problem

quality['average'].view()

service.view()

tip.view()

rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low'])
rule2 = ctrl.Rule(service['average'], tip['medium'])
rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high'])

rule1.view()

tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])

tipping = ctrl.ControlSystemSimulation(tipping_ctrl)

Pass inputs to the ControlSystem using Antecedent labels with Pythonic API

# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
tipping.input['quality'] = 6.5
tipping.input['service'] = 9.8

# Crunch the numbers
tipping.compute()
print (tip)
tip.view(sim=tipping)

plt.show()


问:
Required: no arguments, despite having arguments?
MealDataTotal.java:25: error: constructor MealData in class MealData cannot be applied to given types;
        new MealData("Burger", 5.99, 650.0),
        ^
  required: no arguments
  found: String,double,double
  reason: actual and formal argument lists differ in length</p>

```<code>class MealData
{
  public String name;
  public double price;
  public double calories;

  String MealData (String n,double p,double c)
  {
    name = n;
    price = p;
    calories = c;

    String summaryString;

    summaryString = name + ", $" + Double.toString(price) + ", " + Double.toString(calories) + " calories";
    return summaryString;
  }
}

public class MealDataTotal extends MealData
{

    MealData[] MainCourses = new MealData[]
    {
        new MealData("Burger", 5.99, 650.0),
        new MealData("Sandwich", 3.99, 450.0f),
        new MealData("Mac 'n Cheese", 4.99, 500.0)
    };

    public static void main(String []args)
    {

        System.out.println("Hello World");
    }
}
</code>```

答:
A construct does have a return, it returns the instance of the class, this is why you should not declare the return type.

If you want to convert your instance to a String in a custom way override the toString method.

Body:
MealDataTotal.java:25: error: constructor MealData in class MealData cannot be applied to given types;
        new MealData("Burger", 5.99, 650.0),
        ^
  required: no arguments
  found: String,double,double
  reason: actual and formal argument lists differ in length

class MealData
{
  public String name;
  public double price;
  public double calories;

  String MealData (String n,double p,double c)
  {
    name = n;
    price = p;
    calories = c;

    String summaryString;

    summaryString = name + ", $" + Double.toString(price) + ", " + Double.toString(calories) + " calories";
    return summaryString;
  }
}

public class MealDataTotal extends MealData
{

    MealData[] MainCourses = new MealData[]
    {
        new MealData("Burger", 5.99, 650.0),
        new MealData("Sandwich", 3.99, 450.0f),
        new MealData("Mac 'n Cheese", 4.99, 500.0)
    };

    public static void main(String []args)
    {

        System.out.println("Hello World");
    }
}


问:
Error CS0116: A namespace cannot directly contain members such as fields or methods
Ok so im trying to make a program that checks if a program is currently running. It is giving me a error when ever i declare a void. I am new to C# so im sorry if its a stupid.

```<code>using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.VisualBasic.ApplicationServices;

namespace IsProgramRunning
{
    private void IsRunning()
    {
        Process[] pname = Process.GetProcessesByName("VLC Player");
        if (pname.Length > 0)
        {
            MessageBox.Show("Process Running");
        }
        else
        {
            MessageBox.Show("Process Not running");
        }
        System.Threading.Thread.Sleep(5 * 1000);
    }
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
        new Service1()
        };
        ServiceBase.Run(ServicesToRun);

    }
}
</code>```

If im going about this all wrong and there is a easy way to do it in c++ that would be good to

答:
To have instance members and methods, you need a class. You have confused a namespace with a class

```<code>namespace MyAwesomeNameSpace
{
   public class ProgramRunningHelper
   {
       // put your class code here

   }
}
</code>```

Compiler Error CS0116

A namespace cannot directly contain members such as fields or methods.

A namespace can contain other namespaces, structs, and classes.

Body:
Ok so im trying to make a program that checks if a program is currently running. It is giving me a error when ever i declare a void. I am new to C# so im sorry if its a stupid.

using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.VisualBasic.ApplicationServices;

namespace IsProgramRunning
{
    private void IsRunning()
    {
        Process[] pname = Process.GetProcessesByName("VLC Player");
        if (pname.Length > 0)
        {
            MessageBox.Show("Process Running");
        }
        else
        {
            MessageBox.Show("Process Not running");
        }
        System.Threading.Thread.Sleep(5 * 1000);
    }
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
        new Service1()
        };
        ServiceBase.Run(ServicesToRun);

    }
}

If im going about this all wrong and there is a easy way to do it in c++ that would be good to

Body:
To have instance members and methods, you need a class. You have confused a namespace with a class

namespace MyAwesomeNameSpace
{
   public class ProgramRunningHelper
   {
       // put your class code here

   }
}

Compiler Error CS0116

A namespace cannot directly contain members such as fields or methods.

A namespace can contain other namespaces, structs, and classes.


问:
Is the t2.micro instance enough to fetch hundreds of thousands of rows?
I recently hosted an API on AWS Elastic Beanstalk with the free tier, I inserted 6 million rows. But I can't seem to consistently fetch data (usually around 200k at a time). Sometimes I can fetch around 100k, usually I get the error:

SyntaxError: Unexpected end of JSON input at http://***********.us-east-2.elasticbeanstalk.com/

or:

SyntaxError: Unexpected token < in JSON at position 0

which means it's fetching an HTML string.  I inserted one fake row and tried to fetch that and I'm able to consistently fetch it.

Am I right in assuming the free tier just isn't enough?

答:
The AWS Free Tier is just a billing discount. It does not affect services.

However, the use of a t2.micro does have an impact on network bandwidth and CPU Utilization. See: Burstable Performance Instances - Amazon EC2

You would need to examine the code that is producing the error to determine exactly what is happening. For example, it might be timing-out before all the data can be downloaded due to the limited network bandwidth on such a small instance.

If you're willing to spend a few cents, you could temporarily increase the size of the instance (eg t2.large or m5.large) and see whether it improves the situation.


答:
You did not explain how to combine the elements, so here is a wild guess below. I won't try to decode what you're doing wrong, because the code you posted does not do what you describe? (e.g. You assign comid to o.ownerId, but your expected result does not show that, and you assign user.id to o.extensionId, but I do not see any id property in the original Array with the same value as an extensionId in the expected result)

const customerInformation = [
{"id":"12345678","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"1942f0e6","ownerId":"234566654","exec":{"execId":"20326379004","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"John Smith","accountId":"234566654","comid":"cs169612397275616092-1","status":"Active","phoneNumber":"+442222222222","extensionId":"234566654","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"6374595864","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"1942f0e6","ownerId":"155464348743","exec":{"execId":"1521648743","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Math Lo","accountId":"26726447342","comid":"cs169612397275616092-1","status":"Active","phoneNumber":"+442222222222","extensionId":"234566654","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"98736478","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"hblwrv890","ownerId":"98765322","exec":{"execId":"20326379004","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"James Olive","accountId":"234566654","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"256644477","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"sbdbbgbg","ownerId":"32545453565","exec":{"execId":"32254655464","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Ben Right","accountId":"234566654","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"99326672378372","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"sjvjvnfrrev","ownerId":"28643872329","exec":{"execId":"268474374938","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Lowe John","accountId":"2225454354","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}}
];

const result = customerInformation.reduce((res, el) => {
  const com = el.exec.communication[0];
  // If the result array does not contain that comid yet
  if (!res.some(el2 => el2.comid === com.comid)) {
    // Add it
    res.push({
      id: el.id,
      ownerId: el.ownerId,
      userConnection: el.userConnection,
      status: com.status,
      comid: com.comid,
      extensionId: com.extensionId,
      phoneNumber: com.phoneNumber,
      startAt: el.exec.eventTime
    });
  }
  return res;
}, []);

// Because "it's the requirement"
result[1].id = undefined;

console.log(result);```

Title: Manipulating Array of object in Javascript


问:
How to proportionally (respecting aspect ratio) scale a rectangle?
I'm trying to simply take a given box of x by y and scale it up, either by setting x and finding y, or vice versa. How would this formula be expressed in Python (for readability's sake). I'm trying to fit this box inside of a larger box so that the inner box always fits within the larger box.

答:
```<code>>>> import fractions
>>> x, y = 10, 10
>>> fix_rat = fractions.Fraction(x, y)
>>> fix_rat
Fraction(1, 1)
>>> x = 8
>>> if fractions.Fraction(x, y) != fix_rat:
    y = x / fix_rat #well instead of y you should put the last one that has been changed
                    #but this is just an example

>>> y
Fraction(8, 1)
>>>
</code>```

ContentLicense: CC BY-SA 3.0


问:
MATLAB - factor-out scale factor from column matrix
I have this column matrix:

syms a;
syms b;
myColVector = [-a; 0; 0; 0; 0; 0; 0; -b];
```

I am more interested in the factor of the vector which is -1, how can I achieve this?

I have tried eig(...) function but it didn't work. I also tried the factor(...) command and it didn't work either.

Edit:

Say the function that I am looking for is called findFactor. If I type:

findFactor(myColVector),

then this should output -1.

答:
```<code>>> findSymType(myColVector,'constant')

ans =

[ -1, 0]
</code>```

Not exactly what you are looking for because it also finds the constant "0", but I guess it's close enough to allow you proceeding.

Body:
I have this column matrix:

syms a;
syms b;
myColVector = [-a; 0; 0; 0; 0; 0; 0; -b];

I am more interested in the factor of the vector which is -1, how can I achieve this?

I have tried eig(...) function but it didn't work. I also tried the factor(...) command and it didn't work either.

Edit:

Say the function that I am looking for is called findFactor. If I type:

findFactor(myColVector),

then this should output -1.

Body:
>> findSymType(myColVector,'constant')

ans =

[ -1, 0]

Not exactly what you are looking for because it also finds the constant "0", but I guess it's close enough to allow you proceeding.


问:
Error while reducing the volume of a audio clip using python
I've tried to reduce or raise the volume of an audio clip using pydub.
But when I did so it is giving following error.

```<code> c:/Users/KalyanDk/vsprojects/Games/playsound.py
C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\utils.py:165: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\utils.py:179: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
  warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
  File "c:/Users/KalyanDk/vsprojects/Games/playsound.py", line 12, in <module>
    play(louder_song)
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\playback.py", line 71, in play
    _play_with_ffplay(audio_segment)
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\playback.py", line 18, in _play_with_ffplay
    seg.export(f.name, "wav")
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\audio_segment.py", line 780, in export
    out_f = _fd_or_path_or_tempfile(out_f, 'wb+')
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\utils.py", line 57, in _fd_or_path_or_tempfile
    fd = open(fd, mode=mode)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\KalyanDk\\AppData\\Local\\Temp\\tmposf_nhdb.wav'
</code>```

I'm not able to understand what is wrong..Here is my code

```<code>from pydub import AudioSegment
from pydub.playback import play

song = AudioSegment.from_wav("Bounce.wav")

louder_song = song + 6

quieter_song = song - 3

play(louder_song)

louder_song.export("Bounce.wav", format='wav')'''
</code>```

And the audio file is in the same folder where the current python file reside.

答:
Try installing simpleaudio:  pip install simpleaudio

Pydub uses NamedTemporaryFile many times throughout the program, including in the play() method. There are some apparent inconsistencies across platforms in the way NamedTemporaryFile handles basic file operations. I believe simpleaudio will circumvent the code where NamedTemporaryFile is called in the play() method, though I'm not clear on if this solves the issue for all instances of NamedTemporaryFile in pydub. Simpleaudio definitely fixed the issue for me though - no config needed, just install.

ref:
https://github.com/jiaaro/pydub/issues/343

Body:
I've tried to reduce or raise the volume of an audio clip using pydub.
But when I did so it is giving following error.

 c:/Users/KalyanDk/vsprojects/Games/playsound.py
C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\utils.py:165: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
  warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\utils.py:179: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
  warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
  File "c:/Users/KalyanDk/vsprojects/Games/playsound.py", line 12, in <module>
    play(louder_song)
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\playback.py", line 71, in play
    _play_with_ffplay(audio_segment)
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\playback.py", line 18, in _play_with_ffplay
    seg.export(f.name, "wav")
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\audio_segment.py", line 780, in export
    out_f = _fd_or_path_or_tempfile(out_f, 'wb+')
  File "C:\Users\KalyanDk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydub\utils.py", line 57, in _fd_or_path_or_tempfile
    fd = open(fd, mode=mode)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\KalyanDk\\AppData\\Local\\Temp\\tmposf_nhdb.wav'

I'm not able to understand what is wrong..Here is my code

from pydub import AudioSegment
from pydub.playback import play

song = AudioSegment.from_wav("Bounce.wav")

louder_song = song + 6

quieter_song = song - 3

play(louder_song)

louder_song.export("Bounce.wav", format='wav')'''

And the audio file is in the same folder where the current python file reside.


问:
Amazon S3 permissions granted but users cannot realize their permission
I am an admin using Amazon S3 and have created an S3 bucket. Under Permissions, and under Access Control List, I have specified AWS users to have "List objects" and "Read bucket permissions." However, those same users are not able to list objects or read from the bucket using AWS CLI.

Is there another step I as an admin need to do to give users permission in S3 using AWS CLI, or is there something they need to do to realize the access I have given them using AWS CLI?

答:
While granting access on the bucket itself can allow users to access the bucket, the users themselves also need permission to call the Amazon S3 service. If they do not have such permissions, they won't be able to access any bucket.

The best way to grant specific users access to an Amazon S3 bucket is to use an IAM Policy. This policy can be placed on an IAM User.

If you have a group of users who should receive the same permission, you can create an IAM Group, put the users in the group, then add the policy to the IAM Group.

Here is a sample policy from Writing IAM Policies: How to Grant Access to an Amazon S3 Bucket | AWS Security Blog:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::test"]
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": ["arn:aws:s3:::test/*"]
    }
  ]
}
</code>```

This grants permission to list the contents of the test bucket and retrieve objects from the bucket.

Body:
While granting access on the bucket itself can allow users to access the bucket, the users themselves also need permission to call the Amazon S3 service. If they do not have such permissions, they won't be able to access any bucket.

The best way to grant specific users access to an Amazon S3 bucket is to use an IAM Policy. This policy can be placed on an IAM User.

If you have a group of users who should receive the same permission, you can create an IAM Group, put the users in the group, then add the policy to the IAM Group.

Here is a sample policy from Writing IAM Policies: How to Grant Access to an Amazon S3 Bucket | AWS Security Blog:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::test"]
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": ["arn:aws:s3:::test/*"]
    }
  ]
}

This grants permission to list the contents of the test bucket and retrieve objects from the bucket.


问:
Want to check if one array has a value of another array, and if it does, change the value of the first array and check it again
I am trying to check if one array has a value of another array, and if it does, the value of the other array should be given a number next to it. If there is a value that matches the value in the other array still, the number should be incremented until it no longer matches a value in the other array. I am struggling with this one. Any help is sincerely appreciated!

For example, "Joe" shows in the below code in both arrays. That means "Joe" in the second array should then be "Joe1". Since "Joe1" is also in the array, the "1" in "Joe1" should then be incremented to "Joe2". Any help is very much appreciated!

var arr = [{name:'Bob',num:0},{name:'Joe',num:0},{name:'Alise',num:0}];
var arr2 = [{name:'Frank',num:0},{name:'Joe',num:0},{name:'Jen',num:0},{name:'Joe1',num:0}];
var cnt = 0

arr.forEach(function(element){
  arr2.forEach(function(element2){
    if(element2.name === element.name){
       while(element2.name + element2.num === element.name){
          element2['num'] = ++cnt;
       }
       if(element2.num != 0){
        element2.name += element2.num
       }
    }
  })
})

console.log(arr2)```

答:
var arr = [{name:'Bob',num:0},{name:'Joe',num:0},{name:'Alise',num:0}];
var arr2 = [{name:'Frank',num:0},{name:'Joe',num:0},{name:'Jen',num:0},{name:'Joe1',num:0}];

var arr3;
arr.forEach(e => {
    arr3 = arr2.map(e2 => {
        var name = e2.name.match(/[a-zA-Z]*/)[0]
        if (e.name === name) {
            var number = e2.name.match(/[0-9]+/)
            if (number) {
                e2.name = name + (+number[0] + 1)
            } else {
                e2.name = name + 1
            }
        }
        return e2
    })
})
console.log(arr3)```


问:
Return rows in pandas based on values in multiple columns
Needed some help with pandas...I'm working on this data and I'm trying to calculate some changes over time per region.
Basically, I'm trying to find the oldest quantity and the newest quantity for each area in question. I have code that can give me the year of the most recent and oldest data recordes, however I need to gather the whole row so I can work on the 'quantity' column. Any inputs? here is what i have :

df.groupby(['Country or Area'])['Year'].max()

Thanks in advance!

答:
```<code>df = df.sort_values(by=['Country or Area','Year'])
df.groupby('Country or Area').agg(['first','last']).stack()
</code>```


问:
Calculate dot product between two dictionaries millions of times
I have two dictionaries d1 = {'string1': number1, ..., 'string5 000 000': number5000000} which does not change and many small dictionaries d_i = {'str1': num1, ..., 'str50': num50} (i = 2, 3, ..., a few million). I want to do a dot product between these dictionaries i.e. for every key in dictionary d_i that exists also in d_1 I would like their numbers multiplied and then added to the sum.
The problem is that first dictionary is extremely big and there are millions of small dictionaries.
How do I do that fast? Can I use some big data techniques for that?</p>

答: You can put your data to pandas dataframe and then do dot product between series in dataframe. It can be faster but in you case I would measure how much time it takes in case of python implementation and pandas.</p>


问:
A function to check for hill or valley in a given list, without usage of Numpy or zip?

A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

```<code>def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False
</code>```

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!

Body:
A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!

Body:
Using indexes isn't very pythonic and make the solutions look overly complex to me.  Here's a straightforward way to do it that leverages Python's features a little better:

def hillValey(A):
    if len(A)<3: return
    p1,p2,p3 = A[:3]
    for p in A[3:]:
        if p==p3 : continue
        if  p1==p2 or (p1>p2) == (p2>p3):
            p1,p2,p3 = p2,p3,p
        elif (p3>p) == (p2>p3) :
            p3=p
        else: return
    if p1==p2 or p2==p3:   return
    if (p1<p2) != (p2>p3): return
    return "Valley" if p1>p2 else "Hill"

Tests:

def check(A): print(A,hillValey(A))

check([1,2,3,5,4])
check([5,4,1,2,3])
check([1,2,3,5,4,3,2,1])
check([9,5,4,-1,-2,3,7])
check([1, 1, 1, 1, 1])
check([1, 1])
check([1])
check([1, 2, 3, 5, 5])
check([9, -1, 4, -1, -2, 3])
check([3,2,2])
check([3,2,2,4])
check([3,3,2])
check([1,1,2])
check([1,1,2,1])
check([1,1,2,2,1])
check([1,1,1,2,2,1])
check([2,2,2,1,2,2])

Results:

[1, 2, 3, 5, 4] Hill
[5, 4, 1, 2, 3] Valley
[1, 2, 3, 5, 4, 3, 2, 1] Hill
[9, 5, 4, -1, -2, 3, 7] Valley
[1, 1, 1, 1, 1] None
[1, 1] None
[1] None
[1, 2, 3, 5, 5] None
[9, -1, 4, -1, -2, 3] None
[3, 2, 2] None
[3, 2, 2, 4] Valley
[3, 3, 2] None
[1, 1, 2] None
[1, 1, 2, 1] Hill
[1, 1, 2, 2, 1] Hill
[1, 1, 1, 2, 2, 1] Hill
[2, 2, 2, 1, 2, 2] Valley


问:
SQL Server 2008: MERGE command on a table that has a trigger causes an error
I have a stored procedure that uses the MERGE command to synchronize dbo.tableA with [mylinkedserver].dbo.TableA.

TableA has an insert/update trigger associated with it. To keep things really simple all the trigger does is

```<code>print 'I am a simple trigger because i dont want to cause errors'
</code>```

When the SP is executed (thru a .net windows application), it throws this error:

OLE DB provider "SQLNCLI10" for linked server "MyLinkedServer"
  returned message "No transaction is
  active."

If I delete the trigger and execute the stored proc again, it executes absolutely fine.

The stored procedure also runs fine (with the trigger) if i run it through SSMS.

MSDTC is enabled on both servers.

Server is Windows 2008 server, SQL Server 2008 with service pack 2.

Why would a trigger cause this error ?!?!??

答:
Trigger implementation with Merge is a little tricky.  It boils down to "for each action specified in the merge statement there must be a trigger".

TechNet Says "If the target table has an enabled INSTEAD OF trigger defined on it for an insert, update, or delete action performed by a MERGE statement, then it must have an enabled INSTEAD OF trigger for all of the actions specified in the MERGE statement."

http://technet.microsoft.com/en-us/library/bb510625.aspx

Body:
I have a stored procedure that uses the MERGE command to synchronize dbo.tableA with [mylinkedserver].dbo.TableA.

TableA has an insert/update trigger associated with it. To keep things really simple all the trigger does is

print 'I am a simple trigger because i dont want to cause errors'

When the SP is executed (thru a .net windows application), it throws this error:

OLE DB provider "SQLNCLI10" for linked server "MyLinkedServer"
  returned message "No transaction is
  active."

If I delete the trigger and execute the stored proc again, it executes absolutely fine.

The stored procedure also runs fine (with the trigger) if i run it through SSMS.

MSDTC is enabled on both servers.

Server is Windows 2008 server, SQL Server 2008 with service pack 2.

Why would a trigger cause this error ?!?!??


问:
Should we always use a hook or is it ok to directly call it from the client?
In React, we can use the useMutation or useQuery inside components. But let's say we want to run the query or the mutation inside a helper file (Let's say we extract the part where we format the data and execute the mutation to a helper function away from the component function). In here, we have two options:

Pass the mutation function obtained from useMutation to the helper function

Call the mutation directly inside the helper function like apolloClient.mutate

What is the most recommended way of doing things and what do you recommend?

答:
The hooks expose additional component state for the returned data, loading state and error state. This is really just a convenience because it means you don't have to call useState yourself. As such, it's perfectly fine to use client.mutate if you don't need to keep track of those states. In a sense, it may be better since you're not needlessly using memory for variables you won't use anyway.

The same could be said for useQuery, which really just uses client.watchQuery under the hood and saves you from having to use useState and useEffect.


问:
Convert XML to JSON with NodeJS
I'm trying to convert the following xml to json, thereby I need to get a mapping to the  TS-tc-dt

Here is the xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<TestScenario>
   <TestSuite name="TS_EdgeHome">
      <TestCaseName name="tc_Login">dt_EdgeCaseHome,dt_EdgeCaseRoute</TestCaseName>
      <TestCaseName name="tc_Logout">dt_EdgeCaseRoute</TestCaseName>
   </TestSuite>
   <TestSuite name="TS_EdgePanel">
      <TestCaseName name="tc_AddContract">dt_EdgeCaseHome,dt_EdgeCaseSpectrum</TestCaseName>
   </TestSuite>
      <TestSuite name="TS_EdgeRoute">
      <TestCaseName name="tc_VerifyContract">dt_EdgeCaseRoute</TestCaseName>
      <TestCaseName name="tc_Payment">dt_EdgeCaseRoute</TestCaseName>
   </TestSuite>
   <TestSuite name="TS_EdgeSpectrum">
      <TestCaseName name="tc_ClientFeedback">dt_EdgeCaseSpectrum</TestCaseName>
   </TestSuite>
</TestScenario>
</code>```

How can I achieve this in NodeJS?

答:
Cruftless allows you to 'annotate' the data structure you want to match, to specify how it should be bound to a JSON representation of that same data.

So, if you define your template like this:

<TestScenario>
  <TestSuite name="{{name}}"><?bind suites|array?>
    <TestCaseName name="{{name}}">{{data}}</TestCaseName><?bind cases|array?>
  </TestSuite>
</TestScenario>
```
<p>Then by calling <code>.fromXML</code> on the object created from it, passing in the XML you want to parse, you will get:</p>
```{
  suites: [
    { name: 'tc_Logout', data: 'dt_EdgeCaseRoute' },
    {
      name: 'tc_AddContract',
      data: 'dt_EdgeCaseHome,dt_EdgeCaseSpectrum'
    },
    { name: 'tc_Payment', data: 'dt_EdgeCaseRoute' },
    { name: 'tc_ClientFeedback', data: 'dt_EdgeCaseSpectrum' }
  ]
}
```

Title: Convert XML to JSON with NodeJS

Body:
I'm trying to convert the following xml to json, thereby I need to get a mapping to the  TS-tc-dt

Here is the xml

<?xml version="1.0" encoding="UTF-8"?>
<TestScenario>
   <TestSuite name="TS_EdgeHome">
      <TestCaseName name="tc_Login">dt_EdgeCaseHome,dt_EdgeCaseRoute</TestCaseName>
      <TestCaseName name="tc_Logout">dt_EdgeCaseRoute</TestCaseName>
   </TestSuite>
   <TestSuite name="TS_EdgePanel">
      <TestCaseName name="tc_AddContract">dt_EdgeCaseHome,dt_EdgeCaseSpectrum</TestCaseName>
   </TestSuite>
      <TestSuite name="TS_EdgeRoute">
      <TestCaseName name="tc_VerifyContract">dt_EdgeCaseRoute</TestCaseName>
      <TestCaseName name="tc_Payment">dt_EdgeCaseRoute</TestCaseName>
   </TestSuite>
   <TestSuite name="TS_EdgeSpectrum">
      <TestCaseName name="tc_ClientFeedback">dt_EdgeCaseSpectrum</TestCaseName>
   </TestSuite>
</TestScenario>

How can I achieve this in NodeJS?

Body:
Cruftless allows you to 'annotate' the data structure you want to match, to specify how it should be bound to a JSON representation of that same data.

So, if you define your template like this:

<TestScenario>
  <TestSuite name="{{name}}"><?bind suites|array?>
    <TestCaseName name="{{name}}">{{data}}</TestCaseName><?bind cases|array?>
  </TestSuite>
</TestScenario>

Then by calling .fromXML on the object created from it, passing in the XML you want to parse, you will get:

{
  suites: [
    { name: 'tc_Logout', data: 'dt_EdgeCaseRoute' },
    {
      name: 'tc_AddContract',
      data: 'dt_EdgeCaseHome,dt_EdgeCaseSpectrum'
    },
    { name: 'tc_Payment', data: 'dt_EdgeCaseRoute' },
    { name: 'tc_ClientFeedback', data: 'dt_EdgeCaseSpectrum' }
  ]
}


问:
How to hit URL with parameters within an API
How to pass parameters to an url for get request in python?

Suppose this is my url:

```<code>url = "http://105.119.2.20/data/personal/get/Id/<Id>/empId/<empId>/org_id/<orgId>"
</code>```

I have to pass three parameters to this url:

Id

empId

orgId

I want to know how would be the syntax of passing paramaters to hit this url. Whether to pass through dictionary or by variable?

```<code>r = request.get(url)
</code>```

答:
You can use f-string to format your url just like this</p>

```<code>    Id = 12
    empId = 123
    orgId = 1234

    url = f'http://105.119.2.20/data/personal/get/Id/{Id}/empId/{empId}/org_id/{orgId}'

    r = request.get(url)
</code>```

Body:
How to pass parameters to an url for get request in python?

Suppose this is my url:

url = "http://105.119.2.20/data/personal/get/Id/<Id>/empId/<empId>/org_id/<orgId>"

I have to pass three parameters to this url:

Id

empId

orgId

I want to know how would be the syntax of passing paramaters to hit this url. Whether to pass through dictionary or by variable?

r = request.get(url)

Body:
You can use f-string to format your url just like this

    Id = 12
    empId = 123
    orgId = 1234

    url = f'http://105.119.2.20/data/personal/get/Id/{Id}/empId/{empId}/org_id/{orgId}'

    r = request.get(url)


问:
Changing grid line colours in amCharts
I'm trying to change the grid line (and border) colours of a graph I'm using. I've seen the docs, but only found methods to change the fill. Can't see anything regarding the actual lines.

Demo:

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";
series1.fillOpacity = .3;
series1.stroke = "#4967fa";

/* Create a cursor */
chart.cursor = new am4charts.XYCursor();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  background: grey;
}</code>```

```

By the lines I'm referring to those dark grey grid lines.

Any way to change this?

答:
In the axis renderer, you have access to many components of the axis, such as labels, ticks, and , including the grid lines. You can change the grid line colors by modifying the grid template.

```<code>theXAxis.renderer.grid.template.stroke = "#ff0000";
theYAxis.renderer.grid.template.stroke = "#ff0000";
</code>```

This is also demonstrated in the axis overview in the documentation under the Grid, labels and ticks section.

As for the border, you need to set the stroke on the relevant container's background (in this case, the plotContainer). You can find more information on working with containers here

```<code>chart.plotContainer.background.stroke = "#ff0000";
</code>```

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;
theXAxis.renderer.grid.template.stroke = "#ff0000";
theXAxis.renderer.grid.template.strokeWidth = 2;
theXAxis.renderer.grid.template.strokeOpacity = .8; //make the change more visible for demo purposes
// base/zero line
theXAxis.renderer.baseGrid.stroke = "#ff0000";

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;
theYAxis.renderer.grid.template.stroke = "#ff0000";
theYAxis.renderer.grid.template.strokeWidth = 2;
theYAxis.renderer.grid.template.strokeOpacity = .8; //make the change more visible for demo purposes
// base/zero line
theYAxis.renderer.baseGrid.stroke = "#ff0000";

//border around chart:
chart.plotContainer.background.stroke = "#ff0000";

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";
series1.fillOpacity = .3;
series1.stroke = "#4967fa";

/* Create a cursor */
chart.cursor = new am4charts.XYCursor();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
}</code>```

```

Title: Changing grid line colours in amCharts

Body:
I'm trying to change the grid line (and border) colours of a graph I'm using. I've seen the docs, but only found methods to change the fill. Can't see anything regarding the actual lines.

Demo:

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";
series1.fillOpacity = .3;
series1.stroke = "#4967fa";

/* Create a cursor */
chart.cursor = new am4charts.XYCursor();

body{
  background: grey;
}

By the lines I'm referring to those dark grey grid lines.

Any way to change this?

Body:
In the axis renderer, you have access to many components of the axis, such as labels, ticks, and , including the grid lines. You can change the grid line colors by modifying the grid template.

theXAxis.renderer.grid.template.stroke = "#ff0000";
theYAxis.renderer.grid.template.stroke = "#ff0000";

This is also demonstrated in the axis overview in the documentation under the Grid, labels and ticks section.

As for the border, you need to set the stroke on the relevant container's background (in this case, the plotContainer). You can find more information on working with containers here

chart.plotContainer.background.stroke = "#ff0000";

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;
theXAxis.renderer.grid.template.stroke = "#ff0000";
theXAxis.renderer.grid.template.strokeWidth = 2;
theXAxis.renderer.grid.template.strokeOpacity = .8; //make the change more visible for demo purposes
// base/zero line
theXAxis.renderer.baseGrid.stroke = "#ff0000";

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;
theYAxis.renderer.grid.template.stroke = "#ff0000";
theYAxis.renderer.grid.template.strokeWidth = 2;
theYAxis.renderer.grid.template.strokeOpacity = .8; //make the change more visible for demo purposes
// base/zero line
theYAxis.renderer.baseGrid.stroke = "#ff0000";

//border around chart:
chart.plotContainer.background.stroke = "#ff0000";

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";
series1.fillOpacity = .3;
series1.stroke = "#4967fa";

/* Create a cursor */
chart.cursor = new am4charts.XYCursor();

body{
}

<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>

<div id="dataChart"></div>


问:
Using Angular Observable to subscribe to Session Storage key
I'm trying to accomplish what I had hoped would be a simple "look at the key in Session Storage and update it when it changes" scenario, but Observables really trip me up.

message$ = new Observable(observer => {
    observer.next(window.sessionStorage.getItem('message'));
});

ngOnInit() {
    this.message$.subscribe();
}
```
<p>And the message$ is bound to the HTML, pretty straightforward:</p>
<pre class="lang-html prettyprint-override"><code><p id="message">{{message$ | async}}</p>
</code>```

The Observable will output the text to the HTML if there's already value stored in 'message' but if there's no message on init and then it gets added, or the message value does exist and is updated, nothing happens. I'm obviously doing something wrong, and I would appreciate the insight of someone knowledgeable with Observables.

答:
I think what you're looking for is a StorageEvent

You can create your observable from this event using fromEvent, like this:

```<code>const message$ = fromEvent<StorageEvent>(window, "storage").pipe(
  filter(event => event.storageArea === sessionStorage),
  filter(event => event.key === "message"),
  map(event => event.newValue)
);
</code>```

Notice that I added filters to specifically look for updates of sessionStorage and I specified the key === "message", but you can also use localStorage and any key you want

Also, as Damian C pointed out, you don't need to subscribe to this observable if you're planning to only use it in template.

EDITED: solution above only working when you have multiple tabs opened and want to synchronize changes to storage. Check this answer

I think you have to change a place where you set your value to sessionStorage. My suggestion is to use your own StorageService (my example) where you will set your value to storage and keep an observable, which should emit when you are setting key/value.

I did an example on stackblitz

https://stackblitz.com/edit/angular-3szmzd

Body:
I'm trying to accomplish what I had hoped would be a simple "look at the key in Session Storage and update it when it changes" scenario, but Observables really trip me up.

message$ = new Observable(observer => {
    observer.next(window.sessionStorage.getItem('message'));
});

ngOnInit() {
    this.message$.subscribe();
}

And the message$ is bound to the HTML, pretty straightforward:

{{message$ | async}}

The Observable will output the text to the HTML if there's already value stored in 'message' but if there's no message on init and then it gets added, or the message value does exist and is updated, nothing happens. I'm obviously doing something wrong, and I would appreciate the insight of someone knowledgeable with Observables.

Body:
I think what you're looking for is a StorageEvent

You can create your observable from this event using fromEvent, like this:

const message$ = fromEvent<StorageEvent>(window, "storage").pipe(
  filter(event => event.storageArea === sessionStorage),
  filter(event => event.key === "message"),
  map(event => event.newValue)
);

Notice that I added filters to specifically look for updates of sessionStorage and I specified the key === "message", but you can also use localStorage and any key you want

Also, as Damian C pointed out, you don't need to subscribe to this observable if you're planning to only use it in template.

EDITED: solution above only working when you have multiple tabs opened and want to synchronize changes to storage. Check this answer

I think you have to change a place where you set your value to sessionStorage. My suggestion is to use your own StorageService (my example) where you will set your value to storage and keep an observable, which should emit when you are setting key/value.

I did an example on stackblitz

https://stackblitz.com/edit/angular-3szmzd


问:
Undefined reference error when i try to compile on my home PC
Ok, so I've tried to get more familiar with OOP in C++ and I got the following code:

//main.cpp
#include <iostream>
#include "ZooAnimal.h"

using namespace std;

int main()
{
    ZooAnimal bozo;
    bozo.set_name(12);
    // bozo.Create("Bozo", 408, 1027, 400);

    // cout << "This animal's name is " << bozo.reptName() << endl;

    // bozo.Destroy();
    cout << "Hello";
}
```

<pre class="lang-cpp prettyprint-override"><code>//ZooAnimal.h
#ifndef ZOOANIMAL_H
#define ZOOANIMAL_H

class ZooAnimal
{
private:
    std::string name;
    int cageNumber;
    int weightDate;
    int weight;

public:
    void Create(std::string, int, int, int);
    void Destroy();
    std::string reptName();
    int daysSinceLastWeighted(int today);
    void set_name(int);
};

#endif //ZooAnimal
</code>```

and lastly,

//ZooAnimal.cpp
#include "ZooAnimal.h"
#include <iostream>

void ZooAnimal::Create(std::string a, int b, int c, int d)
{
    //This creates a ZooAnimal Object
    name = a;
    cageNumber = b;
    weightDate = c;
    weight = d;
}

int ZooAnimal::daysSinceLastWeighted(int today)
{
    //calculate how many days have passed since last weight
    return today - weightDate;
}

//clear up the memory
void ZooAnimal::Destroy()
{
    delete &name;
}

// return the animal name
std::string ZooAnimal::reptName()
{
    return name;
}

void ZooAnimal::set_name(int a)
{
    cageNumber = a;
}
```

<p>So, when I try to run this code(from main.cpp of course) it won't compile and I get the following message in the console</p>

```C:\Users\<user>\AppData\Local\Temp\ccOiWb7r.o:main.cpp:(.text+0x2e): undefined reference to `ZooAnimal::set_name(int)'
collect2.exe: error: ld returned 1 exit status
```

I'm using MinGW to compile, working on a Windows 10 machine. The weird thing is that when I try to run the same code on a cloud editor, like repl.it , it works just fine, and if I don't separate my code into multiple files, again, it runs fine.
Any idea of what can I do?

答: You are building main.cpp but not ZooAnimal.cpp.  Try putting some obvious syntax error into ZooAnimal.cpp--does the compiler complain?  If not, you aren't compiling ZooAnimal.cpp at all.  If the compiler does complain about the syntax error, then you are compiling ZooAnimal.cpp but not passing ZooAnimal.o to the linker, resulting in the undefined symbol set_name().

Body:
Ok, so I've tried to get more familiar with OOP in C++ and I got the following code:

//main.cpp
#include <iostream>
#include "ZooAnimal.h"

using namespace std;

int main()
{
    ZooAnimal bozo;
    bozo.set_name(12);
    // bozo.Create("Bozo", 408, 1027, 400);

    // cout << "This animal's name is " << bozo.reptName() << endl;

    // bozo.Destroy();
    cout << "Hello";
}

//ZooAnimal.h
#ifndef ZOOANIMAL_H
#define ZOOANIMAL_H

class ZooAnimal
{
private:
    std::string name;
    int cageNumber;
    int weightDate;
    int weight;

public:
    void Create(std::string, int, int, int);
    void Destroy();
    std::string reptName();
    int daysSinceLastWeighted(int today);
    void set_name(int);
};

#endif //ZooAnimal

and lastly,

//ZooAnimal.cpp
#include "ZooAnimal.h"
#include <iostream>

void ZooAnimal::Create(std::string a, int b, int c, int d)
{
    //This creates a ZooAnimal Object
    name = a;
    cageNumber = b;
    weightDate = c;
    weight = d;
}

int ZooAnimal::daysSinceLastWeighted(int today)
{
    //calculate how many days have passed since last weight
    return today - weightDate;
}

//clear up the memory
void ZooAnimal::Destroy()
{
    delete &name;
}

// return the animal name
std::string ZooAnimal::reptName()
{
    return name;
}

void ZooAnimal::set_name(int a)
{
    cageNumber = a;
}

So, when I try to run this code(from main.cpp of course) it won't compile and I get the following message in the console

C:\Users\<user>\AppData\Local\Temp\ccOiWb7r.o:main.cpp:(.text+0x2e): undefined reference to `ZooAnimal::set_name(int)'
collect2.exe: error: ld returned 1 exit status

I'm using MinGW to compile, working on a Windows 10 machine. The weird thing is that when I try to run the same code on a cloud editor, like repl.it , it works just fine, and if I don't separate my code into multiple files, again, it runs fine.
Any idea of what can I do?


问:
Vocabulary size for Word2Vec model significantly lower than vocab size of the list that its based on?
```<code>model1 = Word2Vec(words_list_no_dupes, min_count=0,size= 20,workers=3, window =3, sg = 1)
print(model1)
print(len(model1.wv.vocab))
print(model.wv.vectors.shape)
</code>```

output:
Word2Vec(vocab=58, size=20, alpha=0.025)
58
(31752, 20)

However when I check to see the length of the list that the model is formed from

```<code>print(len(words_list_no_dupes))
</code>```

output:

1906

Whats causing this?
The full code I used to derive remove duplicates from the list is here:

```<code>words = []
for r in range(0,len(df)):
    temp = []
    for word in nltk.tokenize.WhitespaceTokenizer().tokenize(df["CAR NAME"][r]):
        temp.append(word.lower())
    words.append(temp)
words_flat_list = [item for sublist in words for item in sublist]

def remove_duplicates(x):
  return list(dict.fromkeys(x))

words_list_no_dupes = remove_duplicates(words_flat_list)
</code>```

答:
The vocabulary size will be the number of unique tokens seen in the training corpus.

It won't have any necessary relationship with the length, in number of texts, in the corpus (len(words_list_no_dupes)) – because each text should itself have many words, including many words repeated from other texts.

If your corpus is not like that – if each text is a just one or two words, like a car name, and no words repeat from text to text – then your corpus is not good for word2vec training. Word2vec requires many examples of each word's usage, in contexts with varying mixtures of surrounding words.

That said, your shown output is a little odd: the  len(model1.wv.vocab) should be the same size as model.wv.vectors.shape[0] – but your output shows 58 then 31,752. Are you sure those are the values from your run?

Also, your 'full code I used to derive remove duplicates from the list' is a bit confusing in intent and effect. You could show, in your question, some examples of what's in the list at the beginning, and end, to perhaps reveal why it's not proper input for Word2Vec. For example, what are the 1st few items in words_flat_list?

```<code>print(words_flat_list[0:3])
</code>```

Then, what are the 1st few items in words_list_no_dupes?

```<code>print(words_list_no_dupes[0:3])
</code>```

Is that what you were expecting?

Is that words_list_no_dupes, that you're passing into Word2Vec, what it expects - which is a Python sequence, where each item is a list-of-string-tokens? (If it's anything else, you should expect weird results.)

Body:
model1 = Word2Vec(words_list_no_dupes, min_count=0,size= 20,workers=3, window =3, sg = 1)
print(model1)
print(len(model1.wv.vocab))
print(model.wv.vectors.shape)

output:
Word2Vec(vocab=58, size=20, alpha=0.025)
58
(31752, 20)

However when I check to see the length of the list that the model is formed from

print(len(words_list_no_dupes))

output:

1906

Whats causing this?
The full code I used to derive remove duplicates from the list is here:

words = []
for r in range(0,len(df)):
    temp = []
    for word in nltk.tokenize.WhitespaceTokenizer().tokenize(df["CAR NAME"][r]):
        temp.append(word.lower())
    words.append(temp)
words_flat_list = [item for sublist in words for item in sublist]

def remove_duplicates(x):
  return list(dict.fromkeys(x))

words_list_no_dupes = remove_duplicates(words_flat_list)

Body:
The vocabulary size will be the number of unique tokens seen in the training corpus.

It won't have any necessary relationship with the length, in number of texts, in the corpus (len(words_list_no_dupes)) – because each text should itself have many words, including many words repeated from other texts.

If your corpus is not like that – if each text is a just one or two words, like a car name, and no words repeat from text to text – then your corpus is not good for word2vec training. Word2vec requires many examples of each word's usage, in contexts with varying mixtures of surrounding words.

That said, your shown output is a little odd: the  len(model1.wv.vocab) should be the same size as model.wv.vectors.shape[0] – but your output shows 58 then 31,752. Are you sure those are the values from your run?

Also, your 'full code I used to derive remove duplicates from the list' is a bit confusing in intent and effect. You could show, in your question, some examples of what's in the list at the beginning, and end, to perhaps reveal why it's not proper input for Word2Vec. For example, what are the 1st few items in words_flat_list?

print(words_flat_list[0:3])

Then, what are the 1st few items in words_list_no_dupes?

print(words_list_no_dupes[0:3])

Is that what you were expecting?

Is that words_list_no_dupes, that you're passing into Word2Vec, what it expects - which is a Python sequence, where each item is a list-of-string-tokens? (If it's anything else, you should expect weird results.)


问:
How can I delete committed items that haven't been pushed to git yet?
I tried to push files that were too big for the GitHub limit and couldn't push them. I removed them from the folder, but they're still there, waiting to be committed, and it's blocking other push attempts too.</p>

答: Have you tried git rm {file1} {file2} ... {fileN}? You have to tell git to remove the files from the source tree even if you delete the files themselves.


问:
Accessing SQL data from a list entry
First, I will describe and show how my mini program works visually so my problem is easy to understand

Program Description

Below are the 2 widows that I use for the program:

Main Window

Input Window

The Main Window is shown at the start of the program. I used QListWidget for the 'Macros' list, which shows titles of each entry read from a Sqlite database(DB). A new Input Window is shown when the 'New' button in Main Window is pressed. The 'Save' button in Input Window saves the title and description input to DB and updates the 'Macros' list in Main Window. This will look something like this:

Enter information at Input Window

Updated Main Window

My Sqlite Table

My Problem

I would like to be able to select an entry in 'Macros' list, press "Edit" button, and show Input Window filled with data from DB. However, because QListWidget allows only string input, I can't search using it's PK ('id').

I'm thinking of using QTableWidget instead of QListWidget. I will load the entire table but hide all the columns except the title column, so that only the titles will be displayed in 'Macros' list in Main Window. For querying, I will use the entry's PK by accessing the selected entry's 0'th index.

Please let me know if this is the correct step. If not, please describe what you would use to implement a list that only shows the title, but allows querying of its data. I am a beginner at PyQt/PySide and I would really appreciate any guidance.

Codes

Below are the code executed when 'Save' button is pressed (plus its helper functions)

```<code>def save_macro(self):

    title = self.lineedit.text()
    description = self.textedit.toPlainText()

    add_sql_query = ''' INSERT INTO Macros (title,description)
                  VALUES(?,?) '''

    # Helper func that creates connection to db
    sqlhelper = SqliteHelper("entry name")

    if sqlhelper is not None:  # If db is connected:
        macro_data = (title, description)
        sqlhelper.insert(add_sql_query, macro_data)

    self.close()

class SqliteHelper:

    def __init__(self, name=None):
        self.conn = None
        self.cursor = None

        if name:
            self._create_connection(name)

    def _create_connection(self, name):
        try:
            self.conn = sqlite3.connect(name)
            self.cursor = self.conn.cursor()
            print(sqlite3.version)
        except sqlite3.Error as e:
            print(e)

    def insert(self, query, inserts):  # Insert
        c = self.cursor
        c.execute(query, inserts)
        self.conn.commit()
</code>```

答:
Do not reinvent the wheel, Qt provides classes to interact with the database, for example to handle information on tables you can use QSqlQueryModel, QSqlTableModel, etc. To add a row you must create a QSqlRecord and add it to the model, for the edition you can use a QDataWidgetMapper that maps and edits the information of a row, and to delete you must remove the row and reload the entire table. To indicate which field should be displayed in the QListView, use the setModelColumn() method, which should be the column of the "title" field.

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql

def create_connection(database):
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(database)
    if not db.open():
        print("Cannot open database")
        print(
            "Unable to establish a database connection.\n"
            "This example needs SQLite support. Please read "
            "the Qt SQL driver documentation for information "
            "how to build it.\n\n"
            "Click Cancel to exit."
        )
        return False

    query = QtSql.QSqlQuery()
    if not query.exec_(
        """CREATE TABLE IF NOT EXISTS Macros (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "title" TEXT,
    "description" TEXT)"""
    ):
        print(query.lastError().text())
        return False
    return True

class AddMacroDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.title_le = QtWidgets.QLineEdit()
        self.description_te = QtWidgets.QPlainTextEdit()

        button_box = QtWidgets.QDialogButtonBox(self)
        button_box.setOrientation(QtCore.Qt.Horizontal)
        button_box.setStandardButtons(
            QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok
        )

        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.title_le)
        lay.addWidget(self.description_te)
        lay.addWidget(button_box)

    @property
    def title(self):
        return self.title_le.text()

    @property
    def description(self):
        return self.description_te.toPlainText()

class EditMacroDialog(QtWidgets.QDialog):
    def __init__(self, model, index, parent=None):
        super().__init__(parent)

        self.title_le = QtWidgets.QLineEdit()
        self.description_te = QtWidgets.QPlainTextEdit()

        mapper = QtWidgets.QDataWidgetMapper(
            self, submitPolicy=QtWidgets.QDataWidgetMapper.ManualSubmit
        )
        mapper.setModel(model)
        mapper.addMapping(self.title_le, model.record().indexOf("title"))
        mapper.addMapping(self.description_te, model.record().indexOf("description"))
        mapper.setCurrentIndex(index)

        button_box = QtWidgets.QDialogButtonBox(self)
        button_box.setOrientation(QtCore.Qt.Horizontal)
        button_box.setStandardButtons(
            QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok
        )

        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        button_box.accepted.connect(mapper.submit)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.title_le)
        lay.addWidget(self.description_te)
        lay.addWidget(button_box)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._model = QtSql.QSqlTableModel(self)
        self.model.setTable("Macros")
        self.model.select()

        self.sql_list_view = QtWidgets.QListView()
        self.sql_list_view.setModel(self.model)
        self.sql_list_view.setModelColumn(self.model.record().indexOf("title"))

        self.new_button = QtWidgets.QPushButton(self.tr("New"))
        self.edit_button = QtWidgets.QPushButton(self.tr("Edit"))
        self.remove_button = QtWidgets.QPushButton(self.tr("Remove"))

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)

        grid_layout = QtWidgets.QGridLayout(central_widget)
        grid_layout.addWidget(
            QtWidgets.QLabel(self.tr("Macros"), alignment=QtCore.Qt.AlignCenter)
        )
        grid_layout.addWidget(self.sql_list_view, 1, 0)

        vlay = QtWidgets.QVBoxLayout()
        vlay.addWidget(self.new_button)
        vlay.addWidget(self.edit_button)
        vlay.addWidget(self.remove_button)
        grid_layout.addLayout(vlay, 1, 1)
        self.resize(640, 480)

        self.new_button.clicked.connect(self.new)
        self.edit_button.clicked.connect(self.edit)
        self.remove_button.clicked.connect(self.remove)

        self.sql_list_view.selectionModel().selectionChanged.connect(
            self.onSelectionChanged
        )
        self.onSelectionChanged()

    @property
    def model(self):
        return self._model

    @QtCore.pyqtSlot()
    def new(self):
        d = AddMacroDialog()
        if d.exec_() == QtWidgets.QDialog.Accepted:
            r = self.model.record()
            r.setValue("title", d.title)
            r.setValue("description", d.description)
            if self.model.insertRecord(self.model.rowCount(), r):
                self.model.select()

    @QtCore.pyqtSlot()
    def edit(self):
        ixs = self.sql_list_view.selectionModel().selectedIndexes()
        if ixs:
            d = EditMacroDialog(self.model, ixs[0].row())
            d.exec_()

    @QtCore.pyqtSlot()
    def remove(self):
        ixs = self.sql_list_view.selectionModel().selectedIndexes()
        if ixs:
            self.model.removeRow(ixs[0].row())
            self.model.select()

    @QtCore.pyqtSlot()
    def onSelectionChanged(self):
        state = bool(self.sql_list_view.selectionModel().selectedIndexes())
        self.edit_button.setEnabled(state)
        self.remove_button.setEnabled(state)

if __name__ == "__main__":
    import sys

    database = "entry name"  # ":memory:"
    app = QtWidgets.QApplication(sys.argv)
    if not create_connection(database):
        sys.exit(app.exec_())
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
```

Title: Accessing SQL data from a list entry

Body:
First, I will describe and show how my mini program works visually so my problem is easy to understand

Program Description

Below are the 2 widows that I use for the program:

Main Window

Input Window

The Main Window is shown at the start of the program. I used QListWidget for the 'Macros' list, which shows titles of each entry read from a Sqlite database(DB). A new Input Window is shown when the 'New' button in Main Window is pressed. The 'Save' button in Input Window saves the title and description input to DB and updates the 'Macros' list in Main Window. This will look something like this:

Enter information at Input Window

Updated Main Window

My Sqlite Table

My Problem

I would like to be able to select an entry in 'Macros' list, press "Edit" button, and show Input Window filled with data from DB. However, because QListWidget allows only string input, I can't search using it's PK ('id').

I'm thinking of using QTableWidget instead of QListWidget. I will load the entire table but hide all the columns except the title column, so that only the titles will be displayed in 'Macros' list in Main Window. For querying, I will use the entry's PK by accessing the selected entry's 0'th index.

Please let me know if this is the correct step. If not, please describe what you would use to implement a list that only shows the title, but allows querying of its data. I am a beginner at PyQt/PySide and I would really appreciate any guidance.

Codes

Below are the code executed when 'Save' button is pressed (plus its helper functions)

def save_macro(self):

    title = self.lineedit.text()
    description = self.textedit.toPlainText()

    add_sql_query = ''' INSERT INTO Macros (title,description)
                  VALUES(?,?) '''

    # Helper func that creates connection to db
    sqlhelper = SqliteHelper("entry name")

    if sqlhelper is not None:  # If db is connected:
        macro_data = (title, description)
        sqlhelper.insert(add_sql_query, macro_data)

    self.close()

class SqliteHelper:

    def __init__(self, name=None):
        self.conn = None
        self.cursor = None

        if name:
            self._create_connection(name)

    def _create_connection(self, name):
        try:
            self.conn = sqlite3.connect(name)
            self.cursor = self.conn.cursor()
            print(sqlite3.version)
        except sqlite3.Error as e:
            print(e)

    def insert(self, query, inserts):  # Insert
        c = self.cursor
        c.execute(query, inserts)
        self.conn.commit()


问:
boost on python on Mac
I am trying to use boost library on Python. In C++ I include boost\python.hpp but it says it cannot open pyconfig.h. How should I do that? I have a Mac with Parallels installed and my C++ code is in Visual Studio on Parallels. I installed homebrew and boost from the terminal, I already had boost on the Parallels side which I have used different times in C++. In short, I did a mess. How can I fix this?
Thanks!!</p>

答: You need to find pyconfig.h on your machine, then add its directory to your build like -I/some/path.  Often it will be in a directory called python3.7 or whatever version you have.

Title: boost on python on Mac


问:
why does memory address change in Ubuntu and not in Redhat
I have this program:

```<code>double t;
main() {
}
</code>```

On Ubuntu, I run:

```<code>% gdb a.out
(gdb) p &t
$1 = (double *) 0x4010 <t>
(gdb) run
Starting program: /home/phan/a.out
[Inferior 1 (process 95930) exited normally]
(gdb) p &t
$2 = (double *) 0x555555558010 <t>
</code>```

Why did the address change from 0x4010 to 0x555555558010. Is there someway to prevent this?
On Redhat, it doesn't do that:

```<code>% gdb a.out
(gdb) p &t
$1 = (double *) 0x601038 <t>
(gdb) r
Starting program: /home/phan/a.out
[Inferior 1 (process 23337) exited normally]
(gdb) p &t
$2 = (double *) 0x601038 <t>
</code>```

BTW, this only occurs in Ubuntu 18.04.  In Ubuntu 16.04, it works exactly as Redhat, for example the address is the same before and after.

答:
You are presumably seeing pre and post-relocation addresses for the .bss segment.

You can avoid this by disabling position independent executables, thus making gcc choose the final address of the .bss register up front:

```<code>gcc -no-pie foo.c
</code>```

-static would have the effect.

I don't know why there'd be a difference between Ubuntu and Redhat though.

Body:
I have this program:

double t;
main() {
}

On Ubuntu, I run:

% gdb a.out
(gdb) p &t
$1 = (double *) 0x4010 <t>
(gdb) run
Starting program: /home/phan/a.out
[Inferior 1 (process 95930) exited normally]
(gdb) p &t
$2 = (double *) 0x555555558010 <t>

Why did the address change from 0x4010 to 0x555555558010. Is there someway to prevent this?
On Redhat, it doesn't do that:

% gdb a.out
(gdb) p &t
$1 = (double *) 0x601038 <t>
(gdb) r
Starting program: /home/phan/a.out
[Inferior 1 (process 23337) exited normally]
(gdb) p &t
$2 = (double *) 0x601038 <t>

BTW, this only occurs in Ubuntu 18.04.  In Ubuntu 16.04, it works exactly as Redhat, for example the address is the same before and after.

Body:
You are presumably seeing pre and post-relocation addresses for the .bss segment.

You can avoid this by disabling position independent executables, thus making gcc choose the final address of the .bss register up front:

gcc -no-pie foo.c

-static would have the effect.

I don't know why there'd be a difference between Ubuntu and Redhat though.


答:
You can get oldest and newest with idxmin and idxmax

df.loc[df.groupby(['Country or Area'])['Year'].idxmin()]

Title: Return rows in pandas based on values in multiple columns

Body:
Needed some help with pandas...I'm working on this data and I'm trying to calculate some changes over time per region.
Basically, I'm trying to find the oldest quantity and the newest quantity for each area in question. I have code that can give me the year of the most recent and oldest data recordes, however I need to gather the whole row so I can work on the 'quantity' column. Any inputs? here is what i have :

df.groupby(['Country or Area'])['Year'].max()

Thanks in advance!


问:
Comparing date ranges with JQuery?
I have an option list.

I have a fixed date to go by, for example 2012-01-01.
Option list, the monthly intervals:
eg
2-10 months
7-15 months
11-25 months
14-25 months
18-30 months
30-100 months

I have seen option lists that change the content depending on what you choose in the other lists / other.

Now I would like to have an option list that shows only some choice in my option list, whichever the user specifies in the date box. If the user eg enter 2013-01-01, all choices should appear to match 2012-01-01, that is 7-15 months and 11-25 months.

Does anyone have any suggestions?

答: you should find happiness with DateJs ans its clear API to find the number of month to the first date. Then you can know which option of the select to choose based on this value</p>

Title: Comparing date ranges with JQuery?


问:
List of FFMPEG audio formats and their file extensions
I've tried to find information about this but to no avail.

What audio formats and their file extensions are supported by FFMPEG?

Is there a command that can list them all?

答:
Unfortunately there is no list with extensions.
However you can look up common extensions per muxer.

List all codecs. You can narrow it down with selecting only DEA (Decoding supported, Encoding supported, Audio codec)

ffmpeg -hide_banner -codecs | grep DEA

Now you get a long list.

Take e.g. DEA.LS dts         DCA (DTS Coherent Acoustics) (decoders: dca ) (encoders: dca )

Now query the common extensions for dts:

ffmpeg -hide_banner -h muxer=dts

Result: Common extensions: dts.

(With other codecs you should also try demuxer=)


问:
Producing tasks on-demand in producer-consumer pattern
Let's consider the following situation in producer-consumer pattern:

I cannot wait with a task to be performed. I want to produce task on demand (eg. with Supplier) when a consumer is ready to process it. In SynchronousQueue I need to have actual task when executing put() method. How to solve my problem?

I know that I could solve it by design - just make a set of workers and tell them to produceTask-consume-Task-repeat, but I'm looking for another way.

To be more specific:
Let's consider that I have remote http resource A. I can get a 'task' from it to process in my worker threads. Results are sent asynchronously. But the thing is that I should not get a task from A if I am not able to process it right now.

答:
If I were You, in the case of "producer-consumer pattern" you should not use blocking queues, however You looking for a non-blocking asynchronous queue.

Then everybody notified just in time.

Or is there any other constraint with the actual tasks. Or somehow I misunderstand You? Which side of the producer-consumer goes hungry?


问:
Setting an existing dictionary's values to all zeros
If I have this dict:

```<code>dict1 = {"Key1": [[1, 3, 4], [2, 5, 8]], "key2": [4, 5]}
</code>```

How can I set all the values to 0?

Output should be like this:

```<code>dict1 = {"Key1": [[0,0,0], [0,0,0]], "key2": [0,0]}
</code>```

答:
You can do this with a recursive function that zeros each element of a list or dictionary that is passed to it:

```<code>dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8]], "key2" : [4, 5] }

def zero(e):
    if type(e) is list:
        return [zero(v) for v in e]
    elif type(e) is dict:
        return {k : zero(v) for k, v in e.items()}
    return 0

dict1 = zero(dict1)
print(dict1)
</code>```

Output:

```<code>{'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}
</code>```

Note that this generates a new dictionary rather than mutating the original one.

Body:
If I have this dict:

dict1 = {"Key1": [[1, 3, 4], [2, 5, 8]], "key2": [4, 5]}

How can I set all the values to 0?

Output should be like this:

dict1 = {"Key1": [[0,0,0], [0,0,0]], "key2": [0,0]}

Body:
You can do this with a recursive function that zeros each element of a list or dictionary that is passed to it:

dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8]], "key2" : [4, 5] }

def zero(e):
    if type(e) is list:
        return [zero(v) for v in e]
    elif type(e) is dict:
        return {k : zero(v) for k, v in e.items()}
    return 0

dict1 = zero(dict1)
print(dict1)

Output:

{'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}

Note that this generates a new dictionary rather than mutating the original one.


问:
Select data from specific row of grouped and joined table in MySQL
I have two tables, customers and orders which are inner joined. A customer can have several orders associated with them. In my selection, I then group by customers.id. I need to select the most recent order of each customer, but also the amount of money spent in that order. Currently, I can select the most recent order_date but do not know how to select the amount in the same row as the order_date.

This is my current query:

```<code>SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    amount -- this needs to select amount associated with recent_order
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;
</code>```

The query selects the most recent date, but does not select the amount associated with the most recent order_date.

Table declarations:

```<code>CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_date DATE,
    amount DECIMAL(8,2),
    customer_id INT,
    FOREIGN KEY(customer_id) REFERENCES customers(id)
);
</code>```

答:
I would recommend a correlated subquery in the where clause:

```<code>SELECT c.*, o.*  -- or whatever columns you want
FROM customers c JOIN
     orders o
     ON c.id = o.customer_id
WHERE o.order_date = (SELECT max(o2.order_date)
                      FROM orders o2
                      WHERE o2.customer_id = o.customer_id
                     );
</code>```

For performance, you want an index on orders(customer_id, order_date).

Body:
I have two tables, customers and orders which are inner joined. A customer can have several orders associated with them. In my selection, I then group by customers.id. I need to select the most recent order of each customer, but also the amount of money spent in that order. Currently, I can select the most recent order_date but do not know how to select the amount in the same row as the order_date.

This is my current query:

SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    amount -- this needs to select amount associated with recent_order
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;

The query selects the most recent date, but does not select the amount associated with the most recent order_date.

Table declarations:

CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_date DATE,
    amount DECIMAL(8,2),
    customer_id INT,
    FOREIGN KEY(customer_id) REFERENCES customers(id)
);

Body:
I would recommend a correlated subquery in the where clause:

SELECT c.*, o.*  -- or whatever columns you want
FROM customers c JOIN
     orders o
     ON c.id = o.customer_id
WHERE o.order_date = (SELECT max(o2.order_date)
                      FROM orders o2
                      WHERE o2.customer_id = o.customer_id
                     );

For performance, you want an index on orders(customer_id, order_date).


问:
What's the difference between double quotes and single quote in C#?
What's the difference between double quotes and single quote in C#?

I coded a program to count how many words are in a file

```<code>using System;
using System.IO;
namespace Consoleapp05
{
    class Program
    {
        public static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"C:\words.txt");
            string text = sr.ReadToEnd();
            int howmany = 0;
            int howmany2 = 0;

            for(int i = 0; i < text.Length; i++)
            {
                if(text[i] == " ")
                {
                howmany++;
                }
            }
            howmany2 = howmany + 1;
            Console.WriteLine("It is {0} words in the file", howmany2);
            Console.ReadKey(true);
        }
    }
}
</code>```

This gives me an error because of the double quotes. My teacher told me to use single quote instead, but he didn't tell me why. So what's the difference between double quotes and single quote in C#?

答:
When you say string s = "this string" then s[0] is a character at a specific index in that string (in this case s[0] == 't').

So to answer your question, use double quotes or single quotes. You can think of the following as meaning the same thing:

```<code>string s = " word word";

// Check for space as first character using single quotes
if(s[0] == ' ') {
    // Do something
}

// Check for space using string notation
if(s[0] == " "[0]) {
    // Do something
}
</code>```

As you can see, using a single quote to determine a single character is a lot easier than trying to convert our string into a character just for testing.

```<code>if(s[0] == " "[0]) {
    // Do something
}
</code>```

is really like saying:

```<code>string space = " ";
if(s[0] == space[0]) {
    // Do something
}
</code>```

OwnerDisplayName: You sir are a idoit

LastEditorDisplayName: Jon Skeet

Body:
What's the difference between double quotes and single quote in C#?

I coded a program to count how many words are in a file

using System;
using System.IO;
namespace Consoleapp05
{
    class Program
    {
        public static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"C:\words.txt");
            string text = sr.ReadToEnd();
            int howmany = 0;
            int howmany2 = 0;

            for(int i = 0; i < text.Length; i++)
            {
                if(text[i] == " ")
                {
                howmany++;
                }
            }
            howmany2 = howmany + 1;
            Console.WriteLine("It is {0} words in the file", howmany2);
            Console.ReadKey(true);
        }
    }
}

This gives me an error because of the double quotes. My teacher told me to use single quote instead, but he didn't tell me why. So what's the difference between double quotes and single quote in C#?

Body:
When you say string s = "this string" then s[0] is a character at a specific index in that string (in this case s[0] == 't').

So to answer your question, use double quotes or single quotes. You can think of the following as meaning the same thing:

string s = " word word";

// Check for space as first character using single quotes
if(s[0] == ' ') {
    // Do something
}

// Check for space using string notation
if(s[0] == " "[0]) {
    // Do something
}

As you can see, using a single quote to determine a single character is a lot easier than trying to convert our string into a character just for testing.

if(s[0] == " "[0]) {
    // Do something
}

is really like saying:

string space = " ";
if(s[0] == space[0]) {
    // Do something
}

OwnerDisplayName: Wayne


问:
WinForms ComboBox - Event when Text Input is Clicked Into
I have a feature request that when a ComboBox is 'clicked into' that it clears the text so that the user can start entering in new data to search.  Does anyone know of a way to hook into this?  The 'click' event is raised on when the text is clicked as well as when the drop down arrow is also clicked (which opens up the drop down with items).  I only want it to happen on the first, not the latter.

Right now I'm capturing the click event and filtering on the DroppedDown property like so:

```<code>if(!comboBox.DroppedDown)
{
    // clear selection
}
</code>```

This seems to work most of the time, but bugs out frequently as well... so its not 100%.

If anyone knows of a proper way to do this I would appreciate!

答:
Don't handle the click event. For one thing, it won't fire if the user tabs the focus into the control. Use the Enter event which fires when the control receives focus. And rather than clearing text you should just select it all which will give the best of both worlds:

1) The user can start entering new text which will clear any old text or

2) tab past the control and leave the contained text as it was.

If you always remove the previous text you may anger users.

Body:
I have a feature request that when a ComboBox is 'clicked into' that it clears the text so that the user can start entering in new data to search.  Does anyone know of a way to hook into this?  The 'click' event is raised on when the text is clicked as well as when the drop down arrow is also clicked (which opens up the drop down with items).  I only want it to happen on the first, not the latter.

Right now I'm capturing the click event and filtering on the DroppedDown property like so:

if(!comboBox.DroppedDown)
{
    // clear selection
}

This seems to work most of the time, but bugs out frequently as well... so its not 100%.

If anyone knows of a proper way to do this I would appreciate!


问:
How can we read csv file in asp.net core using CsvHelper?
how to read and write csv file in asp.net core using CsvHelper</p>

答:
Are you asking how to write the code? Have you looked at the examples online?

Note that SoftCircuits.CsvParser is about four times faster than CsvHelper. Here's what it would look like to read a file using SoftCircuits.CsvParser:

```<code>string[] columns = null;
using (CsvReader reader = new CsvReader(path))
{
    while (reader.ReadRow(ref columns))
    {
        // Here columns contains an array of string values that
        // were read from the current line
    }
}
</code>```

Note that both libraries also have the ability to map the columns directly to object properties so you can just create your class that has a property corresponding to each column, and everything will be mapped for you. The example above simply reads the columns as an array of strings.

Body:
Are you asking how to write the code? Have you looked at the examples online?

Note that SoftCircuits.CsvParser is about four times faster than CsvHelper. Here's what it would look like to read a file using SoftCircuits.CsvParser:

string[] columns = null;
using (CsvReader reader = new CsvReader(path))
{
    while (reader.ReadRow(ref columns))
    {
        // Here columns contains an array of string values that
        // were read from the current line
    }
}

Note that both libraries also have the ability to map the columns directly to object properties so you can just create your class that has a property corresponding to each column, and everything will be mapped for you. The example above simply reads the columns as an array of strings.