答:
```<code>perl -i~ -pe '
    s/,/"," x (1 + $commas)/e;
    $commas++ if eof;
' -- file1 file2 file3
</code>```

-p reads the file line by line, after running the code, it prints it

-i~ changes the input files "in place", saving a backup as file1~ etc.

s/,/"," x $commas/e substitutes a comma with evaluated code in the replacement part, i.e. the comma repeated one time for the first file, two times for the second, and so on

eof returns true every time an input file ends, see eof

$commas++ adds 1 to $commas

Title: How to insert empty column in a csv file using perl

Body:
I have a list of CSV file i need to add number of empty column on each, the number of empty column i need to add change on each file in a linear way, first file i want to insert 0 column, second file i want to insert 1 column, third file i want to insert 2 column and so on, the column should be inserted always as second one.
all the input file are a 2 column csv as the example below

file 1

2016/03/07 23:42:40.618 GMT,54.5
2016/03/07 23:43:40.618 GMT,54.0771
2016/03/07 23:44:40.618 GMT,53.9472
2016/03/07 23:45:40.618 GMT,54.2914

file 2

2016/03/07 23:42:40.618 GMT,49.013
2016/03/07 23:43:40.618 GMT,48.688
2016/03/07 23:44:40.618 GMT,47.7052
2016/03/07 23:45:40.618 GMT,47.9057

file3

2016/03/07 23:51:40.618 GMT,50.7858
2016/03/07 23:52:40.618 GMT,52.5267
2016/03/07 23:53:40.618 GMT,54.2865
2016/03/07 23:54:40.618 GMT,53.2014
2016/03/07 23:55:40.618 GMT,52.0538

etc.

I want the output to be

file1

2016/03/07 23:42:40.618 GMT,54.5
2016/03/07 23:43:40.618 GMT,54.0771
2016/03/07 23:44:40.618 GMT,53.9472
2016/03/07 23:45:40.618 GMT,54.2914

File2

2016/03/07 23:42:40.618 GMT,,49.013
2016/03/07 23:43:40.618 GMT,,48.6883
2016/03/07 23:44:40.618 GMT,,47.7052
2016/03/07 23:45:40.618 GMT,,47.9057

file3

2016/03/07 23:51:40.618 GMT,,,50.7858
2016/03/07 23:52:40.618 GMT,,,52.5267
2016/03/07 23:53:40.618 GMT,,,54.2865
2016/03/07 23:54:40.618 GMT,,,53.2014
2016/03/07 23:55:40.618 GMT,,,52.0538

This is the code wrote but it generate the same output for all file with added just one empty column, probably i'm missing something silly but i can't get what

#!/usr/bin/perl
#use strict;
#use diagnostics;
use CGI qw(:standard);
use Cwd;
use File::Find;
use File::Basename;
use Text::CSV;
use Text::Trim qw(trim);
use List::MoreUtils qw(uniq);
use Text::CSV_XS;
sub read_dir{
    my $ph=$_[0];
    my $match=$_[1];
    my @fl = ( );
    #print " will open $ph";
    opendir DH, "$ph" or die "Cannot open Dir $ph: $!";
    #if ($match eq "") {
    @fl = grep !/^\.\.?$\.*/, sort(readdir DH) ;
    #}
    #else {
    #   my @fl = grep {$_ =~ $match} sort(readdir DH) ;
    #}
    closedir DH;
    if ($match ne "") {
        foreach my $file (@fl){
            if ($file =~$match) {
                push(@ffl,$file);
            }
        }
        return @ffl;
    }
    else {
        return @fl;
    }
}
@column=();
$loc="/myfolder";
$offset=1;
@sites=("dir1","dir2","dir3");
$s="subdir";
foreach $t (@sites) {
    $m=0; #number of empty column to insert in the file
    @list=read_dir("$loc/Statistics/$t/$s"); #directory that contain the csv file to manipulate
    foreach $l (@list) {
        #inser the empty column
        open $in, "<","$loc/Statistics/$t/$s/$l" or die $!;
        open $out, ">>", "$loc/Statistics/$t/$s/$l.tmp" or die $!;
        foreach $r (0..$m) {
            print "
 r is $r";
            open $out, ">>", "$loc/Statistics/$t/$s/$l.tmp" or die $!;
            while ($row = $ccsv->getline($in)) {
                splice @$row, $offset, 0, shift @column;
                $ccsv->print($out, $row);
            }
            close $out;
        }
        close $in;
        $m=$m+1;
    }
}

Body:
perl -i~ -pe '
    s/,/"," x (1 + $commas)/e;
    $commas++ if eof;
' -- file1 file2 file3

-p reads the file line by line, after running the code, it prints it

-i~ changes the input files "in place", saving a backup as file1~ etc.

s/,/"," x $commas/e substitutes a comma with evaluated code in the replacement part, i.e. the comma repeated one time for the first file, two times for the second, and so on

eof returns true every time an input file ends, see eof

$commas++ adds 1 to $commas


来源: stackexchange

问:
Button Remains Highlighted after clicked c# (windows form)
Pictures of the button before it is pressed and after: https://imgur.com/a/cVqy2

The button that is clicked on opens a new form, stuff happens, and when that form is closed, the button turns to the dark gray.  I do not want this to happen. I want the button to stay the light gray color.

Help?

I am using the metro style buttons.

答:
Found the following code in some other place where the OP says he also found it in some other place...

In short,

First step :
Create a new static class, copy the following code:

```<code>public static class ExtensionMethods
{
   private static Action EmptyDelegate = delegate() { };

   public static void Refresh(this UIElement uiElement)
   {
      uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
   }
}
</code>```

Also add

using System.Windows.Threading;

on top of the class

Second Step:
Give your button a name in xaml. e.g:

```<code><Button x:Name="myPreciousButton" />
</code>```

In your project, whenever you want the button to turn light grey (or to any default style) again, call:

```<code>myPreciousButton.Refresh();
</code>```

You can call it on the form closing, if you know when it closes. Or maybe just right after you click the button. Or after your first form gains focus after the second form closes. There're many options.

In case that doesn't work or you could never be bothered enough to implement this thing, there's an easier solution:
Again, give your button a name, e.g. "
When you want its color to return to default, type something along the lines:

```<code>myPreciousButton.Background = Brushes.LightGrey
</code>```

Not sure how to change the text's color though, I can't be bothered to think about it ;)

Good luck

ContentLicense: CC BY-SA 3.0

Body:
Found the following code in some other place where the OP says he also found it in some other place...

In short,

First step :
Create a new static class, copy the following code:

public static class ExtensionMethods
{
   private static Action EmptyDelegate = delegate() { };

   public static void Refresh(this UIElement uiElement)
   {
      uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
   }
}

Also add

using System.Windows.Threading;

on top of the class

Second Step:
Give your button a name in xaml. e.g:

<Button x:Name="myPreciousButton" />

In your project, whenever you want the button to turn light grey (or to any default style) again, call:

myPreciousButton.Refresh();

You can call it on the form closing, if you know when it closes. Or maybe just right after you click the button. Or after your first form gains focus after the second form closes. There're many options.

In case that doesn't work or you could never be bothered enough to implement this thing, there's an easier solution:
Again, give your button a name, e.g. "
When you want its color to return to default, type something along the lines:

myPreciousButton.Background = Brushes.LightGrey

Not sure how to change the text's color though, I can't be bothered to think about it ;)

Good luck


问:
Error in the python script
I have this simple python script where myvar1 is accessible in generate() function but not in copy() function. Need help figuring out the error:

```<code>#!/usr/bin/python

import os, time

def Test(tcid,descr,iterations,filsz):

        def setup():
                print "entering set up\n"
                global myvar1, myvar2

                myvar1 = 1.0
                myvar2 = os.getcwd()

        def generate():
                print "entering generate\n"
                print "in generate", myvar1, myvar2

        def copy():

           print "in copy", myvar1, myvar2
           myvar1 += 5.0

        setup()
        generate()

        for loopcount in range(5):
           loopcount = loopcount + 1
           copy()

if __name__ == "__main__":
        Test('test','simple test',2,10)
</code>```

Error:

Traceback (most recent call last):
  File "./pyerror.py", line 35, in
    Test('test','simple test',2,10)
  File "./pyerror.py", line 30, in Test
    copy()
  File "./pyerror.py", line 20, in copy
    print "in copy", myvar1, myvar2
UnboundLocalError: local variable 'myvar1' referenced before assignment

答:
In the copy() function, myvar1 is not declared as global, but assigned to in the statement myvar1 += 5.0.  This implicitly makes the myvar1 a local variable.  The print statement in the first line of the function also tries to access a local variable with the name myvar1, but such a local variable does not exist yet.

Local variables are determined statically, i.e. at compile time.  When the copy() is compiled by Python, myvar1 is marked as local variable for the whole function body.  It may be instructive to look at the easiest code to trigger this error:

```<code>def f():
    print x
    x = 5
x = 3
f()
</code>```

ContentLicense: CC BY-SA 2.5

Title: Error in the python script

Body:
I have this simple python script where myvar1 is accessible in generate() function but not in copy() function. Need help figuring out the error:

#!/usr/bin/python

import os, time

def Test(tcid,descr,iterations,filsz):

        def setup():
                print "entering set up\n"
                global myvar1, myvar2

                myvar1 = 1.0
                myvar2 = os.getcwd()

        def generate():
                print "entering generate\n"
                print "in generate", myvar1, myvar2

        def copy():

           print "in copy", myvar1, myvar2
           myvar1 += 5.0

        setup()
        generate()

        for loopcount in range(5):
           loopcount = loopcount + 1
           copy()

if __name__ == "__main__":
        Test('test','simple test',2,10)

Error:

Traceback (most recent call last):
  File "./pyerror.py", line 35, in
    Test('test','simple test',2,10)
  File "./pyerror.py", line 30, in Test
    copy()
  File "./pyerror.py", line 20, in copy
    print "in copy", myvar1, myvar2
UnboundLocalError: local variable 'myvar1' referenced before assignment

Body:
In the copy() function, myvar1 is not declared as global, but assigned to in the statement myvar1 += 5.0.  This implicitly makes the myvar1 a local variable.  The print statement in the first line of the function also tries to access a local variable with the name myvar1, but such a local variable does not exist yet.

Local variables are determined statically, i.e. at compile time.  When the copy() is compiled by Python, myvar1 is marked as local variable for the whole function body.  It may be instructive to look at the easiest code to trigger this error:

def f():
    print x
    x = 5
x = 3
f()


问:
How to get price from bitcoin to USD with api
Please help me how to get the price from bitcoin to USD with bitpay API. I wrote the following code, but I got USD to bitcoin price. I want bitcoin to USD price. Thanks!</p>

```<code><?php
    $url = "https://bitpay.com/api/rates";

    $json = file_get_contents($url);
    $data = json_decode($json, TRUE);

    $rate = $data[1]["rate"];
    $usd_price = 10;     # Let cost of elephant be 10$

    $bitcoin_price = round( $usd_price / $rate , 8 );
?>
</code>```

答:
Is this what you mean?

```<code>$url='https://bitpay.com/api/rates';
$json=json_decode( file_get_contents( $url ) );
$dollar=$btc=0;

foreach( $json as $obj ){
    if( $obj->code=='USD' )$btc=$obj->rate;
}

echo "1 bitcoin=\$" . $btc . "USD<br />";
$dollar=1 / $btc;
echo "10 dollars = " . round( $dollar * 10,8 )."BTC";
</code>```

returns

```<code>1 bitcoin=$11485USD
10 dollars = 0.0008707BTC
</code>```

Body:
Please help me how to get the price from bitcoin to USD with bitpay API. I wrote the following code, but I got USD to bitcoin price. I want bitcoin to USD price. Thanks!

<?php
    $url = "https://bitpay.com/api/rates";

    $json = file_get_contents($url);
    $data = json_decode($json, TRUE);

    $rate = $data[1]["rate"];
    $usd_price = 10;     # Let cost of elephant be 10$

    $bitcoin_price = round( $usd_price / $rate , 8 );
?>

Body:
Is this what you mean?

$url='https://bitpay.com/api/rates';
$json=json_decode( file_get_contents( $url ) );
$dollar=$btc=0;

foreach( $json as $obj ){
    if( $obj->code=='USD' )$btc=$obj->rate;
}

echo "1 bitcoin=\$" . $btc . "USD<br />";
$dollar=1 / $btc;
echo "10 dollars = " . round( $dollar * 10,8 )."BTC";

returns

1 bitcoin=$11485USD
10 dollars = 0.0008707BTC


问:
Relationships GraphQL
The second week I try to link two collections in the apollo-server-express / MongoDB / Mongoose / GraphQL stack, but I do not understand how. I found a similar lesson with the REST API, what I need is called Relationships. I need this, but in GraphQL

watch video

How to add cars to the User?
I collected the test server, the code is here: https://github.com/gHashTag/test-graphql-server
Help

答:
try to make something like this in your car resolver</p>

```<code>export default {
  getCar: ({ _id: ownId }, { _id }) =>
    Car.findById(ownId || _id);
// here is the rest of your code
</code>```

Title: Relationships GraphQL

Body:
try to make something like this in your car resolver

export default {
  getCar: ({ _id: ownId }, { _id }) =>
    Car.findById(ownId || _id);
// here is the rest of your code


问:
List to array conversion to use ravel() function
I have a list in python and I want to convert it to an array to be able to use ravel() function.

答:
create an int array and a list

```<code>from array import array
listA = list(range(0,50))
for item in listA:
    print(item)
arrayA = array("i", listA)
for item in arrayA:
    print(item)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
create an int array and a list

from array import array
listA = list(range(0,50))
for item in listA:
    print(item)
arrayA = array("i", listA)
for item in arrayA:
    print(item)


问:
invalid volume spec ":/io": invalid volume specification: ':/io'
I'm learning docker using book docker in practice.

I am working on technique 44 in chapter 5.

I have downloaded sample deb file from net using below command.

```<code>$ wget http://mirrors.kernel.org/ubuntu/pool/main/libe/libeatmydata/eatmydata_26-2_amd64.deb
</code>```

Then run the below command

```<code>$ docker run -v ${pwd}:/io dockerinpractice/alienate
docker: Error response from daemon: invalid volume spec ":/io": invalid volume specification: ':/io'.
See 'docker run --help'.
</code>```

My docker version is -

Server Version: 17.06.0-ce

My ubuntu version is -

Description:    Ubuntu 16.10

How to solve this issue?

答:
The problem is with the braces syntax. Replace ${pwd} with $(pwd).

```<code>docker run -v $(pwd):/io dockerinpractice/alienate
</code>```

Body:
I'm learning docker using book docker in practice.

I am working on technique 44 in chapter 5.

I have downloaded sample deb file from net using below command.

$ wget http://mirrors.kernel.org/ubuntu/pool/main/libe/libeatmydata/eatmydata_26-2_amd64.deb

Then run the below command

$ docker run -v ${pwd}:/io dockerinpractice/alienate
docker: Error response from daemon: invalid volume spec ":/io": invalid volume specification: ':/io'.
See 'docker run --help'.

My docker version is -

Server Version: 17.06.0-ce

My ubuntu version is -

Description:    Ubuntu 16.10

How to solve this issue?

Body:
The problem is with the braces syntax. Replace ${pwd} with $(pwd).

docker run -v $(pwd):/io dockerinpractice/alienate


问:
The QVW File Size Is Larger While Using Cube Data
I've made two QlikView (two .qvw files) reports which have almost the same content.
One loads data from Data Warehouse using 'Microsoft OLE DB Provider for SQL Server'.
Another one load data from Cube using 'Microsoft OLE DB Provider for Analysis Services'.

However, the file's size with Cube data is much larger than the file with DW data.
I want to know why this happened.

Thanks for attention.

答:
Define almost the same content :)

QlikView/QlikSense file size are depending on the number of the columns and the distinct values in them.

In general Qlik do not store all the data as it is. Instead it stores the data as lists of distinct values and memory pointers and thats how the data model is build.

For example:

If you have two fields in the database (both with 1M rows) - one with timestamp values and the other with only date values.

In Qlik, the app with the timestamp values will be bigger than the date app because timestamp field have a lot of non distinct values (lets say 80% are non distinct) and date have a lot of distinct values (let say 80% are distinct) and Qlik stores only the distinct values in the background.

In the example above you will end with timestamp file being saved with 800k rows (80% non distinct) and date file with 200k (80% distinct) rows although in the database having both fields with 1M rows.

Im simplifying it, but in general - less fields with high number of distinct values will produce smaller files. Adding 1-2 more columns with a lot non-distinct values can make the file size quite different (especially with bigger datasets).

Real example:

SO_47650951_1.qvw - contains 1 field with "1M" rows. The values in it are floor( rand() * 100) (1,2,3,4 ... 100) and file size is 968Kb

SO_47650951_2.qvw - contains 1 field with "1M" rows. The values in it are rand() (0.70505229476839, 0.22396470652893, 0.59824940375984 etc) and file size is 7,2Mb
"


问:
Select 1 image from gallery and display on multiple ImageViews
```<code>ImageView imageView = (ImageView) findViewById(R.id.Gallery);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD);

        }
    });

}
   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // When an Image is picked
    if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri imageUri = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = getContentResolver().openInputStream(imageUri);
            ImageView imageView = (ImageView) findViewById(R.id.Gallery);
            imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
        } catch (FileNotFoundException e) {
            // Handle the error
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    // Ignore the exception
                }
            }
        }
    }

}
</code>```

<p>This code works fine for adding and image to one imageView. How can i get it to be displayed in multiple imageViews by just selecting an image once instead of repeating the process for every imageView </p>

答:
Do code like this:

```<code> @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
        && null != data) {
    // Get the Image from data

    Uri imageUri = data.getData();
    InputStream imageStream = null;
    try {
        imageStream = getContentResolver().openInputStream(imageUri);
        ImageView imageView = (ImageView) findViewById(R.id.Gallery);

   imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
   imageView1.setImageBitmap(BitmapFactory.decodeStream(imageStream));
   imageView2.setImageBitmap(BitmapFactory.decodeStream(imageStream));
   imageView3.setImageBitmap(BitmapFactory.decodeStream(imageStream));
    } catch (FileNotFoundException e) {
        // Handle the error
    } finally {
        if (imageStream != null) {
            try {
                imageStream.close();
            } catch (IOException e) {
                // Ignore the exception
            }
        }
    }
}
</code>```

Here, imageView,imageView1,imageView2,imageView3 are instance of different image view.

Edited:

```<code>  @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
    && null != data) {
  // Get the Image from data

  Uri imageUri = data.getData();
  InputStream imageStream = null;
  try {
    imageStream = getContentResolver().openInputStream(imageUri);
     Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

            imageView.setImageBitmap(bitmap);
            imageView1.setImageBitmap(bitmap);
            imageView2.setImageBitmap(bitmap);
            imageView3.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
    // Handle the error
} finally {
    if (imageStream != null) {
        try {
            imageStream.close();
        } catch (IOException e) {
            // Ignore the exception
        }
    }
}
}
</code>```

Edited 2:

```<code> public class ThirdJavaActivity extends Activity {

ImageView imageView,imageView1,imageView2,imageView3;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.content_third);

    imageView = (ImageView)findViewById(R.id.imageView);
    imageView1 = (ImageView)findViewById(R.id.imageView1);
    imageView2 = (ImageView)findViewById(R.id.imageView2);
    imageView3 = (ImageView)findViewById(R.id.imageView3);

   Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, 101);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 // When an Image is picked
    if (requestCode == 101 && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri imageUri = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = getContentResolver().openInputStream(imageUri);

            Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

            imageView.setImageBitmap(bitmap);
            imageView1.setImageBitmap(bitmap);
            imageView2.setImageBitmap(bitmap);
            imageView3.setImageBitmap(bitmap);
        } catch (Exception e) {
            // Handle the error
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    // Ignore the exception
                }
            }
        }
    }
}
}
</code>```

Body:
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD);

        }
    });

}
   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // When an Image is picked
    if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri imageUri = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = getContentResolver().openInputStream(imageUri);
            ImageView imageView = (ImageView) findViewById(R.id.Gallery);
            imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
        } catch (FileNotFoundException e) {
            // Handle the error
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    // Ignore the exception
                }
            }
        }
    }

}

This code works fine for adding and image to one imageView. How can i get it to be displayed in multiple imageViews by just selecting an image once instead of repeating the process for every imageView

Body:
Do code like this:

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
        && null != data) {
    // Get the Image from data

    Uri imageUri = data.getData();
    InputStream imageStream = null;
    try {
        imageStream = getContentResolver().openInputStream(imageUri);
        ImageView imageView = (ImageView) findViewById(R.id.Gallery);

   imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
   imageView1.setImageBitmap(BitmapFactory.decodeStream(imageStream));
   imageView2.setImageBitmap(BitmapFactory.decodeStream(imageStream));
   imageView3.setImageBitmap(BitmapFactory.decodeStream(imageStream));
    } catch (FileNotFoundException e) {
        // Handle the error
    } finally {
        if (imageStream != null) {
            try {
                imageStream.close();
            } catch (IOException e) {
                // Ignore the exception
            }
        }
    }
}

Here, imageView,imageView1,imageView2,imageView3 are instance of different image view.

Edited:

  @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
    && null != data) {
  // Get the Image from data

  Uri imageUri = data.getData();
  InputStream imageStream = null;
  try {
    imageStream = getContentResolver().openInputStream(imageUri);
     Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

            imageView.setImageBitmap(bitmap);
            imageView1.setImageBitmap(bitmap);
            imageView2.setImageBitmap(bitmap);
            imageView3.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
    // Handle the error
} finally {
    if (imageStream != null) {
        try {
            imageStream.close();
        } catch (IOException e) {
            // Ignore the exception
        }
    }
}
}

Edited 2:

 public class ThirdJavaActivity extends Activity {

ImageView imageView,imageView1,imageView2,imageView3;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.content_third);

    imageView = (ImageView)findViewById(R.id.imageView);
    imageView1 = (ImageView)findViewById(R.id.imageView1);
    imageView2 = (ImageView)findViewById(R.id.imageView2);
    imageView3 = (ImageView)findViewById(R.id.imageView3);

   Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, 101);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 // When an Image is picked
    if (requestCode == 101 && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri imageUri = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = getContentResolver().openInputStream(imageUri);

            Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

            imageView.setImageBitmap(bitmap);
            imageView1.setImageBitmap(bitmap);
            imageView2.setImageBitmap(bitmap);
            imageView3.setImageBitmap(bitmap);
        } catch (Exception e) {
            // Handle the error
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    // Ignore the exception
                }
            }
        }
    }
}
}


问:
WebRTC : Can't talk at the same time
I'm working on webRTC and I have a problem : with some user I can't talk at the same time (their microphone get automatically muted while I am talking)

Does somebody have some information about that ?

(I'm using simplePeer)

答:
This should be related to a misbehaving AEC (echo cancellation).
Try to disable AEC (and also AGC) on both side and it should fix the problem.

For WebRTC you can do it like this:

```<code>var mediaConstraints = {
audio: {
    echoCancellation: { exact: false },
    googEchoCancellation: { exact: false },
    googAutoGainControl: { exact: false },
    googNoiseSuppression: { exact: false },
      }
}
</code>```

Title: WebRTC : Can't talk at the same time

Body:
This should be related to a misbehaving AEC (echo cancellation).
Try to disable AEC (and also AGC) on both side and it should fix the problem.

For WebRTC you can do it like this:

var mediaConstraints = {
audio: {
    echoCancellation: { exact: false },
    googEchoCancellation: { exact: false },
    googAutoGainControl: { exact: false },
    googNoiseSuppression: { exact: false },
      }
}


问:
Videos sent by android in bytes are not recieved by apache server..
I am using django==1.11 on the backend I am using apache2 server. I am receiving videos in bytes sent by android but I am getting an error "[wsgi:error] [pid 21270] The joined path is located outside of the base path component (/var/www)"

Whereas when running the same server on port 8000 its working fine..
Even images with size more that 1 MB are not received by apache..
Can the issue be of Firewall or apache has some size limit issues??
Any suggestion as what might be the problem..

答: It worked.. Actually the error was our files were not static it had to be in media.. N our media folder was inside static which gave an error when run on apache server... The error was solved when I took the media folder outside static...</p>


问:
JQuery not adding class on click
I'm struggeling with some code, I have code to when I click a
 element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

```<code>function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};
</code>```

HTML

```<code><li class="w-100" id="http://whatever.com/" onclick="return loadIframe(this.id);">
    <p>

        <i class="fa fa-id-badge" aria-hidden="true"></i>
        <span class="nav-label">Intranet</span>

    </p>
</li>
</code>```

答:
you can not use $(this).addClass();

check this and this

Title: JQuery not adding class on click

Body:
I'm struggeling with some code, I have code to when I click a
 element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};

HTML

        Intranet


问:
Export Python dataframe into CSV
I have a dataframe x with the size of ( 2000, 3000) . I would like to export it into CSV to use in R. I tried this code:

```<code> x.to_csv("ab.csv", sep='\t')
</code>```

However, when I open in R by the code:

```<code> data = read.csv(".data/ab.csv")
</code>```

The size of data is (2000,1) because the CSV file can not separate into 3000 columns. Is there any solution to keep the same size after exporting ?

答: By using the parameter sep='\t' you have written a "CSV" which uses tab to separate fields instead of a comma. You could either remove the parameter and write a normal CSV, or use the sep="\t" argument for read.csv in R. If there's no reason to use tab then I would suggest the former option.

Title: Export Python dataframe into CSV

Body:
I have a dataframe x with the size of ( 2000, 3000) . I would like to export it into CSV to use in R. I tried this code:

 x.to_csv("ab.csv", sep='\t')

However, when I open in R by the code:

 data = read.csv(".data/ab.csv")

The size of data is (2000,1) because the CSV file can not separate into 3000 columns. Is there any solution to keep the same size after exporting ?


问:
How to find if a string contains any objects in an array?
Say if I have the following code

```<code>String sum = "(5+5)/2*6";
char[] bodmasChars = {'+','-','*','/','.'.'(',')'};
</code>```

Is there a way to check whether the string contains any of the elements in my char[]?

答:
A regex

```<code>String sum = "(5+5)/2*6";
if (sum.matches("(?s).*[-\\+\\*/\\.()].*")) { ...
</code>```

(?s) lets . also match newlines.
[...] is group of possible character or character ranges. Probably have a backslash too many.

Body:
Say if I have the following code

String sum = "(5+5)/2*6";
char[] bodmasChars = {'+','-','*','/','.'.'(',')'};

Is there a way to check whether the string contains any of the elements in my char[]?

Body:
A regex

String sum = "(5+5)/2*6";
if (sum.matches("(?s).*[-\\+\\*/\\.()].*")) { ...

(?s) lets . also match newlines.
[...] is group of possible character or character ranges. Probably have a backslash too many.


问:
Passing a String variable into a UIImage constructor does not return a UIImage?
I'm having trouble wrapping my head around this issue.

Currently in my Assets folder I have the following decline bench.png image:

In my code, I have a String variable equipmentName set somewhere else.

I set my UIImageView image like so:

```<code>equipmentImageView.image = UIImage(named: equipmentName)
</code>```

However, the image is never returned.

I checked to see if the image can actually be returned:

```<code>if let image = UIImage(named: equipmentName)
{
    print("GOOD")
}
else
{
    print("BAD")
}
</code>```

This prints out BAD.

However if I replaced equipmentName with the actual string name, it returns the correct image, and outputs GOOD:

```<code>if let image = UIImage(named: "decline bench")
{
    print("GOOD")
}
else
{
    print("BAD")
}
</code>```

What gives?

They are both the same thing, the type is a String so why does passing it the variable equipmentName of type String not work, but passing in a literal string work?

The variable equipmentName also contains the string decline bench before equipmentImageView.image is set.

Does it have anything to do with the naming of the image in the Assets folder?

Please help me understand. Thanks!

MORE INFO:
In my code, equipmentName is actually stored with upper-case first letters like so Decline Bench.

When I set the image, I am actually doing:

```<code>equipmentImageView.image = UIImage(named: equipmentName.lowercased())
</code>```

equipmentName.lowercased() still returns a String, which does not work.

However, doing the following does work:

```<code>equipmentName = "decline bench"
equipmentImageView.image = UIImage(named: equipmentName)
</code>```

What is the difference here that I am not doing correctly?

UPDATE: The following print out produces:

print(Data(equipmentName.utf8) as NSData): <4465636c 696e6520 42656e63 680a2020 20202020 20202020 2020>

print(Data(equipmentName.lowercased().utf8) as NSData): <6465636c 696e6520 62656e63 680a2020 20202020 20202020 2020>

答:
Credits to @Martin R and @Larme:

The issue was that equipmentName contained newline characters as well as spacing, causing UIImage(named: equipmentName.lowercased()) to not recognized the passed in String parameter equipmentName.lowercased().

Eliminating the extra spacing in equipmentName before setting the imageView.image resolved the issue.

Body:
I'm having trouble wrapping my head around this issue.

Currently in my Assets folder I have the following decline bench.png image:

In my code, I have a String variable equipmentName set somewhere else.

I set my UIImageView image like so:

equipmentImageView.image = UIImage(named: equipmentName)

However, the image is never returned.

I checked to see if the image can actually be returned:

if let image = UIImage(named: equipmentName)
{
    print("GOOD")
}
else
{
    print("BAD")
}

This prints out BAD.

However if I replaced equipmentName with the actual string name, it returns the correct image, and outputs GOOD:

if let image = UIImage(named: "decline bench")
{
    print("GOOD")
}
else
{
    print("BAD")
}

What gives?

They are both the same thing, the type is a String so why does passing it the variable equipmentName of type String not work, but passing in a literal string work?

The variable equipmentName also contains the string decline bench before equipmentImageView.image is set.

Does it have anything to do with the naming of the image in the Assets folder?

Please help me understand. Thanks!

MORE INFO:
In my code, equipmentName is actually stored with upper-case first letters like so Decline Bench.

When I set the image, I am actually doing:

equipmentImageView.image = UIImage(named: equipmentName.lowercased())

equipmentName.lowercased() still returns a String, which does not work.

However, doing the following does work:

equipmentName = "decline bench"
equipmentImageView.image = UIImage(named: equipmentName)

What is the difference here that I am not doing correctly?

UPDATE: The following print out produces:

print(Data(equipmentName.utf8) as NSData): <4465636c 696e6520 42656e63 680a2020 20202020 20202020 2020>

print(Data(equipmentName.lowercased().utf8) as NSData): <6465636c 696e6520 62656e63 680a2020 20202020 20202020 2020>


答:
You need global wherever you overwrite a global in a function. setup set myvar1 as a global but you used it as a unset local variable. Hence the "local variable 'myvar1' referenced before assignment"

```<code>def copy():
    global myvar1
    print "in copy", myvar1, myvar2
    myvar1 += 5.0
</code>```

If you're reading a tutorial that suggests using global regularly then throw it away, burn it and start with a different one.

Title: Error in the python script

Body:
You need global wherever you overwrite a global in a function. setup set myvar1 as a global but you used it as a unset local variable. Hence the "local variable 'myvar1' referenced before assignment"

def copy():
    global myvar1
    print "in copy", myvar1, myvar2
    myvar1 += 5.0

If you're reading a tutorial that suggests using global regularly then throw it away, burn it and start with a different one.


问:
Idiomatic Gradle script to build 'debug' and 'release' JAR files
I'm trying to create a Gradle build script that will build a Java .jar file in 'release' or 'debug' modes and am having trouble parametrizing the script.

The question is: What is an idiomatic way to do this in a Gradle script, using the Java plugin?
(or, if there's no idiomatic way, what's a hacky solution that actually works?)

I don't mind the method of parametrization, just as long as the command-line and IDE invocations can easily choose between the two output options. The jar file will be used as a library in other projects, e.g. an Android app and a JavaFX app, so I would like the method of parametrization to be invokable/depended-on from their own Gradle scripts.

Ideally I'd like to 'emulate' the Android gradle plugin's ability to have a Debug/Release version of every task, i.e.

```<code>$ ./gradlew build
$ ./gradlew assembleRelease
$ ./gradlew checkDebug
</code>```

but failing that even a top level buildDebug and buildRelease would be suitable.

Stuff I tried

This section isn't really relevant to the question.

Starting point

I have the following gradle file/project:

```<code>group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}
</code>```

This works fine and produces the jar file:

```<code>$ ls TestGradleModule/build/libs/
TestGradleModule-1.0-release.jar
</code>```

which, when the extracted classes are inspected with javap, doesn't contain any debug information. Hurrah. No we need a way to make a debug version.

Add debug & release tasks

```<code>version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-release'
    compileJava {
        options.debug = false
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-debug'
    compileJava {
        options.debug = true
    }
}
</code>```

This didn't work, as the debug project is always built, even if buildRelease is the task given on the command line. I guess this is because the code for both tasks is run at Configuration time (Gradle build lifecycle), whereas I only want one to run. So I guess I want to run them at Execution time?

Add some doLast tasks

```<code>version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-release'
        compileJava {
            options.debug = false

        }
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-debug'
        compileJava {
            options.debug = true
        }
    }
}
</code>```

This is even worse. The output file is always 1.0-release, and that's because of the 'default' at the top level. If I comment that out then a versioned jar is not made, instead the default of TestGradleModule.jar is made. It seems that the contents of the doLast blocks are completely useless in their effect upon the compileJava task (but there's no warning about this?). I guess these modifications are too late to be done at execution time, or that there's something else that needs to be done so that the compileJava tasks is "configured" differently?

Using Configurations?

I noticed the manual for the Java plugin contained a reference to buildConfigName and uploadConfigName, and claimed they depend on "The tasks which produce the artifacts in configuration ConfigName.". Given that I was failing to parametrize stuff at Configuration time, the plugin's ability to do that looked promising:

```<code>group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

configurations {
    debug
    release
}

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}
</code>```

but:

This didn't add buildRelease or buildDebug to the output of ./gradlew tasks --all, as I expected it to. But I could run those tasks.

It only seemed to make buildRelease and buildDebug, not e.g. assembleRelease etc

buildRelease didn't seem to depend on anything when run so therefore had no useful effect.

Iterating tasks?

As a final attempt I've tried to create all of the appropriate tasks and linking the dependencies for everything. I tried iterating over the tasks and adding the dependencies:

```<code>gradle.taskGraph.whenReady { taskGraph ->

    taskGraph.allTasks.each { taskIter ->

        println("iterating" + taskIter)

        def releaseTask = project.task(taskIter.name + "Release")
        def debugTask = project.task(taskIter.name + "Debug")

        taskIter.dependsOn += [releaseTask, debugTask].toSet()
        println("new taskIter.dependsOn:" + taskIter.dependsOn)

        /*
            set debug mode here,
            copy over effects of task to debug/release
            disable effects of task
        */
    }
}
</code>```

but

This didn't seem to create the tasks properly, they weren't accessible from the command line and running "build" didn't run "buildRelease" etc.

I would also have to "move" all of the "actions" from the current, existing tasks and into the debug and release tasks, to avoid duplicating the effects of each. And I don't know how to do that.

In short, I have no idea what I'm doing. As a last resort I could just create all of the tasks manually, but that seems to defeat the point of using the the java plugin and is very spammy?

答:
Not sure but perhaps my gradle-java-flavours plugin could help here. Eg:

```<code>plugins {
    id "com.lazan.javaflavours" version "1.2"
}
javaFlavours {
    flavour 'debug'
    flavour 'release'
}
debugJar {
    version = "${project.version}-debug"
}
releaseJar {
    version = "${project.version}-release"
}
</code>```

Each flavour gets it's own Jar and JavaCompile tasks etc and you can specify custom sources, resources, tests, dependencies for each flavour too.

See here for a bit more overview on the tasks, directories and configurations avaliable and here for a test which covers the functionality.

This approach differes from your GradleBuild style since the "flavours" can happily live together in a single project which builds multiple artifacts rather than running a project twice with two different parameters.

Body:
I'm trying to create a Gradle build script that will build a Java .jar file in 'release' or 'debug' modes and am having trouble parametrizing the script.

The question is: What is an idiomatic way to do this in a Gradle script, using the Java plugin?
(or, if there's no idiomatic way, what's a hacky solution that actually works?)

I don't mind the method of parametrization, just as long as the command-line and IDE invocations can easily choose between the two output options. The jar file will be used as a library in other projects, e.g. an Android app and a JavaFX app, so I would like the method of parametrization to be invokable/depended-on from their own Gradle scripts.

Ideally I'd like to 'emulate' the Android gradle plugin's ability to have a Debug/Release version of every task, i.e.

$ ./gradlew build
$ ./gradlew assembleRelease
$ ./gradlew checkDebug

but failing that even a top level buildDebug and buildRelease would be suitable.

Stuff I tried

This section isn't really relevant to the question.

Starting point

I have the following gradle file/project:

group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

This works fine and produces the jar file:

$ ls TestGradleModule/build/libs/
TestGradleModule-1.0-release.jar

which, when the extracted classes are inspected with javap, doesn't contain any debug information. Hurrah. No we need a way to make a debug version.

Add debug & release tasks

version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-release'
    compileJava {
        options.debug = false
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    project.version = '1.0-debug'
    compileJava {
        options.debug = true
    }
}

This didn't work, as the debug project is always built, even if buildRelease is the task given on the command line. I guess this is because the code for both tasks is run at Configuration time (Gradle build lifecycle), whereas I only want one to run. So I guess I want to run them at Execution time?

Add some doLast tasks

version '1.0-release'
compileJava {
    options.debug = false
}

task buildRelease(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-release'
        compileJava {
            options.debug = false

        }
    }
}

task buildDebug(type: GradleBuild, dependsOn: build) {
    doLast {
        project.version = '1.0-debug'
        compileJava {
            options.debug = true
        }
    }
}

This is even worse. The output file is always 1.0-release, and that's because of the 'default' at the top level. If I comment that out then a versioned jar is not made, instead the default of TestGradleModule.jar is made. It seems that the contents of the doLast blocks are completely useless in their effect upon the compileJava task (but there's no warning about this?). I guess these modifications are too late to be done at execution time, or that there's something else that needs to be done so that the compileJava tasks is "configured" differently?

Using Configurations?

I noticed the manual for the Java plugin contained a reference to buildConfigName and uploadConfigName, and claimed they depend on "The tasks which produce the artifacts in configuration ConfigName.". Given that I was failing to parametrize stuff at Configuration time, the plugin's ability to do that looked promising:

group 'TestGradleProjectGroup'
apply plugin: 'java'
sourceCompatibility = 1.8

configurations {
    debug
    release
}

version '1.0-release'
compileJava {
    options.debug = false
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

but:

This didn't add buildRelease or buildDebug to the output of ./gradlew tasks --all, as I expected it to. But I could run those tasks.

It only seemed to make buildRelease and buildDebug, not e.g. assembleRelease etc

buildRelease didn't seem to depend on anything when run so therefore had no useful effect.

Iterating tasks?

As a final attempt I've tried to create all of the appropriate tasks and linking the dependencies for everything. I tried iterating over the tasks and adding the dependencies:

gradle.taskGraph.whenReady { taskGraph ->

    taskGraph.allTasks.each { taskIter ->

        println("iterating" + taskIter)

        def releaseTask = project.task(taskIter.name + "Release")
        def debugTask = project.task(taskIter.name + "Debug")

        taskIter.dependsOn += [releaseTask, debugTask].toSet()
        println("new taskIter.dependsOn:" + taskIter.dependsOn)

        /*
            set debug mode here,
            copy over effects of task to debug/release
            disable effects of task
        */
    }
}

but

This didn't seem to create the tasks properly, they weren't accessible from the command line and running "build" didn't run "buildRelease" etc.

I would also have to "move" all of the "actions" from the current, existing tasks and into the debug and release tasks, to avoid duplicating the effects of each. And I don't know how to do that.

In short, I have no idea what I'm doing. As a last resort I could just create all of the tasks manually, but that seems to defeat the point of using the the java plugin and is very spammy?

Body:
Not sure but perhaps my gradle-java-flavours plugin could help here. Eg:

plugins {
    id "com.lazan.javaflavours" version "1.2"
}
javaFlavours {
    flavour 'debug'
    flavour 'release'
}
debugJar {
    version = "${project.version}-debug"
}
releaseJar {
    version = "${project.version}-release"
}

Each flavour gets it's own Jar and JavaCompile tasks etc and you can specify custom sources, resources, tests, dependencies for each flavour too.

See here for a bit more overview on the tasks, directories and configurations avaliable and here for a test which covers the functionality.

This approach differes from your GradleBuild style since the "flavours" can happily live together in a single project which builds multiple artifacts rather than running a project twice with two different parameters.


答:
try reading the csv file like this

```<code>data = read.csv(".data/ab.csv",sep="\t")
</code>```

Your csv uses \t to separate each value, using the sep pararmeter you have to specify the separator when opening it

Title: Export Python dataframe into CSV

Body:
try reading the csv file like this

data = read.csv(".data/ab.csv",sep="\t")

Your csv uses \t to separate each value, using the sep pararmeter you have to specify the separator when opening it


问:
How to calculate number of days from a specified data till today?
Hi i have a database something lile this:

custId   gender  firstdate  fisrtregion  lastdate  buytime

abc         m       yymmdd     xws          yymmdd

qwe         f       yymmdd     rty          yymmdd    1

dfg         m       yymmdd     rew          yymmdd    1

and i need to find days between last  purchase date till today.
how can i do it.

答:
I believe you need:</p>

```<code>print (df)
  custId gender firstdate fisrtregion lastdate buytime
0    abc      m    yymmdd         xws   171014       9
1    qwe      f    yymmdd         rty   171116       1
2    dfg      m    yymmdd         rew   171115       1

#convert to datetimes if necessary
df['lastdate'] = pd.to_datetime(df['lastdate'], format='%y%m%d')
print (df)
  custId gender firstdate fisrtregion   lastdate buytime
0    abc      m    yymmdd         xws 2017-10-14       9
1    qwe      f    yymmdd         rty 2017-11-16       1
2    dfg      m    yymmdd         rew 2017-11-15       1

#subtract today with last value in column lastdate
d1 = (pd.to_datetime('today') - df.iloc[-1, df.columns.get_loc('lastdate')]).days
print (d1)
20

#diference with max datetime
d2 = (pd.to_datetime('today') - df['lastdate'].max()).days
print (d2)
19

#subtract today with column lastdate and convert timedeltas to days
df['new'] = (pd.to_datetime('today') - df['lastdate']).dt.days
print (df)
  custId gender firstdate fisrtregion   lastdate buytime  new
0    abc      m    yymmdd         xws 2017-10-14       9   52
1    qwe      f    yymmdd         rty 2017-11-16       1   19
2    dfg      m    yymmdd         rew 2017-11-15       1   20
</code>```

Body:
I believe you need:

print (df)
  custId gender firstdate fisrtregion lastdate buytime
0    abc      m    yymmdd         xws   171014       9
1    qwe      f    yymmdd         rty   171116       1
2    dfg      m    yymmdd         rew   171115       1

#convert to datetimes if necessary
df['lastdate'] = pd.to_datetime(df['lastdate'], format='%y%m%d')
print (df)
  custId gender firstdate fisrtregion   lastdate buytime
0    abc      m    yymmdd         xws 2017-10-14       9
1    qwe      f    yymmdd         rty 2017-11-16       1
2    dfg      m    yymmdd         rew 2017-11-15       1

#subtract today with last value in column lastdate
d1 = (pd.to_datetime('today') - df.iloc[-1, df.columns.get_loc('lastdate')]).days
print (d1)
20

#diference with max datetime
d2 = (pd.to_datetime('today') - df['lastdate'].max()).days
print (d2)
19

#subtract today with column lastdate and convert timedeltas to days
df['new'] = (pd.to_datetime('today') - df['lastdate']).dt.days
print (df)
  custId gender firstdate fisrtregion   lastdate buytime  new
0    abc      m    yymmdd         xws 2017-10-14       9   52
1    qwe      f    yymmdd         rty 2017-11-16       1   19
2    dfg      m    yymmdd         rew 2017-11-15       1   20


问:
Insert two comma splitted fields as rows to temp table at once
I am trying to insert two variables into same temp table at once but facing syntax error.

SQL Server Version used is 2012. Any possible ways of implementing this would be greatly appreciated.
I would prefer support with Azure and Server 2012 as well.

SOURCE DATA:

```<code>VARCHAR(MAX) ProgramName  AS 'SP1, SP2, SP3'
INT ProgramId AS 12,13,14
Id = Identity Column (TO be auto generated with init as 1 and seed as 1)
</code>```

DESIRED OUTPUT:

```<code>Id ---- ProgramName  --- ProgramId

1  ------ SP1   ---------  12

2 ------- SP2   ---------  13

3 ------- SP3   ---------- 14
</code>```

TRIED CODE:

```<code>IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable;

CREATE TABLE #tempTable (
Id          INT IDENTITY(1,1),
ProgramName VARCHAR(50) NULL,
ProgramId   INT  NULL);

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @InsertStatement varchar(max) = 'insert into
#tempTable(ProgramName,ProgramId)
        values ('+REPLACE(@string,',',','+REPLACE(@new,',','),(')+',(')++')';
PRINT(@InsertStatement)
EXECUTE (@InsertStatement);

SELECT * FROM #tempTable;
</code>```

答:
Try this</p>

```<code>IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable;

CREATE TABLE #tempTable
(
    Id          INT IDENTITY(1,1),
    ProgramName VARCHAR(50) NULL,
    ProgramId   INT  NULL
);

declare @t as table
(
    seqno int identity(1,1),
    ProgramId   INT  NULL
)

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @sql1 varchar(max) = 'SELECT '''+REPLACE(@string,',',''' UNION ALL SELECT ''')+''''
DECLARE @sql2 varchar(max) = 'SELECT '''+REPLACE(@new,',',''' UNION ALL SELECT ''')+''''

PRINT(@sql1)
PRINT(@sql2)

insert into #tempTable(ProgramName)
exec(@sql1)

insert into @t(ProgramId)
exec(@sql2)

update a
set
ProgramId = b.ProgramId
from #tempTable a
inner join @t b
on a.Id = b.seqno

SELECT * FROM #tempTable;
</code>```

Body:
I am trying to insert two variables into same temp table at once but facing syntax error.

SQL Server Version used is 2012. Any possible ways of implementing this would be greatly appreciated.
I would prefer support with Azure and Server 2012 as well.

SOURCE DATA:

VARCHAR(MAX) ProgramName  AS 'SP1, SP2, SP3'
INT ProgramId AS 12,13,14
Id = Identity Column (TO be auto generated with init as 1 and seed as 1)

DESIRED OUTPUT:

Id ---- ProgramName  --- ProgramId

1  ------ SP1   ---------  12

2 ------- SP2   ---------  13

3 ------- SP3   ---------- 14

TRIED CODE:

IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable;

CREATE TABLE #tempTable (
Id          INT IDENTITY(1,1),
ProgramName VARCHAR(50) NULL,
ProgramId   INT  NULL);

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @InsertStatement varchar(max) = 'insert into
#tempTable(ProgramName,ProgramId)
        values ('+REPLACE(@string,',',','+REPLACE(@new,',','),(')+',(')++')';
PRINT(@InsertStatement)
EXECUTE (@InsertStatement);

SELECT * FROM #tempTable;

Body:
Try this

IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable;

CREATE TABLE #tempTable
(
    Id          INT IDENTITY(1,1),
    ProgramName VARCHAR(50) NULL,
    ProgramId   INT  NULL
);

declare @t as table
(
    seqno int identity(1,1),
    ProgramId   INT  NULL
)

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @sql1 varchar(max) = 'SELECT '''+REPLACE(@string,',',''' UNION ALL SELECT ''')+''''
DECLARE @sql2 varchar(max) = 'SELECT '''+REPLACE(@new,',',''' UNION ALL SELECT ''')+''''

PRINT(@sql1)
PRINT(@sql2)

insert into #tempTable(ProgramName)
exec(@sql1)

insert into @t(ProgramId)
exec(@sql2)

update a
set
ProgramId = b.ProgramId
from #tempTable a
inner join @t b
on a.Id = b.seqno

SELECT * FROM #tempTable;


问:
Angular5 RequestOptionsArgs search & param what is the difference?
Learning Angular.... below is a simple practice http.get request

```<code>let params = new URLSearchParams();
params.set('term', term);
params.set('media', 'music');
params.set('limit', '20');

let promise = new Promise((resolve, reject)=> {
  this.http.get(this.apiRoot, {params})
      .toPromise()
      .then(
        res => {
            console.log(res.json());
          }
      )
});
return promise;
</code>```

I get this following error:

Argument of type '{ params: URLSearchParams; }' is not assignable to parameter of type 'RequestOptionsArgs'.
  Object literal may only specify known properties, and 'params' does not exist in type 'RequestOptionsArgs'.

If I change params to search the error goes away but when I check the docs https://angular.io/api/http/RequestOptionsArgs#params  both search and params are URLSearchParams type...

What is the difference between these two attributes?  How to properly use them?  why are there two?

Thank you

答:
Properly use:</p>

```<code>let params = new URLSearchParams();
params.set('term', term);
params.set('media', 'music');
params.set('limit', '20');

let promise = new Promise((resolve, reject)=> {
  this.http.get(this.apiRoot, {search: params})
      .toPromise()
      .then(
        res => {
            console.log(res.json());
          }
      )
});
return promise;
</code>```

Body:
Learning Angular.... below is a simple practice http.get request

let params = new URLSearchParams();
params.set('term', term);
params.set('media', 'music');
params.set('limit', '20');

let promise = new Promise((resolve, reject)=> {
  this.http.get(this.apiRoot, {params})
      .toPromise()
      .then(
        res => {
            console.log(res.json());
          }
      )
});
return promise;

I get this following error:

Argument of type '{ params: URLSearchParams; }' is not assignable to parameter of type 'RequestOptionsArgs'.
  Object literal may only specify known properties, and 'params' does not exist in type 'RequestOptionsArgs'.

If I change params to search the error goes away but when I check the docs https://angular.io/api/http/RequestOptionsArgs#params  both search and params are URLSearchParams type...

What is the difference between these two attributes?  How to properly use them?  why are there two?

Thank you

Body:
Properly use:

let params = new URLSearchParams();
params.set('term', term);
params.set('media', 'music');
params.set('limit', '20');

let promise = new Promise((resolve, reject)=> {
  this.http.get(this.apiRoot, {search: params})
      .toPromise()
      .then(
        res => {
            console.log(res.json());
          }
      )
});
return promise;


问:
How do I replace a message body programmatically in Smalltalk?
As part of some testing, I'm looking to, temporarily, replace the contents of a message with one that will return a predictable set of test values. What is the standard Smalltalk-y way to do this type of work? Is there some sample code for me to look at?

Some clarification:

No, this is not a simple unit test. I'm testing a large, complex, system.

Replacing the whole object at runtime is impractical. Significant accumulated state would have to be twiddled by the test, beyond replacing the method.

Subclassing and replacing one method doesn't generalize. I'm testing dozens of similar classes and thousands of objects. Filling up the class hierarchy with tiny one method classes, one for each test-case, would really suck - and it would suck even more to have to update them if I change my test case.

Here's some pseudocode for what I'm looking to write:

```<code>replaceMessage: 'fibonacci'
       onClass: 'funFunctions'
          with: 'returnsPredictableNumbersWithoutCalculatingThem'.

self runTestSet1.

restoreMessage: 'fibonacci'
       onClass: 'funFunctions'.

self runFollowUpSet1. "Depends on state set by Set1"

replaceMessage: 'fibonacci'
       onClass: 'funFunctions'
          with: 'returnsPredictableNumbersWithoutCalculatingThemPart2'.

self runFollowUpSet2. "Depends on state set by followupset1"

restoreMessage: 'fibonacci'
       onClass: 'funFunctions'.
</code>```

答: Maybe MethodWrappers - ECOOP paper Wrappers to the Rescue

Body:
As part of some testing, I'm looking to, temporarily, replace the contents of a message with one that will return a predictable set of test values. What is the standard Smalltalk-y way to do this type of work? Is there some sample code for me to look at?

Some clarification:

No, this is not a simple unit test. I'm testing a large, complex, system.

Replacing the whole object at runtime is impractical. Significant accumulated state would have to be twiddled by the test, beyond replacing the method.

Subclassing and replacing one method doesn't generalize. I'm testing dozens of similar classes and thousands of objects. Filling up the class hierarchy with tiny one method classes, one for each test-case, would really suck - and it would suck even more to have to update them if I change my test case.

Here's some pseudocode for what I'm looking to write:

replaceMessage: 'fibonacci'
       onClass: 'funFunctions'
          with: 'returnsPredictableNumbersWithoutCalculatingThem'.

self runTestSet1.

restoreMessage: 'fibonacci'
       onClass: 'funFunctions'.

self runFollowUpSet1. "Depends on state set by Set1"

replaceMessage: 'fibonacci'
       onClass: 'funFunctions'
          with: 'returnsPredictableNumbersWithoutCalculatingThemPart2'.

self runFollowUpSet2. "Depends on state set by followupset1"

restoreMessage: 'fibonacci'
       onClass: 'funFunctions'.


问:
Merge two LinkedHashMap in Scala

Having this code

```<code>def mergeWith[K, X, Y, Z](xs: mutable.LinkedHashMap[K, X], ys: mutable.LinkedHashMap[K, Y])(f: (X, Y) => Z): mutable.LinkedHashMap[K, Z] =
  xs.flatMap {
    case (k, x) => ys.get(k).map(k -> f(x, _))
  }
</code>```

it gives me this:

```<code>val map1 = LinkedHashMap(4 -> (4), 7 -> (4,7))
val map2 = LinkedHashMap(3 -> (3), 6 -> (3,6), 7 -> (3,7))

val merged = mergeWith(map1,map2){ (x, y) => (x, y) }
merged: scala.collection.mutable.LinkedHashMap[Int,(Any, Any)] = Map(7 -> ((4,7),(3,7)))
</code>```

But what i want is this:

```<code>merged: scala.collection.mutable.LinkedHashMap[Int,(Any, Any)] = Map(3 -> (3), 4 -> (4), 6 -> (3,6), 7 -> ((4,7),(3,7)))
</code>```

How to modify my code to obtain it?

答:
It can't be done with the current mergeWith() signature. In particular, you're trying to create a LinkedHashMap[K,Z] but there is no Z input. The only way to get a Z is to invoke f() which requires both X and Y as passed parameters.

So if xs is type LinkedHashMap[Int,Char] and has element (2 -> 'w'), and ys is type LinkedHashMap[Int,Long] and has element (8 -> 4L), how are you going to invoke f(c:Char, l:Long) so that you have a [K,Z] entry for both keys 2 and 8? Not possible.

If the mergeWith() signature can be simplified you might do something like this.

```<code>def mergeWith[K,V](xs: collection.mutable.LinkedHashMap[K, V]
                  ,ys: collection.mutable.LinkedHashMap[K, V]
                  )(f: (V, V) => V): collection.mutable.LinkedHashMap[K,V] = {
  val ns = collection.mutable.LinkedHashMap[K,V]()
  (xs.keySet ++ ys.keySet).foreach{ k =>
    if (!xs.isDefinedAt(k)) ns.update(k, ys(k))
    else if (!ys.isDefinedAt(k)) ns.update(k, xs(k))
    else ns.update(k, f(xs(k), ys(k)))
  }
  ns
}
</code>```

This produces the desired result for the example you've given, but it has a number of undesirable qualities, not the least of which is the mutable data structures.

BTW, there is no such thing as a Tuple1 so (4) is the same thing as 4. And whenever you see type Any, it's a pretty good sign that your design needs a re-think.

Title: Merge two LinkedHashMap in Scala

Body:
Having this code

def mergeWith[K, X, Y, Z](xs: mutable.LinkedHashMap[K, X], ys: mutable.LinkedHashMap[K, Y])(f: (X, Y) => Z): mutable.LinkedHashMap[K, Z] =
  xs.flatMap {
    case (k, x) => ys.get(k).map(k -> f(x, _))
  }

it gives me this:

val map1 = LinkedHashMap(4 -> (4), 7 -> (4,7))
val map2 = LinkedHashMap(3 -> (3), 6 -> (3,6), 7 -> (3,7))

val merged = mergeWith(map1,map2){ (x, y) => (x, y) }
merged: scala.collection.mutable.LinkedHashMap[Int,(Any, Any)] = Map(7 -> ((4,7),(3,7)))

But what i want is this:

merged: scala.collection.mutable.LinkedHashMap[Int,(Any, Any)] = Map(3 -> (3), 4 -> (4), 6 -> (3,6), 7 -> ((4,7),(3,7)))

How to modify my code to obtain it?

Body:
It can't be done with the current mergeWith() signature. In particular, you're trying to create a LinkedHashMap[K,Z] but there is no Z input. The only way to get a Z is to invoke f() which requires both X and Y as passed parameters.

So if xs is type LinkedHashMap[Int,Char] and has element (2 -> 'w'), and ys is type LinkedHashMap[Int,Long] and has element (8 -> 4L), how are you going to invoke f(c:Char, l:Long) so that you have a [K,Z] entry for both keys 2 and 8? Not possible.

If the mergeWith() signature can be simplified you might do something like this.

def mergeWith[K,V](xs: collection.mutable.LinkedHashMap[K, V]
                  ,ys: collection.mutable.LinkedHashMap[K, V]
                  )(f: (V, V) => V): collection.mutable.LinkedHashMap[K,V] = {
  val ns = collection.mutable.LinkedHashMap[K,V]()
  (xs.keySet ++ ys.keySet).foreach{ k =>
    if (!xs.isDefinedAt(k)) ns.update(k, ys(k))
    else if (!ys.isDefinedAt(k)) ns.update(k, xs(k))
    else ns.update(k, f(xs(k), ys(k)))
  }
  ns
}

This produces the desired result for the example you've given, but it has a number of undesirable qualities, not the least of which is the mutable data structures.

BTW, there is no such thing as a Tuple1 so (4) is the same thing as 4. And whenever you see type Any, it's a pretty good sign that your design needs a re-think.


问:
How to edit this text file as merged information with same headers
I have a huge text file with data like this:-

```<code>EAST DUBBO - Unknown
EAST MAITLAND - 1892
EAST MAITLAND - 1902
EAST MAITLAND - 1920
EAST MAITLAND - 1937
EAST MAITLAND - 1940
EAST MAITLAND - 1956
EBOR - 1905
EBOR - 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920
ELONG ELONG - 1955
</code>```

and I need it to be in this format:-

```<code>EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955
</code>```

It will take days to do by hand so i'm wondering if it can be solved programmatically or if there is an online tool?

答:
```<code>awk -F'-' -v OFS='-' '{a[$1]=(a[$1]=="")?$2:a[$1]","$2}END{PROCINFO["sorted_in"]="@ind_str_asc";for(i in a)print i,a[i]}' file
EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 195
</code>```

Brief explanation,

-F'-' -v OFS='-': set both input and output field separator as '-'

a[$1]=(a[$1]=="")?$2:a[$1]","$2: set $1 as the key in the array, $2 as the value. if a[$1] is already set, append it to a[$1].

PROCINFO["sorted_in"]="@ind_str_asc": this is gawk used only, used to order by indices in ascending order compared as strings

Body:
I have a huge text file with data like this:-

EAST DUBBO - Unknown
EAST MAITLAND - 1892
EAST MAITLAND - 1902
EAST MAITLAND - 1920
EAST MAITLAND - 1937
EAST MAITLAND - 1940
EAST MAITLAND - 1956
EBOR - 1905
EBOR - 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920
ELONG ELONG - 1955

and I need it to be in this format:-

EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955

It will take days to do by hand so i'm wondering if it can be solved programmatically or if there is an online tool?

Body:
awk -F'-' -v OFS='-' '{a[$1]=(a[$1]=="")?$2:a[$1]","$2}END{PROCINFO["sorted_in"]="@ind_str_asc";for(i in a)print i,a[i]}' file
EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 195

Brief explanation,

-F'-' -v OFS='-': set both input and output field separator as '-'

a[$1]=(a[$1]=="")?$2:a[$1]","$2: set $1 as the key in the array, $2 as the value. if a[$1] is already set, append it to a[$1].

PROCINFO["sorted_in"]="@ind_str_asc": this is gawk used only, used to order by indices in ascending order compared as strings


问:
Keep selection on initial row after closing popup Dynpro
I'm working with dynpros and ALV-tables in my ABAP-Report. When I'm selecting an specific row, and clicking on an button for an specific event, an dynpro is beeing called. After closing the dynpro I want to select the same row as in the beginning. How can I set the property to select that specific row in abap?</p>

答:
After the Dynpro is closed, the ALV Grid is displayed again.

You need to set the layout with the selected row in your layout and call the same function module you used previously.

Sample Algorithm:

Display ALV

Trigger Event

Display ALV


问:
How to use preprocessor directives inside a MENU in MFC .rc file?
I want to be able to dynamically change code in my resource file depending on which version of my app is being ran. For example, I have an about menu. I would like the about menuitem to have a different description based on a preprocessor directive. The issue I have is I am able to add the code in. But when I edit the resource file and save it, the .aps file overwrites my preprocessor directives. How can I get around this? The code below is an example of what I would like to have in my resource script.

```<code>IDR_EXAMPLE_MENU MENU
BEGIN

/*

Other Menu items

*/

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
#ifdef TEST_APP
    MENUITEM "&About TEST...",               ID_APP_ABOUT
#else
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
#endif
    END
END
</code>```

If I am running the TEST version I would like it to display "About TEST" in the menuitem and if it the RELEASE version I would like it to display "About RELEASE"
How can I add code like this to my resource file without having the .aps file overwrite the preprocessor directives when saving the .rc file?

Edit: This explains how files are affected by resource editing.

答:
It is also possible to have one resource like e menu twice inside your resource file.

Each resource can have a condition in its properties. And you can have a resource with the same name twice in your resources.

You may add the condition _DEBUG to the first resource. Just copy it and give the the condition _RELEASE. Rename it back to the same Id.

Body:
I want to be able to dynamically change code in my resource file depending on which version of my app is being ran. For example, I have an about menu. I would like the about menuitem to have a different description based on a preprocessor directive. The issue I have is I am able to add the code in. But when I edit the resource file and save it, the .aps file overwrites my preprocessor directives. How can I get around this? The code below is an example of what I would like to have in my resource script.

IDR_EXAMPLE_MENU MENU
BEGIN

/*

Other Menu items

*/

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
#ifdef TEST_APP
    MENUITEM "&About TEST...",               ID_APP_ABOUT
#else
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
#endif
    END
END

If I am running the TEST version I would like it to display "About TEST" in the menuitem and if it the RELEASE version I would like it to display "About RELEASE"
How can I add code like this to my resource file without having the .aps file overwrite the preprocessor directives when saving the .rc file?

Edit: This explains how files are affected by resource editing.


问:
Lock-free "decrement if not zero"
I'm currently reinventing the wheel of a thread pool in C++. I've eliminated almost all locks from the code, except for multiple instances of the following construct:

```<code>std::atomic_size_t counter;

void produce() {
    ++counter;
}

void try_consume() {
    if (counter != 0) {
        --counter;
        // ...
    }
    else {
        // ...
    }
}
</code>```

So, I need a thread-safe lock-free version of this function:

```<code>bool take(std::atomic_size_t& value) {
    if (value != 0) {
        --value;
        return true;
    }
    return false;
}
</code>```

There is one solution that I know of: use boost::lockfree::queue<std::monostate>, where pop() does the job. Is there any better/faster solution?

答:
The construct you're implementing is a counting lock, or counting semaphore. Use one from a library that has a trylock version instead of rolling your own, so you can get optimized OS-supported sleep / wakeup. Or do you always have useful work to do if the trylock (aka take) fails?

Note that you can avoid using any traditional locks while implementing your own, but "lock free" is a technical term with a different meaning than lockless.  A consumer almost by definition can't be lock-free in the computer-science sense, because it can be stuck waiting forever if the producer thread(s) are blocked.  Related: Lock-free Progress Guarantees

CAS is good.  Just make sure that your function doesn't run compare_exchange_weak at all if it sees the counter already 0 with a pure load (typically with memory_order_relaxed).  You don't want your CPU hammering on the location while other threads are trying to increment it so your thread will see a non-zero value.

Another option is a signed counter, and change the compare to >= 0.  Check for overshoot in the result of fetch_add(-1), and if so correct it.  (Threads that see the counter as temporarily negative just see it "locked").  But this is typically not better than a CAS retry loop; failed CAS is rare unless contention is very high.  And extra atomic ops to correct overshoot will probably cost about as much (or more) than CAS retries.

Title: Lock-free "decrement if not zero"

Body:
I'm currently reinventing the wheel of a thread pool in C++. I've eliminated almost all locks from the code, except for multiple instances of the following construct:

std::atomic_size_t counter;

void produce() {
    ++counter;
}

void try_consume() {
    if (counter != 0) {
        --counter;
        // ...
    }
    else {
        // ...
    }
}

So, I need a thread-safe lock-free version of this function:

bool take(std::atomic_size_t& value) {
    if (value != 0) {
        --value;
        return true;
    }
    return false;
}

There is one solution that I know of: use boost::lockfree::queue<std::monostate>, where pop() does the job. Is there any better/faster solution?


问:
Run code every day at a specific time - AlarmManager
Currently, I am trying to run a piece of code at a specific time. After some research, I think the correct way to go is to make usage of the AlarmManger. The code should be executed every day at 3 am. If the phone is at 3 am shut down, the code should be executed directly after turning the phone on.

I used googled and found a lot of results. But my code isn't working correctly.

Yesterday I got a notification. The notification time was 10 pm. But in the code, the time is set to 3 am. I set up a lot of alarm manager over the time (because of testing). Could it be possible, that the triggered AlarmManager was an old one? Note: Before setting up a new AlarmManager I deleted the complete application from my phone and installed it new. (I think this will delete all set AlarmManager's?)

Okay, here is the code I am using:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 0);
calendar.add(Calendar.MINUTE, 0);
calendar.add(Calendar.HOUR, 3);

Intent _myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
_myIntent.putExtra("MyMessage","Content of the message");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 123, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60*24, pendingIntent);```

This code will be executed on every startup of my app (inside MainActivity's onCreate(); method).

答:
I think this is due to the fact, that the Power Manager causes Problems with the App Actvivity.

Try using the Power Manager

PARTIAL_WAKE_LOCK

added in API level 1
  int PARTIAL_WAKE_LOCK
  Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.

If the user presses the power button, then the screen will be turned off but the CPU will be kept on until all partial wake locks have been released.

Constant Value: 1 (0x00000001)

This is just an assumption, if it still doesnt work, could you post some Logs or more code snippets of the activity :)

Example:

```<code>//Initialize the Power Manager
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

 //Create a PARTIAL_WAKE_LOCK
 //This will keep the cpu running in the Background, so that the function will be called on the desired Time
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");

//Check if the WackLock is held (may throw erro if you try to acquire twice)
//TRUE --> Do nothing, all good
//FALSE --> Acquire the WakeLock
 if(!wl.isHeld()){
    wl.acquire();
 }

//*****
//You code for the repeating task goes Here
//*****

//If the Repeating task is not active, release the Lock

//Check if the WackLock is held (may throw error if you try to release a none acquired Lock)
//TRUE --> Release Lock
//FALSE --> Do nothing, all good
 if(wl.isHeld()){
    wl.release();
 }
</code>```

Body:
Currently, I am trying to run a piece of code at a specific time. After some research, I think the correct way to go is to make usage of the AlarmManger. The code should be executed every day at 3 am. If the phone is at 3 am shut down, the code should be executed directly after turning the phone on.

I used googled and found a lot of results. But my code isn't working correctly.

Yesterday I got a notification. The notification time was 10 pm. But in the code, the time is set to 3 am. I set up a lot of alarm manager over the time (because of testing). Could it be possible, that the triggered AlarmManager was an old one? Note: Before setting up a new AlarmManager I deleted the complete application from my phone and installed it new. (I think this will delete all set AlarmManager's?)

Okay, here is the code I am using:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 0);
calendar.add(Calendar.MINUTE, 0);
calendar.add(Calendar.HOUR, 3);

Intent _myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
_myIntent.putExtra("MyMessage","Content of the message");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 123, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60*24, pendingIntent);

This code will be executed on every startup of my app (inside MainActivity's onCreate(); method).

Body:
I think this is due to the fact, that the Power Manager causes Problems with the App Actvivity.

Try using the Power Manager

PARTIAL_WAKE_LOCK

added in API level 1
  int PARTIAL_WAKE_LOCK
  Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.

If the user presses the power button, then the screen will be turned off but the CPU will be kept on until all partial wake locks have been released.

Constant Value: 1 (0x00000001)

This is just an assumption, if it still doesnt work, could you post some Logs or more code snippets of the activity :)

Example:

//Initialize the Power Manager
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

 //Create a PARTIAL_WAKE_LOCK
 //This will keep the cpu running in the Background, so that the function will be called on the desired Time
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");

//Check if the WackLock is held (may throw erro if you try to acquire twice)
//TRUE --> Do nothing, all good
//FALSE --> Acquire the WakeLock
 if(!wl.isHeld()){
    wl.acquire();
 }

//*****
//You code for the repeating task goes Here
//*****

//If the Repeating task is not active, release the Lock

//Check if the WackLock is held (may throw error if you try to release a none acquired Lock)
//TRUE --> Release Lock
//FALSE --> Do nothing, all good
 if(wl.isHeld()){
    wl.release();
 }


问:
Selecting from Datatable , Grouped by multiple Column with condition
I have a datatable which has 4 fields in it.

```<code> ptime, Substation, ColumnTitle, ValueAmount
</code>```

I want to have the row with the maximum ValueAmount , Grouped by Substation and ColumnTitle. So suppose this is my datatable

```<code> ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '01:00'    'AA'       'A'          100
 '03:00'    'AA'       'A'          150
 '01:00'    'BB'       'A'          10
 '02:00'    'BB'       'A'          11
 '01:00'    'AA'       'C'          77
 '02:00'    'AA'       'C'          88
 '04:00'    'AA'       'C'          99
</code>```

So I want to have

```<code>   ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '03:00'    'AA'       'A'          150
 '02:00'    'BB'       'A'          11
 '04:00'    'AA'       'C'          99
</code>```

what is the best linq command for this purpose?
I have programmed this:

```<code> var newSort = from row in dtFinal.AsEnumerable()
   group row by new  {Substation = row.Field<string>("Substation"),
            ColumnTitle= row.Field<string>("ColumnTitle")} into grp
   select new
   {
     Substation = grp.Key.Substation,
     ColumnTitle = grp.Key.ColumnTitle,
     ValueAmount = grp.Max(r => decimal.Parse(r.Field<string>("ValueAmount")))
   };
</code>```

but in this syntax I don't have ptime for that. How can I do that.

Thank you

答:
You can order the group by this value descending to get the "MaxRow", there you find the ptime:

```<code>var newSort = dtFinal.AsEnumerable()
    .GroupBy(row => new
    {
        Substation = row.Field<string>("Substation"),
        ColumnTitle = row.Field<string>("ColumnTitle")
    })
    .Select(g => new
    {
        g.Key.Substation,
        g.Key.ColumnTitle,
        MaxRow = g.OrderByDescending(row => decimal.Parse(row.Field<string>("ValueAmount"))).First()
    })
    .Select(x => new
    {
        ptime = x.MaxRow.Field<string>("ptime"), // voilà
        x.Substation,
        x.ColumnTitle,
        ValueAmount = decimal.Parse(x.MaxRow.Field<string>("ValueAmount"))
    });
</code>```

Since you used query syntax, in this case it's really more readable thanks to the let:

```<code>var newSort = from row in dtFinal.AsEnumerable()
  let xRow = new { Row = row, valueAmount = decimal.Parse(row.Field<string>("ValueAmount")) }
  group xRow by new
  {
     Substation = row.Field<string>("Substation"),
     ColumnTitle = row.Field<string>("ColumnTitle")
  } into grp
  let maxRow = grp.OrderByDescending(x => x.valueAmount).First()
  select new
  {
     ptime = maxRow.Row.Field<string>("ptime"),
     grp.Key.Substation,
     grp.Key.ColumnTitle,
     ValueAmount = maxRow.valueAmount
  };
</code>```

Body:
I have a datatable which has 4 fields in it.

 ptime, Substation, ColumnTitle, ValueAmount

I want to have the row with the maximum ValueAmount , Grouped by Substation and ColumnTitle. So suppose this is my datatable

 ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '01:00'    'AA'       'A'          100
 '03:00'    'AA'       'A'          150
 '01:00'    'BB'       'A'          10
 '02:00'    'BB'       'A'          11
 '01:00'    'AA'       'C'          77
 '02:00'    'AA'       'C'          88
 '04:00'    'AA'       'C'          99

So I want to have

   ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '03:00'    'AA'       'A'          150
 '02:00'    'BB'       'A'          11
 '04:00'    'AA'       'C'          99

what is the best linq command for this purpose?
I have programmed this:

 var newSort = from row in dtFinal.AsEnumerable()
   group row by new  {Substation = row.Field<string>("Substation"),
            ColumnTitle= row.Field<string>("ColumnTitle")} into grp
   select new
   {
     Substation = grp.Key.Substation,
     ColumnTitle = grp.Key.ColumnTitle,
     ValueAmount = grp.Max(r => decimal.Parse(r.Field<string>("ValueAmount")))
   };

but in this syntax I don't have ptime for that. How can I do that.

Thank you

Body:
You can order the group by this value descending to get the "MaxRow", there you find the ptime:

var newSort = dtFinal.AsEnumerable()
    .GroupBy(row => new
    {
        Substation = row.Field<string>("Substation"),
        ColumnTitle = row.Field<string>("ColumnTitle")
    })
    .Select(g => new
    {
        g.Key.Substation,
        g.Key.ColumnTitle,
        MaxRow = g.OrderByDescending(row => decimal.Parse(row.Field<string>("ValueAmount"))).First()
    })
    .Select(x => new
    {
        ptime = x.MaxRow.Field<string>("ptime"), // voilà
        x.Substation,
        x.ColumnTitle,
        ValueAmount = decimal.Parse(x.MaxRow.Field<string>("ValueAmount"))
    });

Since you used query syntax, in this case it's really more readable thanks to the let:

var newSort = from row in dtFinal.AsEnumerable()
  let xRow = new { Row = row, valueAmount = decimal.Parse(row.Field<string>("ValueAmount")) }
  group xRow by new
  {
     Substation = row.Field<string>("Substation"),
     ColumnTitle = row.Field<string>("ColumnTitle")
  } into grp
  let maxRow = grp.OrderByDescending(x => x.valueAmount).First()
  select new
  {
     ptime = maxRow.Row.Field<string>("ptime"),
     grp.Key.Substation,
     grp.Key.ColumnTitle,
     ValueAmount = maxRow.valueAmount
  };


问:
unable to receive json to servlet post method
I was trying to send json data to my serlvlet. But when I try to receive that I got null. Below is my code. Where am I wrong? I don't understand.

index.jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function test(){
    var dataa={
             "otp":"abc",
             "email":"abcabc"
        };
    $.ajax({
       url: "AbcTest",
       type: 'POST',
       dataType: 'json',
       data:
       {    dataa: JSON.stringify(dataa)
          },
       contentType:'application/json; charset=utf-8',
       success: function (response) {
           console.log(JSON.stringify(response));
       },
       error: function(xhr, resp, text) {
          alert("error");
          console.log(xhr, resp, text);
       }
  });
}
</script>
</head>
<body>
<button onclick="test();">Submit</button>
</body>
</html>
</code>```

AbcTest Servlet

```<code>package org.abc.ussd;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AbcTest")
public class AbcTest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AbcTest() {
        super();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("dataa"));
    }
}
</code>```

I am getting null in dataa in servlet. How can I receive json data from jsp page to this servlet.

答:
I was able to resolve this issue when I change the content type to

```<code>contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
</code>```

I got below output in console

Body:
I was trying to send json data to my serlvlet. But when I try to receive that I got null. Below is my code. Where am I wrong? I don't understand.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<button onclick="test();">Submit</button>

AbcTest Servlet

package org.abc.ussd;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AbcTest")
public class AbcTest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AbcTest() {
        super();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("dataa"));
    }
}

I am getting null in dataa in servlet. How can I receive json data from jsp page to this servlet.

Body:
I was able to resolve this issue when I change the content type to

contentType: "application/x-www-form-urlencoded; charset=UTF-8;",

I got below output in console


问:
How can I get CSS selector for text wrapped in a paragraph under
 tag
I am trying to capture an URL in a mail paragraph using a Xpath selector (Xpath: html/body/p[2]/text()[3]). I could not get a proper css selector but with Xpath, I'm getting an error as given below when executing the Selenium webdriver test.

```<code><body>
<p>Dear EmailTest user,</p>
<p>
Your profile on the Swwebsite has been successfully created.
<br/>
To begin, click on the link below. You will be prompted to create a password during the login process.
<br/>
https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd
<br/>
After creating your password, you will be able to access your application with the below username:
<br/>
User Name emailuser_test
<br/>
</p>
</code>```

Getting the below error:

com.ibm.automation.wtf.driver.DriverException: TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element.

  Build info: version: '3.5.2', revision: '10229a9', time: '2017-08-21T17:29:55.15Z'

On some search over internet it seemed a Firefox issue with CSS. Can somebody help me here in fixing the issue or getting a proper CSS selector for capturing URL in the mail

System info: host: 'IBM345-R902EWZ3', ip: '9.162.252.164', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'

  Driver info: org.openqa.selenium.firefox.FirefoxDriver

答:
Java :

To capture the URL we will first capture the total text under the second
 tag, then split it once with positive lookaround to include https in the right hand side, then again split it again with positive lookaround to include After in the right hand side and finally print the remaining left hand part. To achieve this you can use the following block of code :

```<code>String myText = driver.findElement(By.xpath("//body//following::p[2]")).getAttribute("innerHTML");
String[] textParts = myText.split("(?=https)");
String mySubtext = textParts[1];
String[] subparts = mySubtext.split("(?=After)");
String text = subparts[0];
System.out.println(text);
</code>```

This prints the following on my console :

```<code>https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd
</code>```

Title: How can I get CSS selector for text wrapped in a paragraph under<p> tag

Body:
I am trying to capture an URL in a mail paragraph using a Xpath selector (Xpath: html/body/p[2]/text()[3]). I could not get a proper css selector but with Xpath, I'm getting an error as given below when executing the Selenium webdriver test.

Dear EmailTest user,

Your profile on the Swwebsite has been successfully created.

To begin, click on the link below. You will be prompted to create a password during the login process.

https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd

After creating your password, you will be able to access your application with the below username:

User Name emailuser_test

Getting the below error:

com.ibm.automation.wtf.driver.DriverException: TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element.

  Build info: version: '3.5.2', revision: '10229a9', time: '2017-08-21T17:29:55.15Z'

On some search over internet it seemed a Firefox issue with CSS. Can somebody help me here in fixing the issue or getting a proper CSS selector for capturing URL in the mail

System info: host: 'IBM345-R902EWZ3', ip: '9.162.252.164', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'

  Driver info: org.openqa.selenium.firefox.FirefoxDriver

Body:
Java :

To capture the URL we will first capture the total text under the second <p> tag, then split it once with positive lookaround to include https in the right hand side, then again split it again with positive lookaround to include After in the right hand side and finally print the remaining left hand part. To achieve this you can use the following block of code :

String myText = driver.findElement(By.xpath("//body//following::p[2]")).getAttribute("innerHTML");
String[] textParts = myText.split("(?=https)");
String mySubtext = textParts[1];
String[] subparts = mySubtext.split("(?=After)");
String text = subparts[0];
System.out.println(text);

This prints the following on my console :

https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd


问:
How to switch on default filters AND-ed together in odoo?
I have the following Action Window definition

```<code><field name="context">{
                'search_default_mine': 1,
                'search_default_current_year': 1,
   }</field>
</code>```

This gives me back the results where I'm the contact person (mine) or that were created this year (current_year). I would like to have the results that are mine AND were created this year. Can this be done without defining a new filter in the search view?

答:
Solution is very simple just add

```<code>   <separator/>
</code>```

beetwen filters

For example :

```<code> <filter name="first_filter" string="Black Products"
    domain="[('is_black', '=', True)]"/>
        <separator/>
 <filter name="secund_filter" string="Red Products"
    domain="[('is_red', '=', True)]"/>
</code>```

Body:
I have the following Action Window definition

<field name="context">{
                'search_default_mine': 1,
                'search_default_current_year': 1,
   }</field>

This gives me back the results where I'm the contact person (mine) or that were created this year (current_year). I would like to have the results that are mine AND were created this year. Can this be done without defining a new filter in the search view?

Body:
Solution is very simple just add

   <separator/>

beetwen filters

For example :

 <filter name="first_filter" string="Black Products"
    domain="[('is_black', '=', True)]"/>
        <separator/>
 <filter name="secund_filter" string="Red Products"
    domain="[('is_red', '=', True)]"/>