问:
Pivot Table No calculation
I have a simple dataset as follow:

```<code>Name    Question    Answer
A       Allergy     Y
A       Cancer      N
A       Flu         N
B       Allergy     Y
B       Cancer      Y
B       Flu         N
C       Allergy     N
C       Flu         N
</code>```

I would like to display it in the form (in excel)

```<code>      Allergy   Cancer Flu
A     Y            N   N
B     Y            Y   N
C     N                N
</code>```

And I wonder if using pivot table is the way to go. If not, is there a way to display data using my format above? Please note, the dataset I presented above is just a simplified version of a database with million records.

I tried to use Pivot Table in excel with Name in the Row, Question in the Column and Answer in the detail with calculation function Max. The results did not turn out as expected.

Please advise how I should tweak the results to get what I want. I do not need any calculation performed, just show the result as is. Possible?

答:
A pivot table needs numbers in the values area, so it is not the solution in this scenario.

If the source data table is sorted ascending by name, the result can be achieved with a formula. You can use a pivot table to create a list of unique names for the results table that starts in column E in the screenshot. Enter the column labels manually, then use the following formula in F3, copy down and across.

```<code>=VLOOKUP(G$2,INDEX($B:$B,MATCH($F3,$A:$A,0)):INDEX($C:$C,MATCH($F3,$A:$A,1)),2,FALSE)
</code>```

Title: Pivot Table No calculation

Body:
I have a simple dataset as follow:

Name    Question    Answer
A       Allergy     Y
A       Cancer      N
A       Flu         N
B       Allergy     Y
B       Cancer      Y
B       Flu         N
C       Allergy     N
C       Flu         N

I would like to display it in the form (in excel)

      Allergy   Cancer Flu
A     Y            N   N
B     Y            Y   N
C     N                N

And I wonder if using pivot table is the way to go. If not, is there a way to display data using my format above? Please note, the dataset I presented above is just a simplified version of a database with million records.

I tried to use Pivot Table in excel with Name in the Row, Question in the Column and Answer in the detail with calculation function Max. The results did not turn out as expected.

Please advise how I should tweak the results to get what I want. I do not need any calculation performed, just show the result as is. Possible?

Body:
A pivot table needs numbers in the values area, so it is not the solution in this scenario.

If the source data table is sorted ascending by name, the result can be achieved with a formula. You can use a pivot table to create a list of unique names for the results table that starts in column E in the screenshot. Enter the column labels manually, then use the following formula in F3, copy down and across.

=VLOOKUP(G$2,INDEX($B:$B,MATCH($F3,$A:$A,0)):INDEX($C:$C,MATCH($F3,$A:$A,1)),2,FALSE)


来源: stackexchange

问:
Session / Log tables keys design question
I have almost always heard people say not to use FKs with user session and any log tables as those are usually High write tables and once written data almost always tays forever without any updates or deletes.

But the question is I have colunms like these:
User_id (link a session or activity log to the user)
activity_id (linking the log activity table to the system activity lookup table)
session_id (linking the user log table with the parent session)
... and there are 4-5 more colunms.

So if I dont use FKs then how will i "relate" these colunms? Can i join tables and get the user info without FKs? Can i write correct data without FKs? Any performance impact or do people just talk and say this is a no no?

Another question I have is if i dont use FKs can i still connect my data with lookup tables?

答:
FK's can be detrimental in "history log" tables. This kind of table wants to preserve the exact state of what happened at a point in time.

The problem with FK's is they don't store the value, just a pointer to the value. If the value changes, then the history is lost. You DO NOT WANT updates to cascade into your history log. It's OK to have a "fake Foreign key" that you can join on, but you also want to intensionally de-normalize relevant fields to preserve the history.

ContentLicense: CC BY-SA 2.5


问:
Making background slide animation
I made a button group, and want when user select each button background of previous or next button move/slide to selected one, i made this effect with pure css and just used jquery to add or remove active class. now the problem is when you click on All button, then New it works fine, but if you click on Used the slide not work in right position.

For this effect i used transition and ::before, need to solve this with pure css or minimum jquery, not a lot of javascript or jquery codes.

The logic to move this background is:

```<code>.RadioButton .btn:first-child::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:nth-child(2)::before {
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}
</code>```

The problem on .RadioButton .btn:nth-child(2)::before i can't use right:0 or left:0 because if i use each one, the slide effect not work in right position, any solution?

What i tried so far:

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.RadioButton .btn::before {
    content: "";
    height: 100%;
    width: 0%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
}

.btn-active::before {
    width: 100%!important;
}

.RadioButton .btn:nth-child(2)::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn-active:first-child::before {
 left: 0;
 transition: .3s all ease;
}

.btn-active:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}</code>```

 Used
 New
 All

```

答:
Set only one after pseudo, on the last button.
Now, use sibbling selectors and the active class to move it to the left, as appropiate. (see the last 2 styles in the CSS)

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}

.RadioButton .btn:nth-child(3)::before {
    content: "";
    height: 100%;
    width: 100%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
    left: 0px;
}

.btn-active:first-child ~ .btn::before {
    transform: translateX(calc(-4px - 200%));
}
.btn-active:nth-child(2) ~ .btn::before {
    transform: translateX(calc(-2px - 100%));
}</code>```

 Used
 New
 All

```

ContentLicense: CC BY-SA 3.0

Title: Making background slide animation

Body:
I made a button group, and want when user select each button background of previous or next button move/slide to selected one, i made this effect with pure css and just used jquery to add or remove active class. now the problem is when you click on All button, then New it works fine, but if you click on Used the slide not work in right position.

For this effect i used transition and ::before, need to solve this with pure css or minimum jquery, not a lot of javascript or jquery codes.

The logic to move this background is:

.RadioButton .btn:first-child::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:nth-child(2)::before {
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}

The problem on .RadioButton .btn:nth-child(2)::before i can't use right:0 or left:0 because if i use each one, the slide effect not work in right position, any solution?

What i tried so far:

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});

body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.RadioButton .btn::before {
    content: "";
    height: 100%;
    width: 0%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
}

.btn-active::before {
    width: 100%!important;
}

.RadioButton .btn:nth-child(2)::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn-active:first-child::before {
 left: 0;
 transition: .3s all ease;
}

.btn-active:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}

 Used
 New
 All

Body:
Set only one after pseudo, on the last button.
Now, use sibbling selectors and the active class to move it to the left, as appropiate. (see the last 2 styles in the CSS)

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});

body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}

.RadioButton .btn:nth-child(3)::before {
    content: "";
    height: 100%;
    width: 100%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
    left: 0px;
}

.btn-active:first-child ~ .btn::before {
    transform: translateX(calc(-4px - 200%));
}
.btn-active:nth-child(2) ~ .btn::before {
    transform: translateX(calc(-2px - 100%));
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="RadioButton btn-group" id="searchType">
 <a class="btn btn-default" data-val="0">Used</a>
 <a class="btn btn-default" data-val="1">New</a>
 <a class="btn btn-default btn-active" data-val="2">All</a>
</div>


问:
Default invalid select option in Angular 2 model-driven forms?
Is there any way to achieve an invalid default select option in an Angular 2 model driven form?

I'm looking for something like this:

```<code><select name="DateExpiryMonth" [(ngModel)]="model.DateExpiryMonth" ngControl="dateExpiryMonth" required>
    <option value="" selected="selected" disabled>Month...</option>
    <option *ngFor="let month of months" [value]="month">{{ month }}</option>
</select>
</code>```

Ideally, the required attribute on the select would ensure that the first <option> would be considered invalid by Angular 2, yet I can't find any documentation that suggests this is possible.

As it stands, the first "Month..." option is considered valid by Angular 2.

答: I don't think this is an ideal solution, but I found that if I set the field in my model to either null or undefined (in your case model.dateExpiryMonth) that angular would consider the form invalid.

Body:
Is there any way to achieve an invalid default select option in an Angular 2 model driven form?

I'm looking for something like this:

<select name="DateExpiryMonth" [(ngModel)]="model.DateExpiryMonth" ngControl="dateExpiryMonth" required>
    <option value="" selected="selected" disabled>Month...</option>
    <option *ngFor="let month of months" [value]="month">{{ month }}</option>
</select>

Ideally, the required attribute on the select would ensure that the first <option> would be considered invalid by Angular 2, yet I can't find any documentation that suggests this is possible.

As it stands, the first "Month..." option is considered valid by Angular 2.


问:
Protractor: Count all hyperlinks and test them on a page
I am trying to count the number of hyperlinks on a page and test them to see if they work. I have the ability to count all the links and display that count in JavaScript but I can't seem to return that value in protractor on Command Line.

Update Code based on Answers:

```<code>browser.waitForAngularEnabled(false);
describe('Clicks on the correct Drupal hyperlink', function() {

  it('should find all links', function () {
    browser.get('file:///C:/Users/Dasman/Documents/PROTRACTOR_E2E_TESTING/TestSite.html');
    let allLinks = element.all(by.tagName('a'));
    allLinks.count().then(function(link_tally){
      console.log('There are a total of ' + link_tally + " links on this page with proper tags.")
    })
  browser.sleep(2000);

  // A Protracterized httpGet() promise
function httpGet(siteUrl) {
  var http = require('http');
  var defer = protractor.promise.defer();

  http.get(siteUrl, function(response) {

      var bodyString = '';

      response.setEncoding('utf8');

      response.on("data", function(chunk) {
          bodyString += chunk;
      });

      response.on('end', function() {
          defer.fulfill({
              statusCode: response.statusCode,
              bodyString: bodyString
          });
      });

  }).on('error', function(e) {
      defer.reject("Got http.get error: " + e.message);
  });

  return defer.promise;
}

it('should return 200 and contain proper body', function() {
  httpGet(allLinks).then(function(result) {
    allLinks.count().then(function(statusCode){
      console.log('Status code is: ' + statusCode)
    })
      expect(result.statusCode).toBe(200);
      expect(result.bodyString).toContain('Apache');
  });
});
    });
});
</code>```

In addition I want to "check" the links to see if they open. Is there a way to go to a URL and click all the links and have them open on separate windows? or get an attribute if the link works or has a valid URL?

I originally xpath the id and clicked the link and as the test ran - I visually verified. But with 15-20 links on a average page - I need a more automated way.

Ernst's answer pointed me to the solution, but it did need some code restructuring and encapsulation: https://github.com/SDasman/Angular_Protractor_End2End_Tests/tree/master/LinkCheck

答:
You can also try to get Text from each link and count all array element like this:</p>

```<code>var allLinks = element.all(By.tagName('a'));
allLinks.getText().then(function(findAllLink) {
var numberofLinks = findAllLink.length;
console.log(numberofLinks);
})
</code>```

Body:
I am trying to count the number of hyperlinks on a page and test them to see if they work. I have the ability to count all the links and display that count in JavaScript but I can't seem to return that value in protractor on Command Line.

Update Code based on Answers:

browser.waitForAngularEnabled(false);
describe('Clicks on the correct Drupal hyperlink', function() {

  it('should find all links', function () {
    browser.get('file:///C:/Users/Dasman/Documents/PROTRACTOR_E2E_TESTING/TestSite.html');
    let allLinks = element.all(by.tagName('a'));
    allLinks.count().then(function(link_tally){
      console.log('There are a total of ' + link_tally + " links on this page with proper tags.")
    })
  browser.sleep(2000);

  // A Protracterized httpGet() promise
function httpGet(siteUrl) {
  var http = require('http');
  var defer = protractor.promise.defer();

  http.get(siteUrl, function(response) {

      var bodyString = '';

      response.setEncoding('utf8');

      response.on("data", function(chunk) {
          bodyString += chunk;
      });

      response.on('end', function() {
          defer.fulfill({
              statusCode: response.statusCode,
              bodyString: bodyString
          });
      });

  }).on('error', function(e) {
      defer.reject("Got http.get error: " + e.message);
  });

  return defer.promise;
}

it('should return 200 and contain proper body', function() {
  httpGet(allLinks).then(function(result) {
    allLinks.count().then(function(statusCode){
      console.log('Status code is: ' + statusCode)
    })
      expect(result.statusCode).toBe(200);
      expect(result.bodyString).toContain('Apache');
  });
});
    });
});

In addition I want to "check" the links to see if they open. Is there a way to go to a URL and click all the links and have them open on separate windows? or get an attribute if the link works or has a valid URL?

I originally xpath the id and clicked the link and as the test ran - I visually verified. But with 15-20 links on a average page - I need a more automated way.

Ernst's answer pointed me to the solution, but it did need some code restructuring and encapsulation: https://github.com/SDasman/Angular_Protractor_End2End_Tests/tree/master/LinkCheck

Body:
You can also try to get Text from each link and count all array element like this:

var allLinks = element.all(By.tagName('a'));
allLinks.getText().then(function(findAllLink) {
var numberofLinks = findAllLink.length;
console.log(numberofLinks);
})


问:
Automatically set the primary key for one table as the foreign key for another?
I have two Django models:

```<code>class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=True)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id)

class seller_event_items(models.Model):
    item_id = models.AutoField(primary_key=True)
    event_id = models.ForeignKey(seller_event)
    item_name = models.CharField(max_length = 300, default = 'Null')
    item_price = models.CharField(max_length = 300, default = 'Null')
    item_quant = models.CharField(max_length = 300, default = 'Null')

    def __unicode__(self):
        return str(self.item_id)
</code>```

The foreign key for the second table is the primary key for the first table. Essentially, I am trying to associate items with a sale. I have a forms like such:

forms.py:

```<code>class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

class Seller_event_items(forms.ModelForm):

    class Meta:
        model = seller_event_items
        exclude = {'event_id'}
</code>```

views.py:

```<code>def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            seller_event_form = Seller_event(request.POST)
            seller_event_items_form = Seller_event_items(request.POST)
            if seller_event_form.is_valid() and seller_event_items_form.is_valid():
                new_seller_event = seller_event_form.save(commit=False)
                new_seller_event.user = user
                new_seller_event.save()
                seller_event_items_form.save()
                return redirect('/home')

        else:
            seller_event_form = Seller_event()
            seller_event_items_form = Seller_event_items()

        return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form})
</code>```

The form here is helping a seller both create a sale and then populate the sale with items.

How can I go about automatically setting the fk on the items table as the event_id (pk for seller_events table)? I have excluded it from the form, but I'm not sure what to do after this.

Thanks in advance!

答:
add this line before seller_event_items_form.save() when the model is saved
you can reference it as ForeignKey

```<code>seller_event_items.event_id = new_seller_event
</code>```

Body:
I have two Django models:

class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=True)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id)

class seller_event_items(models.Model):
    item_id = models.AutoField(primary_key=True)
    event_id = models.ForeignKey(seller_event)
    item_name = models.CharField(max_length = 300, default = 'Null')
    item_price = models.CharField(max_length = 300, default = 'Null')
    item_quant = models.CharField(max_length = 300, default = 'Null')

    def __unicode__(self):
        return str(self.item_id)

The foreign key for the second table is the primary key for the first table. Essentially, I am trying to associate items with a sale. I have a forms like such:

forms.py:

class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

class Seller_event_items(forms.ModelForm):

    class Meta:
        model = seller_event_items
        exclude = {'event_id'}

views.py:

def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            seller_event_form = Seller_event(request.POST)
            seller_event_items_form = Seller_event_items(request.POST)
            if seller_event_form.is_valid() and seller_event_items_form.is_valid():
                new_seller_event = seller_event_form.save(commit=False)
                new_seller_event.user = user
                new_seller_event.save()
                seller_event_items_form.save()
                return redirect('/home')

        else:
            seller_event_form = Seller_event()
            seller_event_items_form = Seller_event_items()

        return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form})

The form here is helping a seller both create a sale and then populate the sale with items.

How can I go about automatically setting the fk on the items table as the event_id (pk for seller_events table)? I have excluded it from the form, but I'm not sure what to do after this.

Thanks in advance!

Body:
add this line before seller_event_items_form.save() when the model is saved
you can reference it as ForeignKey

seller_event_items.event_id = new_seller_event


问:
Tell a web programmer how to write a very very simple GUI program
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

```<code>if(a>5 || b>3) { final = 4; }
else if ...
</code>```

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?

答:
For me, hands down the easiest is tcl/tk. It takes one line of code to create a label widget, another line of code for an entry widget. One line of code for a button. A few lines of code to do a calculation, and a few lines of code to lay the widgets out on the screen. If you want to get fancy, a few lines of code to guarantee the user only inputs digits and not some other characters.

Many people might vote this answer down because they hate tcl/tk. Don't let that sway you from at least considering it. It's a lot more mature than most people realize. And while the syntax of Tcl isn't everyone's cup of tea, it's trivially easy to learn.

For more information on tk, and to see the variety of languages you can use it on, see http://www.tkdocs.com

Body:
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

if(a>5 || b>3) { final = 4; }
else if ...

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?


问:
db.createCollection is not a function
I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.

My mongo instance is running within docker and the ports have been opened up to my local.

```<code>TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

Copied from w3schools...

```<code>var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    db.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
    });
});
</code>```

No error is returned through the run, and no methods are exposed on the db object.

any ideas?

答:
You're not the one facing this issue. Seems that 3.0 mongo driver has a bug or these are just breaking backwards compatibility changes. Take a look here:
db.collection is not a function when using MongoClient v3.0

To use DB name in the URL, you need to uninstall MongoDB, change to "mongodb": "^2.2.33" in dependencies and do npm install to install the new version.

Or you can install specific version with command npm install mongodb@2.2.33 --save

Title: db.createCollection is not a function

Body:
I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.

My mongo instance is running within docker and the ports have been opened up to my local.

TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

Copied from w3schools...

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    db.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
    });
});

No error is returned through the run, and no methods are exposed on the db object.

any ideas?


问:
How to detect the "key up" event of the CTRL key when releasing CTRL-F?
I am trying to detect the "key up" event of the CTRL key when releasing CTRL+F in the browser. I have tried this:

```<code>    $(document).keyup(function(e){
        if (e.ctrlKey){ // note that I'm not even checking for the F key here
            console.log("CTRL up");
        }
    });
</code>```

but it doesn't work, the event is not triggered. How can I do this?

答: e.ctrlKey returns false on keyUp event and true on keyDown. You can test (e.keyCode === 17) condition.

Body:
I am trying to detect the "key up" event of the CTRL key when releasing CTRL+F in the browser. I have tried this:

    $(document).keyup(function(e){
        if (e.ctrlKey){ // note that I'm not even checking for the F key here
            console.log("CTRL up");
        }
    });

but it doesn't work, the event is not triggered. How can I do this?


问:
APK update break app functionality
I need to deliver app updates via APK download. After downloading signed APK to the device, opening it and installing the update, some app functionality became broken.

For example, it shows the wrong alert.
Here showDefaultAlert is called instead of showWifiAlert

```<code>mNetworkTester = new Runnable() {
    @Override
    public void run() {
        NetworkInfo networkInfo = getActiveNetworkInfo();
        if (networkInfo != null) {
            networkType = networkInfo.getType();
        }
        if (!isNetworkAvailable(networkInfo)) {
            if (!mShowingDefaultAlert) {
                if (networkType == ConnectivityManager.TYPE_WIFI) {
                    showWifiAlert(null, null);
                } else {
                    showDefaultAlert(null, null);
                }
                AppCardServer.reset();
                mShowingDefaultAlert = true;
            }
        } else if (mShowingDefaultAlert) {
            if (internetTest != null && internetTest.getStatus().equals(AsyncTask.Status.PENDING)) {
                internetTest.execute();
            } else {
                internetTest = new InternetTestTask(new OnSocketListener() {
                    @Override
                    public void onConnect(boolean connected) {
                        if (connected) {
                            mShowingDefaultAlert = false;
                            showDialog(null);
                            initConfiguration();
                        }
                    }
                });
            }
        }
        handler.postDelayed(mNetworkTester, INTERVAL);
    }
};
handler.post(mNetworkTester);
</code>```

If I install the same APK using adb install -r, or run it from Android Studio, everything works fine. Why this may happen and how to resolve it?

Here is my AndroidManifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.appcard.androidterminal">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:name=".AppContext"
        android:allowBackup="false"
        android:icon="@drawable/logo_small"
        android:label="@string/app_name"
        android:supportsRtl="false"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">

        <activity
            android:name=".ui.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".KioskService" android:exported="false"/>

        <service
            android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
            android:enabled="true" />

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths"/>
        </provider>

        <receiver android:name=".BootReceiver">
            <intent-filter >
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <receiver
            android:name=".content.UpdateAlarmReceiver"
            android:exported="false" >
        </receiver>

    </application>

</manifest>
</code>```

答:
I was launching installation of downloaded apk like this

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</code>```

The app was still in the background, and after installing the new apk and opening the app some activity flow fails. This solved my problem:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
</code>```

Title: APK update break app functionality

Body:
I need to deliver app updates via APK download. After downloading signed APK to the device, opening it and installing the update, some app functionality became broken.

For example, it shows the wrong alert.
Here showDefaultAlert is called instead of showWifiAlert

mNetworkTester = new Runnable() {
    @Override
    public void run() {
        NetworkInfo networkInfo = getActiveNetworkInfo();
        if (networkInfo != null) {
            networkType = networkInfo.getType();
        }
        if (!isNetworkAvailable(networkInfo)) {
            if (!mShowingDefaultAlert) {
                if (networkType == ConnectivityManager.TYPE_WIFI) {
                    showWifiAlert(null, null);
                } else {
                    showDefaultAlert(null, null);
                }
                AppCardServer.reset();
                mShowingDefaultAlert = true;
            }
        } else if (mShowingDefaultAlert) {
            if (internetTest != null && internetTest.getStatus().equals(AsyncTask.Status.PENDING)) {
                internetTest.execute();
            } else {
                internetTest = new InternetTestTask(new OnSocketListener() {
                    @Override
                    public void onConnect(boolean connected) {
                        if (connected) {
                            mShowingDefaultAlert = false;
                            showDialog(null);
                            initConfiguration();
                        }
                    }
                });
            }
        }
        handler.postDelayed(mNetworkTester, INTERVAL);
    }
};
handler.post(mNetworkTester);

If I install the same APK using adb install -r, or run it from Android Studio, everything works fine. Why this may happen and how to resolve it?

Here is my AndroidManifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.appcard.androidterminal">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:name=".AppContext"
        android:allowBackup="false"
        android:icon="@drawable/logo_small"
        android:label="@string/app_name"
        android:supportsRtl="false"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">

        <activity
            android:name=".ui.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".KioskService" android:exported="false"/>

        <service
            android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
            android:enabled="true" />

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths"/>
        </provider>

        <receiver android:name=".BootReceiver">
            <intent-filter >
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <receiver
            android:name=".content.UpdateAlarmReceiver"
            android:exported="false" >
        </receiver>

    </application>

</manifest>

Body:
I was launching installation of downloaded apk like this

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

The app was still in the background, and after installing the new apk and opening the app some activity flow fails. This solved my problem:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();


问:
Full table background color in swing
I'm building my Java application interface using a lot of Photoshop.
But after implementing a table it doesn't look pretty cool as you can see:

I would like to make the table as transparent as possible, so only letters are shown. I have setted all the colors to black.
Any solution?

答:
JTable#setFillsViewportHeight would be the starting point.

Make sure that the background color of the JTable has been set accordingly

Title: Full table background color in swing


问:
Using the 'class' term in php without meaning the actual keyword
I am parsing a response from a webservice.
in the parser section, i have something like this:

```
foreach ($resXml->readCalls->classify->classification -><b>class</b> as $d) {
 ... do some processing
}
```

the problem is, the 'class' term which is a sub node in my xml response, is mistaken for the 'class' keyword in php, which raises a compile error.

how can i use terms which are incidentally a keyword in php?

Thanks!

答:
It's a reserved word.  So you have to use it as a string:

```<code>foreach ($resXml->readCalls->classify->classification->{'class'} as $d) {
    ... do some processing
}
</code>```

Or

```<code>$field = 'class';

foreach ($resXml->readCalls->classify->classification->$field as $d) {
    ... do some processing
}
</code>```

Body:
I am parsing a response from a webservice.
in the parser section, i have something like this:

foreach ($resXml->readCalls->classify->classification ->class as $d) {
 ... do some processing
}

the problem is, the 'class' term which is a sub node in my xml response, is mistaken for the 'class' keyword in php, which raises a compile error.

how can i use terms which are incidentally a keyword in php?

Thanks!

Body:
It's a reserved word.  So you have to use it as a string:

foreach ($resXml->readCalls->classify->classification->{'class'} as $d) {
    ... do some processing
}

Or

$field = 'class';

foreach ($resXml->readCalls->classify->classification->$field as $d) {
    ... do some processing
}


问:
Python Function Returning List Objects Out of Order
I'm relatively new to the Python language.  I'm aware of most of the basic functionality & theory, all the different classes of object and their behavior/properties etc.

Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively.  One in particular has left me vexed!  Can anyone share any insight into why this result is not as expected?

Here is the code I ran:

```<code>test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for n in k:
        k[k.index(n)] = n * 2
    x, y, z = k
    return k
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)
</code>```

I would have expected the result to be:

```<code>[4, 8, 12]
4
8
12
</code>```

However, the actual result is as follows:

```<code>[8, 4, 12]
8
4
12
</code>```

It seems that the first two items of the list have been swapped.

I can't see what could be causing this?  If anyone can see what's happening here, please share the insight!

Thanks,
Oscar South

答:
You can condense the code into a list comprehension and unpacking:</p>

```<code>test_list = [2, 4, 6]
def test_func(k):
   global x, y, z
   x, y, z = [i*2 for i in k]
   return [x, y, z]
</code>```

Body:
I'm relatively new to the Python language.  I'm aware of most of the basic functionality & theory, all the different classes of object and their behavior/properties etc.

Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively.  One in particular has left me vexed!  Can anyone share any insight into why this result is not as expected?

Here is the code I ran:

test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for n in k:
        k[k.index(n)] = n * 2
    x, y, z = k
    return k
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)

I would have expected the result to be:

[4, 8, 12]
4
8
12

However, the actual result is as follows:

[8, 4, 12]
8
4
12

It seems that the first two items of the list have been swapped.

I can't see what could be causing this?  If anyone can see what's happening here, please share the insight!

Thanks,
Oscar South

Body:
You can condense the code into a list comprehension and unpacking:

test_list = [2, 4, 6]
def test_func(k):
   global x, y, z
   x, y, z = [i*2 for i in k]
   return [x, y, z]


问:
Dynamics365 : Stop Products from Copying when Quote is Created
I am developing plugins in Microsoft Dynamics365 CRM and I need Opportunity Products NOT to get copied when one creates a new quote. I want to manually do that with a plugin, so as to perform certain calculations and set custom fields.

How do I disable this out of box feature?

答:
I doubt you can stop the OOB behavior because of the nature of Sales pipeline (Opportunity products cloned to Quote details on Quote creation).

But anyway you are planning to re-add those products using plugin (guess it is going to be Asynchronous Post Create on Quote). In that plugin, you can delete the cloned products (quote detail) which came from Oppty before re-adding into Quote.


问:
converting datetime string to the correct timezone
I've went through a few useful discussions on the topic, but still don't understand the following:

Say, I have a string "20080730 06:23:54 PDT" which I want to convert to a timezone aware datetime object. I understand, that dateutil.parser.parse() doesn't generally parse timezones like "PDT", but looks like it does parse "UTC" and "EDT" correctly. Are these exceptions? Is "EDT" an exception b/c it's my local timezone?

```<code>import pytz
from dateutil.parser import parse
sdt="20080730 06:23:54 UTC"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzutc())
sdt="20080730 06:23:54 EDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzlocal())
sdt="20080730 06:23:54 PDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54)
</code>```

答:
As a pilot ,i think you just need to learn more about Time Zones .It is not as easy as you think but not difficult too.It is always safer to work/convert to UTC time first and then continue(also you must see about daylight saving time).
If you want to do this for many inputs/outputs you will need a database(internet) and some regex(https://docs.python.org/3.6/howto/regex.html). Look at re-gex lib , and maybe selenium to improve your programm.

Oh sorry , to clear out EDT stands for Eastern Daylight Time (summer) and EST for Eastern Standard Time(winter).E.G. North America observe both and divides them in territories

EDITED
FROM http://pytz.sourceforge.net/*

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

Issues & Limitations

Offsets from UTC are rounded to the nearest whole minute, so timezones such as Europe/Amsterdam pre 1937 will be up to 30 seconds out. This is a limitation of the Python datetime library.
If you think a timezone definition is incorrect, I probably can’t fix it. pytz is a direct translation of the Olson timezone database, and changes to the timezone definitions need to be made to this source. If you find errors they should be reported to the time zone mailing list, linked from http://www.iana.org/time-zones.

Body:
I've went through a few useful discussions on the topic, but still don't understand the following:

Say, I have a string "20080730 06:23:54 PDT" which I want to convert to a timezone aware datetime object. I understand, that dateutil.parser.parse() doesn't generally parse timezones like "PDT", but looks like it does parse "UTC" and "EDT" correctly. Are these exceptions? Is "EDT" an exception b/c it's my local timezone?

import pytz
from dateutil.parser import parse
sdt="20080730 06:23:54 UTC"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzutc())
sdt="20080730 06:23:54 EDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzlocal())
sdt="20080730 06:23:54 PDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54)


问:
Protractor element by Xpath Index
I am trying to get xpath by index and i am not making an progress. protractor says "that the element has more than one element is found for locator choosing the 1st one". however I want to make sure that the 1st one is selected intentionally screen shot below:

My code: that is not working:

I tried the following site nothing works:
https://devhints.io/xpath
xpath get element by index
Any help would be appreciated.

答:
```<code>var payroll = element.all(by.xpath('//*[text()="Payroll"]')).first();
</code>```

Title: Protractor element by Xpath Index


问:
Frequency count for Comma delimited categories within a column
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

```<code>Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
</code>```

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

答:
First of all, consider the comment of @Matt W. about organizing your data frame in a more appropriated way, having a list inside of a cell usually is a symptom of a bad design.

Nevertheless, let's assume that your data frame is df, then:

```<code># iterate over all the cells in the Make column of the dataframe
top3 <- unlist(lapply(df$Make, function(cell) {
  # convert the cell string to a vector
  cars <- unlist(strsplit(cell, ','))
  # count how many of each different type are
  carFreq <- unlist(lapply(unique(cars), function(c) sum(c == cars)))
  # fix the name of carFreq
  names(carFreq) <- unique(cars)
  # return a string with the top 3
  paste0(names(sort(carFreq, decreasing = TRUE)[1:3]), collapse = ', ')
}))

# finally put the extra column in the data frame
df <- cbind(df, top3)
</code>```

There is no need for a library.

Body:
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

Body:
First of all, consider the comment of @Matt W. about organizing your data frame in a more appropriated way, having a list inside of a cell usually is a symptom of a bad design.

Nevertheless, let's assume that your data frame is df, then:

# iterate over all the cells in the Make column of the dataframe
top3 <- unlist(lapply(df$Make, function(cell) {
  # convert the cell string to a vector
  cars <- unlist(strsplit(cell, ','))
  # count how many of each different type are
  carFreq <- unlist(lapply(unique(cars), function(c) sum(c == cars)))
  # fix the name of carFreq
  names(carFreq) <- unique(cars)
  # return a string with the top 3
  paste0(names(sort(carFreq, decreasing = TRUE)[1:3]), collapse = ', ')
}))

# finally put the extra column in the data frame
df <- cbind(df, top3)

There is no need for a library.


问:
Dynamic name tablе in trigger
There is a trigger that copies columns from one table to another. How do I assign a table name to a dynamic variable @nametable?
Every day the name of the table changes depending on the current date.

```<code>USE dbo;
DROP TRIGGER IF EXISTS `update_test`;

GO

DELIMITER |

CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`

FOR EACH ROW

BEGIN

DECLARE nametable VARCHAR(128);

SET @nametable =(DATE_FORMAT(NOW(),"%d%m%Y_v"));

    INSERT INTO `dbo`.`nametable` SET
      `TIME_` =NEW.`recorded`,
      `P1` = NEW.`value1`
   ON DUPLICATE KEY UPDATE
        `TIME_` = NEW.`recorded`,
       `P1` = NEW.`value1`;

END;
</code>```

Have error ERROR 1146: Table 'dbo.nametable' doesn't exist

答:
I decided to do so as a temporary solution:</p>

```<code>CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`
FOR EACH ROW
BEGIN
SET @dateNameTableNOW =(DATE_FORMAT(NOW(),"%d%m%Y_v"));
SET @dateNameTableSELECT1 = '06122017_v';
SET @dateNameTableSELECT2 = '07122017_v';
IF(@dateNameTableNOW = @dateNameTableSELECT1) THEN
 INSERT INTO  dbo.06122017_v  SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;

IF(@dateNameTableNOW = @dateNameTableSELECT2) THEN
 INSERT INTO  dbo.07122017_v  SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;

END;
</code>```

Title: Dynamic name tablе in trigger

Body:
There is a trigger that copies columns from one table to another. How do I assign a table name to a dynamic variable @nametable?
Every day the name of the table changes depending on the current date.

USE dbo;
DROP TRIGGER IF EXISTS `update_test`;

GO

DELIMITER |

CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`

FOR EACH ROW

BEGIN

DECLARE nametable VARCHAR(128);

SET @nametable =(DATE_FORMAT(NOW(),"%d%m%Y_v"));

    INSERT INTO `dbo`.`nametable` SET
      `TIME_` =NEW.`recorded`,
      `P1` = NEW.`value1`
   ON DUPLICATE KEY UPDATE
        `TIME_` = NEW.`recorded`,
       `P1` = NEW.`value1`;

END;

Have error ERROR 1146: Table 'dbo.nametable' doesn't exist

Body:
I decided to do so as a temporary solution:

CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`
FOR EACH ROW
BEGIN
SET @dateNameTableNOW =(DATE_FORMAT(NOW(),"%d%m%Y_v"));
SET @dateNameTableSELECT1 = '06122017_v';
SET @dateNameTableSELECT2 = '07122017_v';
IF(@dateNameTableNOW = @dateNameTableSELECT1) THEN
 INSERT INTO  dbo.06122017_v  SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;

IF(@dateNameTableNOW = @dateNameTableSELECT2) THEN
 INSERT INTO  dbo.07122017_v  SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;

END;


问:
C++ - class issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

```<code>#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}
</code>```

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

答:
1.

```<code>strncpy(m_strName,strName,25);
</code>```

You need to #include <cstring> (where strncpy is declared).

2.

```<code>std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
</code>```

should be

```<code>std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl;
</code>```

3.

```<code>void setInfo(char *strName,int id,double wage)
</code>```

can be set to

```<code>void setInfo(const char *strName,int id,double wage)
</code>```

to get rid of the g++ 4.x.x warning.

Title: C++ - class issue

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

Body:
1.

strncpy(m_strName,strName,25);

You need to #include <cstring> (where strncpy is declared).

2.

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;

should be

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl;

3.

void setInfo(char *strName,int id,double wage)

can be set to

void setInfo(const char *strName,int id,double wage)

to get rid of the g++ 4.x.x warning.


问:
Differences between calculating correlation and feature selection for feature variables?
What would be the difference between using correlation and using feature selection to select important/highly correlated variables? When researching feature selection, I see that it uses statistical tests including pearson correlation.

Part of a college project, our group wants to identify important variables when doing data mining. A partner did correlation analysis using R Studio and I did recursive feature elimination using Sci-kit Learn.

When doing this, one variable was in common between the top 3 highest correlated variables and the top three ranked variables via recursive feature elimination.

Any help would be greatly appreciated, as I am rather new to this!

答:
You can suspect that the most correlated features are redundant. However you cannot say how does the feature influence the performance exactly. Correlation is informative, but the different feature selection techniques can be completely distinct, so it is worth to use them also. Then you can merge the results, for example verify if the correlated feature was redundant.

You can find interesting information here:

http://scikit-learn.org/stable/modules/feature_selection.html

As you can see, tree-based feature selection can be biased by the tree model, but it gives the answer of how much given feature influenced the decisions. This may be completely different indicator than the correlation.


问:
AWS RDS instance created from snapshot very slow
I have restored a snapshot of a PostgreSQL instance as a new instance with exactly the same configuration as the original instance. However, running queries takes much longer on the new instance. A query that takes less than 0.5 ms to execute on the original instance, takes over 1.2 ms on the new one. A nightly Python script that runs in 20 minutes on the old instance is now taking over an hour with the new one. This has been going on for several days now.</p>

答:
Unfortunately this is normal but it should go away after a while.

Snapshots are stored on S3, and when you create a new EBS volume with one, the volume only pulls in blocks of data as they are requested, causing degraded performance until the whole volume is initialized. See these AWS docs for confirmation.

Those docs suggest using dd to force all the data to load, but on RDS you have no way to do that. You might want to try SELECTing everything you can instead, although that will still miss some things (like indexes).


问:
How to look up and fill in data in dataframe python?
```<code>for i, row in lst.iterrows():
     value1 = a
     value2 = b
     result = 12345

     if df[(df['column1'] == value1) & (df['column2'] == value2)]:
          df['column_result'] == result

print df
</code>```

I want to look up in a dataframe a row where column1 equals value1 and column2 equals value2 and fill in result in that row.

I receive this error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

答:
The or and and python statements require truth-values. For pandas these are considered ambiguous so you should use "bitwise" | (or) or & (and) operations:

```<code>result = result[(result['var']>0.25) | (result['var']<-0.25)]
</code>```

These are overloaded for these kind of datastructures to yield the element-wise or (or and).

More Info Here : Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Body:
for i, row in lst.iterrows():
     value1 = a
     value2 = b
     result = 12345

     if df[(df['column1'] == value1) & (df['column2'] == value2)]:
          df['column_result'] == result

print df

I want to look up in a dataframe a row where column1 equals value1 and column2 equals value2 and fill in result in that row.

I receive this error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
The or and and python statements require truth-values. For pandas these are considered ambiguous so you should use "bitwise" | (or) or & (and) operations:

result = result[(result['var']>0.25) | (result['var']<-0.25)]

These are overloaded for these kind of datastructures to yield the element-wise or (or and).

More Info Here : Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()


问:
How to save a function to a dictionary entry?
I have this code, Its a slice of my main dictionary I use for my game

```<code>GAME_DICT = {
    # Player Media, Colors, And Locations
    'BLUE': {
        'COLOR': g.BLUE,
        'PLAYER_IMAGE': m.MEDIA['blue_face'],
        'BULLET_IMAGE': m.MEDIA['blue_bullet'],
        'LOCAL': 220,
        'ABILITY':         # Issue
        }
</code>```

Currently, I want to add a function as a value into the dictionary.
Python spits out a syntax error when I try to add a function using def function_name: and when I create a function from outside the dictionary and just save it to an entry it raises an error needing all the args to be filled, which I don't want as I need to fill in specific things as the args when I call this in another file. Any help?

答:
You can store the name of the function in a dictionary without incident.

If you have:

```<code>def myfunc(x):
    return x * 2
</code>```

You can also have:

```<code>d = {'funcname': myfunc}
</code>```

You make a named function using the def statement.  You can also make a nameless function using the lambda statement.

```<code>d = {'funcname' : lambda x:x * 2}
</code>```

Once you create a function, you can use the name or the lambda reference like any other variable. So...

```<code>f = d['funcname']
print('Double is ', f(2))
</code>```

Body:
I have this code, Its a slice of my main dictionary I use for my game

GAME_DICT = {
    # Player Media, Colors, And Locations
    'BLUE': {
        'COLOR': g.BLUE,
        'PLAYER_IMAGE': m.MEDIA['blue_face'],
        'BULLET_IMAGE': m.MEDIA['blue_bullet'],
        'LOCAL': 220,
        'ABILITY':         # Issue
        }

Currently, I want to add a function as a value into the dictionary.
Python spits out a syntax error when I try to add a function using def function_name: and when I create a function from outside the dictionary and just save it to an entry it raises an error needing all the args to be filled, which I don't want as I need to fill in specific things as the args when I call this in another file. Any help?

Body:
You can store the name of the function in a dictionary without incident.

If you have:

def myfunc(x):
    return x * 2

You can also have:

d = {'funcname': myfunc}

You make a named function using the def statement.  You can also make a nameless function using the lambda statement.

d = {'funcname' : lambda x:x * 2}

Once you create a function, you can use the name or the lambda reference like any other variable. So...

f = d['funcname']
print('Double is ', f(2))


问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
If you just want to group and sort, you don't need a groupingBy() collector, or even a stream at all. Just use a composite sort:

```<code>studlist.sort(Comparator.comparing(Student::getLocation).thenComparing(Student::getId));
</code>```

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
If you just want to group and sort, you don't need a groupingBy() collector, or even a stream at all. Just use a composite sort:

studlist.sort(Comparator.comparing(Student::getLocation).thenComparing(Student::getId));


问:
ClosedXml C# to display formula output numbers
I'm using closedxml to generate and download an xlsx file from a .NET c# application

Is there a way to display the formulas output numbers without the user having to click Enable Editing after downloading and opening the file in excel?

答:
There is an overload which allows you to evaluate formulas when saving the file. It's disabled by default.</p>
```<code>void Save(Boolean validate, Boolean evaluateFormulae = false);

void SaveAs(String file, Boolean validate, Boolean evaluateFormulae = false);
</code>```

Body:
There is an overload which allows you to evaluate formulas when saving the file. It's disabled by default.

void Save(Boolean validate, Boolean evaluateFormulae = false);

void SaveAs(String file, Boolean validate, Boolean evaluateFormulae = false);

ContentLicense: CC BY-SA 4.0


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
You might exploit the fact that the sign of the calculation a - b depends on which number is greater. This is used in many implementations of comparison. But I believe you'll never be able to completely avoid comparison. In this case, you still at least need to evaluate the contents of the sign flag on the processor.

If you just need to display the lower number you can also use arithmetic tricks:

```<code>result = ((a + b) - sqrt((a - b) * (a - b))) / 2
</code>```

EDIT erm … you're allowed to use switch?

I should use switch statements and arithmetic operators.

switch is basically the same as chained if and as such it also uses comparison. This sounds as if you should indeed just compare to zero to see what sign a - b has.

OwnerDisplayName: kvphxga

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

Body:
You might exploit the fact that the sign of the calculation a - b depends on which number is greater. This is used in many implementations of comparison. But I believe you'll never be able to completely avoid comparison. In this case, you still at least need to evaluate the contents of the sign flag on the processor.

If you just need to display the lower number you can also use arithmetic tricks:

result = ((a + b) - sqrt((a - b) * (a - b))) / 2

EDIT erm … you're allowed to use switch?

I should use switch statements and arithmetic operators.

switch is basically the same as chained if and as such it also uses comparison. This sounds as if you should indeed just compare to zero to see what sign a - b has.

OwnerDisplayName: Konrad Rudolph


问:
Multithreading in c++
I want to run one function with different parameters on different threads:

```<code>int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}
</code>```

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

答:
One sample example for Windows,

```<code>#include <Windows.h>

struct thread_data
{
 int m_id;
 thread_data(int id) : m_id(id) {}
};
DWORD WINAPI thread_func(LPVOID lpParameter)
{
 thread_data *td = (thread_data*)lpParameter;
 cout << "thread with id = " << td->m_id << endl;
 return 0;
}
int main()
{
 for (int i=0; i< 10; i++)
 {
  CreateThread(NULL, 0, thread_func, new thread_data(i) , 0, 0);
 }
}
</code>```

In this example, each thread gets different data, namely of type thread_data, which is passed as argument to the thread function thread_func().

Read these to know how to create thread on windows:

http://msdn.microsoft.com/en-us/library/ms682516(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms682453(v=vs.85).aspx

Also, you may like this suggestion as well:

Better design : define a reusable class!

Title: Multithreading in c++

Body:
I want to run one function with different parameters on different threads:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

Body:
One sample example for Windows,

#include <Windows.h>

struct thread_data
{
 int m_id;
 thread_data(int id) : m_id(id) {}
};
DWORD WINAPI thread_func(LPVOID lpParameter)
{
 thread_data *td = (thread_data*)lpParameter;
 cout << "thread with id = " << td->m_id << endl;
 return 0;
}
int main()
{
 for (int i=0; i< 10; i++)
 {
  CreateThread(NULL, 0, thread_func, new thread_data(i) , 0, 0);
 }
}

In this example, each thread gets different data, namely of type thread_data, which is passed as argument to the thread function thread_func().

Read these to know how to create thread on windows:

http://msdn.microsoft.com/en-us/library/ms682516(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms682453(v=vs.85).aspx

Also, you may like this suggestion as well:

Better design : define a reusable class!


问:
How to create Coulomb Matrix with Python?
I need some coulomb matrices of molecules for a machine learning task.
Coulomb Matrix? Here's a paper describing it

I found the Python package molml which has a method for it. However I can't figure out how to use the API for a single molecule only. In all examples they provide the method is called with two molecules, why?

How the example provides the method:

```<code>H2 = (['H', 'H'],
      [[0.0, 0.0, 0.0],
      [1.0, 0.0, 0.0]])

HCN = (['H', 'C', 'N'],
       [[-1.0, 0.0, 0.0],
        [ 0.0, 0.0, 0.0],
        [ 1.0, 0.0, 0.0]])

feat.transform([H2, HCN])
</code>```

I need something like this:

```<code> atomnames = [list of atomsymbols]
 atomcoords = [list of [x,y,z] for the atoms]
 coulombMatrice = CoulombMatrix((atomnames,atomcoords)
</code>```

I also found another lib (QML) which promises the possibility to generate coulomb matrices, but, I'm not able to install it on windows because it depends on Linux gcc-fortran compilers, I already installed cygwin and gcc-fortran for this purpose.

Thank you, guys

答:
I've implemented my own solution for the problem. There's much room for improvements. E.g. randomly sorted coulomb matrix and bag of bonds are still not implemented.</p>

```<code>    import numpy as np

def get_coulombmatrix(molecule, largest_mol_size=None):
    """
    This function generates a coulomb matrix for the given molecule
    if largest_mol size is provided matrix will have dimension lm x lm.
    Padding is provided for the bottom and right _|
    """
    numberAtoms = len(molecule.atoms)
    if largest_mol_size == None or largest_mol_size == 0: largest_mol_size = numberAtoms

    cij = np.zeros((largest_mol_size, largest_mol_size))

    xyzmatrix = [[atom.position.x, atom.position.y, atom.position.z] for atom in molecule.atoms]
    chargearray = [atom.atomic_number for atom in molecule.atoms]

    for i in range(numberAtoms):
        for j in range(numberAtoms):
            if i == j:
                cij[i][j] = 0.5 * chargearray[i] ** 2.4  # Diagonal term described by Potential energy of isolated atom
            else:
                dist = np.linalg.norm(np.array(xyzmatrix[i]) - np.array(xyzmatrix[j]))
                cij[i][j] = chargearray[i] * chargearray[j] / dist  # Pair-wise repulsion
    return cij
</code>```

Body:
I need some coulomb matrices of molecules for a machine learning task.
Coulomb Matrix? Here's a paper describing it

I found the Python package molml which has a method for it. However I can't figure out how to use the API for a single molecule only. In all examples they provide the method is called with two molecules, why?

How the example provides the method:

H2 = (['H', 'H'],
      [[0.0, 0.0, 0.0],
      [1.0, 0.0, 0.0]])

HCN = (['H', 'C', 'N'],
       [[-1.0, 0.0, 0.0],
        [ 0.0, 0.0, 0.0],
        [ 1.0, 0.0, 0.0]])

feat.transform([H2, HCN])

I need something like this:

 atomnames = [list of atomsymbols]
 atomcoords = [list of [x,y,z] for the atoms]
 coulombMatrice = CoulombMatrix((atomnames,atomcoords)

I also found another lib (QML) which promises the possibility to generate coulomb matrices, but, I'm not able to install it on windows because it depends on Linux gcc-fortran compilers, I already installed cygwin and gcc-fortran for this purpose.

Thank you, guys

Body:
I've implemented my own solution for the problem. There's much room for improvements. E.g. randomly sorted coulomb matrix and bag of bonds are still not implemented.

    import numpy as np

def get_coulombmatrix(molecule, largest_mol_size=None):
    """
    This function generates a coulomb matrix for the given molecule
    if largest_mol size is provided matrix will have dimension lm x lm.
    Padding is provided for the bottom and right _|
    """
    numberAtoms = len(molecule.atoms)
    if largest_mol_size == None or largest_mol_size == 0: largest_mol_size = numberAtoms

    cij = np.zeros((largest_mol_size, largest_mol_size))

    xyzmatrix = [[atom.position.x, atom.position.y, atom.position.z] for atom in molecule.atoms]
    chargearray = [atom.atomic_number for atom in molecule.atoms]

    for i in range(numberAtoms):
        for j in range(numberAtoms):
            if i == j:
                cij[i][j] = 0.5 * chargearray[i] ** 2.4  # Diagonal term described by Potential energy of isolated atom
            else:
                dist = np.linalg.norm(np.array(xyzmatrix[i]) - np.array(xyzmatrix[j]))
                cij[i][j] = chargearray[i] * chargearray[j] / dist  # Pair-wise repulsion
    return cij


问:
Pygame - Smooth Transform of Image/Surface
Is there a way to create a smooth transition between one image and another?

Say I have Image X and Image Y

```<code>ImageX = pygame.image.load('foo.png')
ImageY = pygame.image.load('oof.png')
</code>```

Image X transforms into image Y when W = 5
Normally, I would just do this in the draw code:

```<code>if w == 5:
    screen.blit(ImageY, (100, 100))
else:
    screen.blit(ImageX, (100, 100))
</code>```

But that just makes image X become replaced with ImageY, one frame its imageX, another frame its imageY

How would I make ImageX transition into ImageY smoothly? Like the transition attribute in css.

答:
You can assign transparency (0-255) to surface with set_alpha

```<code>ImageX.set_alpha(128)
</code>```

and when you blit ImageX after ImageY then you should see both images.

```<code>blit(ImageY, ...)
blit(ImageX, ...)
</code>```

You have to only change set_alpha() (from 255 to 0) in loop to get smooth efect.

```<code>if transparency > 0:
     transparency -= 1

ImageX.set_alpha(transparency)

blit(ImageY, ...)
blit(ImageX, ...)
</code>```

BTW: probably to use set_alpha() image has to use convert(), not convert_alpha().

See my examples on GitHub: pygame - transparency

Body:
Is there a way to create a smooth transition between one image and another?

Say I have Image X and Image Y

ImageX = pygame.image.load('foo.png')
ImageY = pygame.image.load('oof.png')

Image X transforms into image Y when W = 5
Normally, I would just do this in the draw code:

if w == 5:
    screen.blit(ImageY, (100, 100))
else:
    screen.blit(ImageX, (100, 100))

But that just makes image X become replaced with ImageY, one frame its imageX, another frame its imageY

How would I make ImageX transition into ImageY smoothly? Like the transition attribute in css.

Body:
You can assign transparency (0-255) to surface with set_alpha

ImageX.set_alpha(128)

and when you blit ImageX after ImageY then you should see both images.

blit(ImageY, ...)
blit(ImageX, ...)

You have to only change set_alpha() (from 255 to 0) in loop to get smooth efect.

if transparency > 0:
     transparency -= 1

ImageX.set_alpha(transparency)

blit(ImageY, ...)
blit(ImageX, ...)

BTW: probably to use set_alpha() image has to use convert(), not convert_alpha().

See my examples on GitHub: pygame - transparency


问:
Gradle sync failed upon updating Android Studio version
I recently was instructed by Android Studio to update to the new version (3.0.1, from 2.3.3). After several hours of fixing problems (Why must it be so hard to correctly update this piece of software?) I am now stuck.

I am getting this error on a project that previously worked perfectly:

```<code>Gradle sync failed: com.google.appengine.gradle.model.AppEngineModel PluginClassLoader[com.google.gct, 0.2.8]com.google.appengine.gradle.model.AppEngineModel PluginClassLoader[com.google.gct, 0.2.8]
        Consult IDE log for more details (Help | Show Log) (6s 343ms)
</code>```

Does anyone know a workaround for this problem?

Edit: After adding google() in repositories in build.gradle and changing gradle versions in gradle-wrapper.properties I now have a slightly shorter error message:

```<code>Gradle sync failed: com/google/appengine/gradle/model/AppEngineModelcom/google/appengine/gradle/model/AppEngineModel
        Consult IDE log for more details (Help | Show Log) (236ms)
</code>```

Edit 2: Now I was able to get a slightly different error message:

```<code>Error:(5, 1) A problem occurred evaluating root project 'TestApp2'.
Plugin with id 'appengine' not found.
</code>```

Googling this gives no sensible results either. But this sounds like a simple poblem to solve? Is there some SDK tool that I must add? And which one?

Edit 3: Here is the build script.

```<code>buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        google()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Edit 4: A different error I was able to generate. I get different errors when rebuilding the project.

```<code>Error:A problem occurred configuring root project 'TestApp2'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find jsr305.jar (com.google.code.findbugs:jsr305:1.3.9).
     Searched in the following locations:
         file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar
   > Could not find commons-codec.jar (commons-codec:commons-codec:1.6).
     Searched in the following locations:
         file:/C:/Program Files/Android/Android Studio/gradle/m2repository/commons-codec/commons-codec/1.6/commons-codec-1.6.jar
</code>```

Edit 5: I now uploaded the long log file to https://ufile.io/4qc3s.
I am very thankful for any suggestions on how I should go about to find a way to solve this problem.

Edit 6: I have now discovered that I am unable to open project structure.

答: It turned out that downloading and reinstalling the latest version of Android Studio was the solution. I didn't do this before because there are many answers on this site advising against this.</p>

Body:
I recently was instructed by Android Studio to update to the new version (3.0.1, from 2.3.3). After several hours of fixing problems (Why must it be so hard to correctly update this piece of software?) I am now stuck.

I am getting this error on a project that previously worked perfectly:

Gradle sync failed: com.google.appengine.gradle.model.AppEngineModel PluginClassLoader[com.google.gct, 0.2.8]com.google.appengine.gradle.model.AppEngineModel PluginClassLoader[com.google.gct, 0.2.8]
        Consult IDE log for more details (Help | Show Log) (6s 343ms)

Does anyone know a workaround for this problem?

Edit: After adding google() in repositories in build.gradle and changing gradle versions in gradle-wrapper.properties I now have a slightly shorter error message:

Gradle sync failed: com/google/appengine/gradle/model/AppEngineModelcom/google/appengine/gradle/model/AppEngineModel
        Consult IDE log for more details (Help | Show Log) (236ms)

Edit 2: Now I was able to get a slightly different error message:

Error:(5, 1) A problem occurred evaluating root project 'TestApp2'.
Plugin with id 'appengine' not found.

Googling this gives no sensible results either. But this sounds like a simple poblem to solve? Is there some SDK tool that I must add? And which one?

Edit 3: Here is the build script.

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        google()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

Edit 4: A different error I was able to generate. I get different errors when rebuilding the project.

Error:A problem occurred configuring root project 'TestApp2'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find jsr305.jar (com.google.code.findbugs:jsr305:1.3.9).
     Searched in the following locations:
         file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar
   > Could not find commons-codec.jar (commons-codec:commons-codec:1.6).
     Searched in the following locations:
         file:/C:/Program Files/Android/Android Studio/gradle/m2repository/commons-codec/commons-codec/1.6/commons-codec-1.6.jar

Edit 5: I now uploaded the long log file to https://ufile.io/4qc3s.
I am very thankful for any suggestions on how I should go about to find a way to solve this problem.

Edit 6: I have now discovered that I am unable to open project structure.


问:
Trying to pull specific clob data from oracle database
I have this CLOB column which basically contains fake XML in it. I call it fake because it doesn't follow the same parent child structure as a normal XML document.

Heres a sample from my clob:

```<code> <retryDetails>
    <numberOfRetries>0</numberOfRetries>
    <isToDoEntrySuppressed>false</isToDoEntrySuppressed>
 </retryDetails>
    <interimStatus>D1DS</interimStatus>
    <completionDetail>
    <updateStatusDateTime>2017-07-06-15.24.14</updateStatusDateTime>
    <completionEventDataArea>false</completionEventDataArea>
    <servicePointCompletionDetails>
    <servicePointDataDetails/>
    </servicePointCompletionDetails>
    <messageCompletionInformation/>
    <installDataDetails/>
    <ctCheck>
    <currentTransformerDetails/>
    </ctCheck>
    <vtCheck>
    <voltageTransformerDetails/>
    </vtCheck>
    <existingDevice>
    <deviceCompletionDetails>
    <deviceDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </deviceCompletionDetails>
    <itemCompletionDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    <meterTestDataDetails/>
    <meterDataDetails/>
    </existingDevice>
    <newDevice>
    <deviceCompletionDetails>
    <deviceDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </deviceCompletionDetails>
    <itemCompletionDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    <meterDataDetails/>
    <currentTransformerDetails/>
    <voltageTransformerDetails/>
    </newDevice>
    <completionInformation>
    <customerContactDetails/>
    <remarkTypes/>
    <grantExtensionDetails/>
    <paymentDetails/>
    </completionInformation>
    </completionDetail>
    <responseDetail>
    <message>
    <taskId>01327329221115</taskId>
    <hostExternalId>01327329221115</hostExternalId>
    <taskType>D1-ServiceInvestigation</taskType>
    <completionDateTime>2017-07-06-15.24.14</completionDateTime>
    <completedByCrew>Successfully Issued a work to CREW=E04393</completedByCrew>
    <messageId>01327329221115</messageId>
    <completionInformation>
    <dispatchDateTime>2017-07-06-15.24.14</dispatchDateTime>
    <customerContactDetails/>
    <remarkTypes/>
    </completionInformation>
    <utilityCompletionInformation>
    <servicePointCompletionDetails>
    <servicePointDataDetails>
    <servicePointId>741788842119</servicePointId>
    </servicePointDataDetails>
    </servicePointCompletionDetails>
    <existingDevice>
    <meterCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <meterDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </meterCompletionDetails>
    <itemCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    </existingDevice>
    <newDevice>
    <meterCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <meterDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </meterCompletionDetails>
    <itemCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    </newDevice>
    </utilityCompletionInformation>
    </message>
    <fault/>
    </responseDetail>
</code>```

What I need to do is figure out how, in a select statement, to pull out a specific node in this data mess, specifically the "completedByCrew" node.

I tried this method -

```<code>SELECT XMLQUERY('/root/retryDetails/numberOfRetries/text()'
       PASSING xmltype(to_clob('<root>') ||
                       A.BO_DATA_AREA    ||
                      '</root>') RETURNING CONTENT) AS RESULT
  FROM CISADM.D1_COMM_IN A
</code>```

But when I go past the number of Retries node, the information stops returning and just goes null. Any ideas?

答:
I can't get your example to work, but I think you could just put your raw text in a root element (named "root" in this example) before parsing it, and Oracle's XML engine will be much happier.</p>

```<code>select XMLQUERY('/root/responseDetail/message/completedByCrew/text()'
    PASSING xmltype( to_clob('<root>') || A.BO_DATA_AREA || '</root>' )
    RETURNING CONTENT) AS RESULT
FROM CISADM.D1_COMM_IN A
</code>```

Body:
I have this CLOB column which basically contains fake XML in it. I call it fake because it doesn't follow the same parent child structure as a normal XML document.

Heres a sample from my clob:

 <retryDetails>
    <numberOfRetries>0</numberOfRetries>
    <isToDoEntrySuppressed>false</isToDoEntrySuppressed>
 </retryDetails>
    <interimStatus>D1DS</interimStatus>
    <completionDetail>
    <updateStatusDateTime>2017-07-06-15.24.14</updateStatusDateTime>
    <completionEventDataArea>false</completionEventDataArea>
    <servicePointCompletionDetails>
    <servicePointDataDetails/>
    </servicePointCompletionDetails>
    <messageCompletionInformation/>
    <installDataDetails/>
    <ctCheck>
    <currentTransformerDetails/>
    </ctCheck>
    <vtCheck>
    <voltageTransformerDetails/>
    </vtCheck>
    <existingDevice>
    <deviceCompletionDetails>
    <deviceDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </deviceCompletionDetails>
    <itemCompletionDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    <meterTestDataDetails/>
    <meterDataDetails/>
    </existingDevice>
    <newDevice>
    <deviceCompletionDetails>
    <deviceDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </deviceCompletionDetails>
    <itemCompletionDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    <meterDataDetails/>
    <currentTransformerDetails/>
    <voltageTransformerDetails/>
    </newDevice>
    <completionInformation>
    <customerContactDetails/>
    <remarkTypes/>
    <grantExtensionDetails/>
    <paymentDetails/>
    </completionInformation>
    </completionDetail>
    <responseDetail>
    <message>
    <taskId>01327329221115</taskId>
    <hostExternalId>01327329221115</hostExternalId>
    <taskType>D1-ServiceInvestigation</taskType>
    <completionDateTime>2017-07-06-15.24.14</completionDateTime>
    <completedByCrew>Successfully Issued a work to CREW=E04393</completedByCrew>
    <messageId>01327329221115</messageId>
    <completionInformation>
    <dispatchDateTime>2017-07-06-15.24.14</dispatchDateTime>
    <customerContactDetails/>
    <remarkTypes/>
    </completionInformation>
    <utilityCompletionInformation>
    <servicePointCompletionDetails>
    <servicePointDataDetails>
    <servicePointId>741788842119</servicePointId>
    </servicePointDataDetails>
    </servicePointCompletionDetails>
    <existingDevice>
    <meterCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <meterDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </meterCompletionDetails>
    <itemCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    </existingDevice>
    <newDevice>
    <meterCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <meterDataDetails/>
    <readingCompletionDetails>
    <readingDetails/>
    </readingCompletionDetails>
    </meterCompletionDetails>
    <itemCompletionDetails>
    <verificationDetails>
    <response>
    <readingDetails/>
    </response>
    </verificationDetails>
    <itemDataDetails/>
    </itemCompletionDetails>
    </newDevice>
    </utilityCompletionInformation>
    </message>
    <fault/>
    </responseDetail>

What I need to do is figure out how, in a select statement, to pull out a specific node in this data mess, specifically the "completedByCrew" node.

I tried this method -

SELECT XMLQUERY('/root/retryDetails/numberOfRetries/text()'
       PASSING xmltype(to_clob('<root>') ||
                       A.BO_DATA_AREA    ||
                      '</root>') RETURNING CONTENT) AS RESULT
  FROM CISADM.D1_COMM_IN A

But when I go past the number of Retries node, the information stops returning and just goes null. Any ideas?

Body:
I can't get your example to work, but I think you could just put your raw text in a root element (named "root" in this example) before parsing it, and Oracle's XML engine will be much happier.

select XMLQUERY('/root/responseDetail/message/completedByCrew/text()'
    PASSING xmltype( to_clob('<root>') || A.BO_DATA_AREA || '</root>' )
    RETURNING CONTENT) AS RESULT
FROM CISADM.D1_COMM_IN A


答:
Try</p>

```<code>df.loc[(df['column1'] == value1) & (df['column2'] == value2), 'column_result'] = result
</code>```

Title: How to look up and fill in data in dataframe python?

Body:
for i, row in lst.iterrows():
     value1 = a
     value2 = b
     result = 12345

     if df[(df['column1'] == value1) & (df['column2'] == value2)]:
          df['column_result'] == result

print df

I want to look up in a dataframe a row where column1 equals value1 and column2 equals value2 and fill in result in that row.

I receive this error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
Try

df.loc[(df['column1'] == value1) & (df['column2'] == value2), 'column_result'] = result