问:
Show all limit lines in MP Android Line Chart
I'm trying to build and android application with MP Android chart v 2.0.9 and my problem is i'm affecting 4 limit lines to my chart but it displaying just two.
Any solution?</p>

```<code> LimitLine llg1 = new LimitLine(Charts.refrms , "");
            llg1.setLineWidth(2f);
            llg1.setLineColor(greencolor);
            holder.lineChart.getAxisLeft().addLimitLine(llg1);
            LimitLine llr1 = new LimitLine(Charts.dgrms , "");
            llr1.setLineWidth(2f);
            holder.lineChart.getAxisLeft().addLimitLine(llr1);
            LimitLine lly1 = new LimitLine(Charts.pralrms , "");
            lly1.setLineWidth(2f);
            lly1.setLineColor(yellowcolor);
            holder.lineChart.getAxisLeft().addLimitLine(lly1);
            LimitLine llo1 = new LimitLine(Charts.alrms , "");
            llo1.setLineWidth(2f);
            llo1.setLineColor(orangecolor);
            holder.lineChart.getAxisLeft().addLimitLine(llo1);
            holder.lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
            holder.lineChart.getAxisRight().setEnabled(false);
            LineDataSet dataset = new LineDataSet(Charts.rms, "");
            //dataset.setDrawCubic(true);
//            dataset.setDrawFilled(true);
//            dataset.setColors(ColorTemplate.COLORFUL_COLORS);
            dataset.setDrawValues(false);
            holder.lineChart.animateY(5000);
            LineData data = new LineData(Charts.measdate, dataset);
            holder.lineChart.setData(data);
            holder.lineChart.setDescription("RMS");
            holder.lineChart.setDescriptionTextSize(20);
</code>```

答: the solution was to fix the y axis min and max value holder.lineChart.getAxisLeft().setAxisMaxValue(Charts.dgpeak+2); holder.lineChart.getAxisLeft().setAxisMinValue(0f);</p>

Body:
I'm trying to build and android application with MP Android chart v 2.0.9 and my problem is i'm affecting 4 limit lines to my chart but it displaying just two.
Any solution?

 LimitLine llg1 = new LimitLine(Charts.refrms , "");
            llg1.setLineWidth(2f);
            llg1.setLineColor(greencolor);
            holder.lineChart.getAxisLeft().addLimitLine(llg1);
            LimitLine llr1 = new LimitLine(Charts.dgrms , "");
            llr1.setLineWidth(2f);
            holder.lineChart.getAxisLeft().addLimitLine(llr1);
            LimitLine lly1 = new LimitLine(Charts.pralrms , "");
            lly1.setLineWidth(2f);
            lly1.setLineColor(yellowcolor);
            holder.lineChart.getAxisLeft().addLimitLine(lly1);
            LimitLine llo1 = new LimitLine(Charts.alrms , "");
            llo1.setLineWidth(2f);
            llo1.setLineColor(orangecolor);
            holder.lineChart.getAxisLeft().addLimitLine(llo1);
            holder.lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
            holder.lineChart.getAxisRight().setEnabled(false);
            LineDataSet dataset = new LineDataSet(Charts.rms, "");
            //dataset.setDrawCubic(true);
//            dataset.setDrawFilled(true);
//            dataset.setColors(ColorTemplate.COLORFUL_COLORS);
            dataset.setDrawValues(false);
            holder.lineChart.animateY(5000);
            LineData data = new LineData(Charts.measdate, dataset);
            holder.lineChart.setData(data);
            holder.lineChart.setDescription("RMS");
            holder.lineChart.setDescriptionTextSize(20);


来源: stackexchange

问:
Disable output of hardcoded HTML tags in a PHP file
I am working with a software written in PHP that I have no control over. Some of the PHP files have hardcoded HTML tags in them that I'd like to suppress or exchange with my own code.

Fortunately there is a plugin-system that allows me to execute my own code at certain points, here's an example of the files I'm dealing with:

```<code><!DOCTYPE html>
<html>
  <?php
    execute_plugin_code_1()
  ?>
  <head>
  <!-- some additional tags -->
  </head>
  <?php
    execute_plugin_code_2()
  ?>
  <body>
  </body>
</html>
</code>```

What I want to do here is generate my own  tag. I don't want to alter the file itself so I'd like to suppress the hardcoded tag and its children.

Is there any way to disable the output of hardcoded HTML between execute_plugin_code_1() and execute_plugin_code_2()?

答: To answer your question, no, you cannot "disable" the HTML tags. You would need to remove them from the file, or use an entirely different file. The structure of this file is pretty odd though. I'm not sure what the original developer was trying to allow by providing hooks that run just before, and just after the head of the HTML document. It would have made much more sense to provide a hook within the head and within the body.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am working with a software written in PHP that I have no control over. Some of the PHP files have hardcoded HTML tags in them that I'd like to suppress or exchange with my own code.

Fortunately there is a plugin-system that allows me to execute my own code at certain points, here's an example of the files I'm dealing with:

<!DOCTYPE html>

  <?php
    execute_plugin_code_1()
  ?>

  <?php
    execute_plugin_code_2()
  ?>

What I want to do here is generate my own  tag. I don't want to alter the file itself so I'd like to suppress the hardcoded tag and its children.

Is there any way to disable the output of hardcoded HTML between execute_plugin_code_1() and execute_plugin_code_2()?


问:
CONFUSION MATRIX, R,
I need little help with the following code below. I have to setup a loop to train a neural network model on the TRAINING data with a different number of epochs each time by starting from 5 and adding 3 until I reach 20. Then I have to calculate a line chart showing the accuracy with differing numbers of epochs. I also have to keep all the parameters same as shown. Much of the code is what was given by our instructor. I added the epochs= c(5,8,11,14,17,20) to create a list of epochs and the error.rate = vector() where I intend to store the accuracy from each loop into a vector. The accuracy I want is from the confusion matrix and is found from the formula

h2o.hit_ratio_table(<model>,train = TRUE)[1,2]

The problem I face is that I have tried to create a loop. I am trying to get the results from each loop. I have labled the first part of the loop as X to try to put it into the vector for the accuracy for each loop into a vector error.rate=h2o.hit_ratio_table(x,train=TRUE)[1,2]).

However, it gives an error.

```<code>> Error in is(object, "H2OModelMetrics") : object 'X' not found In
> addition: Warning messages: 1: In 1:epochs : numerical expression has
> 6 elements: only the first used
</code>```

Moreover, when I remove the error.rate=...... part, the function runs fine but there is no way to find the values of the accuracy.

I am a noob at R so a little help will be much appreciated.

```<code>s <- proc.time()
 epochs= c(5,8,11,14,17,20)
 error.rate = vector()

 for (epoch in 1:epochs){#set up loop to go around 6 times
 X=h2o.deeplearning(x = 2:785,  # column numbers for predictors
               y = 1,   # column number for label
               training_frame = train_h2o, # data in H2O format
               activation = "RectifierWithDropout", # mathematical   activation function
               input_dropout_ratio = 0.2, # % of inputs dropout, because some inputs might not matter.
               hidden_dropout_ratios = c(0.25,0.25,0.25,0.25), # % for nodes dropout, because maybe we don't need full connections. Improves generalisability
               balance_classes = T, # over/under samples so that all classes are similar size.
               hidden = c(50,50,50,50), # two layers of 100 nodes
               momentum_stable = 0.99,
               nesterov_accelerated_gradient = T,
               error.rate=h2o.hit_ratio_table(x,train=TRUE)[1,2])
proc.time() - s}
</code>```

答:
You are doing for(epoch in 1:epochs). Here the 'epoch' term changes each loop (and usually you use it within the loop but i don't see it?). 1:epochs will not work as you think it should. It is taking the first element of epochs (5) and basically saying for(epoch in 1:5) where epoch is 1, then 2, ... and then 5. You want something like for(epoch in epochs) and if you DO want a sequence from 1:each epoch in your code you should write it within the loop.

Also, x is rewritten each time it loops. You should initialize it and save subsets of it each loop instead:

```<code>epochs= c(5,8,11,14,17,20)
 x <- list() # save as list #option 1
 y <- list() # for an option 2
 for (epoch in epochs){ #set up loop to go around 6 times
   X[[epoch]] = h2o.deeplearning(... )
   # or NOW you can somehow use 1:epoch where each loop epoch changes
 }
</code>```

But I would really focus on there is no use of using your epoch in your for loop as I see in your post. Perhaps find out where you want to use it...

Title: CONFUSION MATRIX, R,

Body:
I need little help with the following code below. I have to setup a loop to train a neural network model on the TRAINING data with a different number of epochs each time by starting from 5 and adding 3 until I reach 20. Then I have to calculate a line chart showing the accuracy with differing numbers of epochs. I also have to keep all the parameters same as shown. Much of the code is what was given by our instructor. I added the epochs= c(5,8,11,14,17,20) to create a list of epochs and the error.rate = vector() where I intend to store the accuracy from each loop into a vector. The accuracy I want is from the confusion matrix and is found from the formula

h2o.hit_ratio_table(<model>,train = TRUE)[1,2]

The problem I face is that I have tried to create a loop. I am trying to get the results from each loop. I have labled the first part of the loop as X to try to put it into the vector for the accuracy for each loop into a vector error.rate=h2o.hit_ratio_table(x,train=TRUE)[1,2]).

However, it gives an error.

> Error in is(object, "H2OModelMetrics") : object 'X' not found In
> addition: Warning messages: 1: In 1:epochs : numerical expression has
> 6 elements: only the first used

Moreover, when I remove the error.rate=...... part, the function runs fine but there is no way to find the values of the accuracy.

I am a noob at R so a little help will be much appreciated.

s <- proc.time()
 epochs= c(5,8,11,14,17,20)
 error.rate = vector()

 for (epoch in 1:epochs){#set up loop to go around 6 times
 X=h2o.deeplearning(x = 2:785,  # column numbers for predictors
               y = 1,   # column number for label
               training_frame = train_h2o, # data in H2O format
               activation = "RectifierWithDropout", # mathematical   activation function
               input_dropout_ratio = 0.2, # % of inputs dropout, because some inputs might not matter.
               hidden_dropout_ratios = c(0.25,0.25,0.25,0.25), # % for nodes dropout, because maybe we don't need full connections. Improves generalisability
               balance_classes = T, # over/under samples so that all classes are similar size.
               hidden = c(50,50,50,50), # two layers of 100 nodes
               momentum_stable = 0.99,
               nesterov_accelerated_gradient = T,
               error.rate=h2o.hit_ratio_table(x,train=TRUE)[1,2])
proc.time() - s}

Body:
You are doing for(epoch in 1:epochs). Here the 'epoch' term changes each loop (and usually you use it within the loop but i don't see it?). 1:epochs will not work as you think it should. It is taking the first element of epochs (5) and basically saying for(epoch in 1:5) where epoch is 1, then 2, ... and then 5. You want something like for(epoch in epochs) and if you DO want a sequence from 1:each epoch in your code you should write it within the loop.

Also, x is rewritten each time it loops. You should initialize it and save subsets of it each loop instead:

epochs= c(5,8,11,14,17,20)
 x <- list() # save as list #option 1
 y <- list() # for an option 2
 for (epoch in epochs){ #set up loop to go around 6 times
   X[[epoch]] = h2o.deeplearning(... )
   # or NOW you can somehow use 1:epoch where each loop epoch changes
 }

But I would really focus on there is no use of using your epoch in your for loop as I see in your post. Perhaps find out where you want to use it...


问:
Angular - Using *ngIf with *ngFor to specific rows in table
I'm pretty new to Angular and I'm trying to make a pipe to filter items out of my table and am not quite sure how to go about that. I'm trying to only display the table fields where the EmpKey = empInfo[selectedEmployee].EmpKey. Any help would be greatly appreciated! Thanks in advance!

Here's my tracker.component.html

    <button class="form-control" style="width:150px;" (click)="toggleSummary()">Open Summary</button>
    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} - {{emp.EmpID}}</option>
    </select>
    <select id="PTOtype">
      <option selected="selected" disabled>Type of PTO...</option>
      <option value="PTO">PTO</option>
      <option value="ETO-Earned">ETO - Earned</option>
      <option value="ETO-Used">ETO - Used</option>
      <option value="STDLTD">STD/LTD</option>
      <option value="Uncharged">Uncharged</option>
    </select>
    <button class="form-control" style="width: 150px;" (click)="nextEmployee()">Next</button>
    <button class="form-control" style="width: 150px;" (click)="previousEmployee()">Previous</button>

 selectedEmployee">{{empInfo[selectedEmployee].FirstName}} {{empInfo[selectedEmployee].EmpKey}}

          Date
          Full/Half
          Hours
          Scheduled?
          Notes
          In P/R?

          {{pto.date | date: 'MM/dd/y'}}
          {{pto.EmpKey}}
          {{pto.fullhalf}}
          {{pto.hours}}
          {{pto.scheduled}}
          {{pto.notes}}
          {{pto.inPR}}

        <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>

```
</div>
</div>
</p>

<p>and here's my tracker.component.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[];
    ptoData: PTOData[];
    isHidden: boolean = false;
    public selectedEmployee: number;

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
            );
    }

    getPTOData(): void {
        this.ptoDataService.getPTODatas().then(
            ptoData => this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee+1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee-1;
    }
}</code>```

Thanks again!

EDIT for Clarification - The user will select an employee from a dropdown list which will give me the index of the employee that was chosen. from there, I want to filter out the results that don't contain that EmpKey by using the value from empInfo[selectedEmployee].EmpKey. In the table, there are many different EmpKeys and whenever a user is selected, I only want the fields that share that EmpKey to be printed out and change to another employees whenever a different one is selected.

答:
You don't need to create a directive for that :

```<code>    <ng-container *ngFor="let pto of ptoData">
       <tr *ngIf="condition" >
          <td>{{pto.date | date: 'MM/dd/y'}}</td>
          ...
       </tr>
    </ng-container>
</code>```

Now a row will only display if condition.

So your code becomes

```<code>    <ng-container *ngFor="let pto of ptoData">
       <tr *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey" >
          <td>{{pto.date | date: 'MM/dd/y'}}</td>
          ...
       </tr>
    </ng-container>
</code>```

Body:
I'm pretty new to Angular and I'm trying to make a pipe to filter items out of my table and am not quite sure how to go about that. I'm trying to only display the table fields where the EmpKey = empInfo[selectedEmployee].EmpKey. Any help would be greatly appreciated! Thanks in advance!

Here's my tracker.component.html

    <button class="form-control" style="width:150px;" (click)="toggleSummary()">Open Summary</button>
    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} - {{emp.EmpID}}</option>
    </select>
    <select id="PTOtype">
      <option selected="selected" disabled>Type of PTO...</option>
      <option value="PTO">PTO</option>
      <option value="ETO-Earned">ETO - Earned</option>
      <option value="ETO-Used">ETO - Used</option>
      <option value="STDLTD">STD/LTD</option>
      <option value="Uncharged">Uncharged</option>
    </select>
    <button class="form-control" style="width: 150px;" (click)="nextEmployee()">Next</button>
    <button class="form-control" style="width: 150px;" (click)="previousEmployee()">Previous</button>

 selectedEmployee">{{empInfo[selectedEmployee].FirstName}} {{empInfo[selectedEmployee].EmpKey}}

          Date
          Full/Half
          Hours
          Scheduled?
          Notes
          In P/R?

          {{pto.date | date: 'MM/dd/y'}}
          {{pto.EmpKey}}
          {{pto.fullhalf}}
          {{pto.hours}}
          {{pto.scheduled}}
          {{pto.notes}}
          {{pto.inPR}}

        <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>

and here's my tracker.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[];
    ptoData: PTOData[];
    isHidden: boolean = false;
    public selectedEmployee: number;

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
            );
    }

    getPTOData(): void {
        this.ptoDataService.getPTODatas().then(
            ptoData => this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee+1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee-1;
    }
}

Thanks again!

EDIT for Clarification - The user will select an employee from a dropdown list which will give me the index of the employee that was chosen. from there, I want to filter out the results that don't contain that EmpKey by using the value from empInfo[selectedEmployee].EmpKey. In the table, there are many different EmpKeys and whenever a user is selected, I only want the fields that share that EmpKey to be printed out and change to another employees whenever a different one is selected.

Body:
You don't need to create a directive for that :

    <ng-container *ngFor="let pto of ptoData">
       <tr *ngIf="condition" >
          <td>{{pto.date | date: 'MM/dd/y'}}</td>
          ...
       </tr>
    </ng-container>

Now a row will only display if condition.

So your code becomes

    <ng-container *ngFor="let pto of ptoData">
       <tr *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey" >
          <td>{{pto.date | date: 'MM/dd/y'}}</td>
          ...
       </tr>
    </ng-container>


问:
what is typeof((c) + 1) in C
I came across an expression in C like

```<code>typeof((c) + 1) _tmp = c;
</code>```

What exactly does this mean?

Thanks for the reply.

Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?

答:
It is not standard C. C has no such thing as typeof (unless you are dealing with something user-defined).

typeof is normally a compiler extension (GCC compiler most likely). You can read about it here

http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

ContentLicense: CC BY-SA 2.5

Title: what is typeof((c) + 1) in C

Body:
I came across an expression in C like

typeof((c) + 1) _tmp = c;

What exactly does this mean?

Thanks for the reply.

Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?


Title: How to initialise a three dimensional ruby array

Body:
I want to initialise a three dimensional ruby array. For a two-dimensional array, I can do

a = Array.new(4){ Array.new(5, 0) }

so I have tried

a = Array.new(4) { Array.new(5, Array.new(6, 0)) }

but if I do a[1][2][3] = 5, it not only sets that element to 5, it sets the corresponding element to 5 in other sub arrays i.e.

[[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]]

Body:
Just use the same syntax (with a block instead of an argument : Array.new(n){...}) for all the dimensions.

a = Array.new(4) { Array.new(5) { Array.new(6, 0) } }

This way, your code will create 20 distincts Array.new(6, 0) sub-sub-arrays instead of replicating the same object 5 times.

require 'pp'
a = Array.new(4) { Array.new(5) { Array.new(6, 0) } }
a[1][2][3] = 5
pp a
# [[[0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0]],
#  [[0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 5, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0]],
#  [[0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0]],
#  [[0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0],
#   [0, 0, 0, 0, 0, 0]]]


问:
jQuery: Direct child of $(this)
Is it possible to, somehow, select a direct child of $(this)?

I have:

```<code>var obj = $(this);
$("ul", obj).css('width',s*w);
</code>```

And need it to act like this obj > ul

Is it possible?

答:
This works for me ;)</p>

```<code>$('> ul',this)
</code>```

Title: jQuery: Direct child of $(this)

Body:
Is it possible to, somehow, select a direct child of $(this)?

I have:

var obj = $(this);
$("ul", obj).css('width',s*w);

And need it to act like this obj > ul

Is it possible?

Body:
This works for me ;)

$('> ul',this)


问:
how to explain this code : if (strstr(line, *argv) != EOF) != except
Its in K&R.

```<code>#include <stdio.h>
#include <string.h>
#define MAXLINE 1000

int getline(char *line, int max);

int main(int argc, char *argv[])
{

     char line[MAXLINE];
     long lineno = 0;
     int c, except = 0, number = 0, found = 0;

     while(--argc > 0 && (*++argv)[0] == '-')
        while(c = *++argv[0])
          switch(c) {
             case 'x':
                  except = 1;
                  break;
             case 'n':
                  number = 1;
                  break;
             default:
                  printf("find: illegal option %c\n", c);
                  argc = 0;
                  found = -1;
                  break;
          }
    if (argc != 1)
        printf("Usage : find -x, -n, pattern\n");
     else
    while(getline(line, MAXLINE) > 0) {
       lineno++;
        if ((strstr(line, *argv) != NULL) != except) {
           if (number)
              printf("%ld", lineno);
           printf("%s", line);
              found++;
      }
    }
}
</code>```

I have no idea what this statement means: if (strstr(line, *argv) != EOF) != expect) there was some mistakes before and i correctd it.

However, when i try to understand it ,i have some troubles.

Here is what i think: find -x -n. So, the argc = 3. argv[0] = find. argv[1] = -x. argv[2] = -n. argv[3] = NULL. After the first while loop, shouldn't the argc = 0. so i am confused.

答: Add the pattern in the end of ‘find -x -n’. if missed, then argc=0, it will print the sentence: Usage: find -x -n pattern.

Body:
Its in K&R.

#include <stdio.h>
#include <string.h>
#define MAXLINE 1000

int getline(char *line, int max);

int main(int argc, char *argv[])
{

     char line[MAXLINE];
     long lineno = 0;
     int c, except = 0, number = 0, found = 0;

     while(--argc > 0 && (*++argv)[0] == '-')
        while(c = *++argv[0])
          switch(c) {
             case 'x':
                  except = 1;
                  break;
             case 'n':
                  number = 1;
                  break;
             default:
                  printf("find: illegal option %c\n", c);
                  argc = 0;
                  found = -1;
                  break;
          }
    if (argc != 1)
        printf("Usage : find -x, -n, pattern\n");
     else
    while(getline(line, MAXLINE) > 0) {
       lineno++;
        if ((strstr(line, *argv) != NULL) != except) {
           if (number)
              printf("%ld", lineno);
           printf("%s", line);
              found++;
      }
    }
}

I have no idea what this statement means: if (strstr(line, *argv) != EOF) != expect) there was some mistakes before and i correctd it.

However, when i try to understand it ,i have some troubles.

Here is what i think: find -x -n. So, the argc = 3. argv[0] = find. argv[1] = -x. argv[2] = -n. argv[3] = NULL. After the first while loop, shouldn't the argc = 0. so i am confused.


问:
Aggregating data in Pandas python
I have a Dataframe dfa in Pandas containing about 12103 rows with about 10 columns.
Now I would build a new Dataframe dfb, exploiting dfa, where each row in dfb should be computed taking into account the first 300 rowsin dfa, for example:

```<code> value1= dfa['one'].std()
 value2=dfa['one'].max()
</code>```

obtaining dfb having 40 (12103/300) entries.
Basically, the first row of dfb has two columns (e.g., value1, value2) containing values computed as above, the second row contains values computed starting from 301th row of dfa to 600th row.

thanks

Title: Aggregating data in Pandas python

Body:
I have a Dataframe dfa in Pandas containing about 12103 rows with about 10 columns.
Now I would build a new Dataframe dfb, exploiting dfa, where each row in dfb should be computed taking into account the first 300 rowsin dfa, for example:

 value1= dfa['one'].std()
 value2=dfa['one'].max()

obtaining dfb having 40 (12103/300) entries.
Basically, the first row of dfb has two columns (e.g., value1, value2) containing values computed as above, the second row contains values computed starting from 301th row of dfa to 600th row.

thanks

Body:
IIUC, let's try this using groupby and stack:

 dfa.groupby(dfa.index // 300).apply(lambda x: pd.Series({'max':x.stack().max(),'std':x.stack().std()}))

MVCE:

dfa = pd.DataFrame(np.random.randint(1,100,(10,10)), columns=list('ABCDEFGHIJ'))
print(dfa)

Output:

    A   B   C   D   E   F   G   H   I   J
0  81  15  57  42  90  25  72  98   6   8
1  44  63  39  29  11   3  80  15  43  47
2  68  97  42  93  19  73  28  25   2  83
3  38  52  65  61  79  82  98  60  76  93
4  68  39  62  48  44  19  44  47  54  26
5  52  93  14  37  48  81   6  20  91  30
6  39  15  22  48  22   8  35  60  72  43
7  13  26  24  74  41  36  92  93  13  85
8   2  46  35  21  92  15  66  19  87  66
9  77  13  15  69   3  81  75  30  64  63

Create dfb in my example 2 rows at a time instead of 300 rows.

dfb = dfa.groupby(dfa.index // 2).apply(lambda x: pd.Series({'max':x.stack().max(),'std':x.stack().std()}))
print(dfb)

Output:

    max        std
0  98.0  29.754080
1  98.0  28.086521
2  93.0  24.203686
3  93.0  27.390884
4  92.0  30.153072


问:
C++ Array out of strings
I have a new class assignment where i need to make Hangman in c++. I got everything set but I can't figure out how to make an array from a string that a user has already entered. Here is what i got.

```<code>#include <iostream>
using namespace std;

int main(){
    string stringToGuess;
    cout << "Hello user, please enter a word to play hangman" << endl;
    cin >> stringToGuess;
    int arrLength = stringToGuess.length();
    cout << arrLength << endl;
    char arr_To_Guess[arrLength] = {atoi(stringToGuess.c_str())};
    for (int i = 0; i < arrLength; i++){
        cout << arr_To_Guess << " ";
    }
}
</code>```

I realize that i can accomplish this without making an array from the string but it is required to do so in the assignment.                                                      .                                                                                Instructions from your teacher:
We are going to do this one step at a time.
Here is the first step:
Ask the user to enter a word, save it to a string called
stringToGuess
Then, create 2 arrays of chars called
arrToGuess, arrCurrGuess
The first array will contain all of the letters in the word the user entered, the second array will contain all of the letters the player has guess correctly so far.
If the user enter the word
programming
The values of the variables would be:
stringToGuess: "PROGRAMMING"
arrToGuess: [P, R, O, G, R, A, M, M, I, N, G]
arrCurGuess:[_, _, _, _, _, _, _, _, _, _, _]
Your job is to make this work.
Look at this program first: https://repl.it/IZQd/0
Some things to pay attention to:
1) Make all of the letters capital.

答:
Since the length of the array is not known at compile time, you can not use an automatic array. The array has to be allocated dynamically. The simplest solution to copy a string into an array would be to use std::vector.

However, I suspect that your desire to create an array from a string is ill-founded. You probably don't need to do it. You could rewrite your loop like this:

```<code>cin >> stringToGuess;
for (char c : stringToGuess) {
    cout << c << " ";
}
</code>```

```<code>char arr_To_Guess[arrLength]
</code>```

The problem I mentioned earlier, arrLength is not known at compile time, so this declaration is ill-formed.

```<code>= {atoi(stringToGuess.c_str())};
</code>```

This is very strange. You attempt to initialize the first character of the new array to have the numeric value of whatever the string represents. For example:

```<code>string: "123"
becomes: [123, 0, 0]
</code>```

I suspect that this is not what you intended.

Title: C++ Array out of strings

Body:
I have a new class assignment where i need to make Hangman in c++. I got everything set but I can't figure out how to make an array from a string that a user has already entered. Here is what i got.

#include <iostream>
using namespace std;

int main(){
    string stringToGuess;
    cout << "Hello user, please enter a word to play hangman" << endl;
    cin >> stringToGuess;
    int arrLength = stringToGuess.length();
    cout << arrLength << endl;
    char arr_To_Guess[arrLength] = {atoi(stringToGuess.c_str())};
    for (int i = 0; i < arrLength; i++){
        cout << arr_To_Guess << " ";
    }
}

I realize that i can accomplish this without making an array from the string but it is required to do so in the assignment.                                                      .                                                                                Instructions from your teacher:
We are going to do this one step at a time.
Here is the first step:
Ask the user to enter a word, save it to a string called
stringToGuess
Then, create 2 arrays of chars called
arrToGuess, arrCurrGuess
The first array will contain all of the letters in the word the user entered, the second array will contain all of the letters the player has guess correctly so far.
If the user enter the word
programming
The values of the variables would be:
stringToGuess: "PROGRAMMING"
arrToGuess: [P, R, O, G, R, A, M, M, I, N, G]
arrCurGuess:[_, _, _, _, _, _, _, _, _, _, _]
Your job is to make this work.
Look at this program first: https://repl.it/IZQd/0
Some things to pay attention to:
1) Make all of the letters capital.

Body:
Since the length of the array is not known at compile time, you can not use an automatic array. The array has to be allocated dynamically. The simplest solution to copy a string into an array would be to use std::vector.

However, I suspect that your desire to create an array from a string is ill-founded. You probably don't need to do it. You could rewrite your loop like this:

cin >> stringToGuess;
for (char c : stringToGuess) {
    cout << c << " ";
}

char arr_To_Guess[arrLength]

The problem I mentioned earlier, arrLength is not known at compile time, so this declaration is ill-formed.

= {atoi(stringToGuess.c_str())};

This is very strange. You attempt to initialize the first character of the new array to have the numeric value of whatever the string represents. For example:

string: "123"
becomes: [123, 0, 0]

I suspect that this is not what you intended.


答:
create var _tmp st _tmp is of type upcast (max) of c or int and set it to value  of c.

eg

```<code>char c -> int _tmp // char(c) + 1 is int
float c -> float _tmp // float(c) + 1 is float
</code>```

Title: what is typeof((c) + 1) in C

Body:
create var _tmp st _tmp is of type upcast (max) of c or int and set it to value  of c.

eg

char c -> int _tmp // char(c) + 1 is int
float c -> float _tmp // float(c) + 1 is float


问:
Suitability of app with long running tasks for AWS Lambda or AWS Step Functions
I have an application on an AWS EC2 instance that runs once daily. The application fetches some files from a web service, parses the files line by line, updates a database, updates S3 files based on changes in the database, sends notification emails to customers as well as a few other tasks.

This is a series of logical tasks that must take place in sequence, although some of the tasks can be thought of as sub-tasks that can be executed in parallel. All tasks are a combination of Perl scripts and Java programs, with a single Perl script acting as the manager that executes each in turn. Some tasks can take as long as 45 minutes to complete, and the whole process can take up to 3 hours in total.

I'd like to make this whole process serverless. My initial idea was to use AWS Lambda, whereby each task would execute as a Lambda function, until I discovered Lambda functions impose a 5 minute execution timeout. It seems like the AWS Step Functions service is actually a better fit for my use case, but my understanding is that this service is backed by Lambda, so the tasks will still have the 5 min execution limitation.

(I'm also aware that I would have to re-write my Perl scripts to a language supported by Lambda).

I assume that I can work around the execution time limit by refactoring my code into smaller functions that will guarantee to complete in under 5 minutes. In my particular situation though, this seems inefficient.

Currently the database update task processes lines from a file one at a time. For this to work with Lambda, a Lambda function would need to handle only a single line from the file (or a very small number of lines) in order to guarantee not spilling over 5 minutes execution time. This would involve opening and closing a connection with the database on every invocation of the Lambda function. Also, each line processed should result in an entry written to a file, to be stored in S3. Right now, I just keep a file handle in memory and write the file to S3 when all lines are processed, but with Lambda I would need to keep reading the file, updating it and writing it back to S3.

What I'm asking is:

Is my use case a bad fit for AWS Lambda and/or AWS Step Functions?

Have I misunderstood how these services work?

Is there another AWS service that would be a better fit for my use case?

After further research, I think AWS Batch might be a good idea.

答:
So to answer your questions:

1) Yeah, if you've got something that'll run for around 45 minutes, whilst you could engineer it with Lambda/Step functions you're probably better off getting a EC2 micro instance.

2)Nope you've pretty much got it.

3) As above you want to go with EC2 for this, there's a good article on using Data Pipelines to start / stop an EC2 instance here that way by starting instance only when you need it the cost(if any) is negligible.

I have jobs that run in this fashion normally you can get away with with a t2.micro instance which is free tier eligible.

You can also run your perl scripts on an EC2 instance so no need to rewrite them!


问:
Code wont loop through sheets as well as rows
I am trying to write code to loop through all sheets in a workbook, apart from 1, and add a column which is a concatenation of 3 others. This seems to loop through all the rows for one worksheet, but not the others in the book</p>

```<code>Sub addConcats()
  Dim sh As Worksheet
  Dim rw As Range
  Dim RowCount As Integer

  'Run through worksheets
  Dim x As Long
  Sheet1.Select
  For x = 2 To ThisWorkbook.Sheets.Count
    If Sheets(x).Name <> "VAT Transaction Report" Then Sheets(x).Select
    Replace:=False
    Dim LastRow As Long
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count

    For y = 2 To LastRow
      'Concat
      ActiveSheet.Cells(y, 20).Value = ActiveSheet.Cells(y, 7).Value &
ActiveSheet.Cells(y, 9).Value & ActiveSheet.Cells(y, 12).Value
    Next y
  Next x
End Sub
</code>```

答:
No need to select each worksheet for this, or run with x and y.</p>

```<code>Sub addConcats()

Dim sh As Worksheet
Dim LastRow As Long
For Each sh in ThisWorkbook.Worksheets
    If sh.Name <> "VAT Transaction Report" Then
        LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp)
        For y = 2 To LastRow
            'Concat
            sh.Cells(y, 20).Value = sh.Cells(y, 7).Value & sh.Cells(y, 9).Value & sh.Cells(y, 12).Value
        Next y
    End If
Next
End Sub
</code>```

Body:
I am trying to write code to loop through all sheets in a workbook, apart from 1, and add a column which is a concatenation of 3 others. This seems to loop through all the rows for one worksheet, but not the others in the book

Sub addConcats()
  Dim sh As Worksheet
  Dim rw As Range
  Dim RowCount As Integer

  'Run through worksheets
  Dim x As Long
  Sheet1.Select
  For x = 2 To ThisWorkbook.Sheets.Count
    If Sheets(x).Name <> "VAT Transaction Report" Then Sheets(x).Select
    Replace:=False
    Dim LastRow As Long
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count

    For y = 2 To LastRow
      'Concat
      ActiveSheet.Cells(y, 20).Value = ActiveSheet.Cells(y, 7).Value &
ActiveSheet.Cells(y, 9).Value & ActiveSheet.Cells(y, 12).Value
    Next y
  Next x
End Sub

Body:
No need to select each worksheet for this, or run with x and y.

Sub addConcats()

Dim sh As Worksheet
Dim LastRow As Long
For Each sh in ThisWorkbook.Worksheets
    If sh.Name <> "VAT Transaction Report" Then
        LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp)
        For y = 2 To LastRow
            'Concat
            sh.Cells(y, 20).Value = sh.Cells(y, 7).Value & sh.Cells(y, 9).Value & sh.Cells(y, 12).Value
        Next y
    End If
Next
End Sub


问:
Select hr.employee by user_id in odoo 7
I want to select hr.employee automatically by user_id in def read

the field is :

```<code>'tested_by':fields.many2one("hr.employee",string="Tested by"),
</code>```

答:
You need to use <code>_defaults</code>:  </p>

```<code>def _get_employee(self, cr, uid, context=None):
    res = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=c)
    return res and res[0] or False

_columns = {
    'tested_by':fields.many2one("hr.employee",string="Tested by"),
}

_defaults = {
    'tested_by': _get_employee,
}
</code>```

Title: Select hr.employee by user_id in odoo 7

Body:
I want to select hr.employee automatically by user_id in def read

the field is :

'tested_by':fields.many2one("hr.employee",string="Tested by"),

Body:
You need to use _defaults:

def _get_employee(self, cr, uid, context=None):
    res = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=c)
    return res and res[0] or False

_columns = {
    'tested_by':fields.many2one("hr.employee",string="Tested by"),
}

_defaults = {
    'tested_by': _get_employee,
}


问:
How to run one update and commit in single command in ORACLE
I want to run a update query in ORACLE but to reflect the change of that query (means updating the value in database with receptive values) i have to run a commit; after that query (then only the value change will be updated in the database). So, how can i pass the update statement and the commit in same line through C#.

i am running the query like below,

```<code>UPDATE table_name
   SET columnname1 = 'N',
       columnname2 = 1
 WHERE columnname3 = '-2085371064';

COMMIT;
</code>```

答:
Supposing you are using ADO.NET, you can make use of Commit() method:</p>

```<code>using (OracleConnection connection = new OracleConnection(connectionString))
{
    connection.Open();

    OracleCommand command = connection.CreateCommand();
    OracleTransaction transaction;

    transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
    command.Transaction = transaction;

    try
    {
        command.CommandText =
            "UPDATE table_name    SET columnname1 = 'N',        columnname2 = 1 WHERE columnname3 = '-2085371064';";
        command.ExecuteNonQuery();
        transaction.Commit();
    }
    catch (Exception e)
    {
        transaction.Rollback();
        Console.WriteLine(e.ToString());
    }
}
</code>```

Body:
I want to run a update query in ORACLE but to reflect the change of that query (means updating the value in database with receptive values) i have to run a commit; after that query (then only the value change will be updated in the database). So, how can i pass the update statement and the commit in same line through C#.

i am running the query like below,

UPDATE table_name
   SET columnname1 = 'N',
       columnname2 = 1
 WHERE columnname3 = '-2085371064';

COMMIT;

Body:
Supposing you are using ADO.NET, you can make use of Commit() method:

using (OracleConnection connection = new OracleConnection(connectionString))
{
    connection.Open();

    OracleCommand command = connection.CreateCommand();
    OracleTransaction transaction;

    transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
    command.Transaction = transaction;

    try
    {
        command.CommandText =
            "UPDATE table_name    SET columnname1 = 'N',        columnname2 = 1 WHERE columnname3 = '-2085371064';";
        command.ExecuteNonQuery();
        transaction.Commit();
    }
    catch (Exception e)
    {
        transaction.Rollback();
        Console.WriteLine(e.ToString());
    }
}


问:
Changing text color of datepicker
Is it any way to change text color of datepicker in iOS8? I've that it isn't possible in iOS7 and prior, something changed in 8th version?

For example I've found modified picker in Yahoo Weather!

答:
It's working on iOS 10 only if you set both properties.</p>

```<code>datePicker.setValue(UIColor.white, forKeyPath: "textColor")
datePicker.setValue(false, forKeyPath: "highlightsToday")
</code>```

Title: Changing text color of datepicker

Body:
It's working on iOS 10 only if you set both properties.

datePicker.setValue(UIColor.white, forKeyPath: "textColor")
datePicker.setValue(false, forKeyPath: "highlightsToday")


问:
filter for custom column in grid view which is not in table yii2
I have added this 'sla_status' field in gridview and every thing is working fine only issue is I am unable to set filter values for this.
'sla_status' is not in my table.

```<code>[
            'label' => Yii::t('app','Sla Status'),
            'format' => 'raw',
            'filterType' => GridView::FILTER_SELECT2,
            'filter' => $status,
            'filterWidgetOptions' => [
                    'options' => [
                            'placeholder' => Yii::t('app','All...' )
                    ],
                    'pluginOptions' => [
                            'allowClear' => true
                    ]
            ],

            'headerOptions' => ['style' => 'text-align:center;color:#337ab7'],
            'value' => function ($model, $key, $index, $widget)
            {           }
            ]
</code>```

and $status is $status = array('0'=>Yii::t('app', 'Inactive'),'1'=>Yii::t('app', 'Active'));

答:
in Search model you should add attribute sla_status
and in search() add required where.
for example:</p>

```<code>class TaskSearch extends Task{
public $sla_status;
public function search($params){
    $query = Task::find();
    if($this->sla_status){ $query->andWhere(...); }
}}
</code>```

Body:
I have added this 'sla_status' field in gridview and every thing is working fine only issue is I am unable to set filter values for this.
'sla_status' is not in my table.

[
            'label' => Yii::t('app','Sla Status'),
            'format' => 'raw',
            'filterType' => GridView::FILTER_SELECT2,
            'filter' => $status,
            'filterWidgetOptions' => [
                    'options' => [
                            'placeholder' => Yii::t('app','All...' )
                    ],
                    'pluginOptions' => [
                            'allowClear' => true
                    ]
            ],

            'headerOptions' => ['style' => 'text-align:center;color:#337ab7'],
            'value' => function ($model, $key, $index, $widget)
            {           }
            ]

and $status is $status = array('0'=>Yii::t('app', 'Inactive'),'1'=>Yii::t('app', 'Active'));

Body:
in Search model you should add attribute sla_status
and in search() add required where.
for example:

class TaskSearch extends Task{
public $sla_status;
public function search($params){
    $query = Task::find();
    if($this->sla_status){ $query->andWhere(...); }
}}


问:
Create Android App using Apache Cordova and web service
i am really new on this so i need some suggestions.

Using Visual Studio, i want to create an android application and i want to have flexibility so i will use Apache Cordove. It allows you to use standard web technologies - HTML5, CSS3, and JavaScript for cross-platform development.

This is my client-side part and this part will communicate with the server-side ASP.NET Web Service and provide datasources through HTPP Ajax requests.

In this scenario, how can publish my app for testing and maybe after that for publish to outworld?

If i host my Web Service to azure and create the apk file will be work?

答:
Creating a Android app using apache cordova requires a Android SDK.You need to install packages required to create and run the apache cordova using visual studio, There is another alternative for this which I found easy one use ubuntu linux with eclipse and Android SDk latest version which can be configured to create a apache cordova project.

Your another concern is regarding the calling of a webservice hosted on azure environment is as easy and same as calling a webservice's webmethods from javascript you just need to provide the appropriate url of the webservice in ajax call.


问:
VS2017 MFC Class Wizard - how to use it like in VS2015
Please tell me how to use new class wizard in VS2017.
In 2015 I could doublecliked and I got wizard to create class (base f.e. on CDialogEX).
VS generated code with enum, declare_dynamics and others things to connect with dialog.

In 2017 it create simple class only with constructor.

答: Everything ok. I had to modify installation program and add MFC + ALT. I thought that it was installed, because during installation I clicked that I want to use c++.</p>


问:
Powershell $button.add_click executes the whole code inside the add_click block
I am new to WPF and event-handling using powershell, what I want to achieve is on click of a button, the progress bar should be shown from 0-100. But when I am running the following piece of code, it computes the whole code inside the add_click block and it only shows the last iteration in the loop.
I know maybe it is a silly solution, but I do need some help in this.

```<code>$syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)

$psCmd = [PowerShell]::Create().AddScript({
    $XamlPath="C:\Forms\MyFormsv1.xaml"
    $inputXML = Get-Content -Path $XamlPath
    [xml]$Global:xmlWPF = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'

    #Add WPF and Windows Forms assemblies
    try{
    Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
    } catch {
    Throw “Failed to load Windows Presentation Framework assemblies.”
    }

    $syncHash.Window=[Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

    [xml]$XAML = $xmlWPF

    $xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
    $Global:synchash.Add($_.Name,$synchash.Window.FindName($_.Name) )}

    function tool1_progress{
        $var1=50
        for($index=1 ; $index -le $var1; $index++)
        {
            [int]$tmpProgNum= ($index/$var1) * 100
            $syncHash.tool1_pb.Value= $tmpProgNum
            $syncHash.consoleOutput.Text=$index
            Start-Sleep -Milliseconds 250
        }
    }
    $syncHash.myButton.add_click({tool1_progress})
    $syncHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()
</code>```

$tool1 is a label. $tool1_pb is a progress bar. $consoleOutput is a
  text box.

答:
I integrate WPF and PowerShell all the time. This website helped me immensely. You can't update a UI that's running on the same thread, so you need to invoke a new runspace using BeginInvoke()

```<code>$psCmd = [PowerShell]::Create().AddScript({
$Global:uiHash.Error = $Error
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase
$xaml = @"YOURXAMLHERE"
$Global:uiHash.Window=[Windows.Markup.XamlReader]::Parse($xaml )

[xml]$XAML = $xaml
    $xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
    $Global:uihash.Add($_.Name,$uihash.Window.FindName($_.Name) )}
$Global:uiHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$handle = $psCmd.BeginInvoke()
</code>```

Then to update whatever it is you need, you would use Window.Dispatcher.Invoke

```<code>$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.Window.Title = "MyWindowTitle"},"Normal")
</code>```

EDIT

```<code>$Global:uiHash.Button1.Add_Click(tool1_progress)
</code>```

EDIT

Throw in your XML and this will work. You have to create another runspace on top of the other in order to keep updating the textbox and progress bar. Note that synchash MUST be $Global:synchash. Functions courtesy of this post.

```<code>$Global:syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)

$psCmd = [PowerShell]::Create().AddScript({
$XamlPath="C:\Forms\MyFormsv1.xaml"
$inputXML = @"YOURXMLHERE"@
[xml]$Global:xmlWPF = $inputXML

#Add WPF and Windows Forms assemblies
try{
Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
} catch {
Throw “Failed to load Windows Presentation Framework assemblies.”
}

$Global:syncHash.Window=[Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

[xml]$XAML = $xmlWPF

$xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
$Global:synchash.Add($_.Name,$Global:syncHash.Window.FindName($_.Name) )}

function Start-Runspace{
param($scriptblock)
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("SyncHash",$global:synchash)
$psCmd = [PowerShell]::Create().AddScript($ScriptBlock)
$psCmd.Runspace = $newRunspace
$psCMD.BeginInvoke()
}

   $SB = {
    $var1=50
    for($index=1 ; $index -le $var1; $index++)
    {
        [int]$tmpProgNum= ($index/$var1) * 100
        $Global:syncHash.Window.Dispatcher.Invoke([action]{$Global:Synchash.tool1_pb.value = "$tmpprognum"},"Normal")
        $Global:syncHash.Window.Dispatcher.Invoke([action]{$Global:Synchash.consoleoutput.text = "$index"},"Normal")
        Start-Sleep -Milliseconds 250

    }

}

$Global:syncHash.myButton.add_click({Start-Runspace $SB})
$Global:syncHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()
start-sleep -Milliseconds 300
</code>```

Body:
I am new to WPF and event-handling using powershell, what I want to achieve is on click of a button, the progress bar should be shown from 0-100. But when I am running the following piece of code, it computes the whole code inside the add_click block and it only shows the last iteration in the loop.
I know maybe it is a silly solution, but I do need some help in this.

$syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)

$psCmd = [PowerShell]::Create().AddScript({
    $XamlPath="C:\Forms\MyFormsv1.xaml"
    $inputXML = Get-Content -Path $XamlPath
    [xml]$Global:xmlWPF = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'

    #Add WPF and Windows Forms assemblies
    try{
    Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
    } catch {
    Throw “Failed to load Windows Presentation Framework assemblies.”
    }

    $syncHash.Window=[Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

    [xml]$XAML = $xmlWPF

    $xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
    $Global:synchash.Add($_.Name,$synchash.Window.FindName($_.Name) )}

    function tool1_progress{
        $var1=50
        for($index=1 ; $index -le $var1; $index++)
        {
            [int]$tmpProgNum= ($index/$var1) * 100
            $syncHash.tool1_pb.Value= $tmpProgNum
            $syncHash.consoleOutput.Text=$index
            Start-Sleep -Milliseconds 250
        }
    }
    $syncHash.myButton.add_click({tool1_progress})
    $syncHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()

$tool1 is a label. $tool1_pb is a progress bar. $consoleOutput is a
  text box.

Body:
I integrate WPF and PowerShell all the time. This website helped me immensely. You can't update a UI that's running on the same thread, so you need to invoke a new runspace using BeginInvoke()

$psCmd = [PowerShell]::Create().AddScript({
$Global:uiHash.Error = $Error
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase
$xaml = @"YOURXAMLHERE"
$Global:uiHash.Window=[Windows.Markup.XamlReader]::Parse($xaml )

[xml]$XAML = $xaml
    $xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
    $Global:uihash.Add($_.Name,$uihash.Window.FindName($_.Name) )}
$Global:uiHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$handle = $psCmd.BeginInvoke()

Then to update whatever it is you need, you would use Window.Dispatcher.Invoke

$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.Window.Title = "MyWindowTitle"},"Normal")

EDIT

$Global:uiHash.Button1.Add_Click(tool1_progress)

EDIT

Throw in your XML and this will work. You have to create another runspace on top of the other in order to keep updating the textbox and progress bar. Note that synchash MUST be $Global:synchash. Functions courtesy of this post.

$Global:syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)

$psCmd = [PowerShell]::Create().AddScript({
$XamlPath="C:\Forms\MyFormsv1.xaml"
$inputXML = @"YOURXMLHERE"@
[xml]$Global:xmlWPF = $inputXML

#Add WPF and Windows Forms assemblies
try{
Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
} catch {
Throw “Failed to load Windows Presentation Framework assemblies.”
}

$Global:syncHash.Window=[Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

[xml]$XAML = $xmlWPF

$xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
$Global:synchash.Add($_.Name,$Global:syncHash.Window.FindName($_.Name) )}

function Start-Runspace{
param($scriptblock)
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("SyncHash",$global:synchash)
$psCmd = [PowerShell]::Create().AddScript($ScriptBlock)
$psCmd.Runspace = $newRunspace
$psCMD.BeginInvoke()
}

   $SB = {
    $var1=50
    for($index=1 ; $index -le $var1; $index++)
    {
        [int]$tmpProgNum= ($index/$var1) * 100
        $Global:syncHash.Window.Dispatcher.Invoke([action]{$Global:Synchash.tool1_pb.value = "$tmpprognum"},"Normal")
        $Global:syncHash.Window.Dispatcher.Invoke([action]{$Global:Synchash.consoleoutput.text = "$index"},"Normal")
        Start-Sleep -Milliseconds 250

    }

}

$Global:syncHash.myButton.add_click({Start-Runspace $SB})
$Global:syncHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()
start-sleep -Milliseconds 300


问:
Get headers from http response
I am new to elm,
I have a login api which returns a JWT token in its hedears

```<code>curl  http://localhost:4000/api/login?email=bob@example&password=1234
</code>```

response:

```<code>HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8

success
</code>```

now Im trying to write a function that will send request and return the token from the headers in elm

```<code>authUser =
    Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"
</code>```

how do I do this in a simple way?

答:
In order to extract a header from a response, you will have to use Http.request along with the expectStringResponse function, which includes the full response including headers.

The expectStringResponse function takes a Http.Response a value, so we can create a function that accepts a header name and a response, then returns Ok headerValue or Err msg depending on whether the header was found:

extractHeader : String -> Http.Response String -> Result String String
extractHeader name resp =
    Dict.get name resp.headers
        |> Result.fromMaybe ("header " ++ name ++ " not found")
```

<p>This could be used by a request builder like so:</p>

<pre class="lang-elm prettyprint-override"><code>getHeader : String -> String -> Http.Request String
getHeader name url =
    Http.request
        { method = "GET"
        , headers = []
        , url = url
        , body = Http.emptyBody
        , expect = Http.expectStringResponse (extractHeader name)
        , timeout = Nothing
        , withCredentials = False
        }
</code>```

Here is an example on ellie-app.com which returns the value of content-type as an example. You can substitute "authorization" for your purposes.

Title: Get headers from http response

Body:
I am new to elm,
I have a login api which returns a JWT token in its hedears

curl  http://localhost:4000/api/login?email=bob@example&password=1234

response:

HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8

success

now Im trying to write a function that will send request and return the token from the headers in elm

authUser =
    Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"

how do I do this in a simple way?

Body:
In order to extract a header from a response, you will have to use Http.request along with the expectStringResponse function, which includes the full response including headers.

The expectStringResponse function takes a Http.Response a value, so we can create a function that accepts a header name and a response, then returns Ok headerValue or Err msg depending on whether the header was found:

extractHeader : String -> Http.Response String -> Result String String
extractHeader name resp =
    Dict.get name resp.headers
        |> Result.fromMaybe ("header " ++ name ++ " not found")

This could be used by a request builder like so:

getHeader : String -> String -> Http.Request String
getHeader name url =
    Http.request
        { method = "GET"
        , headers = []
        , url = url
        , body = Http.emptyBody
        , expect = Http.expectStringResponse (extractHeader name)
        , timeout = Nothing
        , withCredentials = False
        }

Here is an example on ellie-app.com which returns the value of content-type as an example. You can substitute "authorization" for your purposes.


问:
Add header(copyright) information to existing source files
I want to add our company's copyright information to all of our EXISTING source code files.

The project is developed in Eclipse. so, for new files I can modify the settings as suggested here. But for existing files, how am I supposed to do this. How can I modify hundreds of java files to add the copyright information. (And I'm unable to open the releng plugin mentioned in the above link.

Any windows based text maniputaion scripting language will also help.

答:
I would install CygWin (core + find) and do something of a kind

find . -name *.java -exec mv '{}' tmp && cp copyright '{}' && cat tmp >> '{}' && rm tmp \;


问:
how to create a list containing of 100 number of strings whose names are in series
a list of string objects is like

```<code>nodes=["#A_CN1","#A_CN2","#A_CN3","#A_CN4","#A_CN5","#A_CN6","#A_CN7","#A_CN8","#A_CN9","#A_CN10"]
</code>```

Here in the above list there are 10 elements but i need to use around 100 elements and the element is like #A_CN100

Is there any way to represent it shortly rather than writing 100 times in python ?

If suppose there is a list of 100 elements where each element itself is a list like, node1 , node2.. all are some lists

```<code>nodes=[node1,node2,node3,node4,node5,node6....node100]
</code>```

if I express this as

```<code>nodes=[node{0}.format(i) for i in range(1,101)]
</code>```

But,this throws an error! How to rectify this?

答:
You omitted quotes (or apostrophes). Instead of

```<code>nodes=[node{0}.format(i) for i in range(1,101)]
</code>```

use

```<code>nodes=["node{0}".format(i) for i in range(1,101)]
</code>```

Body:
a list of string objects is like

nodes=["#A_CN1","#A_CN2","#A_CN3","#A_CN4","#A_CN5","#A_CN6","#A_CN7","#A_CN8","#A_CN9","#A_CN10"]

Here in the above list there are 10 elements but i need to use around 100 elements and the element is like #A_CN100

Is there any way to represent it shortly rather than writing 100 times in python ?

If suppose there is a list of 100 elements where each element itself is a list like, node1 , node2.. all are some lists

nodes=[node1,node2,node3,node4,node5,node6....node100]

if I express this as

nodes=[node{0}.format(i) for i in range(1,101)]

But,this throws an error! How to rectify this?

Body:
You omitted quotes (or apostrophes). Instead of

nodes=[node{0}.format(i) for i in range(1,101)]

use

nodes=["node{0}".format(i) for i in range(1,101)]


答:
The problem is that you select a sheet, but do not use Sheet.Activate. Next you use ActiveSheet. It is better to avoid selecting sheets altogether and just work against a Worksheet object (sh variable)

Try the following:

```<code>Sub addConcats()

Dim sh As Worksheet
Dim x As Integer
Dim y As Integer
Dim LastRow As Long

For x = 1 To ThisWorkbook.Sheets.Count
    Set sh = Sheets(x)
    If sh.Name <> "VAT Transaction Report" Then
        LastRow = sh.UsedRange.Rows.Count
        For y = 2 To LastRow
        'Concat
            sh.Cells(y, 20).Value = sh.Cells(y, 7).Value & sh.Cells(y, 9).Value & sh.Cells(y, 12).Value
        Next y
    End If
Next x

End Sub
</code>```

Title: Code wont loop through sheets as well as rows

Body:
The problem is that you select a sheet, but do not use Sheet.Activate. Next you use ActiveSheet. It is better to avoid selecting sheets altogether and just work against a Worksheet object (sh variable)

Try the following:

Sub addConcats()

Dim sh As Worksheet
Dim x As Integer
Dim y As Integer
Dim LastRow As Long

For x = 1 To ThisWorkbook.Sheets.Count
    Set sh = Sheets(x)
    If sh.Name <> "VAT Transaction Report" Then
        LastRow = sh.UsedRange.Rows.Count
        For y = 2 To LastRow
        'Concat
            sh.Cells(y, 20).Value = sh.Cells(y, 7).Value & sh.Cells(y, 9).Value & sh.Cells(y, 12).Value
        Next y
    End If
Next x

End Sub


问:
Android: CollapsingToolbarLayout with ImageView Toolbar background
I would like to implement a CollapsingToolbarLayout like this:

The challenge here is that I need to have a custom Toolbar with a gif as background and therefore I need an ImageView as background for the Toolbar. You can see my implementation in the following xml:

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

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:background="@color/colorAccent"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:contentScrim="@color/colorAccent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

        <!-- Container which should be scrolled parallax and contains the image gallery -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="parallax">

            <RelativeLayout
                android:id="@+id/image_layer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <android.support.v4.view.ViewPager
                    android:id="@+id/image_gallery"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorAccent"
                    android:layout_marginTop="?attr/actionBarSize"/>

                <LinearLayout
                    android:id="@+id/image_indicators"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:padding="@dimen/defaultPadding"
                    android:gravity="center"
                    android:layout_alignParentBottom="true"/>
            </RelativeLayout>
        </LinearLayout>

        <!-- Container which contains the background for the toolbar and the toolbar itself  -->
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/toolbar_background"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:scaleType="centerCrop"
                android:layout_gravity="top"
                android:background="@color/colorPrimaryLight"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize">

                <de.views.CustomTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textColor="#FF0000"
                    android:textStyle="bold"
                    android:gravity="center"
                    android:maxLines="1"
                    android:ellipsize="end"
                    android:layout_gravity="center"
                    android:id="@+id/toolbar_title"
                    tools:text="Restauranttitel"/>
            </android.support.v7.widget.Toolbar>
        </RelativeLayout>

        <!-- Tablayout -->
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            app:tabBackground="@drawable/selected_tab_background"
            app:tabIndicatorColor="@android:color/transparent"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabMaxWidth="2000dp"/> <!-- we need to set this value to a very big value so that a single tab gets displayed over the full width too -->

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/activity_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</code>```

With this implementation the whole view is scrolling and neither the Toolbar nor the TabLayout gets pinned to the top of the screen.

I've worked through lots of tutorials and stackoverflow answers, f.e.

https://antonioleiva.com/collapsing-toolbar-layout/

http://blog.iamsuleiman.com/parallax-scrolling-tabs-design-support-library/

They all gave nice explanations on how to work with CollapsingToolbarLayout. I think the problem of my implementation is the RelativeLayout containing the ImageView and the Toolbar. When removing the RelativeLayout and the ImageView and set the collapseMode of Toolbar to 'pin' everything worked as expected and both the Toolbar and Tablayout gets pinned at the top of the screen if the user is scrolling. But unfortunately I need to have the ImageView above the toolbar to be able to load a GIF as Toolbar background.

Maybe one of you got an awesome idea on how to solve this issue. Or you've another idea how I can achieve the desired behaviour? Please let me know :)

Update: I've created an example project (https://drive.google.com/open?id=0B1aHkcAaWIA-dHBTZnUyeUt3eTQ) with which you can reproduce the wrong scroll behaviour.

答:
I have changed the activity_main.xml.
Here is the code :-

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

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:id="@+id/image_layer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax"
                android:layout_marginTop="?attr/actionBarSize"
                android:layout_marginBottom="?attr/actionBarSize">

                <android.support.v4.view.ViewPager
                    android:id="@+id/image_gallery"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorAccent"
                    android:layout_alignParentTop="true"/>

                <LinearLayout
                    android:id="@+id/image_indicators"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:padding="8dp"
                    android:gravity="center"
                    android:layout_alignParentBottom="true">

                    <View
                        android:layout_width="8dp"
                        android:layout_height="8dp"
                        android:layout_margin="4dp"
                        android:background="@drawable/indicator"/>

                    <View
                        android:layout_width="8dp"
                        android:layout_height="8dp"
                        android:layout_margin="4dp"
                        android:background="@drawable/indicator"/>

                    <View
                        android:layout_width="8dp"
                        android:layout_height="8dp"
                        android:layout_margin="4dp"
                        android:background="@drawable/indicator"/>

                </LinearLayout>
            </RelativeLayout>

            <ImageView
                android:id="@+id/toolbar_background"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:scaleType="centerCrop"
                android:visibility="gone"
                android:layout_gravity="top"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:background="@drawable/banner_gif"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                >

                <de.scrollbehaviour.CustomTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#FF0000"
                    android:textStyle="bold"
                    android:gravity="center"
                    android:maxLines="1"
                    android:ellipsize="end"
                    android:layout_gravity="center"
                    android:id="@+id/toolbar_title"
                    tools:text="Titel"/>
            </android.support.v7.widget.Toolbar>

         <!-- we need to set this value to a very big value so that a single tab gets displayed over the full width too -->

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/activity_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tabBackground="@color/colorWhite"
        app:tabTextColor="#000000"
        app:tabGravity="fill"
        android:layout_gravity="top"
        app:tabMode="fixed"
        app:tabMaxWidth="2000dp"/>
    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewpager"
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"/>
</FrameLayout>
</code>```

Body:
I would like to implement a CollapsingToolbarLayout like this:

The challenge here is that I need to have a custom Toolbar with a gif as background and therefore I need an ImageView as background for the Toolbar. You can see my implementation in the following xml:

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

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:background="@color/colorAccent"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:contentScrim="@color/colorAccent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="parallax">

            <RelativeLayout
                android:id="@+id/image_layer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <android.support.v4.view.ViewPager
                    android:id="@+id/image_gallery"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorAccent"
                    android:layout_marginTop="?attr/actionBarSize"/>

                <LinearLayout
                    android:id="@+id/image_indicators"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:padding="@dimen/defaultPadding"
                    android:gravity="center"
                    android:layout_alignParentBottom="true"/>
            </RelativeLayout>
        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/toolbar_background"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:scaleType="centerCrop"
                android:layout_gravity="top"
                android:background="@color/colorPrimaryLight"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize">

                <de.views.CustomTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textColor="#FF0000"
                    android:textStyle="bold"
                    android:gravity="center"
                    android:maxLines="1"
                    android:ellipsize="end"
                    android:layout_gravity="center"
                    android:id="@+id/toolbar_title"
                    tools:text="Restauranttitel"/>
            </android.support.v7.widget.Toolbar>
        </RelativeLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            app:tabBackground="@drawable/selected_tab_background"
            app:tabIndicatorColor="@android:color/transparent"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabMaxWidth="2000dp"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/activity_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

With this implementation the whole view is scrolling and neither the Toolbar nor the TabLayout gets pinned to the top of the screen.

I've worked through lots of tutorials and stackoverflow answers, f.e.

https://antonioleiva.com/collapsing-toolbar-layout/

http://blog.iamsuleiman.com/parallax-scrolling-tabs-design-support-library/

They all gave nice explanations on how to work with CollapsingToolbarLayout. I think the problem of my implementation is the RelativeLayout containing the ImageView and the Toolbar. When removing the RelativeLayout and the ImageView and set the collapseMode of Toolbar to 'pin' everything worked as expected and both the Toolbar and Tablayout gets pinned at the top of the screen if the user is scrolling. But unfortunately I need to have the ImageView above the toolbar to be able to load a GIF as Toolbar background.

Maybe one of you got an awesome idea on how to solve this issue. Or you've another idea how I can achieve the desired behaviour? Please let me know :)

Update: I've created an example project (https://drive.google.com/open?id=0B1aHkcAaWIA-dHBTZnUyeUt3eTQ) with which you can reproduce the wrong scroll behaviour.

Body:
I have changed the activity_main.xml.
Here is the code :-

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

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:id="@+id/image_layer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax"
                android:layout_marginTop="?attr/actionBarSize"
                android:layout_marginBottom="?attr/actionBarSize">

                <android.support.v4.view.ViewPager
                    android:id="@+id/image_gallery"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorAccent"
                    android:layout_alignParentTop="true"/>

                <LinearLayout
                    android:id="@+id/image_indicators"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:padding="8dp"
                    android:gravity="center"
                    android:layout_alignParentBottom="true">

                    <View
                        android:layout_width="8dp"
                        android:layout_height="8dp"
                        android:layout_margin="4dp"
                        android:background="@drawable/indicator"/>

                    <View
                        android:layout_width="8dp"
                        android:layout_height="8dp"
                        android:layout_margin="4dp"
                        android:background="@drawable/indicator"/>

                    <View
                        android:layout_width="8dp"
                        android:layout_height="8dp"
                        android:layout_margin="4dp"
                        android:background="@drawable/indicator"/>

                </LinearLayout>
            </RelativeLayout>

            <ImageView
                android:id="@+id/toolbar_background"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:scaleType="centerCrop"
                android:visibility="gone"
                android:layout_gravity="top"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:background="@drawable/banner_gif"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                >

                <de.scrollbehaviour.CustomTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#FF0000"
                    android:textStyle="bold"
                    android:gravity="center"
                    android:maxLines="1"
                    android:ellipsize="end"
                    android:layout_gravity="center"
                    android:id="@+id/toolbar_title"
                    tools:text="Titel"/>
            </android.support.v7.widget.Toolbar>

         <!-- we need to set this value to a very big value so that a single tab gets displayed over the full width too -->

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/activity_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tabBackground="@color/colorWhite"
        app:tabTextColor="#000000"
        app:tabGravity="fill"
        android:layout_gravity="top"
        app:tabMode="fixed"
        app:tabMaxWidth="2000dp"/>
    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewpager"
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"/>
</FrameLayout>


问:
How to force CocoaPods to use the latest release for a Github repo?
I am trying to create my first CocoaPods Printer. I have gone through all the steps which are required to create your own. This is the latest release version to which I want my pod to point. But somehow the pod is pointing to some other version which I have deleted to overcome "duplicate entry" error. What should I do to force CocoaPods to use the latest release available? For a note, if you could check the pod on the CocoaPods it has a difference of "stars" received for the repo. I am not sure what I am doing wrong here?

This is the Podspec file for that repo.

答:
You should update your repo.
Go to Terminal then enter:
pod repo update --verbose

--verbose is used to show everything happening on the terminal.

after the update finishes try pod install

ScreenShot of the class
Printer.swift


问:
How do i remove "random.math" enemies on my canvas at level three
I am creating a small game atm. There is infinite levels in the game. In the different levels enemies spawn from the y-akses with the "Random.math", so they just spawn randomly. There is player, who have to shoot the small enemies.

Regarding to my question. At level 3 i want the "Random.math" enemies to disappear and add a "Boss" istead. A link to the under progress

game

http://www.beproductive.dk/examgame/ss.html

This is my nextLevel function:

```<code>function nextLevel() {
"use strict"
settings.level++;
addEnemies();
// change text
levelText.text = "level " + settings.level;
// put it to the left of the screen
levelText.x = -100;
levelText.y = -100;
levelText.textAlign = "center";
levelText.textBaseline = "middle";

// animate in
createjs.Tween.get(levelText).to({
        x: 300,
        y: 400

    }, 1500, createjs.Ease.backOut).wait(500).to({
            x: 800,
            y: -100
        },
        1000)
    // animate out

// sound
createjs.Sound.play('vundet');

if (settings.level == 3) {
     console.log("bosslevel");

    var temp = new createjs.Sprite(enemiesSS, "sprite4");
    temp.width = 16;
    temp.height = 16;
    temp.x = 50;
    temp.y = 50;

    stage.addChild(temp);

}
</code>```

}

With this piece of code here, it should remove the ramdom spawn enemies, where only the "Boss" is left on the canvas. I just can't figure it out where to place it in my nextlevel function:

```<code>   for (var i = enemies.length - 1; i >= 0; i--) {
        stage.removeChild(enemies[i]);
    } enemies = []
</code>```

Yours sincerely

答:
UPDATE: THIS IS HOW THE CODE LOOKS LIKE NOW. TRIED TO CONSOLE.LOG IT. " WE ARE AT LVL 3" AND BOSS IS ADDED DOESENT GO THROUGH</p>

```<code> console.log("go through")
if (settings.level == 3) {
    console.log("we are at lvl 3 ");
    var temp = new createjs.Sprite(enemiesSS, "sprite4");
    temp.width = 16;
    temp.height = 16;
    temp.x = 50;
    temp.y = 50;
    stage.addChild(temp);
    console.log("boss is added");

} else {
    console.log("enemies added to other lvls");
    addEnemies();
}
</code>```

Body:
I am creating a small game atm. There is infinite levels in the game. In the different levels enemies spawn from the y-akses with the "Random.math", so they just spawn randomly. There is player, who have to shoot the small enemies.

Regarding to my question. At level 3 i want the "Random.math" enemies to disappear and add a "Boss" istead. A link to the under progress

game

http://www.beproductive.dk/examgame/ss.html

This is my nextLevel function:

function nextLevel() {
"use strict"
settings.level++;
addEnemies();
// change text
levelText.text = "level " + settings.level;
// put it to the left of the screen
levelText.x = -100;
levelText.y = -100;
levelText.textAlign = "center";
levelText.textBaseline = "middle";

// animate in
createjs.Tween.get(levelText).to({
        x: 300,
        y: 400

    }, 1500, createjs.Ease.backOut).wait(500).to({
            x: 800,
            y: -100
        },
        1000)
    // animate out

// sound
createjs.Sound.play('vundet');

if (settings.level == 3) {
     console.log("bosslevel");

    var temp = new createjs.Sprite(enemiesSS, "sprite4");
    temp.width = 16;
    temp.height = 16;
    temp.x = 50;
    temp.y = 50;

    stage.addChild(temp);

}

}

With this piece of code here, it should remove the ramdom spawn enemies, where only the "Boss" is left on the canvas. I just can't figure it out where to place it in my nextlevel function:

   for (var i = enemies.length - 1; i >= 0; i--) {
        stage.removeChild(enemies[i]);
    } enemies = []

Yours sincerely

Body:
UPDATE: THIS IS HOW THE CODE LOOKS LIKE NOW. TRIED TO CONSOLE.LOG IT. " WE ARE AT LVL 3" AND BOSS IS ADDED DOESENT GO THROUGH

 console.log("go through")
if (settings.level == 3) {
    console.log("we are at lvl 3 ");
    var temp = new createjs.Sprite(enemiesSS, "sprite4");
    temp.width = 16;
    temp.height = 16;
    temp.x = 50;
    temp.y = 50;
    stage.addChild(temp);
    console.log("boss is added");

} else {
    console.log("enemies added to other lvls");
    addEnemies();
}


问:
rotating a quaternion on 1 axis?
I have a model rotated by a quaternion. I can only set the rotation, I can't add or subtract from anything.  I need to get the value of an axis, and than add an angle to it (maybe a degree or radian?) and than re-add the modified quaternion.

How can I do this? (answer on each axis).

答:
You can multiply two quaternions together to produce a third quaternion that is the result of the two rotations. Note that quaternion multiplication is not commutative, meaning order matters (if you do this in your head a few times, you can see why).

You can produce a quaternion that represents a rotation by a given angle around a particular axis with something like this (excuse the fact that it is c++, not java):

```<code>Quaternion Quaternion::create_from_axis_angle(const double &xx, const double &yy, const double &zz, const double &a)
{
    // Here we calculate the sin( theta / 2) once for optimization
    double factor = sin( a / 2.0 );

    // Calculate the x, y and z of the quaternion
    double x = xx * factor;
    double y = yy * factor;
    double z = zz * factor;

    // Calcualte the w value by cos( theta / 2 )
    double w = cos( a / 2.0 );

    return Quaternion(x, y, z, w).normalize();
}
</code>```

So to rotate around the x axis for example, you could create a quaternion with createFromAxisAngle(1, 0, 0, M_PI/2) and multiply it by the current rotation quaternion of your model.

Title: rotating a quaternion on 1 axis?

Body:
You can multiply two quaternions together to produce a third quaternion that is the result of the two rotations. Note that quaternion multiplication is not commutative, meaning order matters (if you do this in your head a few times, you can see why).

You can produce a quaternion that represents a rotation by a given angle around a particular axis with something like this (excuse the fact that it is c++, not java):

Quaternion Quaternion::create_from_axis_angle(const double &xx, const double &yy, const double &zz, const double &a)
{
    // Here we calculate the sin( theta / 2) once for optimization
    double factor = sin( a / 2.0 );

    // Calculate the x, y and z of the quaternion
    double x = xx * factor;
    double y = yy * factor;
    double z = zz * factor;

    // Calcualte the w value by cos( theta / 2 )
    double w = cos( a / 2.0 );

    return Quaternion(x, y, z, w).normalize();
}

So to rotate around the x axis for example, you could create a quaternion with createFromAxisAngle(1, 0, 0, M_PI/2) and multiply it by the current rotation quaternion of your model.


问:
Intellij Cannot resolve symbol on import
This problem happens intermittently for different libraries and different projects.
When trying to import a library, the package will be recognized, but the class name can't be resolved.

If on the import statement, I right-click -> Goto -> the package's declaration, I see all the decompiled classes displayed in the side pane -- Including the ones I need --
If I try to auto-complete the import statement, I notice the class I need is not featured in the dropdown.

I tried invalidating caches already, doesn't work. I cannot find any class conflicts -- there is no other jar file in my classpath with the same package name.
I am able to import this class into other projects.

Please see screen shots:

Anyone have a clue?

答:
I had the same issue and the reason for that was incorrect marking of the project's sources.

I manually created the Root Content and didn't notice that src/main/test folder was marked as Sources instead of Tests. So that is why my test classes were assumed to have all their test libraries (JUnit, Mockito, etc.) with the scope of Compile, not Test.

As soon as I marked src/main/test as Tests and rebuilt the module all errors were gone.

ContentLicense: CC BY-SA 4.0


问:
Android AOSP build fails with "Communication error with Jack server"
I have successfully sync the source code of android-7.1.2_r11 from AOSP. Now, I got the following error while I was trying to build the source code. Anyone can tell me how I can fix it, and finish a successful build? Thanks much in advance.

Please see the attached screenshot for detailed build error.

BTW, my ubuntu version is 16.04. OpenJDK version is 1.8.

screenshot

error log:

Communication error with Jack server (56). Try 'jack-diagnose'
ninja: build stopped: subcommand failed.
build/core/ninja.mk:148: recipe for target 'ninja_wrapper' failed
make: *** [ninja_wrapper] Error 1

make failed to build some targets (02:17:10 (hh:mm:ss))

答:
Restart jack or reboot your machine

In your source tree root:

```<code>$ prebuilts/sdk/tools/jack-admin stop-server 2>&1 > /dev/null
$ prebuilts/sdk/tools/jack-admin cleanup-server 2>&1 > /dev/null
$ prebuilts/sdk/tools/jack-admin start-server 2>&1 > /dev/null
</code>```

You might want to do that multiple times to ensure it works properly.

Body:
Restart jack or reboot your machine

In your source tree root:

$ prebuilts/sdk/tools/jack-admin stop-server 2>&1 > /dev/null
$ prebuilts/sdk/tools/jack-admin cleanup-server 2>&1 > /dev/null
$ prebuilts/sdk/tools/jack-admin start-server 2>&1 > /dev/null

You might want to do that multiple times to ensure it works properly.


问:
SQL Query To Obtain Value that Occurs more than once
I need to query my database to show the records inside my table where lastname occurs more than three times. Example: in my Students Table, there are 3 people with Lastname 'Smith', 4 with 'Johnson', and 1 with 'Potter'. My query should show the records of those with the lastnames Smith, and Johnson since these values occur more than or equal to 3 times.

Can anyone point me to this? I was thinking of using COUNT() but I can't seem to think how to apply it?

答:
The answers mentioned here is quite elegant https://stackoverflow.com/a/6095776/1869562 but upon testing, I realize it only returns the last name.
What if you want to return the entire record itself ?
Do this
(For Mysql)</p>

```<code>SELECT *
FROM `beneficiary`
WHERE `lastname`
IN (

  SELECT `lastname`
  FROM `beneficiary`
  GROUP BY `lastname`
  HAVING COUNT( `lastname` ) >1
)
</code>```

Body:
The answers mentioned here is quite elegant https://stackoverflow.com/a/6095776/1869562 but upon testing, I realize it only returns the last name.
What if you want to return the entire record itself ?
Do this
(For Mysql)

SELECT *
FROM `beneficiary`
WHERE `lastname`
IN (

  SELECT `lastname`
  FROM `beneficiary`
  GROUP BY `lastname`
  HAVING COUNT( `lastname` ) >1
)