问:
Virtual Keyboard scales Web Page
This is probably a stupid question but I'm stuck so: I am building a page with a bunch of input fields. These input fields should fill a certain percentage of the screen as the resolution will vary on different devices. Thus I will have styles like these:

```<code>input { height: 20%; }
</code>```

I would expect it to calculate the height and keep it, but thats not what happens.

So my guess is that when the virtual keyboard comes up, it resizes the page and  the input fields have 20% of the new height.

After some frustration I created a page with nothing but an input field and checked if I can prevent it from resizing somehow. Heres what did not work:

-setting min-height in percentages

-trying to maintain page height in js

```<code> var initialHeight = document.body.scrollHeight;
        window.onresize = function(event){
            document.body.scrollHeight = initialHeight;
        }
</code>```

(does that mean percentages are relative to visible sizes only?)

-putting the input field in a div that has a  fixed min-height in pixels

A minimum height on the input field itself (in pixels) does seem to work, but it is not the solution I am looking for.

How do I create an input field that will not resize when the virtual keyboard comes up?

答:
Set the height to a fixed value, not a percentage. If you set it to 20% it will be the 20% of the size of it's parent and scale with it's parent, in this case the whole page.

You may want to use the viewport meta tag to scale better on different devices.
https://www.w3schools.com/css/css_rwd_viewport.asp

Title: Virtual Keyboard scales Web Page

Body:
This is probably a stupid question but I'm stuck so: I am building a page with a bunch of input fields. These input fields should fill a certain percentage of the screen as the resolution will vary on different devices. Thus I will have styles like these:

input { height: 20%; }

I would expect it to calculate the height and keep it, but thats not what happens.

So my guess is that when the virtual keyboard comes up, it resizes the page and  the input fields have 20% of the new height.

After some frustration I created a page with nothing but an input field and checked if I can prevent it from resizing somehow. Heres what did not work:

-setting min-height in percentages

-trying to maintain page height in js

 var initialHeight = document.body.scrollHeight;
        window.onresize = function(event){
            document.body.scrollHeight = initialHeight;
        }

(does that mean percentages are relative to visible sizes only?)

-putting the input field in a div that has a  fixed min-height in pixels

A minimum height on the input field itself (in pixels) does seem to work, but it is not the solution I am looking for.

How do I create an input field that will not resize when the virtual keyboard comes up?


来源: stackexchange

问:
Angular Material 2 multi select does not retain the selected values when search(filter) is applied
I am using Angular material 2 multi select with Angular 5.
I have added a search filter to it but when user searches for particular item and select those then it removes the items which was selected before.

I want to retain all the selected items unless and until the user deselect them.

Eg: I have a list of regions, if user selects Africa and Asia then searches and selects for Europe so we only see Europe as selected.

filterRegion.html

```<code><mat-select [compareWith]="compareFn"  placeholder="REGION" [formControl]="region" multiple>
        <mat-select-trigger>
            {{region.value ? region.value[0]?.value : ''}}
            <span *ngIf="region.value?.length > 1" >
              (+{{region.value.length - 1}})
            </span>
          </mat-select-trigger>
        <mat-form-field class="searchBox">
            <input matInput placeholder="Search" [(ngModel)]="searchRegion" >
        </mat-form-field>
      <mat-option *ngFor="let r of regionList | filterSearch: searchRegion" [value]="r">{{r.value}}</mat-option>
    </mat-select>
</code>```

filter-search-pipe.ts

```<code>    import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterSearch'
})
export class FilterSearchPipe implements PipeTransform {

  transform(value: any, input: string): any {
    if (input) {
      input = input.toLowerCase();
      return value.filter(function (el: Object) {
          return el['value'].toLowerCase().indexOf(input) > -1;
      })
    }
  return value;
  }

  }
</code>```

I tried using this : https://github.com/albyrock87/material2/blob/5c196ad65d1bd5d8cb02a6bd78407ee2ef5be198/src/demo-app/select/select-demo.html

But i was getting error for mat-select-header and mat-select-search.

答:
for this problem i suggest you to use autoComplete module of angular-material.

```<code><mat-form-field>
   <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
</mat-form-field>

<mat-autocomplete #auto="matAutocomplete">
   <mat-option *ngFor="let option of options" [value]="option">
      {{ option }}
   </mat-option>
</mat-autocomplete>
</code>```

then for multiSelecting must use an chips container (a material module)

```<code><mat-form-field class="demo-chip-list">
  <mat-chip-list #chipList>
    <mat-chip *ngFor="let fruit of fruits" [selectable]="selectable"
             [removable]="removable" (remove)="remove(fruit)">
      {{fruit.name}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input placeholder="New fruit..."
           [matChipInputFor]="chipList"
           [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
           [matChipInputAddOnBlur]="addOnBlur"
           (matChipInputTokenEnd)="add($event)" />
  </mat-chip-list>
</mat-form-field>
</code>```

and in the ts file of component. place:

```<code>import {Component} from '@angular/core';
import {MatChipInputEvent} from '@angular/material';
import {ENTER, COMMA} from '@angular/cdk/keycodes';

/**
 * @title Chips with input
 */
@Component({
  selector: 'chips-input-example',
  templateUrl: 'chips-input-example.html',
  styleUrls: ['chips-input-example.css']
})
export class ChipsInputExample {
  visible: boolean = true;
  selectable: boolean = true;
  removable: boolean = true;
  addOnBlur: boolean = true;

  // Enter, comma
  separatorKeysCodes = [ENTER, COMMA];

  fruits = [
    { name: 'Lemon' },
    { name: 'Lime' },
    { name: 'Apple' },
  ];

  add(event: MatChipInputEvent): void {
    let input = event.input;
    let value = event.value;

    // Add our fruit
    if ((value || '').trim()) {
      this.fruits.push({ name: value.trim() });
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

  remove(fruit: any): void {
    let index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }
}
</code>```

therfore you must merge autoComplete and chip container. it become a very good UX.

ContentLicense: CC BY-SA 3.0

Body:
I am using Angular material 2 multi select with Angular 5.
I have added a search filter to it but when user searches for particular item and select those then it removes the items which was selected before.

I want to retain all the selected items unless and until the user deselect them.

Eg: I have a list of regions, if user selects Africa and Asia then searches and selects for Europe so we only see Europe as selected.

filterRegion.html

<mat-select [compareWith]="compareFn"  placeholder="REGION" [formControl]="region" multiple>
        <mat-select-trigger>
            {{region.value ? region.value[0]?.value : ''}}
             1" >
              (+{{region.value.length - 1}})

          </mat-select-trigger>
        <mat-form-field class="searchBox">
            <input matInput placeholder="Search" [(ngModel)]="searchRegion" >
        </mat-form-field>
      <mat-option *ngFor="let r of regionList | filterSearch: searchRegion" [value]="r">{{r.value}}</mat-option>
    </mat-select>

filter-search-pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterSearch'
})
export class FilterSearchPipe implements PipeTransform {

  transform(value: any, input: string): any {
    if (input) {
      input = input.toLowerCase();
      return value.filter(function (el: Object) {
          return el['value'].toLowerCase().indexOf(input) > -1;
      })
    }
  return value;
  }

  }

I tried using this : https://github.com/albyrock87/material2/blob/5c196ad65d1bd5d8cb02a6bd78407ee2ef5be198/src/demo-app/select/select-demo.html

But i was getting error for mat-select-header and mat-select-search.

Body:
for this problem i suggest you to use autoComplete module of angular-material.

<mat-form-field>
   <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
</mat-form-field>

<mat-autocomplete #auto="matAutocomplete">
   <mat-option *ngFor="let option of options" [value]="option">
      {{ option }}
   </mat-option>
</mat-autocomplete>

then for multiSelecting must use an chips container (a material module)

<mat-form-field class="demo-chip-list">
  <mat-chip-list #chipList>
    <mat-chip *ngFor="let fruit of fruits" [selectable]="selectable"
             [removable]="removable" (remove)="remove(fruit)">
      {{fruit.name}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input placeholder="New fruit..."
           [matChipInputFor]="chipList"
           [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
           [matChipInputAddOnBlur]="addOnBlur"
           (matChipInputTokenEnd)="add($event)" />
  </mat-chip-list>
</mat-form-field>

and in the ts file of component. place:

import {Component} from '@angular/core';
import {MatChipInputEvent} from '@angular/material';
import {ENTER, COMMA} from '@angular/cdk/keycodes';

/**
 * @title Chips with input
 */
@Component({
  selector: 'chips-input-example',
  templateUrl: 'chips-input-example.html',
  styleUrls: ['chips-input-example.css']
})
export class ChipsInputExample {
  visible: boolean = true;
  selectable: boolean = true;
  removable: boolean = true;
  addOnBlur: boolean = true;

  // Enter, comma
  separatorKeysCodes = [ENTER, COMMA];

  fruits = [
    { name: 'Lemon' },
    { name: 'Lime' },
    { name: 'Apple' },
  ];

  add(event: MatChipInputEvent): void {
    let input = event.input;
    let value = event.value;

    // Add our fruit
    if ((value || '').trim()) {
      this.fruits.push({ name: value.trim() });
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

  remove(fruit: any): void {
    let index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }
}

therfore you must merge autoComplete and chip container. it become a very good UX.


问:
Is there a way to set a walltime on AWS Batch jobs?
Is there a way to set a maximum running time for AWS Batch jobs (or queues)? This is a standard setting in most batch managers, which avoids wasting resources when a job hangs for whatever reason.</p>

答:
AFAIK there is no feature to do this. However, a workaround was suggested in the forum for a similar question.

One idea is to call Batch as an Activity from Step Functions, pingback
  back on a schedule (e.g. every minute) from that job. If it stops
  responding then you can detect that situation as a Timeout in the
  activity and act accordingly (terminate the job etc.). Not an ideal
  solution (especially if the job continues to ping back as a "zombie"),
  but it's a start. You'd also likely have to store activity tokens in a
  database to trace them to Batch job id.

Alternatively, you split that setup into 2 steps, and schedule a Batch
  job from a Lambda in the first state, then pass the Batch job id to
  the second step which then polls Batch (from another Lambda) for its
  state with Retry and IntervalSeconds (e.g. once every minute, or even
  with exponential backoff), and MaxAttempts calculated based on your
  timeout. This way, you don't need any external state storage
  mechanism, long polling or even a "ping back" from the job (it CAN be
  a zombie), but the downside is more steps.


问:
Equality check for two boolean expressions (TSQL)
I have two tables and I want to join two tables based on the sign of the related columns

I'm joining on the condition a<0 = b<0 but the equality sign gives me a syntax error. I don't want to do (a<0 AND b<0) OR (Not a<0 AND Not b<0) because it doesn't look clean

答:
As Arvo suggested, you can use Sign(). Assuming that a and b are integer types:

```<code>where Sign( Sign( a ) + 1 ) = Sign( Sign( b ) + 1 )
</code>```

Explanation: The inner Sign() calls convert the input values to -1, 0 or 1. Adding 1 shifts those values to 0, 1 or 2. The outer Sign() calls collapse that back to 0 or 1 representing negative and non-negative inputs.

This kind of code is occassionally useful, but should be accompanied by a comment explaining the intent. If the technique is truly impenetrable then it should be explained in the comment or a citation provided.

Body:
As Arvo suggested, you can use Sign(). Assuming that a and b are integer types:

where Sign( Sign( a ) + 1 ) = Sign( Sign( b ) + 1 )

Explanation: The inner Sign() calls convert the input values to -1, 0 or 1. Adding 1 shifts those values to 0, 1 or 2. The outer Sign() calls collapse that back to 0 or 1 representing negative and non-negative inputs.

This kind of code is occassionally useful, but should be accompanied by a comment explaining the intent. If the technique is truly impenetrable then it should be explained in the comment or a citation provided.


问:
How do I add a Java backend to an existing PHP site without adding a tomcat server for Java Bridge?
Currently we're using PHP for our websites. Now we're thinking about writing the backend in Java, because of the type safety of the language, and the availability of all kind of tools for Java.
I've been reading about Java Bridge and now I'm wondering how to set this up.

We're using PHP already through Apache. I read that to use Java Bridge I need to install Tomcat as well. That means I have two servers (Apache and Tomcat), and I need to add security to the backend, because it is open to the whole wide world suddenly... Am I missing something? Is there another way to make the PHP-Java connection without an additional server? How is this usually done?

Any directions or links on how to to do this or any best practices on how to set it up are greatly appreciated. I didn't find the official Java Bridge site very clear.
Thanks!

答:
You don't need tomcat. As per instructions you can start Java as

java -Djava.ext.dirs=lib -jar JavaBridge.jar HTTP_LOCAL:8080 2 logfile &

lib contains the Java libraries you want to use.

Peter

ContentLicense: CC BY-SA 2.5


问:
Clang ambiguity with custom conversion operator
I've been developing a kind of adapter class, when I encountered a problem under clang. When both conversion operators for lvalue-reference and rvalue reference are defined you get an ambiguity compilation error trying to move from your class (when such code should be fine, as

```<code>operator const T& () const&
</code>```

is allowed only for lvalues AFAIK). I've reproduced error with simple example:

```<code>#include <string>

class StringDecorator
{
public:
  StringDecorator()
  : m_string( "String data here" )
  {}

  operator const std::string& () const& // lvalue only
  {
    return m_string;
  }

  operator std::string&& () && // rvalue only
  {
    return std::move( m_string );
  }

private:
    std::string m_string;
};

void func( const std::string& ) {}
void func( std::string&& ) {}

int main(int argc, char** argv)
{
  StringDecorator my_string;

  func( my_string ); // fine, operator std::string&& not allowed
  func( std::move( my_string ) ); // error "ambiguous function call"
}
</code>```

Compiles fine on gcc 4.9+, fails on any clang version.
So the question: is there any workaround? Is my understanding of const& function modifier right?

P.S.: To clarify - the question is about fixing StringDecorator class itself (or finding the workaround for such class as if were a library code). Please refrain providing answers that call operator T&&() directly or specify conversion type explicitly.

答:
Oliv answer is correct, as standard seems to be quite clear in this case. The solution I've chosen at a time was to leave only one conversion operator:

```<code>operator const std::string& () const&
</code>```

The problem exists because both conversion operators are considered viable. So this can be avoided by changing type of implicit argument of lvalue conversion operator from const& to &:

```<code>operator const std::string& () & // lvalue only (rvalue can't bind to non-const reference)
{
    return m_string;
}

operator std::string&& () && // rvalue only
{
    return std::move( m_string );
}
</code>```

But this breaks conversion from const StringDecorator, making its usage awkward in typical cases.

This broken solution led me thinking if there is a way to specify member function qualifier that will make conversion operator viable with const lvalue object, but not with the rvalue. And I've managed to achieve this by specifying implicit argument for const conversion operator as const volatile&:

```<code>operator const std::string& () const volatile& // lvalue only (rvalue can't bind to volatile reference)
{
    return const_cast< const StringDecorator* >( this )->m_string;
}

operator std::string&& () && // rvalue only
{
    return std::move( m_string );
}
</code>```

Per [dcl.init.ref]/5, for a reference to be initialized by binding to
  an rvalue, the reference must be a const non-volatile lvalue
  reference, or an rvalue reference:

While lvalue reference and const lvalue reference can bind to const volatile reference. Obviously volatile modifier on member function serves completely different thing. But hey, it works and sufficient for my use-case. The only remaining problem is that code becomes misleading and astonishing.

Body:
I've been developing a kind of adapter class, when I encountered a problem under clang. When both conversion operators for lvalue-reference and rvalue reference are defined you get an ambiguity compilation error trying to move from your class (when such code should be fine, as

operator const T& () const&

is allowed only for lvalues AFAIK). I've reproduced error with simple example:

#include <string>

class StringDecorator
{
public:
  StringDecorator()
  : m_string( "String data here" )
  {}

  operator const std::string& () const& // lvalue only
  {
    return m_string;
  }

  operator std::string&& () && // rvalue only
  {
    return std::move( m_string );
  }

private:
    std::string m_string;
};

void func( const std::string& ) {}
void func( std::string&& ) {}

int main(int argc, char** argv)
{
  StringDecorator my_string;

  func( my_string ); // fine, operator std::string&& not allowed
  func( std::move( my_string ) ); // error "ambiguous function call"
}

Compiles fine on gcc 4.9+, fails on any clang version.
So the question: is there any workaround? Is my understanding of const& function modifier right?

P.S.: To clarify - the question is about fixing StringDecorator class itself (or finding the workaround for such class as if were a library code). Please refrain providing answers that call operator T&&() directly or specify conversion type explicitly.

Body:
Oliv answer is correct, as standard seems to be quite clear in this case. The solution I've chosen at a time was to leave only one conversion operator:

operator const std::string& () const&

The problem exists because both conversion operators are considered viable. So this can be avoided by changing type of implicit argument of lvalue conversion operator from const& to &:

operator const std::string& () & // lvalue only (rvalue can't bind to non-const reference)
{
    return m_string;
}

operator std::string&& () && // rvalue only
{
    return std::move( m_string );
}

But this breaks conversion from const StringDecorator, making its usage awkward in typical cases.

This broken solution led me thinking if there is a way to specify member function qualifier that will make conversion operator viable with const lvalue object, but not with the rvalue. And I've managed to achieve this by specifying implicit argument for const conversion operator as const volatile&:

operator const std::string& () const volatile& // lvalue only (rvalue can't bind to volatile reference)
{
    return const_cast< const StringDecorator* >( this )->m_string;
}

operator std::string&& () && // rvalue only
{
    return std::move( m_string );
}

Per [dcl.init.ref]/5, for a reference to be initialized by binding to
  an rvalue, the reference must be a const non-volatile lvalue
  reference, or an rvalue reference:

While lvalue reference and const lvalue reference can bind to const volatile reference. Obviously volatile modifier on member function serves completely different thing. But hey, it works and sufficient for my use-case. The only remaining problem is that code becomes misleading and astonishing.


问:
mPDF 6.0 Custom Progress Bar Issue
I'm using mpdf 6.0.

The issue is when I css as 10%

```<code><div class="progressbar">
                        <div class="progressbar-value bg-color-green" style="width: 10%; overflow: hidden;">  10%</div>
                    </div>
</code>```

The result as:

And when I add 3%, it covers the whole width

```<code><div class="progressbar">
                            <div class="progressbar-value bg-color-green" style="width: 3%; overflow: hidden;">  3%</div>
                        </div>
</code>```

The result is:

Please guide me to solve this problem.

PHP:

```<code><?php
set_time_limit(600);
ini_set('display_errors', 'Off');
ini_set("memory_limit","256M");

require 'mpdf.php';

$mpdf = new \mPDF();

$html = "";

        $html .= <<<EOD
                    <div class="progressbar">
                        <div class="progressbar-value bg-color-green" style="width: 3%; overflow: hidden;">  11%</div>
                    </div>

EOD;

$stylesheet = file_get_contents('style.css');

$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html, 2);

$mpdf->Output('','I');

exit;
?>
</code>```

CSS (style.css):

```<code>.progress, .progress-bar, .progressbar {
    position: relative;
    display: block;
    background: rgba(0, 0, 0, .05);
    overflow: hidden;
    font-weight: bold;
    line-height: 20px;
    height: 20px;
    border-radius: 4px;
    color: white;
}
.progressbar-value {
    display: block;
    white-space: nowrap;
    overflow: hidden;
}
.text-left {
    text-align: left !important;
}
.bg-color-green {
    background-color: #61BD4F;
}
</code>```

答:
I solved the above issue by using background: linear-gradient() and background-size: x%

```<code><div class="progressbar" style="float:left;">
  <div class="progressbar-value" style="background-image: linear-gradient(to left, #00FF00 100%); background-size:3%;float:left; height:15px;width:100%;">
    <div class="text" style="text-align: left; float: left;display:block;font-size:12px;height:15px;">3%</div>
  </div>
</div>
</code>```

Now the result is

Title: mPDF 6.0 Custom Progress Bar Issue

Body:
I'm using mpdf 6.0.

The issue is when I css as 10%

  10%

The result as:

And when I add 3%, it covers the whole width

  3%

The result is:

Please guide me to solve this problem.

PHP:

<?php
set_time_limit(600);
ini_set('display_errors', 'Off');
ini_set("memory_limit","256M");

require 'mpdf.php';

$mpdf = new \mPDF();

$html = "";

        $html .= <<<EOD

  11%

EOD;

$stylesheet = file_get_contents('style.css');

$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html, 2);

$mpdf->Output('','I');

exit;
?>

CSS (style.css):

.progress, .progress-bar, .progressbar {
    position: relative;
    display: block;
    background: rgba(0, 0, 0, .05);
    overflow: hidden;
    font-weight: bold;
    line-height: 20px;
    height: 20px;
    border-radius: 4px;
    color: white;
}
.progressbar-value {
    display: block;
    white-space: nowrap;
    overflow: hidden;
}
.text-left {
    text-align: left !important;
}
.bg-color-green {
    background-color: #61BD4F;
}

Body:
I solved the above issue by using background: linear-gradient() and background-size: x%

<div class="progressbar" style="float:left;">
  <div class="progressbar-value" style="background-image: linear-gradient(to left, #00FF00 100%); background-size:3%;float:left; height:15px;width:100%;">
    <div class="text" style="text-align: left; float: left;display:block;font-size:12px;height:15px;">3%</div>
  </div>
</div>

Now the result is


问:
How to compare with a string array and string
I want to compare one string with the string array because I need to match a phone number if it starts with some specific number then I need to do something.

Here is what I'm doing now. But I want to make this simpler.

```<code>string[] startNumList = new string[] {"4", "5", "6", "7", "8" };
foreach (string x in startNumList)
{
      if(request.ReferenceNumber.StartsWith(x))
       {
            //do something
       }
 }
</code>```

I was jut wondering if this is possible to do the same with one line LINQ.
Thanks in advance.

答:
If you want to avoid the foreach loop you can use "Any" method from Linq to see if any items in your "startNumList" match the condition.</p>

```<code>if(startNumList.Any(x => request.ReferenceNumber.StartsWith(x)))
{
                //do something
}
</code>```

Body:
I want to compare one string with the string array because I need to match a phone number if it starts with some specific number then I need to do something.

Here is what I'm doing now. But I want to make this simpler.

string[] startNumList = new string[] {"4", "5", "6", "7", "8" };
foreach (string x in startNumList)
{
      if(request.ReferenceNumber.StartsWith(x))
       {
            //do something
       }
 }

I was jut wondering if this is possible to do the same with one line LINQ.
Thanks in advance.

Body:
If you want to avoid the foreach loop you can use "Any" method from Linq to see if any items in your "startNumList" match the condition.

if(startNumList.Any(x => request.ReferenceNumber.StartsWith(x)))
{
                //do something
}


问:
How to access to Sails config variable in Tasks files
I have in tasks/config/custom.js:

module.exports = function(grunt) {
    /* code */
    grunt.loadNpmTasks(sails.config.mywebsite.foo);
};
```

sails.config.mywebsite.foo

But when calling a configuration variable, Sails shows me an error of GruntFile.

I think that in these files can not access the configuration variables. But, How I can access them here?

Thanks.

答:
You need to lift sails first:</p>

```<code>var Sails = require('sails');

module.exports = function(grunt) {
  grunt.registerTask('foo', 'Foo tast', function() {
    var done = this.async();

    Sails.lift({}, function() {
      console.log(sails.config.mywebsite.foo);

      done();
    })
  });
};
</code>```

Body:
I have in tasks/config/custom.js:

module.exports = function(grunt) {
    /* code */
    grunt.loadNpmTasks(sails.config.mywebsite.foo);
};

sails.config.mywebsite.foo

But when calling a configuration variable, Sails shows me an error of GruntFile.

I think that in these files can not access the configuration variables. But, How I can access them here?

Thanks.

Body:
You need to lift sails first:

var Sails = require('sails');

module.exports = function(grunt) {
  grunt.registerTask('foo', 'Foo tast', function() {
    var done = this.async();

    Sails.lift({}, function() {
      console.log(sails.config.mywebsite.foo);

      done();
    })
  });
};


问:
How to parse the AndroidManifest.xml file inside an .apk package
This file appears to be in a binary XML format.  What is this format and how can it be parsed programmatically (as opposed to using the aapt dump tool in the SDK)?

This binary format is not discussed in the documentation here.

Note: I want to access this information from outside the Android environment, preferably from Java.

答:
I have been running with the Ribo code posted above for over a year, and it has served us well. With recent updates (Gradle 3.x) though, I was no longer able to parse the AndroidManifest.xml, I was getting index out of bounds errors, and in general it was no longer able to parse the file.

Update: I now believe that our issues was with upgrading to Gradle 3.x. This article describes how AirWatch had issues and can be fixed by using a Gradle setting to use aapt instead of aapt2 AirWatch seems to be incompatible with Android Plugin for Gradle 3.0.0-beta1

In searching around I came across this open source project, and it's being maintained and I was able to get to the point and read both my old APKs that I could previously parse, and the new APKs that the logic from Ribo threw exceptions

https://github.com/xgouchet/AXML

From his example this is what I'm doing

```<code>  zf = new ZipFile(apkFile);

  //Getting the manifest
  ZipEntry entry = zf.getEntry("AndroidManifest.xml");
  InputStream is = zf.getInputStream(entry);

     // Read our manifest Document
     Document manifestDoc = new CompressedXmlParser().parseDOM(is);

     // Make sure we got a doc, and that it has children
     if (null != manifestDoc && manifestDoc.getChildNodes().getLength() > 0) {
        //
        Node firstNode = manifestDoc.getFirstChild();

        // Now get the attributes out of the node
        NamedNodeMap nodeMap = firstNode.getAttributes();

        // Finally to a point where we can read out our values
        versionName = nodeMap.getNamedItem("android:versionName").getNodeValue();
        versionCode = nodeMap.getNamedItem("android:versionCode").getNodeValue();
     }
</code>```

Body:
I have been running with the Ribo code posted above for over a year, and it has served us well. With recent updates (Gradle 3.x) though, I was no longer able to parse the AndroidManifest.xml, I was getting index out of bounds errors, and in general it was no longer able to parse the file.

Update: I now believe that our issues was with upgrading to Gradle 3.x. This article describes how AirWatch had issues and can be fixed by using a Gradle setting to use aapt instead of aapt2 AirWatch seems to be incompatible with Android Plugin for Gradle 3.0.0-beta1

In searching around I came across this open source project, and it's being maintained and I was able to get to the point and read both my old APKs that I could previously parse, and the new APKs that the logic from Ribo threw exceptions

https://github.com/xgouchet/AXML

From his example this is what I'm doing

  zf = new ZipFile(apkFile);

  //Getting the manifest
  ZipEntry entry = zf.getEntry("AndroidManifest.xml");
  InputStream is = zf.getInputStream(entry);

     // Read our manifest Document
     Document manifestDoc = new CompressedXmlParser().parseDOM(is);

     // Make sure we got a doc, and that it has children
     if (null != manifestDoc && manifestDoc.getChildNodes().getLength() > 0) {
        //
        Node firstNode = manifestDoc.getFirstChild();

        // Now get the attributes out of the node
        NamedNodeMap nodeMap = firstNode.getAttributes();

        // Finally to a point where we can read out our values
        versionName = nodeMap.getNamedItem("android:versionName").getNodeValue();
        versionCode = nodeMap.getNamedItem("android:versionCode").getNodeValue();
     }


问:
Ajax with CakePHP and Javascript
i' m pretty new in using CakePHP and Javascript, i read many articles about request handling in cake, but i'm still confused, what i'm try to do is to send ajax request from my Javascript code to cakePHP and obtain some data in json format, i tried many ways to do this, but all the time I get simply html of page, instead of data i want to get, I have generated by default app controller class, as a url in Javascript request i use "http://localhost/pages/main" which is url of my view page where i have input controls, i wonder where in controller class should i put code responsible for handling request, and how to implement sending json response, thanks in advance

php code AppController class

```<code>public function beforeRender(Event $event)
{
    // Note: These defaults are just to get started quickly with development
    // and should not be used in production. You should instead set "_serialize"
    // in each action as required.
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);

        if ($this->request->is('ajax')) {
            $data = ['data1', 'data2'];
            $this->set(compact('data'));
            $this->set('_serialize', ['data']);
        }
    }

    **javascript:**

    var xhr = new XMLHttpRequest();
    var url = 'localhost/pages/main.json';
    var data = {
        unit: 'someUnit',
        name: this.name
    };

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            console.log(xhr.response);
        }
    };
    xhr.open('POST', url);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(data);
</code>```

答:
You can start here: CakePHP official documentation for REST

Example:

```<code>// src/Controller/RecipesController.php
class RecipesController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function index()
    {
        $recipes = $this->Recipes->find('all');
        $this->set([
            'recipes' => $recipes,
            '_serialize' => ['recipes']
        ]);
    }
}
</code>```

Title: Ajax with CakePHP and Javascript

Body:
i' m pretty new in using CakePHP and Javascript, i read many articles about request handling in cake, but i'm still confused, what i'm try to do is to send ajax request from my Javascript code to cakePHP and obtain some data in json format, i tried many ways to do this, but all the time I get simply html of page, instead of data i want to get, I have generated by default app controller class, as a url in Javascript request i use "http://localhost/pages/main" which is url of my view page where i have input controls, i wonder where in controller class should i put code responsible for handling request, and how to implement sending json response, thanks in advance

php code AppController class

public function beforeRender(Event $event)
{
    // Note: These defaults are just to get started quickly with development
    // and should not be used in production. You should instead set "_serialize"
    // in each action as required.
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);

        if ($this->request->is('ajax')) {
            $data = ['data1', 'data2'];
            $this->set(compact('data'));
            $this->set('_serialize', ['data']);
        }
    }

    **javascript:**

    var xhr = new XMLHttpRequest();
    var url = 'localhost/pages/main.json';
    var data = {
        unit: 'someUnit',
        name: this.name
    };

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            console.log(xhr.response);
        }
    };
    xhr.open('POST', url);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(data);

Body:
You can start here: CakePHP official documentation for REST

Example:

// src/Controller/RecipesController.php
class RecipesController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function index()
    {
        $recipes = $this->Recipes->find('all');
        $this->set([
            'recipes' => $recipes,
            '_serialize' => ['recipes']
        ]);
    }
}


问:
No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

```<code>/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.
</code>```

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

```<code><style name="Base.V26.Widget.AppCompat.Toolbar" parent="Base.V7.Widget.AppCompat.Toolbar">
    <item name="android:touchscreenBlocksFocus">true</item>
    <item name="android:keyboardNavigationCluster">true</item>
</style>
</code>```

We're using the following versions:

```<code>ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"
</code>```

```<code>compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
</code>```

Any ideas?

答:
In my react-native project, this error is generated in the react-native-fbsdk. Updating the react-native-fbsdk/android/build.gradle as following fixes the issue.

```<code>compileSdkVersion 26
buildToolsVersion "26.0.1"
</code>```

Body:
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

We're using the following versions:

ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"

compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION

Any ideas?

Body:
In my react-native project, this error is generated in the react-native-fbsdk. Updating the react-native-fbsdk/android/build.gradle as following fixes the issue.

compileSdkVersion 26
buildToolsVersion "26.0.1"


问:
SQL - Turn one date column into FromDate & ToDate columns
I am new to SQL and mostly use the data from Queries in Power BI.

I  to split my date column into two date columns in SQL based on Status. (on The days that status was changed)

I have an SQL query which gives me below straightforward results

```<code>SERIAL NO         ENTITY_CODE COMPANY_NAME      STATUS       TRANSACTION_DATE
AB:CD:EF:GH:IJ:KL FRANCIS     MADICAL           Activation      27-04-12 18:30
AB:CD:EF:GH:IJ:KL DEADPOOL    FAST TRANSPORT    Disconnection   27-12-14 15:01
12345678901       DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:30
12345678901       DEADPOOL    FAST TRANSPORT    Disconnection   17-01-16 16:35
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:31
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Disconnection   02-12-13 13:26
78901234567       BANDHU      BANDHU CABS       Activation      27-04-12 19:12
78901234567       BANDHU      BANDHU CABS       Disconnection   27-10-13 19:42
78901234567       DEADPOOL    FAST TRANSPORT    Reconnection    25-02-14 13:53
78901234567       DEADPOOL    FAST TRANSPORT    Disconnection   08-04-16 17:14
</code>```

This one is simple 'select' query with some conditions and 'Order By'.

In order to find, how many days this Serial No was Active and DisConnected, I need this data in below-mentioned format. Which I need for Power BI.

```<code>SERIAL NO           ENTITY_CODE  COMPANY_NAME   STATUS          FromDate      ToDATE
AB:CD:EF:GH:IJ:KL   FRANCIS      MADICAL        Activation      27-04-12 18:30  27-12-14 15:01
AB:CD:EF:GH:IJ:KL   DEADPOOL     FAST TRANSPORT Disconnection   27-12-14 15:01  TODAY'S DATE
12345678901         DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:30  17-01-16 16:35
12345678901         DEADPOOL     FAST TRANSPORT Disconnection   17-01-16 16:35  TODAY'S DATE
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:31  02-12-13 13:26
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Disconnection   02-12-13 13:26  TODAY'S DATE
78901234567         BANDHU       BANDHU CABS    Activation      27-04-12 19:12  27-10-13 19:42
78901234567         BANDHU       BANDHU CABS    Disconnection   27-10-13 19:42  25-02-14 13:53
78901234567         DEADPOOL     FAST TRANSPORT Reconnection    25-02-14 13:53  08-04-16 17:14
78901234567         DEADPOOL     FAST TRANSPORT Disconnection   08-04-16 17:14  TODAY'S DATE
</code>```

Please note 'Today's Date' in ToDate Column.
This data will ultimately give me Status of every Serial No on Every day of that Number's Life.

I need to divide  'Transaction History' based on every transaction date so that I will be able to find out that certain Serial Number was active from  date1 to date2, and then disconnected from date 2 to date 3, and so on

Can someone help?

答:
```<code>SELECT
    SERIAL NO
        ,ENTITY_CODE COMPANY_NAME
        ,STATUS
        ,TRANSACTION_DATE
    ,CASE STATUS
        WHEN 'Activation' THEN <WHAT EVER YOU WANT TO HAPPEN>
        WHEN 'Disconnection' THEN <WHAT EVER YOU WANT TO HAPPEN>
        WHEN 'Reconnection' THEN <WHAT EVER YOU WANT TO HAPPEN>
        ELSE <WHAT EVER YOU WANT TO HAPPEN>
        END as ToDATE
FROM
    <Table Name>
</code>```

Body:
I am new to SQL and mostly use the data from Queries in Power BI.

I  to split my date column into two date columns in SQL based on Status. (on The days that status was changed)

I have an SQL query which gives me below straightforward results

SERIAL NO         ENTITY_CODE COMPANY_NAME      STATUS       TRANSACTION_DATE
AB:CD:EF:GH:IJ:KL FRANCIS     MADICAL           Activation      27-04-12 18:30
AB:CD:EF:GH:IJ:KL DEADPOOL    FAST TRANSPORT    Disconnection   27-12-14 15:01
12345678901       DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:30
12345678901       DEADPOOL    FAST TRANSPORT    Disconnection   17-01-16 16:35
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:31
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Disconnection   02-12-13 13:26
78901234567       BANDHU      BANDHU CABS       Activation      27-04-12 19:12
78901234567       BANDHU      BANDHU CABS       Disconnection   27-10-13 19:42
78901234567       DEADPOOL    FAST TRANSPORT    Reconnection    25-02-14 13:53
78901234567       DEADPOOL    FAST TRANSPORT    Disconnection   08-04-16 17:14

This one is simple 'select' query with some conditions and 'Order By'.

In order to find, how many days this Serial No was Active and DisConnected, I need this data in below-mentioned format. Which I need for Power BI.

SERIAL NO           ENTITY_CODE  COMPANY_NAME   STATUS          FromDate      ToDATE
AB:CD:EF:GH:IJ:KL   FRANCIS      MADICAL        Activation      27-04-12 18:30  27-12-14 15:01
AB:CD:EF:GH:IJ:KL   DEADPOOL     FAST TRANSPORT Disconnection   27-12-14 15:01  TODAY'S DATE
12345678901         DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:30  17-01-16 16:35
12345678901         DEADPOOL     FAST TRANSPORT Disconnection   17-01-16 16:35  TODAY'S DATE
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:31  02-12-13 13:26
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Disconnection   02-12-13 13:26  TODAY'S DATE
78901234567         BANDHU       BANDHU CABS    Activation      27-04-12 19:12  27-10-13 19:42
78901234567         BANDHU       BANDHU CABS    Disconnection   27-10-13 19:42  25-02-14 13:53
78901234567         DEADPOOL     FAST TRANSPORT Reconnection    25-02-14 13:53  08-04-16 17:14
78901234567         DEADPOOL     FAST TRANSPORT Disconnection   08-04-16 17:14  TODAY'S DATE

Please note 'Today's Date' in ToDate Column.
This data will ultimately give me Status of every Serial No on Every day of that Number's Life.

I need to divide  'Transaction History' based on every transaction date so that I will be able to find out that certain Serial Number was active from  date1 to date2, and then disconnected from date 2 to date 3, and so on

Can someone help?


答: There is no option to set timeout on batch job but you can setup a lambda function that triggers every 1 hour or so and deletes jobs created before say 24 hours.

Title: Is there a way to set a walltime on AWS Batch jobs?

Body: Is there a way to set a maximum running time for AWS Batch jobs (or queues)? This is a standard setting in most batch managers, which avoids wasting resources when a job hangs for whatever reason.


问:
Replace Node Name
Is it possible to replace a nodes name? Like:

HTML:

```<code><strong id="element">Text</strong>
</code>```

Javascript:

```<code>var element = document.getElementById("element");
    element.nodeName = "b";
</code>```

As I see it's not working, if it's not possible in this way, then how can it be done?

Why I need it:

I'm building a Text Editor, and IE uses strong instead of b in the execCommand() function and I would like to change that, I tried to build the execCommand("bold") from scratch but there is a lots of problem and differences even between IE 8 and 9. So now I decided to change it's node name, it would be really easy, but doesn't works.. :(

Note: I need this to work only in Internet Explorer.

Thanks

答:
You could try getting the outerHTML and replacing the start and end tags.

```<code>var element = document.getElementById("element");
element.outerHTML = element.outerHTML.trim()
                                     .replace('<strong ','<button ')
                                     .replace('</strong>'.'</button');
</code>```

Note well though, the solution above is applicable only for simple use cases. For a better solution go through snippet below.

var element = document.getElementById("element");
changeNodeName(element,'button');

function changeNodeName(el,str){
  var elNodeName = el.nodeName.toLowerCase();
  var newString = el.outerHTML.trim()
                    .replace('<'+ elNodeName,'<'+str);

  // To replace the end tag, we can't simply use replace()
  // because, replace() will replace the first occurrence,
  // which means if our element has a child element with the
  // same node name the end tag of the *child element* will be
  // replaced, not the parent element. So,

  newString = newString
           .slice(0,newString.lastIndexOf('</'+str+'>'));
  //now newString = "<button id='element'>Text"

  newString = newString + "</" + str + ">";
  el.outerHTML = newString;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><strong id="element">
  <strong>
    Text
  </strong>
</strong></code>```

Title: Replace Node Name

Body:
Is it possible to replace a nodes name? Like:

HTML:

Text

Javascript:

var element = document.getElementById("element");
    element.nodeName = "b";

As I see it's not working, if it's not possible in this way, then how can it be done?

Why I need it:

I'm building a Text Editor, and IE uses strong instead of b in the execCommand() function and I would like to change that, I tried to build the execCommand("bold") from scratch but there is a lots of problem and differences even between IE 8 and 9. So now I decided to change it's node name, it would be really easy, but doesn't works.. :(

Note: I need this to work only in Internet Explorer.

Thanks

Body:
You could try getting the outerHTML and replacing the start and end tags.

var element = document.getElementById("element");
element.outerHTML = element.outerHTML.trim()
                                     .replace('<strong ','<button ')
                                     .replace('</strong>'.'</button');

Note well though, the solution above is applicable only for simple use cases. For a better solution go through snippet below.

var element = document.getElementById("element");
changeNodeName(element,'button');

function changeNodeName(el,str){
  var elNodeName = el.nodeName.toLowerCase();
  var newString = el.outerHTML.trim()
                    .replace('<'+ elNodeName,'<'+str);

  // To replace the end tag, we can't simply use replace()
  // because, replace() will replace the first occurrence,
  // which means if our element has a child element with the
  // same node name the end tag of the *child element* will be
  // replaced, not the parent element. So,

  newString = newString
           .slice(0,newString.lastIndexOf('</'+str+'>'));
  //now newString = "<button id='element'>Text"

  newString = newString + "</" + str + ">";
  el.outerHTML = newString;
}

<strong id="element">
  <strong>
    Text
  </strong>
</strong>


问:
Reason for: Trying to get property of non-object in php
```<code>    if(isset($_POST['uname']))
    {
        $query = "SELECT * FROM user_info";
        $res = $mysqli->query($query);
        $num = $res->num_rows;
        $i = 0;
        $cpwd = $_POST["pswd"];
        $hpwd = SHA1($cpwd);
        $tmp = $_POST["uname"];
        while($i < $num)
        {
            $row = $res->fetch_object();
            $name = $row->Username;
            $pwd = $row->Password;
            if($name == $tmp)
            {
                   //check if user is blocked
            }
            //hashed pwd
            if($pwd == $hpwd)
            {
                //success
                exit();
            }
            //request for pwd change
        else if($pwd == $cpwd)
            {
            //change
                exit();
            }
            else if($pwd != $hpwd)
            {

                //incorrect pwd
            }
        }
        $i++;
    }
    if($i == $num)
    {
        //new user
    }
}
</code>```

答: So $res->fetch_object() did not return an object. Take a look at the documentation of this function. What does it return when it finds nothing?


问:
Convert a date to intervals of time
I have a column in my data.frame that is formatted as date ("2006-03-09 17:00:00") and I want a new column that gives me ranges like "morning", "afternoon", "evening". I am trying the following without success:

```<code>mydf <- mydf %>%
        mutate (dateInterval = ifelse (data < "13:00", "morning",
                               ifelse (data > "18:00", "evening", "afternoon")))
</code>```

答:
You have not shared your data so it is difficult to produce an ad-hoc solution.

The steps are the following:
1) Be sure that your date is in POSIXct class

```<code>mydf$timestamp <- as.POSIXct(paste(mydf$timestamp, mydf$timestamp), format="%Y-%m-%d %H:%M:%S")
</code>```

2) Extract the Hour component from this Date&Time object

```<code>mydf$hour <- format(strptime(as.character(mydf$timestamp), "%H:%M:%S"), "%H:%M:%S")
</code>```

3) Create a table containing the time_slot information

```<code>description <- c("Morning", "Day", "Evening", "Night")
from <- as.character(c("07:00:00", "10:30:00", "17:30:00", "20:30:00"))
to <- as.character(c("10:29:59", "17:29:59", "20:29:59", "06:59:59"))
context_table <- data.frame(description, from, to)
</code>```

4) Be sure that context_table$from and context_table$to are character type in order to allow comparison with mydf$hour

```<code>context_table$from <- as.character(context_table$from)
context_table$to <- as.character(context_table$to)
</code>```

5) Associate the context_table$description to each record in mydf

```<code>mydf$time_slot <- NULL
for (i in 1:(dim(context_table)[1]-1)){
        mydf[mydf$hour_crash >= context_table$from[i] & mydf$hour_crash <= context_table$to[i], "time_slot"] <- context_table[i, "description"]
}
mydf[is.na(mydf$time_slot), "time_slot"] <- context_table[dim(context_table), "description"]
</code>```

Since the clock is circular in the interval [00:00:00; 23:59:59], it is necessary to do the workaround of point 5).

Title: Convert a date to intervals of time

Body:
I have a column in my data.frame that is formatted as date ("2006-03-09 17:00:00") and I want a new column that gives me ranges like "morning", "afternoon", "evening". I am trying the following without success:

mydf <- mydf %>%
        mutate (dateInterval = ifelse (data < "13:00", "morning",
                               ifelse (data > "18:00", "evening", "afternoon")))

Body:
You have not shared your data so it is difficult to produce an ad-hoc solution.

The steps are the following:
1) Be sure that your date is in POSIXct class

mydf$timestamp <- as.POSIXct(paste(mydf$timestamp, mydf$timestamp), format="%Y-%m-%d %H:%M:%S")

2) Extract the Hour component from this Date&Time object

mydf$hour <- format(strptime(as.character(mydf$timestamp), "%H:%M:%S"), "%H:%M:%S")

3) Create a table containing the time_slot information

description <- c("Morning", "Day", "Evening", "Night")
from <- as.character(c("07:00:00", "10:30:00", "17:30:00", "20:30:00"))
to <- as.character(c("10:29:59", "17:29:59", "20:29:59", "06:59:59"))
context_table <- data.frame(description, from, to)

4) Be sure that context_table$from and context_table$to are character type in order to allow comparison with mydf$hour

context_table$from <- as.character(context_table$from)
context_table$to <- as.character(context_table$to)

5) Associate the context_table$description to each record in mydf

mydf$time_slot <- NULL
for (i in 1:(dim(context_table)[1]-1)){
        mydf[mydf$hour_crash >= context_table$from[i] & mydf$hour_crash <= context_table$to[i], "time_slot"] <- context_table[i, "description"]
}
mydf[is.na(mydf$time_slot), "time_slot"] <- context_table[dim(context_table), "description"]

Since the clock is circular in the interval [00:00:00; 23:59:59], it is necessary to do the workaround of point 5).


问:
How to create a tkinter error message box
I am wanting to create a simple message box in Tkinter that appears and displays the exact error message.  Could anyone direct me to how this might be
 achieved in tkinter, I have not been able to find much on this topic.

E.g:

```<code>traceback.format_exc().replace(':', '-')
ctypes.windll.user32.MessageBoxW(0, "Error", "Have you checked your fridge?"d, 1)
                                                             ^
#'SyntaxError: invalid syntax'
</code>```

I am wanting to add this with pyinstaller.  I suppose pyinstaller creates a text file and you can see in cmd before it closes, but it would be nice if a message box appear with exact traceerror.

答:
```<code>from tkinter import messagebox

messagebox.showerror("Title", "Message")
</code>```

check here for more info

Body:
I am wanting to create a simple message box in Tkinter that appears and displays the exact error message.  Could anyone direct me to how this might be
 achieved in tkinter, I have not been able to find much on this topic.

E.g:

traceback.format_exc().replace(':', '-')
ctypes.windll.user32.MessageBoxW(0, "Error", "Have you checked your fridge?"d, 1)
                                                             ^
#'SyntaxError: invalid syntax'

I am wanting to add this with pyinstaller.  I suppose pyinstaller creates a text file and you can see in cmd before it closes, but it would be nice if a message box appear with exact traceerror.

Body:
from tkinter import messagebox

messagebox.showerror("Title", "Message")

check here for more info

ContentLicense: CC BY-SA 4.0


问:
Centimeter to pixel
How do I convert centimeter to pixel in c# ?</p>

答:
<s>As I said in my comment, you'll have to give more information. (Is this a Windows Forms app? ASP.Net?)</s>

The fundamental approach is:

Find out the DPI of the output device in question. (It's frequently 96 [96 dots per inch], but you cannot assume that.) This thread may help you do that, if it's a Windows Forms app. Also, the Graphics class has the DpiX and DpiY members, so you can use those.

Convert the DPI to DPC [dots-per-centimeter] (DPC = DPI / 2.54).

Multiply your number of centimeters by your DPC value.

Title: Centimeter to pixel


问:
Having javascript apply to multiple elements created by php foreach loop
I have this php foreach loop, which read the videos saved in a folder and load them into my page.
Under the videos I have created a like and dislike button, which i would like to work with javascript.
The problem is that I cant figure out, how to point js to buttons, when i create unique ID's for the buttons, with a counter in my foreach loop.

My php.

```<code>$i=1;
foreach($allfiles as $file) {
if($file != '.' && $file != '..' && $file != video/ini) // sikre den ikke
producere . og .. files
{

echo "<div>
        <div>
                        <video width=\"$videoW\" height=\"$videoH\"
controls>
                          <source src=\"". $dir . $file ."\" type=\"video/mp4\">
                          <source src=\"". $dir . $file ."\" type=\"video/ogg\">
                        </video>
                    </div>

<div><strong> Recorded:</strong> $file </div> </div>";

echo '<img src="/img/like-icon.png" id="like'.$i.'"
style="width:40px;height:40px;">';
echo '<img src="/img/dislike-icon.png" id="dislike'.$i.'"
style="width:40px;height:40px;">';
echo '<p style=display:none; id="text'.$i.'">Submitted!</p>';
$i++;
</code>```

My javascript

```<code><script type='text/javascript'>
      for (var i = 0; i < 100; i++) {

        var button = document.getElementById(like[i]);
        var button2 = document.getElementById(dislike[i]);

        button.onclick = function() {
           var text = document.getElementById(text[i]);
           var like = document.getElementById(like[i]);
           var dislike = document.getElementById(dislike[i]);
           if (text.style.display !== 'none') {
              text.style.display = 'none';

           }
           else {
              text.style.display = 'block';
              like.style.display = 'none';
              dislike.style.display = 'none';
        }
     };

        button2.onclick = function() {
           var text = document.getElementById(text[i]);
           var dislike = document.getElementById(dislike[i]);
           var like = document.getElementById(like[i]);

           if (text.style.display !== 'none') {
              text.style.display = 'none';

           }
           else {
             text.style.display = 'block';
             like.style.display = 'none';
             dislike.style.display = 'none';
        }

     };
  };
</code>```

答:
If I am not wrong,you want like/dislike for perticular video,then try

onclick event on like/dislike image icon .

```<code>onclick="user_responce(responce,id)"
</code>```

where,

responce:- 1:like,2:dislike

id:- unique video id

In user_responce function do what you want according to responce.

Hope this work for you.

Body:
I have this php foreach loop, which read the videos saved in a folder and load them into my page.
Under the videos I have created a like and dislike button, which i would like to work with javascript.
The problem is that I cant figure out, how to point js to buttons, when i create unique ID's for the buttons, with a counter in my foreach loop.

My php.

$i=1;
foreach($allfiles as $file) {
if($file != '.' && $file != '..' && $file != video/ini) // sikre den ikke
producere . og .. files
{

echo "

                        <video width=\"$videoW\" height=\"$videoH\"
controls>
                          <source src=\"". $dir . $file ."\" type=\"video/mp4\">
                          <source src=\"". $dir . $file ."\" type=\"video/ogg\">
                        </video>

 Recorded: $file

";

echo '';
echo '';
echo '
Submitted!
';
$i++;

My javascript

Body:
If I am not wrong,you want like/dislike for perticular video,then try

onclick event on like/dislike image icon .

onclick="user_responce(responce,id)"

where,

responce:- 1:like,2:dislike

id:- unique video id

In user_responce function do what you want according to responce.

Hope this work for you.


问:
Kafka logs configuration is not be picked up when starting kafka via Confluent CLI
I am trying to upgrade from the apache kafka to the confluent kafka

As the storage of the temp folder is quite limited I have changed the log.dirs of server.properties to a custom folder

```<code>log.dirs=<custom  location>
</code>```

Then try to start kafka server via the Confluent CLI (version 4.0) using below command :

```<code>bin/confluent start kafka
</code>```

However when I check the kafka data folder, the data still persitted under the temp folder instead of the customzied one.

I have tried to start kafka server directly which is not using the Confluent CLI

```<code>bin/kafka-server-start etc/kafka/server.properties
</code>```

then seen the config has been picked up properly

is this a bug with confluent CLI or it is supposed to be

答:
Confluent CLI is meant to be used during development with Confluent Platform. Therefore, it currently gathers all the data and logs under a common location in order for a developer to be able to easily inspect (with confluent log or manually) and delete (with confluent destroy or manually) such data.

You are able to change this common location by setting

export CONFLUENT_CURRENT=<top-level-logs-and-data-directory>

and get which location is used any time with:

confluent current

The rest of the properties are used as set in the various .properties files for each service.

Body:
I am trying to upgrade from the apache kafka to the confluent kafka

As the storage of the temp folder is quite limited I have changed the log.dirs of server.properties to a custom folder

log.dirs=<custom  location>

Then try to start kafka server via the Confluent CLI (version 4.0) using below command :

bin/confluent start kafka

However when I check the kafka data folder, the data still persitted under the temp folder instead of the customzied one.

I have tried to start kafka server directly which is not using the Confluent CLI

bin/kafka-server-start etc/kafka/server.properties

then seen the config has been picked up properly

is this a bug with confluent CLI or it is supposed to be


问:
getting parsed json value
I am trying to utilize bcrypt to check the hashes saved in my db for passwords, but the json response is currently returning below:

```<code>[
    {
        "password": "$2a$10$8/o1McdQ24pL5MU7dkbhmewkjne83M2duPKp0cb6uowWvOPS"
    }
]
</code>```

This is causing an error on the bcrypt compare, because it is comparing that entire response instead of just the hash inside of it.  How can I get just the value of the hash in my response?  Below is my code:

```<code>app.get('/checkHash/:username/:pass', function(req, res) {
    console.log('below is the data');
    console.log(req.params);
    var pass = req.params.pass

        var createPromise = interact.getHash(req.params.username);
        //did promise
        createPromise.then(function(createResponse) {
            //below checks to see if the password value matches the hash
            if(bcrypt.compareSync(pass, createResponse)) {
                //this means that the hashes are the same for user login
                res.json("yes");
            } else {
                //this means that the password hashes didn't match
                res.json("no");
         }
        }).catch(function(err) {
        console.log(err);
    });
});
</code>```

答:
Your response is apparently an object array. If you just want to compare the first result of your array, you have to pass the index to your array. </p>

```<code>app.get('/checkHash/:username/:pass', function(req, res) {
    console.log('below is the data');
    console.log(req.params);
    var pass = req.params.pass

        var createPromise = interact.getHash(req.params.username);
        //did promise
        createPromise.then(function(createResponse) {
            //below checks to see if the password value matches the hash
            if(bcrypt.compareSync(pass, createResponse[0].password)) {
                //this means that the hashes are the same for user login
                res.json("yes");
            } else {
                //this means that the password hashes didn't match
                res.json("no");
         }
        }).catch(function(err) {
        console.log(err);
    });
});
</code>```

Title: getting parsed json value

Body:
I am trying to utilize bcrypt to check the hashes saved in my db for passwords, but the json response is currently returning below:

[
    {
        "password": "$2a$10$8/o1McdQ24pL5MU7dkbhmewkjne83M2duPKp0cb6uowWvOPS"
    }
]

This is causing an error on the bcrypt compare, because it is comparing that entire response instead of just the hash inside of it.  How can I get just the value of the hash in my response?  Below is my code:

app.get('/checkHash/:username/:pass', function(req, res) {
    console.log('below is the data');
    console.log(req.params);
    var pass = req.params.pass

        var createPromise = interact.getHash(req.params.username);
        //did promise
        createPromise.then(function(createResponse) {
            //below checks to see if the password value matches the hash
            if(bcrypt.compareSync(pass, createResponse)) {
                //this means that the hashes are the same for user login
                res.json("yes");
            } else {
                //this means that the password hashes didn't match
                res.json("no");
         }
        }).catch(function(err) {
        console.log(err);
    });
});

Body:
Your response is apparently an object array. If you just want to compare the first result of your array, you have to pass the index to your array.

app.get('/checkHash/:username/:pass', function(req, res) {
    console.log('below is the data');
    console.log(req.params);
    var pass = req.params.pass

        var createPromise = interact.getHash(req.params.username);
        //did promise
        createPromise.then(function(createResponse) {
            //below checks to see if the password value matches the hash
            if(bcrypt.compareSync(pass, createResponse[0].password)) {
                //this means that the hashes are the same for user login
                res.json("yes");
            } else {
                //this means that the password hashes didn't match
                res.json("no");
         }
        }).catch(function(err) {
        console.log(err);
    });
});


问:
Where are Angular's webpack bundles configured?
With the default new Angular CLI based project and it's webpack integration some things are weird. Where are the default bundles configured?

I removed the styles.css file now the project doesn't build.

```<code>chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]chunk {main} main.bundle.js, main.bundle.js.map (main) 303 bytes [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 323 bytes [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 342 bytes [initial] [rendered]

ERROR in multi ./src/styles.css
Module not found: Error: Can't resolve 'D:\project\src\styles.css'
</code>```

答: Inside your .angular-cli.json file there is still a reference to the styles.css. Remove the entry from apps.styles as well, and it won't throw an error anymore

Body:
With the default new Angular CLI based project and it's webpack integration some things are weird. Where are the default bundles configured?

I removed the styles.css file now the project doesn't build.

chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]chunk {main} main.bundle.js, main.bundle.js.map (main) 303 bytes [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 323 bytes [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 342 bytes [initial] [rendered]

ERROR in multi ./src/styles.css
Module not found: Error: Can't resolve 'D:\project\src\styles.css'


问:
Select statement in a for-loop reading from a closed channel gives zero values forever
Given this code that simulates fetching of some website-stuff for 3 URL's using a fan-in pattern and range over the condensed channel: https://play.golang.org/p/MSkRI7x4vz

```<code>for s := range r {
    println(s)
}
</code>```

This works well, but I want to use an overall timeout signal channel, so I try to use a select in a for-loop like this:
https://play.golang.org/p/LjDoIc0j-z

```<code>totalTimeout := time.After(300 * time.Millisecond)
loop:
    for {
        select {
        case s := <-r:
            fmt.Println(s)
        case <-totalTimeout: // signaling usage of a channel
            fmt.Println("Timed out")
            break loop
        }
    }
}
</code>```

This behaves not well: After the input channels are closed, the condensed channel from fan-in is closed. But now zero-values are read until the timeout effectively occurs. When I read http://www.tapirgames.com/blog/golang-channel or the specs https://golang.org/ref/spec#Close it seems that receiving from a closed channel "never blocks" and thus gives back zero values. I can only guess, that a range detects the close, where the select cannot, because it's condition is a read from a channel in itself.

I could break out like this

```<code>case s := <-r:
    if s == "" {
        break loop
    }
    fmt.Println(s)
</code>```

Is there another approach to stop getting empty values or is this the proper idiomatic way using a select in a for loop?

答:
Receive on a closed channel yields the zero value after all elements in the channel are received.

Use the two value receive to detect when the channel is closed and break from the loop.  The second value is false when the channel yields a zero value because the channel is closed.

```<code>for {
    select {
    case s, ok := <-r:
        if !ok {
            break loop
        }
        fmt.Println(s)
    case <-totalTimeout: // signaling usage of a channel
        fmt.Println("Timed out")
        break loop
    }
}
</code>```

Body:
Given this code that simulates fetching of some website-stuff for 3 URL's using a fan-in pattern and range over the condensed channel: https://play.golang.org/p/MSkRI7x4vz

for s := range r {
    println(s)
}

This works well, but I want to use an overall timeout signal channel, so I try to use a select in a for-loop like this:
https://play.golang.org/p/LjDoIc0j-z

totalTimeout := time.After(300 * time.Millisecond)
loop:
    for {
        select {
        case s := <-r:
            fmt.Println(s)
        case <-totalTimeout: // signaling usage of a channel
            fmt.Println("Timed out")
            break loop
        }
    }
}

This behaves not well: After the input channels are closed, the condensed channel from fan-in is closed. But now zero-values are read until the timeout effectively occurs. When I read http://www.tapirgames.com/blog/golang-channel or the specs https://golang.org/ref/spec#Close it seems that receiving from a closed channel "never blocks" and thus gives back zero values. I can only guess, that a range detects the close, where the select cannot, because it's condition is a read from a channel in itself.

I could break out like this

case s := <-r:
    if s == "" {
        break loop
    }
    fmt.Println(s)

Is there another approach to stop getting empty values or is this the proper idiomatic way using a select in a for loop?

Body:
Receive on a closed channel yields the zero value after all elements in the channel are received.

Use the two value receive to detect when the channel is closed and break from the loop.  The second value is false when the channel yields a zero value because the channel is closed.

for {
    select {
    case s, ok := <-r:
        if !ok {
            break loop
        }
        fmt.Println(s)
    case <-totalTimeout: // signaling usage of a channel
        fmt.Println("Timed out")
        break loop
    }
}


问:
What APIs do I need to look at to code my own windows drive letter
I was thinking of messing around with my own file system code, as a learning exercise. To start with this could be a RAM drive, or just mounted within a file on another drive. Questions:

What windows APIs would I need to program to implement my own drive letter (eg an M: with my system)

Where is the documentation for these APIs?

Can you implement them using C#?

NB:

I know there are other Ram drive implementations out there - I don't need a list of them.

I've tried googling, but found it very hard to find the right search terms.

I'm not fussy for now about which version of windows, any version is fine as I'm developing using Windows 7, but I hope that version for earlier Windows will still work

答:
Depending on what you need (implement a file system or just a virtual disk with existing file system) you can use one of our virtual storage products: Callback File System and CallbackDisk respectively.

The difference is that CallbackDisk emulates a disk device (so you can mount, for example, ISO image there), and Callback File System lets you build your own file system (eg. distributed, or just remotely stored)

.NET APIs are available in both products.


问:
Spring GeneratedValue annotation usage
Let's say that I have a Car entity:

```<code>@Entity
public class Car {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private Integer id;
</code>```

How does spring know what value to autoincrement when I add a new object to the database?

答:
Here is a good explanation of primary keys generation strategies

There are 4 options to generate primary keys

GenerationType.AUTO

The GenerationType.AUTO is the default generation type and lets the
  persistence provider choose the generation strategy.

If you use Hibernate as your persistence provider, it selects a
  generation strategy based on the database specific dialect. For most
  popular databases, it selects GenerationType.SEQUENCE.

GenerationType.IDENTITY

The GenerationType.IDENTITY is the easiest to use but not the best one
  from a performance point of view. It relies on an auto-incremented
  database column and lets the database generate a new value with each
  insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn’t require any additional statements.

This approach has a significant drawback if you use Hibernate.
  Hibernate requires a primary key value for each managed entity and
  therefore has to perform the insert statement immediately. This
  prevents it from using different optimization techniques like JDBC
  batching.

GenerationType.SEQUENCE

The GenerationType.SEQUENCE uses a database sequence to generate
  unique values. It requires additional select statements to get the
  next value from a database sequence. But this has no performance
  impact for most applications.

If you don’t provide any additional information, Hibernate will
  request the next value from its default sequence. You can change that
  by referencing the name of a @SequenceGenerator in the generator
  attribute of the @GeneratedValue annotation. The @SequenceGenerator
  annotation lets you define the name of the generator, the name, and
  schema of the database sequence and the allocation size of the
  sequence.

```<code>@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@SequenceGenerator(name="car_generator", sequenceName = "car_seq", allocationSize=50)
private Long id;
</code>```

(Side note: Usually prefer Long for ids instead of Integer so you're less likely to run out)

GenerationType.TABLE

The GenerationType.TABLE gets only rarely used nowadays. It simulates
  a sequence by storing and updating its current value in a database
  table which requires the use of pessimistic locks which put all
  transactions into a sequential order. This slows down your
  application, and you should, therefore, prefer the
  GenerationType.SEQUENCE, if your database supports sequences, which
  most popular databases do.

Title: Spring GeneratedValue annotation usage

Body:
Let's say that I have a Car entity:

@Entity
public class Car {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private Integer id;

How does spring know what value to autoincrement when I add a new object to the database?

Body:
Here is a good explanation of primary keys generation strategies

There are 4 options to generate primary keys

GenerationType.AUTO

The GenerationType.AUTO is the default generation type and lets the
  persistence provider choose the generation strategy.

If you use Hibernate as your persistence provider, it selects a
  generation strategy based on the database specific dialect. For most
  popular databases, it selects GenerationType.SEQUENCE.

GenerationType.IDENTITY

The GenerationType.IDENTITY is the easiest to use but not the best one
  from a performance point of view. It relies on an auto-incremented
  database column and lets the database generate a new value with each
  insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn’t require any additional statements.

This approach has a significant drawback if you use Hibernate.
  Hibernate requires a primary key value for each managed entity and
  therefore has to perform the insert statement immediately. This
  prevents it from using different optimization techniques like JDBC
  batching.

GenerationType.SEQUENCE

The GenerationType.SEQUENCE uses a database sequence to generate
  unique values. It requires additional select statements to get the
  next value from a database sequence. But this has no performance
  impact for most applications.

If you don’t provide any additional information, Hibernate will
  request the next value from its default sequence. You can change that
  by referencing the name of a @SequenceGenerator in the generator
  attribute of the @GeneratedValue annotation. The @SequenceGenerator
  annotation lets you define the name of the generator, the name, and
  schema of the database sequence and the allocation size of the
  sequence.

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@SequenceGenerator(name="car_generator", sequenceName = "car_seq", allocationSize=50)
private Long id;

(Side note: Usually prefer Long for ids instead of Integer so you're less likely to run out)

GenerationType.TABLE

The GenerationType.TABLE gets only rarely used nowadays. It simulates
  a sequence by storing and updating its current value in a database
  table which requires the use of pessimistic locks which put all
  transactions into a sequential order. This slows down your
  application, and you should, therefore, prefer the
  GenerationType.SEQUENCE, if your database supports sequences, which
  most popular databases do.


问:
get first letter of a String (sentence) given in a column and create a new column in python
I have a column in pandas dataframe which has items like following,

```<code>SubBrand
Sam William Mathew
Jonty Rodes
Chris Gayle
</code>```

I want to create a new column (SubBrand_new) such as

```<code>  SubBrand_new
0 SWM
1 JR
2 CG
</code>```

I am using this piece of code,

```<code>df1["SubBrand_new"] = "".join([x[0] for x in (df1["SubBrand"].str.split())])
</code>```

but not able to get what I am looking for. Can anybody help?

答:
You want to apply a function to every line and return a new column with its result. This kind of operation can be applied with the .apply() method, a simple = attribution will not do the trick. A solution in the spirit of your code would be:

```<code>df = pd.DataFrame({'Name': ['Marcus Livius Drussus',
                            'Lucius Cornelius Sulla',
                            'Gaius Julius Caesar']})
df['Abrev'] = df.Name.apply(lambda x: "".join([y[0] for y in (x.split())]))
</code>```

Which yields

```<code>df
    Name                    Abrev
0   Marcus Levius Drussus   MLD
1   Lucius Cornelius Sulla  LCS
2   Gaius Julius Caesar     GJC
</code>```

EDIT:

I compared it to the other solution, thinking that the apply() method with join() would be pretty slow. I was surprised to find that it is in fact faster. Setting:

```<code>N = 3000000
bank = pd.util.testing.rands_array(3,N)
vec = [bank[3*i] + ' ' + bank[3*i+1] + ' ' + bank[3*i+2]  for i in range(N/3)]
df = pd.DataFrame({'Name': vec})
</code>```

I find:

```<code>df.Name.apply(lambda x: "".join([y[0] for y in (x.split())]))
executed in 581ms

df.Name.str.split(expand=True).apply(lambda x : x.str[0]).fillna('').sum(1)
executed in 2.81s
</code>```

Body:
I have a column in pandas dataframe which has items like following,

SubBrand
Sam William Mathew
Jonty Rodes
Chris Gayle

I want to create a new column (SubBrand_new) such as

  SubBrand_new
0 SWM
1 JR
2 CG

I am using this piece of code,

df1["SubBrand_new"] = "".join([x[0] for x in (df1["SubBrand"].str.split())])

but not able to get what I am looking for. Can anybody help?

Body:
You want to apply a function to every line and return a new column with its result. This kind of operation can be applied with the .apply() method, a simple = attribution will not do the trick. A solution in the spirit of your code would be:

df = pd.DataFrame({'Name': ['Marcus Livius Drussus',
                            'Lucius Cornelius Sulla',
                            'Gaius Julius Caesar']})
df['Abrev'] = df.Name.apply(lambda x: "".join([y[0] for y in (x.split())]))

Which yields

df
    Name                    Abrev
0   Marcus Levius Drussus   MLD
1   Lucius Cornelius Sulla  LCS
2   Gaius Julius Caesar     GJC

EDIT:

I compared it to the other solution, thinking that the apply() method with join() would be pretty slow. I was surprised to find that it is in fact faster. Setting:

N = 3000000
bank = pd.util.testing.rands_array(3,N)
vec = [bank[3*i] + ' ' + bank[3*i+1] + ' ' + bank[3*i+2]  for i in range(N/3)]
df = pd.DataFrame({'Name': vec})

I find:

df.Name.apply(lambda x: "".join([y[0] for y in (x.split())]))
executed in 581ms

df.Name.str.split(expand=True).apply(lambda x : x.str[0]).fillna('').sum(1)
executed in 2.81s


问:
Why DTD is not extensible?
I know that a language is extensible if it allows users to create any tags needed and then describing those tags and their permitted uses.

If I'm not wrong, in this example

code:

```<code><!ELEMENT people_list (person)*>
<!ELEMENT person (name, birthdate?, gender?, socialsecuritynumber?)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT birthdate (#PCDATA)>
<!ELEMENT gender (#PCDATA)>
<!ELEMENT socialsecuritynumber (#PCDATA)>
</code>```

The DTD is defining an element (tag) called person, another element called name etc...

So, why this is not extensible as XSD?

答:
Background: DTD exists to support the extensibility of XML.  Instead of
   a fixed markup language, XML allows you to define your own vocabulary
   and grammar via a schema such as DTD.

Why DTD is not extensible?

DTD is extensible.

DTDs can be extended via various techniques.  Examples include repeating ATTLIST to add attributes and redefining parameter ENTITIES.

There's a long history of clever DTD extensibility applied to substantial projects.  Examples:

TEI: The Text Encoding Initiative has extensible DTDs.

XHTML: See Developing DTDs with defined and extended modules.

So, why this is not extensible as XSD?

Because DTD predates XSD, and progress occurs.

See also

Is DTD deprecated?

Title: Why DTD is not extensible?

Body:
I know that a language is extensible if it allows users to create any tags needed and then describing those tags and their permitted uses.

If I'm not wrong, in this example

code:

<!ELEMENT people_list (person)*>
<!ELEMENT person (name, birthdate?, gender?, socialsecuritynumber?)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT birthdate (#PCDATA)>
<!ELEMENT gender (#PCDATA)>
<!ELEMENT socialsecuritynumber (#PCDATA)>

The DTD is defining an element (tag) called person, another element called name etc...

So, why this is not extensible as XSD?


答:
The Angular CLI provides configurations options using .angular-cli.json. This has a defined schema that defines the options that can be configured. As the Angular CLI wraps up Webpack for you, you can't get direct access to the Webpack config itself when using the Angular CLI. You have a couple of options:

Change the relevant settings in .angular-cli.json, if they fit.

Use ng eject on your project:

ng eject ejects your app and output the proper webpack configuration and scripts.

Once ejected, you can modify the Webpack configuration accordingly.

In order to fix your specific issue with styles.css, you can just go with option 1 and update .angular-cli.json to exclude this file - It's essentially specified under apps[0].styles, which defaults to an array with a single element: styles.css.

Title: Where are Angular's webpack bundles configured?


答: In WPF, one centimeter is about 37.8 device independent pixels.</p>

Title: Centimeter to pixel

Body: How do I convert centimeter to pixel in c# ?


问:
Modifying the color of an android drawable
I would like to be able to use the same drawable to represent both:

 and

as the same drawable, and re-color the drawable based on some programmatic values, so that the end user could re-theme the interface.

What is the best way to do this? I have tried (and reused the icons from) this previous S.O. question but I can't represent the change as a simple change of hue, since it also varies in saturation and value..

Is it best to store the icon as all white in the area I want changed? or transparent? or some other solid color?

Is there some method that allows you to figure out the matrix based on the difference between Color of red_icon and Color of blue_icon?

答:
This is what i did after looking into documentation

```<code>public PorterDuffColorFilter getDrawableFilter(){
        return new PorterDuffColorFilter(ContextCompat.getColor(this, R.color.color_black), PorterDuff.Mode.SRC_ATOP);
    }
</code>```

and called it

```<code>yourdrawable.setColorFilter(getDrawableFilter());
</code>```

Body:
This is what i did after looking into documentation

public PorterDuffColorFilter getDrawableFilter(){
        return new PorterDuffColorFilter(ContextCompat.getColor(this, R.color.color_black), PorterDuff.Mode.SRC_ATOP);
    }

and called it

yourdrawable.setColorFilter(getDrawableFilter());


问:
Syntax error on multiple join statement

Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks

```<code>String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";
</code>```

I was hoping that I could do multiple joins

But I am getting a syntax error.

答:
For access, parenthesis with multiple joins means the following. If you have three joins, there are two left parenthesis after the from.  The last join does not have a right parenthesis.

```<code>String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";
</code>```

Access SQL injection has been covered in other threads .

Title: Syntax error on multiple join statement

Body:
Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks

String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";

I was hoping that I could do multiple joins

But I am getting a syntax error.

Body:
For access, parenthesis with multiple joins means the following. If you have three joins, there are two left parenthesis after the from.  The last join does not have a right parenthesis.

String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";

Access SQL injection has been covered in other threads .


问:
Convert time duration (BigDecimal value + time units) to milliseconds long
I have to create a function that has 2 input parameters:
Time duration in BigDecimal (precision 38, scale 6)
and
TimeUnitsType enum (DAYS, HOURS, MINUTES or SECONDS).

And I need to get long value (milliseconds) as a result;
As I understand, the longValue() method from BigDecimal won't work precisely here as it set scale to 0, and longValueExact() will throw ArithmeticException("Overflow") (because precision - scale > 19)

```<code>public static long convertTimeToMillis(BigDecimal time, TimeUnitsType timeUnitsType) {
    long timeLong = time.longValue();
    switch (timeUnitsType) {
        case DAYS:
            return TimeUnit.DAYS.toMillis(timeLong);
        case HOURS:
            return TimeUnit.HOURS.toMillis(timeLong);
        case MINUTES:
            return TimeUnit.MINUTES.toMillis(timeLong);
        default:
            return TimeUnit.SECONDS.toMillis(timeLong);
    }
}
</code>```

So I need to make individual calculation for each case separately. Can you please help me? BigDecimal operations scares me a little, because I haven't work with them before :) And the precision is required in the rest of the task.

P.S. Java version is 1.6

答:
If time is in the unit of timeUnitsType and you are converting that time (in its units) to milliseconds then there is always the chance of an overflow. long simply cannot hold more than 19 digits, while here you could have 32 digits 6 decimal places in seconds and converting that to milliseconds would make it up to 35 digits. 32 digit days to milliseconds is even worse...

Are you sure you need to convert this BigDecimal in its TimeUnit to a single long in milliseconds?

BigDecimal.longValueExact() will throw an exception if there would be any information lost. So if you check for that exception and handle it then I guess things will be ok.

Body:
I have to create a function that has 2 input parameters:
Time duration in BigDecimal (precision 38, scale 6)
and
TimeUnitsType enum (DAYS, HOURS, MINUTES or SECONDS).

And I need to get long value (milliseconds) as a result;
As I understand, the longValue() method from BigDecimal won't work precisely here as it set scale to 0, and longValueExact() will throw ArithmeticException("Overflow") (because precision - scale > 19)

public static long convertTimeToMillis(BigDecimal time, TimeUnitsType timeUnitsType) {
    long timeLong = time.longValue();
    switch (timeUnitsType) {
        case DAYS:
            return TimeUnit.DAYS.toMillis(timeLong);
        case HOURS:
            return TimeUnit.HOURS.toMillis(timeLong);
        case MINUTES:
            return TimeUnit.MINUTES.toMillis(timeLong);
        default:
            return TimeUnit.SECONDS.toMillis(timeLong);
    }
}

So I need to make individual calculation for each case separately. Can you please help me? BigDecimal operations scares me a little, because I haven't work with them before :) And the precision is required in the rest of the task.

P.S. Java version is 1.6


问:
Misconception in Compiler's function
I have studied many articles to understand whether Compiler generates Object Code or Assembly Code and there is conflict, even in stack overflow. Some says Compiler generates Object Code while other says Compiler generates Assembly Code which is then converted to Object Code by Assembler. Both answers has up-votes. Is there any clarification or justification for this.

答:
Ultimately, the compiler has to somehow produce object files with the code that will end up in the application, and the linker combines the code from object files and libraries (which are just collections of object files) to produce the application. So it's correct to say that the compiler produces object files and the linker combines them.

On the other hand, there are various ways that the compiler can produce the object files. One way is to directly generate object files. Another way is to generate assembler code and run the assembler to produce the object files. That introduces some flexibility, because the compiler doesn't have to know the details of how object files are laid out; the assembler does that. Yet another way is to generate C code and run the C compiler (which could, in turn generate assembler code and run the assembler) on that to produce object files. That's how cfront worked back in the olden days of C++. It's also how some modern compiler front-ends work. For example, Edison Design Group sells a C++ front-end that vendors can hook up to their own back-end for code generation. They also provide a version that generates C code, for use during compiler development when the back-end isn't yet working. Typically in these cases, the compiler will have a switch to keep the C or assembler file around, so you can examine that to see what's going on.

Title: Misconception in Compiler's function


问:
How to get elevation from current latitude and longitude using leafltejs OR mapbox javascript API
I am working with leafletjs.com and added MAP. I want to get elevation from current latitude and longitude or current place only, but it will return whole path elevation.

```<code>var el = L.control.elevation();
el.addTo(map);
var gjl = L.geoJson(geojson,{
     onEachFeature: el.addData.bind(el)
}).addTo(map);
map.addLayer(service).fitBounds(bounds);
</code>```

How can I find the elevation with either mapbox or leafletjs.

答:
Leaflet is a map display library, not a data API, not a elevation raster query library.

For this, you will have to rely in some kind of elevation dataset (which one is "better" depends on your definition of "better").

For example, see Getting Altitude(height from sea level) of my location in iphone SDK

Whether to use a service like that or whether you should have your own elevation dataset is up to you. In any case, Leaflet does not provide a favourite elevation query service by default (contrary to what Google Maps does, as it relies on Google's elevation datasets).

Body:
I am working with leafletjs.com and added MAP. I want to get elevation from current latitude and longitude or current place only, but it will return whole path elevation.

var el = L.control.elevation();
el.addTo(map);
var gjl = L.geoJson(geojson,{
     onEachFeature: el.addData.bind(el)
}).addTo(map);
map.addLayer(service).fitBounds(bounds);

How can I find the elevation with either mapbox or leafletjs.