答:
You can use regex here

```<code>import re
for i in range(len(data)):
    data[i][0] = re.sub(r'(\w)\s\s+(\w)', r'\1 \2', data[i][0])
    data[i][0] = re.sub(r'\s\s+', r'', data[i][0])
    data[i][0] = re.sub(r"(\w)\s([.])", r"\1\2", dat[i][0])
</code>```

The regex pattern \s\s+ matches all groups of 2 or more whitespace characters. As noted that would eliminate spacing between words if there was more than 1 space between two words. The r'\w\s\s+\w', r'\1 \2' takes care of that by eliminating the spaces between word boundaries with a single space.

Also note that it's data[i][0] because strangely the data is a list of lists.

Title: How would I eliminate spacing, line breaks to have a space-delimited string for each string within my list python

Body:
You can use regex here

import re
for i in range(len(data)):
    data[i][0] = re.sub(r'(\w)\s\s+(\w)', r'\1 \2', data[i][0])
    data[i][0] = re.sub(r'\s\s+', r'', data[i][0])
    data[i][0] = re.sub(r"(\w)\s([.])", r"\1\2", dat[i][0])

The regex pattern \s\s+ matches all groups of 2 or more whitespace characters. As noted that would eliminate spacing between words if there was more than 1 space between two words. The r'\w\s\s+\w', r'\1 \2' takes care of that by eliminating the spaces between word boundaries with a single space.

Also note that it's data[i][0] because strangely the data is a list of lists.


来源: stackexchange

问:
Compose a method name with a variable
I have this code in a Mojolicious template:

```<code>my $lang = 'de'; # de, en, ...
% $col = 'internet' . '_' . $lang;
%== markdown($rs->$col); # outputs correctly the content of the column internet_de
</code>```

Is there a way to combine the lines 2 and 3 into something like:

```<code>%== markdown($rs->'internet' . '_' . $lang); # syntax error at template ..., near "->'internet'"
</code>```

答:
Readabbility is quite an issue, so i would add a helper function to your Module:

```<code>sub access_it {
    my ($obj, $fun) = @_;
    return $obj->$fun
}
</code>```

after that you should be able to use

```<code>%== markdown(access_it($rs,'internet' . '_' . $lang));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Compose a method name with a variable

Body:
I have this code in a Mojolicious template:

my $lang = 'de'; # de, en, ...
% $col = 'internet' . '_' . $lang;
%== markdown($rs->$col); # outputs correctly the content of the column internet_de

Is there a way to combine the lines 2 and 3 into something like:

%== markdown($rs->'internet' . '_' . $lang); # syntax error at template ..., near "->'internet'"

Body:
Readabbility is quite an issue, so i would add a helper function to your Module:

sub access_it {
    my ($obj, $fun) = @_;
    return $obj->$fun
}

after that you should be able to use

%== markdown(access_it($rs,'internet' . '_' . $lang));


问:
Save data to firebase Realtime database from Android service
I want to save user's location after every 30 seconds to firebase realtime database from android service,my service stops when i add firebase, there is no crash log, any suggestions? or best solution to achieve this? Thanks</p>

```<code>public class LocationService extends Service {
    double pLatitude, pLongitude;
    private DatabaseReference mDatabase;
    FirebaseUser user;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(getApplicationContext(),"Service Started", Toast.LENGTH_SHORT).show();
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //service stops(crashes) on below two lines
            mDatabase = FirebaseDatabase.getInstance().getReference();
            user = FirebaseAuth.getInstance().getCurrentUser();

        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
                            pushtofirebase(getLocation());

                        } catch (Exception e) {
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 30000);

    }

    private void pushtofirebase(GPSTracker gps) {
            pLatitude = gps.getLatitude();
            pLongitude = gps.getLongitude();

            mDatabase.child("location").child(user.getUid()).push().setValue(String.valueOf(pLatitude));
            mDatabase.child("location").child(user.getUid()).setValue(pLongitude);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

    private GPSTracker getLocation() {

        GPSTracker gps = new GPSTracker(getApplicationContext());
        if (gps.canGetLocation()) {
            Toast.makeText(getApplicationContext(), gps.getLongitude() + " " + gps.getLatitude(), Toast.LENGTH_SHORT).show();

        } else {
            gps.showSettingsAlert();
        }
        return gps;
    }
}
</code>```

答: it may be a native crash change the logcat crash level to verbose and application to no filter

Body:
I want to save user's location after every 30 seconds to firebase realtime database from android service,my service stops when i add firebase, there is no crash log, any suggestions? or best solution to achieve this? Thanks

public class LocationService extends Service {
    double pLatitude, pLongitude;
    private DatabaseReference mDatabase;
    FirebaseUser user;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(getApplicationContext(),"Service Started", Toast.LENGTH_SHORT).show();
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //service stops(crashes) on below two lines
            mDatabase = FirebaseDatabase.getInstance().getReference();
            user = FirebaseAuth.getInstance().getCurrentUser();

        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
                            pushtofirebase(getLocation());

                        } catch (Exception e) {
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 30000);

    }

    private void pushtofirebase(GPSTracker gps) {
            pLatitude = gps.getLatitude();
            pLongitude = gps.getLongitude();

            mDatabase.child("location").child(user.getUid()).push().setValue(String.valueOf(pLatitude));
            mDatabase.child("location").child(user.getUid()).setValue(pLongitude);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

    private GPSTracker getLocation() {

        GPSTracker gps = new GPSTracker(getApplicationContext());
        if (gps.canGetLocation()) {
            Toast.makeText(getApplicationContext(), gps.getLongitude() + " " + gps.getLatitude(), Toast.LENGTH_SHORT).show();

        } else {
            gps.showSettingsAlert();
        }
        return gps;
    }
}


问:
Share data between main app and today widget macOS
I'm trying to share data between my main macOS app and the extension I created.

I saw I have to use the "App Groups" and share the data with "UserDefault(suiteName: "name")"

The problem : After turned on App Groups on the main app and added a name, I then turn on App Groups on extension and the list is empty, I don't see the group I'v just created ?

Any idea ?

btw: the team profil is the same on both app and extension. I'v tried to delete temporary file, clean project, restored Xcode and computer.

EDIT 1 : On iOS project the app groups are detected....

EDIT 2 : I tried with Xcode 9 but same problem.

EDIT 3 : On Certificates, Identifiers & Profiles apple website, you don't have the category "App Groups" for macOS, is it deprecated ??

EDIT 4 : If I add both add groups names manually, then I got an error in output :.
[User Defaults] Failed to read values in CFPrefsPlistSource<0x6000000e4200> (Domain: 726328455Z.test, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null)): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd.

Edit 5 :  Looks like it work, the data is successfully saved with this code

```<code>UserDefaults(suiteName: "7263xxx55Z.test")!.set(selectedRow, forKey: "selectedRow")
UserDefaults(suiteName: "7263xxx55Z.test")!.synchronize()
</code>```

And fetch with this code, I got the previous error but I just ignore it

```<code>let selectedRow = UserDefaults(suiteName: "726xxx55Z.test")!.integer(forKey: "selectedRow")
</code>```

答:
To share data between app/app extension in macOS project :

1/ In your Main project target, select Capabilities and enable "App Groups".

2/ Click on "+" and add a new app group name, it must start with your team ID (e.g. 643J438K.name.app)

3/ Repeat 1/ and 2/ for your extension app target, be sure to add the same name

4/ To save and fetch data use :

```<code>// Store data
UserDefaults(suiteName: "643J438K.name.app")!.set(yourVariable, forKey: "yourKey")
UserDefaults(suiteName: "643J438K.name.app")!.synchronize()

// Fetch data (integer type here)
UserDefaults(suiteName: "643J438K.name.app")!.integer(forKey: "yourKey")
</code>```

5/ You can check that your data is correctly saved by opening this file :

```<code>/Users/UserName/Library/Group Containers/643J438K.name.app/Preferences/643J438K.name.app.plist
</code>```

Body:
I'm trying to share data between my main macOS app and the extension I created.

I saw I have to use the "App Groups" and share the data with "UserDefault(suiteName: "name")"

The problem : After turned on App Groups on the main app and added a name, I then turn on App Groups on extension and the list is empty, I don't see the group I'v just created ?

Any idea ?

btw: the team profil is the same on both app and extension. I'v tried to delete temporary file, clean project, restored Xcode and computer.

EDIT 1 : On iOS project the app groups are detected....

EDIT 2 : I tried with Xcode 9 but same problem.

EDIT 3 : On Certificates, Identifiers & Profiles apple website, you don't have the category "App Groups" for macOS, is it deprecated ??

EDIT 4 : If I add both add groups names manually, then I got an error in output :.
[User Defaults] Failed to read values in CFPrefsPlistSource<0x6000000e4200> (Domain: 726328455Z.test, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null)): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd.

Edit 5 :  Looks like it work, the data is successfully saved with this code

UserDefaults(suiteName: "7263xxx55Z.test")!.set(selectedRow, forKey: "selectedRow")
UserDefaults(suiteName: "7263xxx55Z.test")!.synchronize()

And fetch with this code, I got the previous error but I just ignore it

let selectedRow = UserDefaults(suiteName: "726xxx55Z.test")!.integer(forKey: "selectedRow")

Body:
To share data between app/app extension in macOS project :

1/ In your Main project target, select Capabilities and enable "App Groups".

2/ Click on "+" and add a new app group name, it must start with your team ID (e.g. 643J438K.name.app)

3/ Repeat 1/ and 2/ for your extension app target, be sure to add the same name

4/ To save and fetch data use :

// Store data
UserDefaults(suiteName: "643J438K.name.app")!.set(yourVariable, forKey: "yourKey")
UserDefaults(suiteName: "643J438K.name.app")!.synchronize()

// Fetch data (integer type here)
UserDefaults(suiteName: "643J438K.name.app")!.integer(forKey: "yourKey")

5/ You can check that your data is correctly saved by opening this file :

/Users/UserName/Library/Group Containers/643J438K.name.app/Preferences/643J438K.name.app.plist


问:
Plot two histograms on single chart with matplotlib
I created a histogram plot using data from a file and no problem. Now I wanted to superpose data from another file in the same histogram, so I do something like this

```<code>n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)
</code>```

but the problem is that for each interval, only the bar with the highest value appears, and the other is hidden. I wonder how could I plot both histograms at the same time with different colors.

答:
Here is a simple method to plot two histograms, with their bars side-by-side, on the same plot when the data has different sizes: </p>

```<code>def plotHistogram(p, o):
    """
    p and o are iterables with the values you want to
    plot the histogram of
    """
    plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
    plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a histogram plot using data from a file and no problem. Now I wanted to superpose data from another file in the same histogram, so I do something like this

n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)

but the problem is that for each interval, only the bar with the highest value appears, and the other is hidden. I wonder how could I plot both histograms at the same time with different colors.

Body:
Here is a simple method to plot two histograms, with their bars side-by-side, on the same plot when the data has different sizes:

def plotHistogram(p, o):
    """
    p and o are iterables with the values you want to
    plot the histogram of
    """
    plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
    plt.show()


问:
I want to get column data from sql server using datatable and store it in a string variable?
```<code>query = "select id from user_detail where status='Processing...'";
        DataTable datatable = Handler.FetchDataTable(query);
        if (datatable != null && datatable.Rows.Count > 0)
        {
            data = (datatable).ToString();
        }
</code>```

this is my code. i want to get all record from column and store it in data variable one by one

答:
I would argue that the ideal way to do this is with "dapper":

```<code>List<string> ids = connection.Query<string>(query).AsList();
</code>```

Note that it supports full parameterization etc too.

However, with your existing code:

```<code>var col = datatable.Columns[0];

foreach(DataRow row in datatable.Rows)
{
    string s = (string)row[col];
    //...
}
</code>```

Body:
query = "select id from user_detail where status='Processing...'";
        DataTable datatable = Handler.FetchDataTable(query);
        if (datatable != null && datatable.Rows.Count > 0)
        {
            data = (datatable).ToString();
        }

this is my code. i want to get all record from column and store it in data variable one by one

Body:
I would argue that the ideal way to do this is with "dapper":

List<string> ids = connection.Query<string>(query).AsList();

Note that it supports full parameterization etc too.

However, with your existing code:

var col = datatable.Columns[0];

foreach(DataRow row in datatable.Rows)
{
    string s = (string)row[col];
    //...
}


问:
Reduce battery drain using Voip and Location services Enabled
We have implemented a chat based application based on mqtt.But recently we implemented calling feature by enabling voip and using Sinch frame work. After  enabling voip battery consumption in settings showing as 85% - 90%.How to improve battery life.</p>

答: When you are enable any Background modes from capability, it will run your app in the background mode that consumes a lot of battery. If any app runs in background it will consume more battery, so its better to customize your app while using background mode.</p>


问:
Retrieving data table headers from GEO using GEOquery
For a study in GEO, I would like to obtain the data table header descriptions, specifically the "VALUE" column for all samples in the study.

If you go here and then scroll down and click one of the samples: let's choose "GSM2644971". Then scroll down and you should see "Data table header descriptions" and below that you should see "VALUE Normalized (provided the normalization method) Average Beta". That information is what I want.

I tried using assayData() from the Biobase package but I didn't know whether the method takes a sample, a matrix of samples, or something else as a parameter. Apparently it takes a S4 and then returns some random text but I don't know how to use that random text.

EDIT:

For example, if I do:

```<code>library(Biobase)
library(GEOquery)

getgeo<-getGEO("GSE99511")
assayData(getgeo$GSE99511_series_matrix.txt.gz)
</code>```

When I use assayData() I would want it to return:

"Normalized (provided the normalization method) Average Beta".

Instead it returns:

<environment: 0x110674178>

Please let me know if the question doesn't make sense or if there's another method that I should be using.

答:
You can get the normalized beta values with exprs function, for example:

```<code>e <- exprs(getgeo$GSE99511_series_matrix.txt.gz)
head(e)
</code>```

Body:
For a study in GEO, I would like to obtain the data table header descriptions, specifically the "VALUE" column for all samples in the study.

If you go here and then scroll down and click one of the samples: let's choose "GSM2644971". Then scroll down and you should see "Data table header descriptions" and below that you should see "VALUE Normalized (provided the normalization method) Average Beta". That information is what I want.

I tried using assayData() from the Biobase package but I didn't know whether the method takes a sample, a matrix of samples, or something else as a parameter. Apparently it takes a S4 and then returns some random text but I don't know how to use that random text.

EDIT:

For example, if I do:

library(Biobase)
library(GEOquery)

getgeo<-getGEO("GSE99511")
assayData(getgeo$GSE99511_series_matrix.txt.gz)

When I use assayData() I would want it to return:

"Normalized (provided the normalization method) Average Beta".

Instead it returns:

<environment: 0x110674178>

Please let me know if the question doesn't make sense or if there's another method that I should be using.

Body:
You can get the normalized beta values with exprs function, for example:

e <- exprs(getgeo$GSE99511_series_matrix.txt.gz)
head(e)


问:
Strange behaviour while debugging Call to a member function format() on boolean
tl;dr When iterating over an array of 1000 objects containing a DateTime property and dumping this property, I get 1000 valid DateTime objects in response. When adding a ->format can on a subsequent dump line, termination stops immediately at the first element. Adding a format() call outside of a dump statement only stops termination at the 1000th element.

I'm currently experiencing the following error in my php (symfony) project:

Call to a member function format() on boolean

Normally this would be an easy fix, but I've encountered some strange behaviour while debugging.

```<code>private function filterDuplicates(array $data) {
  $duplicateMap = [];

  foreach($data as $index => $item) {
    // dump here, see below
    $hashKey = md5($item->getBracelet()->getId() . $item->getTimestamp()->format('d/m/y H:i'));
    if (isset($duplicateMap[$hashKey])) {
      unset($data[$index]);
      unset($data[$duplicateMap[$hashKey]]);
    } else {
      $duplicateMap[$hashKey] = $index;
    }
  }

  return $data;
}
</code>```

This code currently gives me the format error right where I'm attempting to set the $hashkey variable. Apparently, one of the $item objects contains an invalid DateTime, or so I thought.

When adding a dump($item->getTimeStamp());, I get exactly 1000 correct DateTime objects, followed by the same format() error. Initially, I figured this meant that the error occured on the latest object in the array.

However, my array only contains exactly 1000 objects, which I have tested using dump(count($data));.

Odd. But okay. I rewrote my dump as such: dump($item->getTimestamp() instanceof \DateTime). This printed 1000 times true. Everything seems like it should be working.

Now for the strange part.

I now changed my dump to this:

```<code>dump($index);
$hashKey = md5($item->getBracelet()->getId() . $item->getTimestamp()->format('d/m/y H:i'));
</code>```

And received this output:

```<code>...
996
997
998
999
PHP Fatal error:  Call to a member function format() on boolean in /Users/svenhoskens/Documents/web_projects/Tomorrowland_api/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php on line 53
</code>```

HOWEVER, upon changin that to this:

```<code>dump($index);
dump($item->getTimestamp()->format('d/m/y H:i'));
$hashKey = md5($item->getBracelet()->getId() . $item->getTimestamp()->format('d/m/y H:i'));
</code>```

I got this strange output:

```<code>0
PHP Fatal error:  Call to a member function format() on boolean in /Users/svenhoskens/Documents/web_projects/Tomorrowland_api/src/AdminPanelBundle/Command/ProcessDatafileCommand.php on line 374
</code>```

As you can see, instead of looping over the 1000 objects and throwing an error at the end, php now throws the error at the very start, even though my dump is immediately followed by the very same format call which causes the error!

What am I missing here? What could cause such a behaviour?

答: The issue is currently resolved, though I'm afraid I don't know why. After a complete restart of my machine, the issue could not be reproduced again. The loop now fails at the correct time, regardless of the contents or order of the dump commands. If anyone encounters something like this again, let me know.</p>

Body:
tl;dr When iterating over an array of 1000 objects containing a DateTime property and dumping this property, I get 1000 valid DateTime objects in response. When adding a ->format can on a subsequent dump line, termination stops immediately at the first element. Adding a format() call outside of a dump statement only stops termination at the 1000th element.

I'm currently experiencing the following error in my php (symfony) project:

Call to a member function format() on boolean

Normally this would be an easy fix, but I've encountered some strange behaviour while debugging.

private function filterDuplicates(array $data) {
  $duplicateMap = [];

  foreach($data as $index => $item) {
    // dump here, see below
    $hashKey = md5($item->getBracelet()->getId() . $item->getTimestamp()->format('d/m/y H:i'));
    if (isset($duplicateMap[$hashKey])) {
      unset($data[$index]);
      unset($data[$duplicateMap[$hashKey]]);
    } else {
      $duplicateMap[$hashKey] = $index;
    }
  }

  return $data;
}

This code currently gives me the format error right where I'm attempting to set the $hashkey variable. Apparently, one of the $item objects contains an invalid DateTime, or so I thought.

When adding a dump($item->getTimeStamp());, I get exactly 1000 correct DateTime objects, followed by the same format() error. Initially, I figured this meant that the error occured on the latest object in the array.

However, my array only contains exactly 1000 objects, which I have tested using dump(count($data));.

Odd. But okay. I rewrote my dump as such: dump($item->getTimestamp() instanceof \DateTime). This printed 1000 times true. Everything seems like it should be working.

Now for the strange part.

I now changed my dump to this:

dump($index);
$hashKey = md5($item->getBracelet()->getId() . $item->getTimestamp()->format('d/m/y H:i'));

And received this output:

...
996
997
998
999
PHP Fatal error:  Call to a member function format() on boolean in /Users/svenhoskens/Documents/web_projects/Tomorrowland_api/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php on line 53

HOWEVER, upon changin that to this:

dump($index);
dump($item->getTimestamp()->format('d/m/y H:i'));
$hashKey = md5($item->getBracelet()->getId() . $item->getTimestamp()->format('d/m/y H:i'));

I got this strange output:

0
PHP Fatal error:  Call to a member function format() on boolean in /Users/svenhoskens/Documents/web_projects/Tomorrowland_api/src/AdminPanelBundle/Command/ProcessDatafileCommand.php on line 374

As you can see, instead of looping over the 1000 objects and throwing an error at the end, php now throws the error at the very start, even though my dump is immediately followed by the very same format call which causes the error!

What am I missing here? What could cause such a behaviour?


问:
Error while installing chatterBot
Whenever I try to install ChatterBot using command pip install ChatterBot it gives this error:

```<code>Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003687898>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)': /simple/chatterbot/
  Could not find a version that satisfies the requirement chatterbot (from versi
ons: )
No matching distribution found for chatterbot
</code>```

I downgraded from Python 3.6 to 2.7, yet receiving the same error.

I am using windows 8, Anaconda 2.7

答:
The problem here is not ChatterBot but the pip command.

Try install chatterbot from it's source:
https://github.com/gunthercox/ChatterBot/archive/master.zip

Then unzip the file.

After open up cmd and type in: cd chatter_bot_master_directory

Finally just type: python(3) setup.py install

If it doesn't work, retry it with more permission: Open up cmd in admin mode.

Title: Error while installing chatterBot

Body:
Whenever I try to install ChatterBot using command pip install ChatterBot it gives this error:

Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003687898>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)': /simple/chatterbot/
  Could not find a version that satisfies the requirement chatterbot (from versi
ons: )
No matching distribution found for chatterbot

I downgraded from Python 3.6 to 2.7, yet receiving the same error.

I am using windows 8, Anaconda 2.7


问:
Decode a binary protocol in python
Im trying to write a simple python client to decode a binary stream generated from a program called sdrdaemon.

The protocol is described here (copied below for convenience). My understanding is the first 42 bytes should contain the meta frame which I thought to read/decode with the python struct module.

I started off with something very simple.

```<code>import select, socket
from struct import *

port = 19090
bufferSize = 512

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('localhost', port))
s.setblocking(0)

i=0
while i<10:
  result = select.select([s],[],[])
  msg = result[0][0].recv(bufferSize)
  # The meta section?
  msg = msg[:42]

  # Log raw bytes
  #print ' '.join('{0:08b}'.format(ord(x), 'b') for x in msg)

  print unpack(">QIxBHIHIIIQ", msg)  # big endian
  i += 1
</code>```

However Im unfamiliar enough with this kind of thing to understand how I would synchronise so Im decoding the right sections. The description below points to the CRC but Im unsure how to go about it. A bit of guidance would be great. A github issue got no response.

The full explanation of the protocol is given here but also copied below:

Packaging

The block of data retrieved from the hardware device is sliced into blocks of the UDP payload size. This sequence of blocks is called a "frame" in the following. A special block called the "meta" block is sent before a frame. It is used to convey "meta" data about the frame and its data that follows. A CRC on 64 bits is calculated on this "meta" data and appended to it. It serves as a verification and also to recognize the "meta" block from the data blocks thus achieving synchronization. There is effectively a very low probability to mix it up with a data block.

A compressed stream may pack several data blocks retrieved from the hardware in one frame to improve compression efficiency. So the case may arise that a change of meta data occurs from one "hardware" block to the next in the same frame. In this case the frame is split and a new frame is constructed with a starting "meta" block from the block where the meta data has changed. The first part of the original frame being sent immediately over UDP. This ensures that the data frame and its "meta" block are always consistent.

Meta data block

The block of "meta" data consists of the following (values expressed in bytes):

Total size is 42 bytes including the 8 bytes CRC.

Data blocks

When the stream is uncompressed UDP blocks of the payload size are stuffed with complete I/Q samples leaving a possible unused gap of less than an I/Q sample at the end of the block. The last block is filled only with the remainder samples. The number of maximally filled blocks and remainder samples in the last block is given in the "meta" data. Of course as the data stream is uncompressed these values can also be calculated from the total number of samples and the payload size.

When the stream is compressed UDP blocks are stuffed completely with bytes of the compressed stream. The last block being filled only with the remainder bytes. The number of full blocks and remainder bytes is given in the "meta" block and these values cannot be calculated otherwise.

Summary diagram

Uncompressed stream

```
hardware block (2 byte I or Q samples):
|I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q|

UDP block (22 bytes):
|xxxxxxxxxxxxxxxxxxxxxx|

Frame:
|Meta:xxxxxxxxxxxxxxxxx|I/Q:I/Q:I/Q:I/Q:I/Q:xx|I/Q:I/Q:I/Q:I/Q:I/Q:xx|I/Q:I/Q:I/Q:xxxxxxxxxx|

Number of samples in a hardware block: 13
Number of blocks in a frame..........:  1 (always if uncompressed)
Number of bytes in a frame...........: 52 (4 * 13)
Complete blocks......................:  2 (calculated)
Remainder samples....................:  3 (calculated)
```

Edit: : I ending up abandoning this approach (in favour of SoapySDR) soon after posting so can't really comment relevantly anymore.

答:
I do not have any example but I had a similar problem the last days and therefore I found this lib. But here is a example: https://github.com/construct/construct/tree/master/construct/examples/protocols

If it is not okay I can also delete my answers.

Title: Decode a binary protocol in python

Body:
Im trying to write a simple python client to decode a binary stream generated from a program called sdrdaemon.

The protocol is described here (copied below for convenience). My understanding is the first 42 bytes should contain the meta frame which I thought to read/decode with the python struct module.

I started off with something very simple.

import select, socket
from struct import *

port = 19090
bufferSize = 512

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('localhost', port))
s.setblocking(0)

i=0
while i<10:
  result = select.select([s],[],[])
  msg = result[0][0].recv(bufferSize)
  # The meta section?
  msg = msg[:42]

  # Log raw bytes
  #print ' '.join('{0:08b}'.format(ord(x), 'b') for x in msg)

  print unpack(">QIxBHIHIIIQ", msg)  # big endian
  i += 1

However Im unfamiliar enough with this kind of thing to understand how I would synchronise so Im decoding the right sections. The description below points to the CRC but Im unsure how to go about it. A bit of guidance would be great. A github issue got no response.

The full explanation of the protocol is given here but also copied below:

Packaging

The block of data retrieved from the hardware device is sliced into blocks of the UDP payload size. This sequence of blocks is called a "frame" in the following. A special block called the "meta" block is sent before a frame. It is used to convey "meta" data about the frame and its data that follows. A CRC on 64 bits is calculated on this "meta" data and appended to it. It serves as a verification and also to recognize the "meta" block from the data blocks thus achieving synchronization. There is effectively a very low probability to mix it up with a data block.

A compressed stream may pack several data blocks retrieved from the hardware in one frame to improve compression efficiency. So the case may arise that a change of meta data occurs from one "hardware" block to the next in the same frame. In this case the frame is split and a new frame is constructed with a starting "meta" block from the block where the meta data has changed. The first part of the original frame being sent immediately over UDP. This ensures that the data frame and its "meta" block are always consistent.

Meta data block

The block of "meta" data consists of the following (values expressed in bytes):

Total size is 42 bytes including the 8 bytes CRC.

Data blocks

When the stream is uncompressed UDP blocks of the payload size are stuffed with complete I/Q samples leaving a possible unused gap of less than an I/Q sample at the end of the block. The last block is filled only with the remainder samples. The number of maximally filled blocks and remainder samples in the last block is given in the "meta" data. Of course as the data stream is uncompressed these values can also be calculated from the total number of samples and the payload size.

When the stream is compressed UDP blocks are stuffed completely with bytes of the compressed stream. The last block being filled only with the remainder bytes. The number of full blocks and remainder bytes is given in the "meta" block and these values cannot be calculated otherwise.

Summary diagram

Uncompressed stream

hardware block (2 byte I or Q samples):
|I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q:I/Q|

UDP block (22 bytes):
|xxxxxxxxxxxxxxxxxxxxxx|

Frame:
|Meta:xxxxxxxxxxxxxxxxx|I/Q:I/Q:I/Q:I/Q:I/Q:xx|I/Q:I/Q:I/Q:I/Q:I/Q:xx|I/Q:I/Q:I/Q:xxxxxxxxxx|

Number of samples in a hardware block: 13
Number of blocks in a frame..........:  1 (always if uncompressed)
Number of bytes in a frame...........: 52 (4 * 13)
Complete blocks......................:  2 (calculated)
Remainder samples....................:  3 (calculated)

Edit: : I ending up abandoning this approach (in favour of SoapySDR) soon after posting so can't really comment relevantly anymore.


问:
Rest Assured - java.lang.NoSuchFieldError: DEF_CONTENT_CHARSET
Tests used to pass until last week and now it started failing. The error is displayed below.

rest-assured=2.9.0
httpclient-4.5.1.jar
httpcore-4.4.3.jar

I excluded the other httpclient and core jars from ivy these two above versions come from rest assured. Please I really need help with this.

```<code>import static com.jayway.restassured.RestAssured.given
@Test
public void getSummary(){
given().
contentType("application/json").
when().
get("http://example.org/ab/resources/client/case/123455").
then().
statusCode(200).
extract().path("id");
;

//statusCode(200);
</code>```

}

```<code>java.lang.NoSuchFieldError: DEF_CONTENT_CHARSET
at com.jayway.restassured.config.EncoderConfig.(EncoderConfig.java:61)
at com.jayway.restassured.config.RestAssuredConfig.(RestAssuredConfig.java:41)
at com.jayway.restassured.RestAssured.(RestAssured.java:423)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:278)
at org.codehaus.groovy.runtime.callsite.CallSiteArray$1.run(CallSiteArray.java:68)
at org.codehaus.groovy.runtime.callsite.CallSiteArray$1.run(CallSiteArray.java:65)
at java.security.AccessController.doPrivileged(Native Method)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:65)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:194)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:198)
at com.thomson.tssq.jwb.restapitests.RestAPITest.getSummary(RestAPITest.groovy:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
</code>```

答:
See if you have below listed jars in classpath or in maven pom.xml</p>

```<code>[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ rest-assured ---
[INFO] io.rest-assured:rest-assured:jar:3.0.2-SNAPSHOT
[INFO] +- org.codehaus.groovy:groovy:jar:2.4.6:compile
[INFO] +- org.codehaus.groovy:groovy-xml:jar:2.4.6:compile
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
[INFO] |  +- org.apache.httpcomponents:httpcore:jar:4.4.4:compile
[INFO] |  +- commons-logging:commons-logging:jar:1.2:compile
[INFO] |  \- commons-codec:commons-codec:jar:1.9:compile
[INFO] +- org.apache.httpcomponents:httpmime:jar:4.5.1:compile
[INFO] +- com.github.scribejava:scribejava-apis:jar:2.5.3:compile
[INFO] |  \- com.github.scribejava:scribejava-core:jar:2.5.3:compile
[INFO] +- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] +- org.hamcrest:hamcrest-library:jar:1.3:compile
[INFO] +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:compile
[INFO] +- io.rest-assured:json-path:jar:3.0.2-SNAPSHOT:compile
[INFO] |  +- org.codehaus.groovy:groovy-json:jar:2.4.6:compile
[INFO] |  \- io.rest-assured:rest-assured-common:jar:3.0.2-SNAPSHOT:compile
[INFO] +- io.rest-assured:xml-path:jar:3.0.2-SNAPSHOT:compile
[INFO] |  \- org.apache.commons:commons-lang3:jar:3.4:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.3:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.7.3:compile
[INFO] +- org.codehaus.jackson:jackson-core-asl:jar:1.9.11:compile
[INFO] +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.11:compile
[INFO] +- com.google.code.gson:gson:jar:2.6.2:compile
[INFO] +- com.googlecode.json-simple:json-simple:jar:1.1.1:compile
[INFO] +- junit:junit:jar:4.12:test
[INFO] \- org.assertj:assertj-core:jar:1.7.0:test
</code>```

Body:
Tests used to pass until last week and now it started failing. The error is displayed below.

rest-assured=2.9.0
httpclient-4.5.1.jar
httpcore-4.4.3.jar

I excluded the other httpclient and core jars from ivy these two above versions come from rest assured. Please I really need help with this.

import static com.jayway.restassured.RestAssured.given
@Test
public void getSummary(){
given().
contentType("application/json").
when().
get("http://example.org/ab/resources/client/case/123455").
then().
statusCode(200).
extract().path("id");
;

//statusCode(200);

}

java.lang.NoSuchFieldError: DEF_CONTENT_CHARSET
at com.jayway.restassured.config.EncoderConfig.(EncoderConfig.java:61)
at com.jayway.restassured.config.RestAssuredConfig.(RestAssuredConfig.java:41)
at com.jayway.restassured.RestAssured.(RestAssured.java:423)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:278)
at org.codehaus.groovy.runtime.callsite.CallSiteArray$1.run(CallSiteArray.java:68)
at org.codehaus.groovy.runtime.callsite.CallSiteArray$1.run(CallSiteArray.java:65)
at java.security.AccessController.doPrivileged(Native Method)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:65)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:194)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:198)
at com.thomson.tssq.jwb.restapitests.RestAPITest.getSummary(RestAPITest.groovy:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Body:
See if you have below listed jars in classpath or in maven pom.xml

[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ rest-assured ---
[INFO] io.rest-assured:rest-assured:jar:3.0.2-SNAPSHOT
[INFO] +- org.codehaus.groovy:groovy:jar:2.4.6:compile
[INFO] +- org.codehaus.groovy:groovy-xml:jar:2.4.6:compile
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
[INFO] |  +- org.apache.httpcomponents:httpcore:jar:4.4.4:compile
[INFO] |  +- commons-logging:commons-logging:jar:1.2:compile
[INFO] |  \- commons-codec:commons-codec:jar:1.9:compile
[INFO] +- org.apache.httpcomponents:httpmime:jar:4.5.1:compile
[INFO] +- com.github.scribejava:scribejava-apis:jar:2.5.3:compile
[INFO] |  \- com.github.scribejava:scribejava-core:jar:2.5.3:compile
[INFO] +- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] +- org.hamcrest:hamcrest-library:jar:1.3:compile
[INFO] +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:compile
[INFO] +- io.rest-assured:json-path:jar:3.0.2-SNAPSHOT:compile
[INFO] |  +- org.codehaus.groovy:groovy-json:jar:2.4.6:compile
[INFO] |  \- io.rest-assured:rest-assured-common:jar:3.0.2-SNAPSHOT:compile
[INFO] +- io.rest-assured:xml-path:jar:3.0.2-SNAPSHOT:compile
[INFO] |  \- org.apache.commons:commons-lang3:jar:3.4:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.3:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.7.3:compile
[INFO] +- org.codehaus.jackson:jackson-core-asl:jar:1.9.11:compile
[INFO] +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.11:compile
[INFO] +- com.google.code.gson:gson:jar:2.6.2:compile
[INFO] +- com.googlecode.json-simple:json-simple:jar:1.1.1:compile
[INFO] +- junit:junit:jar:4.12:test
[INFO] \- org.assertj:assertj-core:jar:1.7.0:test


问:
How to create a web page with the link like page.example.com
I am creating a website in 000webhost. If I purchase a domain ( for example www.example.com ), the index.html page opens when the user types the address in the URL bar. I want a specific page (for example page.html) to open when the user types page.example.com . How do I do that?</p>

答:
You can use redirects with a .htaccess file

htacces redirect


问:
MySQL showing that select * from has internal limit 0,1000 . how to stop it
i am accesing my Mysql database server using Mysql workbench.and i have encountered a prolem.
there is a table, named tags, in my database.which will have have more than thousands of tags in future.the problem is when i am executing select * from tags; query Mysql workbench is executing this (or taking action) like select * from tags LIMIT 0, 1000. i am giving you a snapshot

my question is how can i stop it.because when i will launch my application it will have thousands(much more than 1000) of tags.if it implies LIMIT 0, 1000 internally then my php script wont have all the tags at the time of executing my tagging system.

all i want is to have no limits on select *.how can i do that?what will be the modified Select * query not to have any limits

答: Go to -> MySQL Workbench -> Edit Menu -> preferences -> SQL Editor -> Query Results -> Uncheck Limit Rows.</p>


问:
Frequency of events in a week
My data has trips with datetime info, user id for each trip and trip type (single, round, pseudo).

Here's a data sample (pandas dataframe), named All_Data:

```<code>HoraDTRetirada        idpass        type
2016-02-17 15:36:00  39579449489   'single'
2016-02-18 19:13:00  39579449489   'single'
2016-02-26 09:20:00  72986744521   'pseudo'
2016-02-27 12:11:00  72986744521   'round'
2016-02-27 14:55:00  11533148958   'pseudo'
2016-02-28 12:27:00  72986744521   'round'
2016-02-28 16:32:00  72986744521   'round'
</code>```

I would like to count the number of times each category repeats in a "week of year" by user.

For example, if the event happens on a monday and the next event happens on a thursday for a same user, that makes two events on the same week; however, if one event happens on a saturday and the next event happens on the following monday, they happened in different weeks.

The output I am looking for would be in a form like this:

```<code>idpass        weekofyear   type      frequency
39579449489    1           'single'   2
72986744521    2           'round'    3
72986744521    2           'pseudo'   1
11533148958    2           'pseudo'   1
</code>```

Edit: this older question approaches a similar problem, but I don't know how to do it with pandas.

答:
My suggestion would be to do this:

make sure your timestamp is pandas datetime and add frequency column

df['HoraDTRetirada'] = pd.to_datetime(df['HoraDTRetirada'])

df['freq'] = 1

Group it and count

res = df.groupby(['idpass', 'type', pd.Grouper(key='HoraDTRetirada', freq='1W')]).count().reset_index()

Convert time to week of a year

res['HoraDTRetirada'] = res['HoraDTRetirada'].apply(lambda x: x.week)

Final result looks like that:

EDIT:

You are right, in your case we should do step 3 before step 2, and if you want to do that, remember that groupby will change, so finally step 2 will be:

```<code>res['HoraDTRetirada'] = res['HoraDTRetirada'].apply(lambda x: x.week)
</code>```

and step 3 :

```<code>res = df.groupby(['idpass', 'type', 'HoraDTRetirada')]).count().reset_index()
</code>```

It's a bit different because the "Hora" variable is not a time anymore, but just an int representing a week.

Title: Frequency of events in a week

Body:
My data has trips with datetime info, user id for each trip and trip type (single, round, pseudo).

Here's a data sample (pandas dataframe), named All_Data:

HoraDTRetirada        idpass        type
2016-02-17 15:36:00  39579449489   'single'
2016-02-18 19:13:00  39579449489   'single'
2016-02-26 09:20:00  72986744521   'pseudo'
2016-02-27 12:11:00  72986744521   'round'
2016-02-27 14:55:00  11533148958   'pseudo'
2016-02-28 12:27:00  72986744521   'round'
2016-02-28 16:32:00  72986744521   'round'

I would like to count the number of times each category repeats in a "week of year" by user.

For example, if the event happens on a monday and the next event happens on a thursday for a same user, that makes two events on the same week; however, if one event happens on a saturday and the next event happens on the following monday, they happened in different weeks.

The output I am looking for would be in a form like this:

idpass        weekofyear   type      frequency
39579449489    1           'single'   2
72986744521    2           'round'    3
72986744521    2           'pseudo'   1
11533148958    2           'pseudo'   1

Edit: this older question approaches a similar problem, but I don't know how to do it with pandas.

Body:
My suggestion would be to do this:

make sure your timestamp is pandas datetime and add frequency column

df['HoraDTRetirada'] = pd.to_datetime(df['HoraDTRetirada'])

df['freq'] = 1

Group it and count

res = df.groupby(['idpass', 'type', pd.Grouper(key='HoraDTRetirada', freq='1W')]).count().reset_index()

Convert time to week of a year

res['HoraDTRetirada'] = res['HoraDTRetirada'].apply(lambda x: x.week)

Final result looks like that:

EDIT:

You are right, in your case we should do step 3 before step 2, and if you want to do that, remember that groupby will change, so finally step 2 will be:

res['HoraDTRetirada'] = res['HoraDTRetirada'].apply(lambda x: x.week)

and step 3 :

res = df.groupby(['idpass', 'type', 'HoraDTRetirada')]).count().reset_index()

It's a bit different because the "Hora" variable is not a time anymore, but just an int representing a week.


问:
communicating between two controller in angularjs using factory
I have created a plunker that communicates between two different controller in nested views using factory. Below is the url of plunker.
https://plnkr.co/edit/fWA2Xugjbkf3QvHKfTa0?p=preview .
Here is the factory.

```<code>routerApp.factory("widgetService",function($state){
    var callbackFunctions=[];
    var counter=0;

    var addWidget=function(name){
        callbackFunctions[0](name);
    }

    var addCallback=function(callback){
        if (callbackFunctions.length===0) {
            callbackFunctions.push(callback);
        }
    }
    return{
        addCallback: addCallback,
        addWidget: addWidget
    }
})
</code>```

Scenario 1:
1. Click on "List" menu under the home page.
2. Click on "verify" button. notice the change in highlighted area with yellow. Text changes from "Chandan" to "singh1".
3. Click again on verify button.  Text changes from "singh1" to "singh2". So i am able to communicate between two controller in this.

Scenario 2:
1. Repeat the scenario 1 till step 2.
2. Click on "PARAGRAPH" menu under home page.
3. Click on "List" menu under home page. Click verify button. The text wont change. It will remain "chandan".
 Communication is not working as we change the state.

Also i have observed  that the model is changing but same is not getting reflected in view. Moreover if we bind the view to rootscope, view is getting updated.
Please clarify.

答:
When you switch between list and paragraph states, your list controller is destroyed (and recreated next time you go to list). So when it is recreated it gets a new scope.

The callbackFunction that is registered in your service, refers to the changeMyName() function on the old controller scope, so whenever you call addWidget() in your service, you're actually calling the callback in your old scope.

To make this work as expected (at least in your sample code here), you would have to change your service to allow changing the old callback in the addCallback()-function. Something like this:

```<code>var addCallback=function(callback){
    callbackFunctions[0] = callback;
}
</code>```

Body:
I have created a plunker that communicates between two different controller in nested views using factory. Below is the url of plunker.
https://plnkr.co/edit/fWA2Xugjbkf3QvHKfTa0?p=preview .
Here is the factory.

routerApp.factory("widgetService",function($state){
    var callbackFunctions=[];
    var counter=0;

    var addWidget=function(name){
        callbackFunctions[0](name);
    }

    var addCallback=function(callback){
        if (callbackFunctions.length===0) {
            callbackFunctions.push(callback);
        }
    }
    return{
        addCallback: addCallback,
        addWidget: addWidget
    }
})

Scenario 1:
1. Click on "List" menu under the home page.
2. Click on "verify" button. notice the change in highlighted area with yellow. Text changes from "Chandan" to "singh1".
3. Click again on verify button.  Text changes from "singh1" to "singh2". So i am able to communicate between two controller in this.

Scenario 2:
1. Repeat the scenario 1 till step 2.
2. Click on "PARAGRAPH" menu under home page.
3. Click on "List" menu under home page. Click verify button. The text wont change. It will remain "chandan".
 Communication is not working as we change the state.

Also i have observed  that the model is changing but same is not getting reflected in view. Moreover if we bind the view to rootscope, view is getting updated.
Please clarify.

Body:
When you switch between list and paragraph states, your list controller is destroyed (and recreated next time you go to list). So when it is recreated it gets a new scope.

The callbackFunction that is registered in your service, refers to the changeMyName() function on the old controller scope, so whenever you call addWidget() in your service, you're actually calling the callback in your old scope.

To make this work as expected (at least in your sample code here), you would have to change your service to allow changing the old callback in the addCallback()-function. Something like this:

var addCallback=function(callback){
    callbackFunctions[0] = callback;
}


问:
How to make a variable globally accessible in Prestashop
I'm modifying a module in Prestashop, which has folder structure like this..

```<code>css
translations
index.php
module.php
module.tpl
</code>```

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

答:
Defining a constant could do the job or maybe using sessions. All is accessible by smarty in templates afterwards.

Ex in your module :

```<code>      define('MYGLOBALVAR', 'data');
</code>```

In your template :

```<code>      $smarty.const.MYGLOBALVAR
</code>```

Body:
I'm modifying a module in Prestashop, which has folder structure like this..

css
translations
index.php
module.php
module.tpl

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

Body:
Defining a constant could do the job or maybe using sessions. All is accessible by smarty in templates afterwards.

Ex in your module :

      define('MYGLOBALVAR', 'data');

In your template :

      $smarty.const.MYGLOBALVAR


问:
How to run python script?
Say Suppose, the name of my python script file is hello.
How the script can be executed ?
Sometimes, I see that most of the python scripts are executed by (python hello.py) and sometimes (./hello.py). Which one of these executing is true? If both are same, why it is mentioned as different commands?</p>

答:
The syntax ./hello.py is typically used on Unix-like systems (including Linux and OSX); it requires two things:

that hello.py has proper rights (execute bit set)

that the first line of hello.py is #!/usr/bin/python (or similar, depending on location of your Python interpreter)

The other form - python hello.py - does not have such requirements.

Title: How to run python script?


问:
Hide div while scrolling down
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

```<code>//This is the image I just want to show at first
<img src="images/logo-wh.png" alt="" class="logo-white">

//This is the image I just want to show when scroll down
<img src="images/logo.png" alt="" class="logo-default">

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });
</code>```

But it isn't working as I expected. Any suggestions?

答:
Here's working example,
just used both elements with hide show differences you needed.

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
        $('.logo-default').show();
    } else {
        $('.logo-default').hide();
        $('.logo-white').show();
    }
 });
$(window).trigger('scroll');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo-white, .logo-default {
  width: 100px;
  height: 100px;
  background: #000;
  position: relative;
}

.logo-default { background: #d20000; }

body { height: 500px; overflow: scroll; }</code>```

```

Title: Hide div while scrolling down

Body:
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

//This is the image I just want to show at first

//This is the image I just want to show when scroll down

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });

But it isn't working as I expected. Any suggestions?

Body:
Here's working example,
just used both elements with hide show differences you needed.

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
        $('.logo-default').show();
    } else {
        $('.logo-default').hide();
        $('.logo-white').show();
    }
 });
$(window).trigger('scroll');

.logo-white, .logo-default {
  width: 100px;
  height: 100px;
  background: #000;
  position: relative;
}

.logo-default { background: #d20000; }

body { height: 500px; overflow: scroll; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logo-white"></div>

<div class="logo-default"></div>


问:
R: runif produces NAN
I want to generate some data which correspond to a quantile function. But the data need a min and a max value.

```<code>set.seed(30)
a1<-950 ; a2<-0; a3<-2.48; a4<-1.92
invcdf<-function (x)(a1+a2*a3*((-log(x))^(1/a4)))/(a3*((-log(x))^(1/a4))+1)
t<-invcdf(runif(2000,min=80,max=800))
</code>```

When I use min and max in the runif function NaN's are produced.
How can I improve this code to avoid NaN's? I can't change the parameters.

答:
Since you don't explain what exactly you are trying to do (which distribution are you trying to sample?), all I can do is interpret this as an attempt to generate random variable according to some distribution using its inverse CDF function. Because I don't know which it is, I can't comment on whether your implementation of it is correct.

However, when you use this method, you should know that the CDF function takes values between 0 and 1, as it is a cumulative density, starting at 0, and going to 1 in some limit.

The inverse of that function then only makes sense if you feed it values between 0 and 1, and that is where a possible error lies. runif(2000,min=80,max=800) generates random values between 80 and 800, way outside the (0,1) interval.

If you instead do this:

t <- invcdf(runif(2000))

We do get results (which happen to lie between 80 and 800 mostly):

Title: R: runif produces NAN

Body:
I want to generate some data which correspond to a quantile function. But the data need a min and a max value.

set.seed(30)
a1<-950 ; a2<-0; a3<-2.48; a4<-1.92
invcdf<-function (x)(a1+a2*a3*((-log(x))^(1/a4)))/(a3*((-log(x))^(1/a4))+1)
t<-invcdf(runif(2000,min=80,max=800))

When I use min and max in the runif function NaN's are produced.
How can I improve this code to avoid NaN's? I can't change the parameters.


问:
Setting opacity / alpha on rgba in css variable
I am trying out CSS variables and I would like to use RGB colours.

Here's my current CSS Variable:

```<code>--primary: rgb(112, 199, 255);
</code>```

So this works absolutely fine when using the following code:

```<code>color: var(--primary)
</code>```

But some paragraphs also use this primary colour and I would like to give them a slight transparency. Now I could replace that and create another CSS Variable like so:

```<code>--primary: rgb(112, 199, 255);
--primary-alpha: rgba(112, 199, 255, 0.7);
</code>```

But that just feels messy and confusing having two primary colours and what If I use a few different transparencies. I could also use the following CSS Variable:

```<code>--primary: 112, 199, 255;
--alpha: 0.7;
</code>```

and output it using the following code:

```<code>color: rgba(var(--white), var(--alpha));
</code>```

This works as I want and I personally think is a nicer way of doing it but my colours don't preview in my code editor see image.

Look at the --dark variable, it won't show the colour using this code.

Ideally, I would like to use:

```<code>--primary: rgb(112, 199, 255);
</code>```

and output it like so:

```<code>color: var(--white), var(--alpha);
</code>```

But it won't work?

答:
Assuming you're using atom-pigment. The color detection works within comments as well. So you could perhaps add the actual rgb value in the comments only for reference & use the variable as usual. Like so:</p>

```<code>--dark: 18, 38, 51 /* this color is - rgb(18, 38, 51) */
</code>```

Body:
I am trying out CSS variables and I would like to use RGB colours.

Here's my current CSS Variable:

--primary: rgb(112, 199, 255);

So this works absolutely fine when using the following code:

color: var(--primary)

But some paragraphs also use this primary colour and I would like to give them a slight transparency. Now I could replace that and create another CSS Variable like so:

--primary: rgb(112, 199, 255);
--primary-alpha: rgba(112, 199, 255, 0.7);

But that just feels messy and confusing having two primary colours and what If I use a few different transparencies. I could also use the following CSS Variable:

--primary: 112, 199, 255;
--alpha: 0.7;

and output it using the following code:

color: rgba(var(--white), var(--alpha));

This works as I want and I personally think is a nicer way of doing it but my colours don't preview in my code editor see image.

Look at the --dark variable, it won't show the colour using this code.

Ideally, I would like to use:

--primary: rgb(112, 199, 255);

and output it like so:

color: var(--white), var(--alpha);

But it won't work?

Body:
Assuming you're using atom-pigment. The color detection works within comments as well. So you could perhaps add the actual rgb value in the comments only for reference & use the variable as usual. Like so:

--dark: 18, 38, 51 /* this color is - rgb(18, 38, 51) */


问:
How Run A Stored Procedure (with Parameters - Has A return Value) From Code Behind?
How can I use a stored procedure (with parameters - has a return value of type int) from code behind?

My stored procedure looks like this :

```<code>ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
AS
-----------------
Declare @Sum bigint
-----------------
BEGIN
    SELECT
       @Sum = SUM(TotalPay)
    FROM Noskheh
    WHERE
       (Co_ID = @Co_ID)

    RETURN @Sum
END
</code>```

I want to use @Sum in code behind ...

Would you please show me a way for doing that ?

Thanks in advance

best regards

答:
You can add an SqlParameter @Sum with Direction set to ReturnValue

Example:

```<code>SqlCommand cmd = new SqlCommand():

cmd.Connection = // place your SqlConnection object;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoreProcedureName";

cmd.Parameters.Add("@Sum", SqlDbType.BigInt).Direction = ParameterDirection.ReturnValue
</code>```

Body:
How can I use a stored procedure (with parameters - has a return value of type int) from code behind?

My stored procedure looks like this :

ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
AS
-----------------
Declare @Sum bigint
-----------------
BEGIN
    SELECT
       @Sum = SUM(TotalPay)
    FROM Noskheh
    WHERE
       (Co_ID = @Co_ID)

    RETURN @Sum
END

I want to use @Sum in code behind ...

Would you please show me a way for doing that ?

Thanks in advance

best regards

Body:
You can add an SqlParameter @Sum with Direction set to ReturnValue

Example:

SqlCommand cmd = new SqlCommand():

cmd.Connection = // place your SqlConnection object;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoreProcedureName";

cmd.Parameters.Add("@Sum", SqlDbType.BigInt).Direction = ParameterDirection.ReturnValue

ContentLicense: CC BY-SA 2.5


问:
Vue.js - Don't bind an object when 'copying it' to another data attribute
I have an object coming from my API and when loading a modal I need to 'duplicate' the object to another.

This works:

```<code>this.servicesForm.services = this.team.services;

// New object                // API object
</code>```

The issue now is that I DON'T want the team.services object to be bound to and update when I update the servicesForm.services object.

How do I do that?

答:
An ES6 solution would be to use Object.assign:

```<code>this.servicesForm.services = Object.assign({}, this.team.services);
</code>```

Note that this is only a shallow copy, if you need a deep copy you would need to apply this method recursively.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Body:
I have an object coming from my API and when loading a modal I need to 'duplicate' the object to another.

This works:

this.servicesForm.services = this.team.services;

// New object                // API object

The issue now is that I DON'T want the team.services object to be bound to and update when I update the servicesForm.services object.

How do I do that?

Body:
An ES6 solution would be to use Object.assign:

this.servicesForm.services = Object.assign({}, this.team.services);

Note that this is only a shallow copy, if you need a deep copy you would need to apply this method recursively.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


问:
How to enter multiple user defined values on data Refresh in Business Objects
I am trying to run a Business Objects report in 5.1.9.

When I refresh the report it asks me in a box labelled "Enter and Select Values"

I can either enter a single free text value in the text box or I can type % to leave it unfiltered.

I would like to specify several values in this box rather than one or all. How do I do this? I have looked everywhere on google but perhaps I have the wrong search terms?

答:
Wow - 5.1.9 almost 15 years old.

The box you're seeing is a prompt.  Prompts can be defined either in the report's query, or in a universe object that's used in the query.

If it's defined in the query, then it's easy to change.  Open up the query panel via Data -> Edit Data Provider (assuming you're using Full Client, WebI is a little different).  You'll see the query panel with result object in the top-right pane and conditions in the lower-right pane.  Look for a condition that includes the text you see in the prompt.  That condition will likely have an "Equal To" operator.  Change that to "In List", and the prompt should then accept multiple values.

If the prompt is not present in the conditions pane, then it is most likely applied via a universe object.  If you want to make this change for this report only, you could modify the query's SQL (but only if you're using Full Client; for WebI, you'd need to modify the universe as described below).  Hit the SQL button, and you will see the generated SQL.  First, check off the "Do not generate SQL" checkbox in the lower-left of the dialog.  Not doing so will cause your changes to be lost.  Look through the SQL for a @prompt() function.  Within that function, you should see mono -- change that to multi, and close the panel.

If you don't want to change the query's SQL, or if you want the change to apply to all reports, then you will need to modify the universe object that produces the prompt.  You will need to access to Designer, and permission to import/export the universe.  You will also need to locate the object that produces the prompt.  Once you do, change mono to multi as described above, and export the universe.


问:
AssertionError: Element odoo has extra content: report, line 7
When i try to give report_name in report tag it throws below error:
AssertionError: Element odoo has extra content: report, line 7

*.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>

   <report id="action_report_followup"
   model="account_followup.followup"
   report_name="PPPPPPPPPPpppp" //Here is the problem
   string="Follow-up Report"
   report_type="qweb-pdf"
   name="payment_followup.report_followup"
   file="payment_followup.report_followup"
   menu="True"/>

</odoo>
</code>```

If i remove attribute report_name it will work fine, and use value of string as report name. I need to give other name. How can i resolve this issue?

答:
You can try this once.</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <report
            string="Follow-up Report"
            id="action_report_followup"
            model="account_followup.followup"
            report_type="qweb-pdf"
            name="payment_followup.report_followup"
            file="payment_followup.report_followup"
            menu="True"/>
    </data>
</odoo>
</code>```

Body:
When i try to give report_name in report tag it throws below error:
AssertionError: Element odoo has extra content: report, line 7

*.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>

   <report id="action_report_followup"
   model="account_followup.followup"
   report_name="PPPPPPPPPPpppp" //Here is the problem
   string="Follow-up Report"
   report_type="qweb-pdf"
   name="payment_followup.report_followup"
   file="payment_followup.report_followup"
   menu="True"/>

</odoo>

If i remove attribute report_name it will work fine, and use value of string as report name. I need to give other name. How can i resolve this issue?

Body:
You can try this once.

<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <report
            string="Follow-up Report"
            id="action_report_followup"
            model="account_followup.followup"
            report_type="qweb-pdf"
            name="payment_followup.report_followup"
            file="payment_followup.report_followup"
            menu="True"/>
    </data>
</odoo>


问:
Why variable value is not showing in insert query
I have this code snippet

```<code>$taskAssignedCompleteId = $row["TaskAssignCompletionId"];
echo "taskAssignedCompleteId::".$taskAssignedCompleteId. "\n";

if($taskAssignedCompleteId == 0 || $taskAssignedCompleteId = null)
{
    echo "Currently no task assigned to you. If you are not doing a task on PMS and still receving this massage then, contact your team lead";
    return;
}

$sqlInsert = "INSERT INTO emp_task_finished_request (EmpTaskAssignCompletionId, RequestDateTime) VALUES (".$taskAssignedCompleteId.", '$date')";
echo "output : ".$sqlInsert;
$queryInsert = $connPDO->exec($sqlInsert);

    echo "\n output : ".$queryInsert;
</code>```

Surprisingly $taskAssignedCompleteId value is not showing in query when i echo my $queryInsert varaiable while it is perfectly showing when i directly echo $taskAssignedCompleteId. Why is the problem? it is very strange for me.
here is my output

```<code>taskAssignedCompleteId::13
sqlInsert full : INSERT INTO emp_task_finished_request (EmpTaskAssignCompletionId, RequestDateTime) VALUES (, '2017-07-05 16:53:45')
 output :
</code>```

答:
you should use == for comparison operator . = is assignment operator .so it's assigning null to $taskAssignedCompleteId variable .

```<code>if($taskAssignedCompleteId == 0 || $taskAssignedCompleteId == null) { .. }
</code>```

Body:
I have this code snippet

$taskAssignedCompleteId = $row["TaskAssignCompletionId"];
echo "taskAssignedCompleteId::".$taskAssignedCompleteId. "\n";

if($taskAssignedCompleteId == 0 || $taskAssignedCompleteId = null)
{
    echo "Currently no task assigned to you. If you are not doing a task on PMS and still receving this massage then, contact your team lead";
    return;
}

$sqlInsert = "INSERT INTO emp_task_finished_request (EmpTaskAssignCompletionId, RequestDateTime) VALUES (".$taskAssignedCompleteId.", '$date')";
echo "output : ".$sqlInsert;
$queryInsert = $connPDO->exec($sqlInsert);

    echo "\n output : ".$queryInsert;

Surprisingly $taskAssignedCompleteId value is not showing in query when i echo my $queryInsert varaiable while it is perfectly showing when i directly echo $taskAssignedCompleteId. Why is the problem? it is very strange for me.
here is my output

taskAssignedCompleteId::13
sqlInsert full : INSERT INTO emp_task_finished_request (EmpTaskAssignCompletionId, RequestDateTime) VALUES (, '2017-07-05 16:53:45')
 output :

Body:
you should use == for comparison operator . = is assignment operator .so it's assigning null to $taskAssignedCompleteId variable .

if($taskAssignedCompleteId == 0 || $taskAssignedCompleteId == null) { .. }


问:
PHPStan - change type of constructor parameter
When running PHPStan on my codebase I get the error:

```<code>Parameter #2 $credentials of class Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken constructor expects string, null given.
</code>```

This is because the constructor's docblock only specifies a string as valid type. But when you check the eraseCredentials() method, it seems that null also is a valid value for $credentials.

Now I want to instruct PHPStan that the type of the $credentials parameter is string|null as opposed to string.

I think I would need an implementation of MethodsClassReflectionExtension to do that. But when I register this it does not seem to get called for the right class.

My current implementation:

```<code>class UsernamePasswordToken implements MethodsClassReflectionExtension
{
    public function hasMethod(ClassReflection $classReflection, string $methodName): bool
    {
        if ($classReflection->getName()===\Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::class) {
            var_dump(__FILE__ . ':' . __LINE__ . ' :: ' . __METHOD__);die();
        }
        if ($methodName === '__construct' && $classReflection->getName() === UsernamePasswordTokenClass::class) {
            return true;
        }

        return false;
    }

    public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection
    {
        var_dump(__FILE__ . ':' . __LINE__ . ' :: ' . __METHOD__);die();
    }
}
</code>```

What do I need to do to make PHPStan understand that the $credentials property accepts both string and null values?

答:
Unfortunately you cannot use extensions to override information about existing method. There's currently no way to convince PHPStan that a method has a different signature than the one in the code.

I'm a little bit confused by the reported error, because UsernamePasswordToken currently accepts mixed (meaning anything) as the type of $credentials. So your issue can go away just by upgrading Symfony (not sure to which version). And also I don't know what you mean by referencing the eraseCredentials method.

If you need to solve a similar issue and the parameter documentation is wrong even in the recent version of your dependency, you have currently two options:

1) Send a PR to the depedency that fixes their typehint or phpDoc.
2) Write a regexp for ignoreErrors (see README) that ignores this issue.

In the future, there will be a third option. I'm planning to enable overriding 3rd party types by offering configuration options to do that.

Body:
When running PHPStan on my codebase I get the error:

Parameter #2 $credentials of class Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken constructor expects string, null given.

This is because the constructor's docblock only specifies a string as valid type. But when you check the eraseCredentials() method, it seems that null also is a valid value for $credentials.

Now I want to instruct PHPStan that the type of the $credentials parameter is string|null as opposed to string.

I think I would need an implementation of MethodsClassReflectionExtension to do that. But when I register this it does not seem to get called for the right class.

My current implementation:

class UsernamePasswordToken implements MethodsClassReflectionExtension
{
    public function hasMethod(ClassReflection $classReflection, string $methodName): bool
    {
        if ($classReflection->getName()===\Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::class) {
            var_dump(__FILE__ . ':' . __LINE__ . ' :: ' . __METHOD__);die();
        }
        if ($methodName === '__construct' && $classReflection->getName() === UsernamePasswordTokenClass::class) {
            return true;
        }

        return false;
    }

    public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection
    {
        var_dump(__FILE__ . ':' . __LINE__ . ' :: ' . __METHOD__);die();
    }
}

What do I need to do to make PHPStan understand that the $credentials property accepts both string and null values?


问:
Accessing Object attributes
```<code><html>
  <head>
    <script>
      function User(name,age){
        this.name=name;
        this.age=age;
      }
      var user = new User('Daniel', 45 );
      document.write(user[name]+' '+'is'+' '); //line 1
      document.write(user[age]+' '+'years old!'); // line 2
    </script>
  </head>
  <body>

  </body>
</html>
</code>```

In above code,
              When i tried accessing properties of object user
              For name, i got 'undefined' as output
              For age, i got Error saying that age is Not defined
         Not able to understand why I'm getting Error for line 2
         and 'undefined' value for line 1. Both should give same Error Right?
    Please clarify my doubt here.

答:
There is a property of the window object named name.

What it is or for I have no idea.
[EDIT] the name of the window is used primarily for setting targets for hyperlinks and forms.

So since it it defined you don't get the Not defined error as you get in line 2.

user[name] is equivalent to user[window.name], which is user[''], since the window name wasn't set.

Title: Accessing Object attributes


答:
Change $taskAssignedCompleteId = null to $taskAssignedCompleteId == null

By doing this, you are assigning taskAssignedCompleteId to a null value. To compare use "==" but you already know that. Just a typo I guess.

Darn, somebody beat me to the answer as I'm typing this.

Title: Why variable value is not showing in insert query


问:
Save as .CSV and .txt
I am sure this is straightforward but is baffling me beyond belief. I have written the below code. You can see in to places that I am saving My pay final and Non-mypay Final as CSV files. Is there a way I can get the files to save as txt files as well. Ideally with the same location if possible? As always, your help is greatly appreciated.</p>

```<code> Option Explicit

 Sub BACSConversion()

 Dim MyNewBook As String
 Dim MySaveFile As String
 Dim fileToOpen As Variant
 Dim fileName As String
 Dim sheetName As String
 Dim rCopy As Range

 'Turn off display alerts
 Application.DisplayAlerts = False
 'Turn off screen updates
 Application.ScreenUpdating = False

 'Ensures that the file open directory is always the same
  ChDir "S:\MERIT OUTPUTS FOLDER\MSI Recruitment Limited\"

 'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If
 'Creates the file name based on txt file name
  fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Save active file as...
  ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\BACS File Original\" & _
  fileName & ".CSV")

 'Selects all data in column A and copies to clipboard
  Set rCopy = Range("A1", Range("A1").End(xlDown))

 'Open the original document where the BACS file is located
   Workbooks.Open "S:\Accounts (New)\Management Information
 (Analysis)\Phil Hanmore - Analysis\bacs conversation calc.xlsx"
 'Selects the worksheet called "Original"
  Sheets("Original").Range("A:A").ClearContents

 'Paste selected values from previous sheet
  rCopy.Copy
  Sheets("Original").Range("A1").PasteSpecial Paste:=xlPasteValues

 'Selects appropriate worksheet - Non-MyPayFINAL
   Sheets("Non-MyPay FINAL").Select

  'Selects all data in column A and copies to clipboard
   Range("A1", Range("A1").End(xlDown)).Select
  Selection.Copy

  'Add a new workbook
   Workbooks.Add
 'Paste selected values from previous sheet
  Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
  MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
 'Save template file as...
  ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & MySaveFile)
 'Close the new saved file
   ActiveWorkbook.Close

 'Selects appropriate worksheet - MyPayFINAL
   Sheets("MyPay FINAL").Select

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
 Selection.Copy

 'Add a new workbook
  Workbooks.Add
 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
  MySaveFile = Format(Now(), "DDMMYYYY") & "MyPayFINAL" & ".CSV"
 'Save template file as...
  ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & MySaveFile)
  'Close the new saved file
   ActiveWorkbook.Close
 'Close original source workbook (template)
  Workbooks("bacs conversation calc").Close

 'Turn on display alerts
Application.DisplayAlerts = True
 'Turn on screen updates
Application.ScreenUpdating = True

 End Sub
</code>```

答:
After you save it as a .csv file, just re-do the same code but instead of .csv change it to .txt

But that won't necessarily change the type of file.  After your Activeworkbook.SaveAs command, add FileFormat:= xlTextWindows. This will actually save it as a textfile.

It should look like:

ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & MySaveFile), FileFormat:= xlTextWindows

I would recommend also looking up the multiple different types of "FileFormats" when it comes to saving workbooks, just to familiarize yourself with them.  Just search Excel FileFormats, and you should be able to find information about all of them.

Update:

As mentioned in the comments, your CSV file you are saving may not be actually saving as comma delimited.  To do so, similarly to what I said above, you can change the fileformat of your initial save to xlCSV. This can be achieved by adding FileFormat:= xlcsv to the end of your first ActiveWorkbook.SaveAs

FileFormats are required when you are actually interested in changing the filetype and not just the extension.  Here is the link to the MSDN site explaining all the different formats. MSDN XLFileFormats.  Instead of using the text xlCSV or xlTextWindows you can also use the numeric values assigned to those formats.  Instead of FileFormat:= xlCSV you can do FileFormat:= 6 or for xlTextWindows you can do FileFormat:= 20

Title: Save as .CSV and .txt

Body:
I am sure this is straightforward but is baffling me beyond belief. I have written the below code. You can see in to places that I am saving My pay final and Non-mypay Final as CSV files. Is there a way I can get the files to save as txt files as well. Ideally with the same location if possible? As always, your help is greatly appreciated.

 Option Explicit

 Sub BACSConversion()

 Dim MyNewBook As String
 Dim MySaveFile As String
 Dim fileToOpen As Variant
 Dim fileName As String
 Dim sheetName As String
 Dim rCopy As Range

 'Turn off display alerts
 Application.DisplayAlerts = False
 'Turn off screen updates
 Application.ScreenUpdating = False

 'Ensures that the file open directory is always the same
  ChDir "S:\MERIT OUTPUTS FOLDER\MSI Recruitment Limited\"

 'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If
 'Creates the file name based on txt file name
  fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Save active file as...
  ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\BACS File Original\" & _
  fileName & ".CSV")

 'Selects all data in column A and copies to clipboard
  Set rCopy = Range("A1", Range("A1").End(xlDown))

 'Open the original document where the BACS file is located
   Workbooks.Open "S:\Accounts (New)\Management Information
 (Analysis)\Phil Hanmore - Analysis\bacs conversation calc.xlsx"
 'Selects the worksheet called "Original"
  Sheets("Original").Range("A:A").ClearContents

 'Paste selected values from previous sheet
  rCopy.Copy
  Sheets("Original").Range("A1").PasteSpecial Paste:=xlPasteValues

 'Selects appropriate worksheet - Non-MyPayFINAL
   Sheets("Non-MyPay FINAL").Select

  'Selects all data in column A and copies to clipboard
   Range("A1", Range("A1").End(xlDown)).Select
  Selection.Copy

  'Add a new workbook
   Workbooks.Add
 'Paste selected values from previous sheet
  Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
  MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
 'Save template file as...
  ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & MySaveFile)
 'Close the new saved file
   ActiveWorkbook.Close

 'Selects appropriate worksheet - MyPayFINAL
   Sheets("MyPay FINAL").Select

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
 Selection.Copy

 'Add a new workbook
  Workbooks.Add
 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
  MySaveFile = Format(Now(), "DDMMYYYY") & "MyPayFINAL" & ".CSV"
 'Save template file as...
  ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & MySaveFile)
  'Close the new saved file
   ActiveWorkbook.Close
 'Close original source workbook (template)
  Workbooks("bacs conversation calc").Close

 'Turn on display alerts
Application.DisplayAlerts = True
 'Turn on screen updates
Application.ScreenUpdating = True

 End Sub


问:
Jmeter only logs only first failed assertion to .jtl file
Edit: Jmeter version: 3.1 r1770033

Im breaking my head on the following issue with Jmeter. I have tried several options including shifting around the order of the assertions. So far no result.

Functional wish

Basically I want the .jtl log file to reflect the content of the 'assertion result' view in the Jmeter Gui mode.

Current setup

I connect to a PostgreSQL database and execute a simple select from table query:

```<code>select * from progress_collaboration
</code>```

This gives me the following resultset:

```<code>id  curr_env_id
999 1
</code>```

On the sampler I have set 3 assertions:

Size Assertion

Response Assertion (string contains)

Duration Assertion

Problem

So far so good, up until only one assertion fails. When multiple assertions fail the 'assertion results' view shows me the following:
assertionview image

However, the .jtl logfile (created by running the project from the commandline) only contains the first failed assertion.

```<code>timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect
1499254721391,455,Check Beheer Variable,200,OK,Thread Group 1-1,text,false,"The result was the wrong size: It was 21 bytes, but should have been equal to 170 bytes.",21,0,1,1,453,0,443
</code>```

How do I ensure the .jtl logfile contains ALL failed assertions?

Data

Hashtree with sampler and assertions:

```<code>        <JDBCSampler guiclass="TestBeanGUI" testclass="JDBCSampler" testname="Check Beheer Variable" enabled="true">
          <stringProp name="dataSource">myDatabase</stringProp>
          <stringProp name="query">select * from progress_collaboration</stringProp>
          <stringProp name="queryArguments"></stringProp>
          <stringProp name="queryArgumentsTypes"></stringProp>
          <stringProp name="queryTimeout"></stringProp>
          <stringProp name="queryType">Select Statement</stringProp>
          <stringProp name="resultSetHandler">Store as String</stringProp>
          <stringProp name="resultVariable"></stringProp>
          <stringProp name="variableNames"></stringProp>
        </JDBCSampler>
        <hashTree>
          <SizeAssertion guiclass="SizeAssertionGui" testclass="SizeAssertion" testname="Size Assertion" enabled="true">
            <stringProp name="Assertion.test_field">SizeAssertion.response_network_size</stringProp>
            <stringProp name="SizeAssertion.size">170</stringProp>
            <intProp name="SizeAssertion.operator">1</intProp>
          </SizeAssertion>
          <hashTree/>
          <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Response Assertion" enabled="true">
            <collectionProp name="Asserion.test_strings">
              <stringProp name="56601">999</stringProp>
              <stringProp name="-715001365">incorrect_string</stringProp>
            </collectionProp>
            <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
            <boolProp name="Assertion.assume_success">true</boolProp>
            <intProp name="Assertion.test_type">2</intProp>
          </ResponseAssertion>
          <hashTree/>
          <DurationAssertion guiclass="DurationAssertionGui" testclass="DurationAssertion" testname="Duration Assertion" enabled="true">
            <stringProp name="DurationAssertion.duration">1000</stringProp>
            <stringProp name="Assertion.scope">all</stringProp>
          </DurationAssertion>
          <hashTree/>
        </hashTree>

</code>```

答:
In jmeter.properties define/update propery:

jmeter.save.saveservice.assertion_results=all

(you probably have jmeter.save.saveservice.assertion_results=first defined)

Also listener should have Save as XML check box checked (inside Configure)

Body:
Edit: Jmeter version: 3.1 r1770033

Im breaking my head on the following issue with Jmeter. I have tried several options including shifting around the order of the assertions. So far no result.

Functional wish

Basically I want the .jtl log file to reflect the content of the 'assertion result' view in the Jmeter Gui mode.

Current setup

I connect to a PostgreSQL database and execute a simple select from table query:

select * from progress_collaboration

This gives me the following resultset:

id  curr_env_id
999 1

On the sampler I have set 3 assertions:

Size Assertion

Response Assertion (string contains)

Duration Assertion

Problem

So far so good, up until only one assertion fails. When multiple assertions fail the 'assertion results' view shows me the following:
assertionview image

However, the .jtl logfile (created by running the project from the commandline) only contains the first failed assertion.

timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect
1499254721391,455,Check Beheer Variable,200,OK,Thread Group 1-1,text,false,"The result was the wrong size: It was 21 bytes, but should have been equal to 170 bytes.",21,0,1,1,453,0,443

How do I ensure the .jtl logfile contains ALL failed assertions?

Data

Hashtree with sampler and assertions:

        <JDBCSampler guiclass="TestBeanGUI" testclass="JDBCSampler" testname="Check Beheer Variable" enabled="true">
          <stringProp name="dataSource">myDatabase</stringProp>
          <stringProp name="query">select * from progress_collaboration</stringProp>
          <stringProp name="queryArguments"></stringProp>
          <stringProp name="queryArgumentsTypes"></stringProp>
          <stringProp name="queryTimeout"></stringProp>
          <stringProp name="queryType">Select Statement</stringProp>
          <stringProp name="resultSetHandler">Store as String</stringProp>
          <stringProp name="resultVariable"></stringProp>
          <stringProp name="variableNames"></stringProp>
        </JDBCSampler>
        <hashTree>
          <SizeAssertion guiclass="SizeAssertionGui" testclass="SizeAssertion" testname="Size Assertion" enabled="true">
            <stringProp name="Assertion.test_field">SizeAssertion.response_network_size</stringProp>
            <stringProp name="SizeAssertion.size">170</stringProp>
            <intProp name="SizeAssertion.operator">1</intProp>
          </SizeAssertion>
          <hashTree/>
          <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Response Assertion" enabled="true">
            <collectionProp name="Asserion.test_strings">
              <stringProp name="56601">999</stringProp>
              <stringProp name="-715001365">incorrect_string</stringProp>
            </collectionProp>
            <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
            <boolProp name="Assertion.assume_success">true</boolProp>
            <intProp name="Assertion.test_type">2</intProp>
          </ResponseAssertion>
          <hashTree/>
          <DurationAssertion guiclass="DurationAssertionGui" testclass="DurationAssertion" testname="Duration Assertion" enabled="true">
            <stringProp name="DurationAssertion.duration">1000</stringProp>
            <stringProp name="Assertion.scope">all</stringProp>
          </DurationAssertion>
          <hashTree/>
        </hashTree>