问:
How to create an `ffi_type` that represents a c array?
```<code>typedef struct _StructWithCArray {
  char a[3];
  char b;
} StructWithCArray;
</code>```

I represent the a[3] as a struct contain three char, but it will fail on iOS i386 simulator.

Anyone has any ideas how to handle this?

Here is a demo to show the bug. You should use a simulator not newer than iPhone 5 to run the BugReport project, and simulator newer than iPhone 5 seems has no problem in this case.

答:
What about this.

```<code>ffi_type* ffi_type_nullptr = 0;
ffi_type ffi_type_array;

ffi_type_array.alignment = ffi_type_uchar.alignment;
ffi_type_array.size = ffi_type_uchar.size * 3;
ffi_type_array.type = FFI_TYPE_STRUCT; // Trick.
ffi_type_array.elements = &ffi_type_nullptr; // Pointer to a null pointer.

ffi_type* members[2];
members[0] = & ffi_type_array;
members[1] = 0;

ffi_type ffi_type_T = {0, 0, FFI_TYPE_STRUCT, members};
</code>```

Body:
typedef struct _StructWithCArray {
  char a[3];
  char b;
} StructWithCArray;

I represent the a[3] as a struct contain three char, but it will fail on iOS i386 simulator.

Anyone has any ideas how to handle this?

Here is a demo to show the bug. You should use a simulator not newer than iPhone 5 to run the BugReport project, and simulator newer than iPhone 5 seems has no problem in this case.

Body:
What about this.

ffi_type* ffi_type_nullptr = 0;
ffi_type ffi_type_array;

ffi_type_array.alignment = ffi_type_uchar.alignment;
ffi_type_array.size = ffi_type_uchar.size * 3;
ffi_type_array.type = FFI_TYPE_STRUCT; // Trick.
ffi_type_array.elements = &ffi_type_nullptr; // Pointer to a null pointer.

ffi_type* members[2];
members[0] = & ffi_type_array;
members[1] = 0;

ffi_type ffi_type_T = {0, 0, FFI_TYPE_STRUCT, members};


来源: stackexchange

问:
Python Custering algorithm with fixed diameter and minimized count
What is the best method to cluster points of a set with a maximum diameter as threshold and as few clusters as possible?

So for example having a set of gps points and a diameter threshold of 500m. How to use an algorithm to minimize the count of clusters?

As I am using python, is there any package yet?

答:
Use complete linkage clustering. I am surprised you didn't know this method, it is one of the oldest. Here also is Leader, but that one is really low quality.

You cannot afford to check all possibilities (which would be NP hard), but there are algorithms to find a good solution in O(n²) and O(n³).

ContentLicense: CC BY-SA 3.0


问:
How do I become "test infected" with TDD?
I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it.  They've "had the makeover" as it were.  The question is, how do I get like that?</p>

答: Part of the point of being "test infected" is that you've used TDD enough and seen the successes enough that you don't want to code without it. Once you've gone through a cycle of writing tests first, then coding and refactoring and seeing your bug counts go down and your code get better as a result, not only does it become second nature like Zxaos said, you have a hard time going back to Code First. This is being test infected.

OwnerDisplayName: Andrew Harmel-Law

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MattGrommes

LastEditorDisplayName: MattGrommes


问:
Can the iPhone determine if you're facing north, south, east or west?
Can the iPhone determine if you're facing north, south, east or west?</p>

答:
This maybe a bit of a hack but what I was doing was keeping tracking of the lat/long and then determining by that the direction.

Within my code that returns the GPS information I created a delegate that would return back the latitude and longitude

```<code>[[self delegate] currentDirectionLat:newLocation.coordinate.latitude Long:newLocation.coordinate.longitude];
</code>```

The code that was consuming the delegate would then have a method like so to get the coordinates and then set a label on the screen to the direction.

```<code>-(void)currentDirectionLat:(float)latitude Long:(float)longitude
{
    prevLongitude = currentLongitude;
    prevLatitude  = currentLatitude;

    currentLongitude = longitude;
    currentLatitude = latitude;

    NSString *latDirection = @"";
    if (currentLatitude > prevLatitude)
        latDirection = @"N";
    else if (currentLatitude < prevLatitude)
        latDirection = @"S";

    NSString *longDirection = @"";
    if (currentLongitude > prevLongitude)
        longDirection = @"E";
    else if (currentLongitude < prevLongitude)
        longDirection = @"W";

    if ([longDirection length] > 0)
        [lblDirection setText:[NSString stringWithFormat:@"%@%@",latDirection,longDirection]];
}
</code>```

I've not 100% tested this out but seems to have worked on my one application I was writing.  If you want more information please let me know and I can forward you my code that I've done on it.

You will also not get a good reading until the iPhone is moving to get the lat and long change.  However, this does not take much to get it to change!

LastEditorDisplayName: Chris Hanson

Body:
This maybe a bit of a hack but what I was doing was keeping tracking of the lat/long and then determining by that the direction.

Within my code that returns the GPS information I created a delegate that would return back the latitude and longitude

[[self delegate] currentDirectionLat:newLocation.coordinate.latitude Long:newLocation.coordinate.longitude];

The code that was consuming the delegate would then have a method like so to get the coordinates and then set a label on the screen to the direction.

-(void)currentDirectionLat:(float)latitude Long:(float)longitude
{
    prevLongitude = currentLongitude;
    prevLatitude  = currentLatitude;

    currentLongitude = longitude;
    currentLatitude = latitude;

    NSString *latDirection = @"";
    if (currentLatitude > prevLatitude)
        latDirection = @"N";
    else if (currentLatitude < prevLatitude)
        latDirection = @"S";

    NSString *longDirection = @"";
    if (currentLongitude > prevLongitude)
        longDirection = @"E";
    else if (currentLongitude < prevLongitude)
        longDirection = @"W";

    if ([longDirection length] > 0)
        [lblDirection setText:[NSString stringWithFormat:@"%@%@",latDirection,longDirection]];
}

I've not 100% tested this out but seems to have worked on my one application I was writing.  If you want more information please let me know and I can forward you my code that I've done on it.

You will also not get a good reading until the iPhone is moving to get the lat and long change.  However, this does not take much to get it to change!

OwnerDisplayName: hniels


问:
Initialization list std::pair
Is there a way of initializing a std::vector of std::pair<int,int> in the initialization list in a constructor? I have a std::vector<std::pair<int,int> > and I want to initialize a certain number of pairs to (0, 0). For example, I may want to initialize 3 pairs of (0, 0) for a member in a class. How would I go about doing this?

答:
You can do this by using the std::vector constructor which takes in a size and a default value to use:

```<code>class MyClass {
public:
    MyClass();
    /* ... */

private:
    std::vector<pair<int, int> > elems;
};

MyClass::MyClass() : elems(3, std::make_pair(0, 0)) {
    /* ... */
}
</code>```

Title: Initialization list std::pair

Body:
You can do this by using the std::vector constructor which takes in a size and a default value to use:

class MyClass {
public:
    MyClass();
    /* ... */

private:
    std::vector<pair<int, int> > elems;
};

MyClass::MyClass() : elems(3, std::make_pair(0, 0)) {
    /* ... */
}


问:
Sharing configuration between Azure services
How can configuration in Azure be shared between an Azure Worker Role and an Azure Web Service?</p>

答:
Store them in a Key Vault. Cache the configuration values, it seems Key Vault is currently (end of 2017) only able to manage around 250 connections per second.

https://github.com/Azure-Samples/app-service-msi-keyvault-dotnet/


问:
Horizontal translate with mouseenter, mouseleave function not working

I want to make some texts translated horizontally when I hover the mouse in the list. In this case, I want ".java1" translate when I hover to "#java".

$(document).ready(function() {
  $("#java").on("mouseenter", function() {
    $(".java1").transition({
      x: "+=70"
    }, 10);
  });

  $("#java").on("mouseleave", function() {
    $(".java1").transition({
      x: "-=70"
    }, 10);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media (min-width:601px) {
  .quarter {
    width: 24.99999%!important;
  }
  .third {
    width: 33.33333%!important;
  }
  .twothird {
    width: 66.66666%!important;
  }
}

p {
  color: #757575!important;
}

ul {
  text-align: left;
}

li {
  color: #333333!important;
  text-decoration: none;
  list-style-type: none;
  float: left;
  padding-left: 17px;
  padding-right: 17px;
  padding-bottom: 10px;
  margin-top: 3px;
  margin-right: 2px;
  height: 30px;
}

.box {
  width: 100px;
  height: 30px;
  top: 750px;
  position: absolute;
  text-align: left;
  border-radius: 5px;
  float: left;
  margin-left: -50px;
}

.box-container {
  background-color: #f1f1f1;
  color: #009688;
  padding: 5px;
}

.content {
  max-width: 980px;
  margin: auto;
}

.center {
  text-align: center!important;
}

.round-xlarge {
  border-radius: 16px;
}

.teal {
  color: #fff!important;
  background-color: #009688!important;
}

.hover-white:hover {
  color: #000!important;
  background-color: #fff!important;
}

.margin-right {
   margin-right : 16px!important;
}</code>```

public

static

void

main

(String[] args)

My Skill Set

Java

Spring MVC

HTML5

CSS

Javascript

jQuery

...................................................

Language

English

Indonesia

Korea

```

The boxes are hiding in minus margin and I want it to appear after hovering mouse in #java.

However the boxes are unmoved. I can't point it out what's wrong with the script actually? Please help and thank you!

答:
You have to use css method in jQuery and target transform css property, I'm sending you example

$(document).ready(function() {
  $("#java").on("mouseenter", function() {
    $(".java1").css('transform','translateX(-70px)');
  });

  $("#java").on("mouseleave", function() {
    $(".java1").css('transform','translateX(70px)');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media (min-width:601px) {
  .quarter {
    width: 24.99999%!important;
  }
  .third {
    width: 33.33333%!important;
  }
  .twothird {
    width: 66.66666%!important;
  }
}

p {
  color: #757575!important;
}

ul {
  text-align: left;
}

li {
  color: #333333!important;
  text-decoration: none;
  list-style-type: none;
  float: left;
  padding-left: 17px;
  padding-right: 17px;
  padding-bottom: 10px;
  margin-top: 3px;
  margin-right: 2px;
  height: 30px;
}

.box {
  width: 100px;
  height: 30px;
  top: 750px;
  position: absolute;
  text-align: left;
  border-radius: 5px;
  float: left;
  margin-left: -50px;
}

.box-container {
  background-color: #f1f1f1;
  color: #009688;
  padding: 5px;
}

.content {
  max-width: 980px;
  margin: auto;
}

.center {
  text-align: center!important;
}

.round-xlarge {
  border-radius: 16px;
}

.teal {
  color: #fff!important;
  background-color: #009688!important;
}

.hover-white:hover {
  color: #000!important;
  background-color: #fff!important;
}

.margin-right {
   margin-right : 16px!important;
}</code>```

public

static

void

main

(String[] args)

My Skill Set

Java

Spring MVC

HTML5

CSS

Javascript

jQuery

...................................................

Language

English

Indonesia

Korea

```

Body:
I want to make some texts translated horizontally when I hover the mouse in the list. In this case, I want ".java1" translate when I hover to "#java".

$(document).ready(function() {
  $("#java").on("mouseenter", function() {
    $(".java1").transition({
      x: "+=70"
    }, 10);
  });

  $("#java").on("mouseleave", function() {
    $(".java1").transition({
      x: "-=70"
    }, 10);
  });
});

@media (min-width:601px) {
  .quarter {
    width: 24.99999%!important;
  }
  .third {
    width: 33.33333%!important;
  }
  .twothird {
    width: 66.66666%!important;
  }
}

p {
  color: #757575!important;
}

ul {
  text-align: left;
}

li {
  color: #333333!important;
  text-decoration: none;
  list-style-type: none;
  float: left;
  padding-left: 17px;
  padding-right: 17px;
  padding-bottom: 10px;
  margin-top: 3px;
  margin-right: 2px;
  height: 30px;
}

.box {
  width: 100px;
  height: 30px;
  top: 750px;
  position: absolute;
  text-align: left;
  border-radius: 5px;
  float: left;
  margin-left: -50px;
}

.box-container {
  background-color: #f1f1f1;
  color: #009688;
  padding: 5px;
}

.content {
  max-width: 980px;
  margin: auto;
}

.center {
  text-align: center!important;
}

.round-xlarge {
  border-radius: 16px;
}

.teal {
  color: #fff!important;
  background-color: #009688!important;
}

.hover-white:hover {
  color: #000!important;
  background-color: #fff!important;
}

.margin-right {
   margin-right : 16px!important;
}

public

static

void

main

(String[] args)

My Skill Set

Java

Spring MVC

HTML5

CSS

Javascript

jQuery

...................................................

Language

English

Indonesia

Korea

The boxes are hiding in minus margin and I want it to appear after hovering mouse in #java.

However the boxes are unmoved. I can't point it out what's wrong with the script actually? Please help and thank you!

Body:
You have to use css method in jQuery and target transform css property, I'm sending you example

$(document).ready(function() {
  $("#java").on("mouseenter", function() {
    $(".java1").css('transform','translateX(-70px)');
  });

  $("#java").on("mouseleave", function() {
    $(".java1").css('transform','translateX(70px)');
  });
});

@media (min-width:601px) {
  .quarter {
    width: 24.99999%!important;
  }
  .third {
    width: 33.33333%!important;
  }
  .twothird {
    width: 66.66666%!important;
  }
}

p {
  color: #757575!important;
}

ul {
  text-align: left;
}

li {
  color: #333333!important;
  text-decoration: none;
  list-style-type: none;
  float: left;
  padding-left: 17px;
  padding-right: 17px;
  padding-bottom: 10px;
  margin-top: 3px;
  margin-right: 2px;
  height: 30px;
}

.box {
  width: 100px;
  height: 30px;
  top: 750px;
  position: absolute;
  text-align: left;
  border-radius: 5px;
  float: left;
  margin-left: -50px;
}

.box-container {
  background-color: #f1f1f1;
  color: #009688;
  padding: 5px;
}

.content {
  max-width: 980px;
  margin: auto;
}

.center {
  text-align: center!important;
}

.round-xlarge {
  border-radius: 16px;
}

.teal {
  color: #fff!important;
  background-color: #009688!important;
}

.hover-white:hover {
  color: #000!important;
  background-color: #fff!important;
}

.margin-right {
   margin-right : 16px!important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <div class="box-container">
    <p style="text-indent: 5px;" class="java1">public</p>
    <p style="text-indent: 5px;" class="java1">static</p>
    <p style="text-indent: 5px;" class="java1">void</p>
    <p style="text-indent: 5px;" class="java1">main</p>
    <p style="text-indent: 5px;" class="java1">(String[] args)</p>
  </div>
</div>

<div class="content">
  <div class="third center">
    <div class="center">
      <ul>
        <p><i class="fa fa-asterisk margin-right teal-text"></i>My Skill Set</p>
        <li class="round-xlarge teal hover-white" style="width : 23%" id="java">Java</li>
        <li class="round-xlarge teal hover-white" style="width : 43%">Spring MVC</li>
        <li class="round-xlarge teal hover-white" style="width : 28%">HTML5</li>
        <li class="round-xlarge teal hover-white" style="width : 23%">CSS</li>
        <li class="round-xlarge teal hover-white" style="width : 40%">Javascript</li>
        <li class="round-xlarge teal hover-white" style="width : 28%">jQuery</li>
        <p>...................................................</p>
      </ul>
      <ul>
        <p><i class="fa fa-globe margin-right teal-text"></i>Language</p>
        <li class="round-xlarge teal hover-white" style="width : 30%">English</li>
        <li class="round-xlarge teal hover-white" style="width : 38%">Indonesia</li>
        <li class="round-xlarge teal hover-white" style="width : 26%">Korea</li>
      </ul>
    </div>
  </div>
</div>


问:
Vim: How to split command line arguments?
According to the f-args documentation, the command line arguments passed to a user defined function, will be automatically split at white-space or tabs as the help shows:

```<code>                                    *<f-args>*
To allow commands to pass their arguments on to a user-defined function, there
is a special form <f-args> ("function args").  This splits the command
arguments at spaces and tabs, quotes each argument individually, and the
<f-args> sequence is replaced by the comma-separated list of quoted arguments.
See the Mycmd example below.  If no arguments are given <f-args> is removed.
   To embed whitespace into an argument of <f-args>, prepend a backslash.
<f-args> replaces every pair of backslashes (\\) with one backslash.  A
backslash followed by a character other than white space or a backslash
remains unmodified.  Overview:

    command        <f-args> ~
    XX ab          'ab'
    XX a\b         'a\b'
    XX a\ b        'a b'
    XX a\  b       'a ', 'b'
    XX a\\b        'a\b'
    ....
</code>```

However the most basic example does not work:

```<code>function! TestFunc(...)
  echo a:0
  echo a:000
endfunction

command! -nargs=? TestFunc call TestFunc(<f-args>)

-------------------------------------------------

>  :TestFunc foo bar bla bla, fooo
>  1
>  ['foo bar bla bla, fooo']

>  :TestFunc foo\ bar
>  1
>  ['foo\ bar']
</code>```

I have a bunch of arguments split by whitespaces but vim sees it as one. Why does that happen?

Side question ( can it be somehow configured to actually split arguments at comma? )

答:
You specified -nargs=?.

The documentation says:

-nargs=?    0 or 1 arguments are allowed

-nargs=1    Exactly one argument is required, it includes spaces

and

Arguments are considered to be separated by (unescaped) spaces or tabs in this
  context, except when there is one argument, then the white space is part of
  the argument.

(Emphasis mine.)

If you use -nargs=* instead, you get the normal behavior.

Body:
According to the f-args documentation, the command line arguments passed to a user defined function, will be automatically split at white-space or tabs as the help shows:

                                    *<f-args>*
To allow commands to pass their arguments on to a user-defined function, there
is a special form <f-args> ("function args").  This splits the command
arguments at spaces and tabs, quotes each argument individually, and the
<f-args> sequence is replaced by the comma-separated list of quoted arguments.
See the Mycmd example below.  If no arguments are given <f-args> is removed.
   To embed whitespace into an argument of <f-args>, prepend a backslash.
<f-args> replaces every pair of backslashes (\\) with one backslash.  A
backslash followed by a character other than white space or a backslash
remains unmodified.  Overview:

    command        <f-args> ~
    XX ab          'ab'
    XX a\b         'a\b'
    XX a\ b        'a b'
    XX a\  b       'a ', 'b'
    XX a\\b        'a\b'
    ....

However the most basic example does not work:

function! TestFunc(...)
  echo a:0
  echo a:000
endfunction

command! -nargs=? TestFunc call TestFunc(<f-args>)

-------------------------------------------------

>  :TestFunc foo bar bla bla, fooo
>  1
>  ['foo bar bla bla, fooo']

>  :TestFunc foo\ bar
>  1
>  ['foo\ bar']

I have a bunch of arguments split by whitespaces but vim sees it as one. Why does that happen?

Side question ( can it be somehow configured to actually split arguments at comma? )


问:
Angular - convert HAL to JSON
The following service extracts category objects from a REST service which returns them in HAL format. Now I try to convert that response into JSON. For that I searched and tried different solutions, e.g. chariotsolutions or so. Some are based on Response from '@angular/http' which is deprecated and which I cannot make work.

How can I do the conversion?

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { Category } from './category';

@Injectable()
export class CategoryService {

  private categoriesUrl = 'http://localhost:8080/account/categories';

  constructor(private http: HttpClient) { }

  getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl);
  }

}
</code>```

The response as HAL

```<code>{
  "_embedded": {
    "categories": [
      {
        "id": 1,
        "name": "hardware",
        "description": "comprises all computer hardware",
        "level": "FIRST",
        "_links": {
          "self": {
            "href": "http://localhost:8080/account/categories/1"
          },
          "categoryEntity": {
            "href": "http://localhost:8080/account/categories/1"
          }
        }
      },
      {
        "id": 2,
        "name": "hardware_notebook",
        "description": "all notebooks",
        "level": "SECOND",
        "_links": {
          "self": {
            "href": "http://localhost:8080/account/categories/2"
          },
          "categoryEntity": {
            "href": "http://localhost:8080/account/categories/2"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/account/categories{?page,size,sort}",
      "templated": true
    },
    "profile": {
      "href": "http://localhost:8080/account/profile/categories"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 8,
    "totalPages": 1,
    "number": 0
  }
}
</code>```

答:
```<code>getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl)
        .map((result:any)=>{
           console.log(result); //<--it's an object
           //result={"_embedded": {"categories": [..]..}
           return result._embedded.categories; //just return "categories"
        });
}
</code>```

With Rjxs 6.0 we must use pipe(map)

```<code>getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl).pipe(
        map((result:any)=>{
           console.log(result); //<--it's an object
           //result={"_embedded": {"categories": [..]..}
           return result._embedded.categories; //just return "categories"
        }));
}
</code>```

Title: Angular - convert HAL to JSON

Body:
The following service extracts category objects from a REST service which returns them in HAL format. Now I try to convert that response into JSON. For that I searched and tried different solutions, e.g. chariotsolutions or so. Some are based on Response from '@angular/http' which is deprecated and which I cannot make work.

How can I do the conversion?

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { Category } from './category';

@Injectable()
export class CategoryService {

  private categoriesUrl = 'http://localhost:8080/account/categories';

  constructor(private http: HttpClient) { }

  getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl);
  }

}

The response as HAL

{
  "_embedded": {
    "categories": [
      {
        "id": 1,
        "name": "hardware",
        "description": "comprises all computer hardware",
        "level": "FIRST",
        "_links": {
          "self": {
            "href": "http://localhost:8080/account/categories/1"
          },
          "categoryEntity": {
            "href": "http://localhost:8080/account/categories/1"
          }
        }
      },
      {
        "id": 2,
        "name": "hardware_notebook",
        "description": "all notebooks",
        "level": "SECOND",
        "_links": {
          "self": {
            "href": "http://localhost:8080/account/categories/2"
          },
          "categoryEntity": {
            "href": "http://localhost:8080/account/categories/2"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/account/categories{?page,size,sort}",
      "templated": true
    },
    "profile": {
      "href": "http://localhost:8080/account/profile/categories"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 8,
    "totalPages": 1,
    "number": 0
  }
}

Body:
getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl)
        .map((result:any)=>{
           console.log(result); //<--it's an object
           //result={"_embedded": {"categories": [..]..}
           return result._embedded.categories; //just return "categories"
        });
}

With Rjxs 6.0 we must use pipe(map)

getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl).pipe(
        map((result:any)=>{
           console.log(result); //<--it's an object
           //result={"_embedded": {"categories": [..]..}
           return result._embedded.categories; //just return "categories"
        }));
}

ContentLicense: CC BY-SA 4.0


问:
check if timestamp column is in date range from another dataframe
I have a dataframe, df_A with two columns 'amin' and 'amax', which is a set of time range.

My objective is to find whether a column in df_B lies between any of the rows of range in df_A 'amin' and 'amax' columns.

```<code>df_A[['amin','amax'] ]

                  amin                   amax
          0 2016-07-16 19:37:03   2016-07-17 11:16:32
          1 2016-07-04 21:15:54   2016-07-05 10:57:46
          2 2016-07-24 23:30:41   2016-07-25 15:38:02
          3 2016-07-12 03:02:38   2016-07-12 22:11:01

df_B['created_date']

      created_date
   2016-07-17 01:16:32
   2016-07-05 10:15:54
   2016-07-12 12:11:01

df_A['amin'] = pd.to_datetime(df_A['amin'], errors='coerce')
df_A['amax'] = pd.to_datetime(df_A['amax'], errors='coerce')
df_B['created_date'] = pd.to_datetime(df_B['created_date'],errors='coerce')

def dt2epoch(value):
   epoch = (value - pd.to_datetime(datetime(2015,12,31).strftime('%Y-%m-%d %H:%M:%S.%f'))).total_seconds()
   return epoch

df_A['amax_epoch']=df_A['amax'].apply(dt2epoch)
df_A['amin_epoch']=df_A['amin'].apply(dt2epoch)
df_B['created_date_epoch']=df_B['created_date'].apply(dt2epoch)

def make_tuple(row):
     n= len(row)
     row = [(x,row[n - 1]) for x in row]
     return row

minMaxTuple = minMax.apply(make_tuple, axis =1)
</code>```

Above is part of my code, I've tried below(not sure if it's necessary):

convert them to epoch values

convert df_A into a tuple.

However, df_A and df_B has a different number of rows. Also, I dont have any id column to merge them together.

```<code>label = []

for l in df_B['created_date_epoch']:

    if (m[0] for m in minMaxTuple) <= l <= (m[1] for m in minMaxTuple):
        label.append('1')
    else:
        label.append('0')
</code>```

However, when I run this, the result I get for 'label' is an empty list.

Also, the label should be a column that has the same number of rows as df_A.

Ultimately, I would like to add a new 'label' column in df_A:

```<code>                              minMaxTuple                      label
            (2016-07-16 19:37:03, 2016-07-17 11:16:32)            1
            (2016-07-04 21:15:54, 2016-07-05 10:57:46)            1
            (2016-07-24 23:30:41, 2016-07-25 15:38:02)            0
            (2016-07-12 03:02:38, 2016-07-12 22:11:01)            1
</code>```

答:
Very similar to @dubbbdan 's answer but maybe simpler using any and the and operator:

```<code>any_in_range = lambda row, iterable: any(
    [(row[0] < x) & (x < row[1]) for x in iterable])
df_A['label'] = df_A.apply(any_in_range, iterable=df_B['created_date'], axis=1)
print df_A
</code>```

Prints:

```<code>                 amin                amax  label
0 2016-07-16 19:37:03 2016-07-17 11:16:32   True
1 2016-07-04 21:15:54 2016-07-05 10:57:46   True
2 2016-07-24 23:30:41 2016-07-25 15:38:02  False
3 2016-07-12 03:02:38 2016-07-12 22:11:01   True
</code>```

Body:
I have a dataframe, df_A with two columns 'amin' and 'amax', which is a set of time range.

My objective is to find whether a column in df_B lies between any of the rows of range in df_A 'amin' and 'amax' columns.

df_A[['amin','amax'] ]

                  amin                   amax
          0 2016-07-16 19:37:03   2016-07-17 11:16:32
          1 2016-07-04 21:15:54   2016-07-05 10:57:46
          2 2016-07-24 23:30:41   2016-07-25 15:38:02
          3 2016-07-12 03:02:38   2016-07-12 22:11:01

df_B['created_date']

      created_date
   2016-07-17 01:16:32
   2016-07-05 10:15:54
   2016-07-12 12:11:01

df_A['amin'] = pd.to_datetime(df_A['amin'], errors='coerce')
df_A['amax'] = pd.to_datetime(df_A['amax'], errors='coerce')
df_B['created_date'] = pd.to_datetime(df_B['created_date'],errors='coerce')

def dt2epoch(value):
   epoch = (value - pd.to_datetime(datetime(2015,12,31).strftime('%Y-%m-%d %H:%M:%S.%f'))).total_seconds()
   return epoch

df_A['amax_epoch']=df_A['amax'].apply(dt2epoch)
df_A['amin_epoch']=df_A['amin'].apply(dt2epoch)
df_B['created_date_epoch']=df_B['created_date'].apply(dt2epoch)

def make_tuple(row):
     n= len(row)
     row = [(x,row[n - 1]) for x in row]
     return row

minMaxTuple = minMax.apply(make_tuple, axis =1)

Above is part of my code, I've tried below(not sure if it's necessary):

convert them to epoch values

convert df_A into a tuple.

However, df_A and df_B has a different number of rows. Also, I dont have any id column to merge them together.

label = []

for l in df_B['created_date_epoch']:

    if (m[0] for m in minMaxTuple) <= l <= (m[1] for m in minMaxTuple):
        label.append('1')
    else:
        label.append('0')

However, when I run this, the result I get for 'label' is an empty list.

Also, the label should be a column that has the same number of rows as df_A.

Ultimately, I would like to add a new 'label' column in df_A:

                              minMaxTuple                      label
            (2016-07-16 19:37:03, 2016-07-17 11:16:32)            1
            (2016-07-04 21:15:54, 2016-07-05 10:57:46)            1
            (2016-07-24 23:30:41, 2016-07-25 15:38:02)            0
            (2016-07-12 03:02:38, 2016-07-12 22:11:01)            1

Body:
Very similar to @dubbbdan 's answer but maybe simpler using any and the and operator:

any_in_range = lambda row, iterable: any(
    [(row[0] < x) & (x < row[1]) for x in iterable])
df_A['label'] = df_A.apply(any_in_range, iterable=df_B['created_date'], axis=1)
print df_A

Prints:

                 amin                amax  label
0 2016-07-16 19:37:03 2016-07-17 11:16:32   True
1 2016-07-04 21:15:54 2016-07-05 10:57:46   True
2 2016-07-24 23:30:41 2016-07-25 15:38:02  False
3 2016-07-12 03:02:38 2016-07-12 22:11:01   True


问:
How to get same number of item from two random arrays?
The question may sounds a bit weird, but I'll try to explain what I want to achieve.
I have two arrays:

```<code>$combined_alt_blur = array($bg['pic_blur'], $bg['pic_blur2'], $bg['pic_blur3'], $bg['pic_blur4'], $bg['pic_blur5']);
$combined_alt_normal = array($bg['pic_normal'], $bg['pic_normal2'], $bg['pic_normal3'], $bg['pic_normal4'], $bg['pic_normal5']);
</code>```

Then I show them on the website:

```<code><div class="fullscreen_blur" style="background-image: url('/medias/<?php print $combined_alt_blur[array_rand($combined_alt_blur)]; ?>.jpg');"></div>
<div class="fullscreen"  style="background-image: url('/medias/<?php print $combined_alt_normal[array_rand($combined_alt_normal)]; ?>.png');"></div>
</code>```

But there's a huge problem with this one. If the random from the first array chooses the 3rd item (pic_blur3), then it must choose the 3rd item from the second array as well (pic_normal3). How can I achieve this?

With the current code it's just two seperate random arrays.

答:
Create a random number and use it as an index for both</p>

```<code>$index = rand(0, count($combined_alt_blur) - 1);
$combined_alt_normal[$index];
</code>```

Body:
The question may sounds a bit weird, but I'll try to explain what I want to achieve.
I have two arrays:

$combined_alt_blur = array($bg['pic_blur'], $bg['pic_blur2'], $bg['pic_blur3'], $bg['pic_blur4'], $bg['pic_blur5']);
$combined_alt_normal = array($bg['pic_normal'], $bg['pic_normal2'], $bg['pic_normal3'], $bg['pic_normal4'], $bg['pic_normal5']);

Then I show them on the website:

<div class="fullscreen_blur" style="background-image: url('/medias/<?php print $combined_alt_blur[array_rand($combined_alt_blur)]; ?>.jpg');">

<div class="fullscreen"  style="background-image: url('/medias/<?php print $combined_alt_normal[array_rand($combined_alt_normal)]; ?>.png');">

But there's a huge problem with this one. If the random from the first array chooses the 3rd item (pic_blur3), then it must choose the 3rd item from the second array as well (pic_normal3). How can I achieve this?

With the current code it's just two seperate random arrays.

Body:
Create a random number and use it as an index for both

$index = rand(0, count($combined_alt_blur) - 1);
$combined_alt_normal[$index];


问:
Scraping flight data with Python requests
The following URL shows a flight and offers further details (toggle e.g. "Flugweg" or "Statistik" on the left side). I would like to read this data and later convert that into lists.

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

So what I have been doing so far is the following:

```<code>import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)
</code>```

doing a response.text gives me a page back, basically telling me that "The requested page doesn't exist".

I then tried to add header information, as I read that sometimes this is a reason a request is denied:

```<code>headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}
</code>```

And then have

```<code>response = requests.post(API_url, headers = headers)
</code>```

This did not change anything and is simply fishing in murky waters.

Searching with Chrome for XHR offers three files and they contain what I want, but I am running out of ideas, how to get them. What would be the correct approach to access the data?

答:
The url you tried returns 404. Please check the url in the browser. Please try this:

```<code>page_url = ""https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html?nature=track&ref=977301232""
response = requests.get(page_url)
</code>```

Added the extra params("nature" and "ref") which gets shown in when inspected. Passing this with the url returns us the xml data. Maybe we can use python's Elementree for parsing the XML data.

Body:
The following URL shows a flight and offers further details (toggle e.g. "Flugweg" or "Statistik" on the left side). I would like to read this data and later convert that into lists.

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

So what I have been doing so far is the following:

import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)

doing a response.text gives me a page back, basically telling me that "The requested page doesn't exist".

I then tried to add header information, as I read that sometimes this is a reason a request is denied:

headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}

And then have

response = requests.post(API_url, headers = headers)

This did not change anything and is simply fishing in murky waters.

Searching with Chrome for XHR offers three files and they contain what I want, but I am running out of ideas, how to get them. What would be the correct approach to access the data?

Body:
The url you tried returns 404. Please check the url in the browser. Please try this:

page_url = ""https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html?nature=track&ref=977301232""
response = requests.get(page_url)

Added the extra params("nature" and "ref") which gets shown in when inspected. Passing this with the url returns us the xml data. Maybe we can use python's Elementree for parsing the XML data.


问:
Add css class to all li parent elements in the ul with javascript
I have html code like this:

```<code><ul class="dropdown-menu mega-dropdown-menu">
    <li class="should be = col-sm-4">
        <ul>
            <li class="should be = dropdown-header">Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
    <li class="should be = col-sm-4">
        <ul>
            <li class="should be = dropdown-header">Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
    <li class="should be = col-sm-4">
        <ul>
            <li class="should be = dropdown-header">Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
</ul>
</code>```

this code is generated from server side, now my question is, how can I append col-sm-4 css class to all li parents and add css class dropdown-header to first li child elements with javascript?

答:
Vanilla Javascript Solution:

By storing all applicable list items in a variable, that can be later ustilised in a for loop, we can iterate through each instance and add the required class.

This solution is preferable if an entire javascript library or framework (like jQuery) is not required for trivial change that only needs to occur once.

Code Snippet Demonstration:

// Get direct descendant list-item children using querySelectorAll and CSS child combinator selector
var listItems = document.querySelectorAll('.dropdown-menu > li');

// Add class to each instance in for loop
for(var i = 0; i < listItems.length; i++) {
  listItems[i].className = 'col-sm-4';
}

// Get first list-item child of nested ul element with class name "col-sm-4" using querySelectorAll and CSS :first-child pseudo-selector
var headerListItems = document.querySelectorAll('.dropdown-menu .col-sm-4 li:first-child');

// Add class to each instance in for loop
for(var i = 0; i < listItems.length; i++) {
  headerListItems[i].className = 'dropdown-header';
}

// Note: "querySelectorAll" allows for the ability to specify selectors using CSS Selector Syntax```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="dropdown-menu mega-dropdown-menu">
    <li >
        <ul>
            <li>Item0</li>
            <li>Item1</li>
            <li>Item2</li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li>Item1</li>
            <li>Item2</li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li>Item1</li>
            <li>Item2</li>
        </ul>
    </li>
</ul></code>```

jQuery Solution:

Consider using the .addClass() method to add the required classes by specifying the intended selectors as demonstrated in the embedded code snippet below.

This solution is preferable if this change needs to occur more than once or elsewhere in a similar scope.

Code Snippet Demonstration:

jQuery('.dropdown-menu > li').addClass('col-sm-4');

jQuery('.dropdown-menu .col-sm-4 li:first-child').addClass('dropdown-header');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu mega-dropdown-menu">
    <li >
        <ul>
            <li>Item0</li>
            <li>Item1</li>
            <li>Item2</li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li>Item1</li>
            <li>Item2</li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li>Item1</li>
            <li>Item2</li>
        </ul>
    </li>
</ul></code>```

Alternative: Standard CSS Selector Syntax

The elements in question can still be targeted using CSS Selector Syntax with the following methods:

For what would be "col-sm-4": .dropdown-menu > li

Selecting the first direct descendant list-item element using the child combinator (>)

For what would be "dropdown-header": .dropdown-menu ul li:first-child

Selecting the first child list-item element using :first-child pseudo-selector

Body:
I have html code like this:

Item0

Item1

Item2

Item0

Item1

Item2

Item0

Item1

Item2

this code is generated from server side, now my question is, how can I append col-sm-4 css class to all li parents and add css class dropdown-header to first li child elements with javascript?

Body:
Vanilla Javascript Solution:

By storing all applicable list items in a variable, that can be later ustilised in a for loop, we can iterate through each instance and add the required class.

This solution is preferable if an entire javascript library or framework (like jQuery) is not required for trivial change that only needs to occur once.

Code Snippet Demonstration:

// Get direct descendant list-item children using querySelectorAll and CSS child combinator selector
var listItems = document.querySelectorAll('.dropdown-menu > li');

// Add class to each instance in for loop
for(var i = 0; i < listItems.length; i++) {
  listItems[i].className = 'col-sm-4';
}

// Get first list-item child of nested ul element with class name "col-sm-4" using querySelectorAll and CSS :first-child pseudo-selector
var headerListItems = document.querySelectorAll('.dropdown-menu .col-sm-4 li:first-child');

// Add class to each instance in for loop
for(var i = 0; i < listItems.length; i++) {
  headerListItems[i].className = 'dropdown-header';
}

// Note: "querySelectorAll" allows for the ability to specify selectors using CSS Selector Syntax

<ul class="dropdown-menu mega-dropdown-menu">
    <li >
        <ul>
            <li>Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
</ul>

jQuery Solution:

Consider using the .addClass() method to add the required classes by specifying the intended selectors as demonstrated in the embedded code snippet below.

This solution is preferable if this change needs to occur more than once or elsewhere in a similar scope.

Code Snippet Demonstration:

jQuery('.dropdown-menu > li').addClass('col-sm-4');

jQuery('.dropdown-menu .col-sm-4 li:first-child').addClass('dropdown-header');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu mega-dropdown-menu">
    <li >
        <ul>
            <li>Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
    <li >
        <ul>
            <li >Item0</li>
            <li><a href="#">Item1</a></li>
            <li><a href="#">Item2</a></li>
        </ul>
    </li>
</ul>

Alternative: Standard CSS Selector Syntax

The elements in question can still be targeted using CSS Selector Syntax with the following methods:

For what would be "col-sm-4": .dropdown-menu > li

Selecting the first direct descendant list-item element using the child combinator (>)

For what would be "dropdown-header": .dropdown-menu ul li:first-child

Selecting the first child list-item element using :first-child pseudo-selector


问:
Tail-recursive program in prolog which outputs odd numbers in a list
I've written a tail-recursive predicate in Prolog which outputs the integers between A and B in a list K. I've used "reverse" to bring the numbers into the right order:

```<code>numbers(A,B,K) :- numbers(A,B,[],K).
numbers(Y,Y,X,K) :- !, reverse([Y|X],K).
numbers(A,B,X,K) :- A<B, C is A+1, numbers(C,B,[A|X],K).
</code>```

Query:

```<code>?- numbers(3,6, K).
   K=[3,4,5,6]
</code>```

All works fine. What I now want to do is that I only want to have odd numbers of the range between A and B in the list K. How can I do that? Thanks in advance!

答:
Firstly, I would try to avoid using reverse/2. If you have such a solution, it's often an indicator that there's a better way to get the answer forwards more directly. Not always, but most often. reverse/2 is probably the 2nd favorite band-aid in Prolog right behind use of the cut. :)

In many problems, an auxiliary accumulator is needed. In this particular case, it is not. Also, I would tend to use CLP(FD) operations when involving integers since it's the more relational approach to reasoning over integers. But you can use the solution below with is/2, etc, if you wish. It just won't be as general.

```<code>numbers(S, E, []) :- S #> E.   % null case
numbers(X, X, [X]).
numbers(S, E, [S|T]) :-
    S #< E,
    S1 #= S + 1,
    numbers(S1, E, T).

| ?- numbers(3, 8, L).

L = [3,4,5,6,7,8] ? ;

no
| ?- numbers(A, B, [2,3,4,5]).

A = 2
B = 5 ? ;

no
| ?-
</code>```

This solution avoids reverse/2 and is tail recursive.

To update it for odd integers, the first thought is that we can easily modify the above to do every other number by just adding 2 instead of 1:

```<code>every_other_number(S, E, []) :- S #> E.
every_other_number(X, X, [X]).
every_other_number(S, E, [S|T]) :-
    S #< E,
    S1 #= S + 2,
    every_other_number(S1, E, T).

| ?- every_other_number(3, 7, L).

L = [3,5,7] ? ;

no
| ?- every_other_number(3, 8, L).

L = [3,5,7] ? ;

no
| ?- every_other_number(4, 8, L).

L = [4,6,8] ? ;

no
| ?-
</code>```

Then we can do odd numbers by creating an initial predicate to ensure the condition that the first value is odd and calling every_other_number/3:

```<code>odd_numbers(S, E, L) :-
    S rem 2 #= 1,
    every_other_number(S, E, L).
odd_numbers(S, E, L) :-
    S rem 2 #= 0,
    S1 #= S + 1,
    every_other_number(S1, E, L).

| ?- odd_numbers(2, 8, L).

L = [3,5,7] ? ;

no
| ?- odd_numbers(2, 9, L).

L = [3,5,7,9] ? ;

no
| ?- odd_numbers(3, 8, L).

L = [3,5,7] ? ;

no
| ?-
</code>```

Body:
I've written a tail-recursive predicate in Prolog which outputs the integers between A and B in a list K. I've used "reverse" to bring the numbers into the right order:

numbers(A,B,K) :- numbers(A,B,[],K).
numbers(Y,Y,X,K) :- !, reverse([Y|X],K).
numbers(A,B,X,K) :- A<B, C is A+1, numbers(C,B,[A|X],K).

Query:

?- numbers(3,6, K).
   K=[3,4,5,6]

All works fine. What I now want to do is that I only want to have odd numbers of the range between A and B in the list K. How can I do that? Thanks in advance!

Body:
Firstly, I would try to avoid using reverse/2. If you have such a solution, it's often an indicator that there's a better way to get the answer forwards more directly. Not always, but most often. reverse/2 is probably the 2nd favorite band-aid in Prolog right behind use of the cut. :)

In many problems, an auxiliary accumulator is needed. In this particular case, it is not. Also, I would tend to use CLP(FD) operations when involving integers since it's the more relational approach to reasoning over integers. But you can use the solution below with is/2, etc, if you wish. It just won't be as general.

numbers(S, E, []) :- S #> E.   % null case
numbers(X, X, [X]).
numbers(S, E, [S|T]) :-
    S #< E,
    S1 #= S + 1,
    numbers(S1, E, T).

| ?- numbers(3, 8, L).

L = [3,4,5,6,7,8] ? ;

no
| ?- numbers(A, B, [2,3,4,5]).

A = 2
B = 5 ? ;

no
| ?-

This solution avoids reverse/2 and is tail recursive.

To update it for odd integers, the first thought is that we can easily modify the above to do every other number by just adding 2 instead of 1:

every_other_number(S, E, []) :- S #> E.
every_other_number(X, X, [X]).
every_other_number(S, E, [S|T]) :-
    S #< E,
    S1 #= S + 2,
    every_other_number(S1, E, T).

| ?- every_other_number(3, 7, L).

L = [3,5,7] ? ;

no
| ?- every_other_number(3, 8, L).

L = [3,5,7] ? ;

no
| ?- every_other_number(4, 8, L).

L = [4,6,8] ? ;

no
| ?-

Then we can do odd numbers by creating an initial predicate to ensure the condition that the first value is odd and calling every_other_number/3:

odd_numbers(S, E, L) :-
    S rem 2 #= 1,
    every_other_number(S, E, L).
odd_numbers(S, E, L) :-
    S rem 2 #= 0,
    S1 #= S + 1,
    every_other_number(S1, E, L).

| ?- odd_numbers(2, 8, L).

L = [3,5,7] ? ;

no
| ?- odd_numbers(2, 9, L).

L = [3,5,7,9] ? ;

no
| ?- odd_numbers(3, 8, L).

L = [3,5,7] ? ;

no
| ?-


问:
Symfony 4, Twig & VueJS - Redirecting to Symfony routes in Vue component
I am getting started with Symfony 4 using Twig templating and VueJS for UI components.

I have a very basic component in a .vue file for listing tasks, which currently renders a basic table.

```<code>// task-list.vue

<template>
    <div>
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>
                    Task
                </th>
                <th>
                    Description
                </th>
                <th>
                    Completed?
                </th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="task in parsedTasks">
                <td>
                    {{ task.title }}
                </td>
                <td>
                    {{ task.description }}
                </td>
                <td>
                    {{ task.completed ? 'Yes' : 'No' }}
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
      name: 'task-list',
      props: {
        tasks: {required: true}
      },
      computed: {
        parsedTasks() {
          return JSON.parse(this.tasks);
        }
      },
    };
</script>
</code>```

This component is registered in the root JS file;

```<code>// assets/js/app.js

Vue.component('task-list', TaskList);

new Vue({
  el: '#app-root'
});
</code>```

This is then used in a Twig template;

```<code>// tasks/list.html.twig

...
<task-list tasks="{{ tasks | json_encode }}"></task-list>
...
</code>```

I want to be able to use the path() Twig function so that, when a row in the task list is clicked, the user is redirected to the generated route/path. Is this possible given that the Vue component is not in a Twig file?

As a side question, is there a better way to pass a Twig variable to a Vue component than json encoding then parsing the data as above?

答:
There is two main approaches:
Generate the URL in the backend and use it in javascript:

```<code>var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";
</code>```

https://symfony.com/doc/current/routing/generate_url_javascript.html

Or using a javascript routing library that integrates with symfony routes like FOSJsRouting:

```<code>var url = Routing.generate('blog_show', {
    'slug': 'my-blog-post'
});
</code>```

https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

Body:
I am getting started with Symfony 4 using Twig templating and VueJS for UI components.

I have a very basic component in a .vue file for listing tasks, which currently renders a basic table.

// task-list.vue

<template>

                    Task

                    Description

                    Completed?

                    {{ task.title }}

                    {{ task.description }}

                    {{ task.completed ? 'Yes' : 'No' }}

</template>

This component is registered in the root JS file;

// assets/js/app.js

Vue.component('task-list', TaskList);

new Vue({
  el: '#app-root'
});

This is then used in a Twig template;

// tasks/list.html.twig

...
<task-list tasks="{{ tasks | json_encode }}"></task-list>
...

I want to be able to use the path() Twig function so that, when a row in the task list is clicked, the user is redirected to the generated route/path. Is this possible given that the Vue component is not in a Twig file?

As a side question, is there a better way to pass a Twig variable to a Vue component than json encoding then parsing the data as above?

Body:
There is two main approaches:
Generate the URL in the backend and use it in javascript:

var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";

https://symfony.com/doc/current/routing/generate_url_javascript.html

Or using a javascript routing library that integrates with symfony routes like FOSJsRouting:

var url = Routing.generate('blog_show', {
    'slug': 'my-blog-post'
});

https://github.com/FriendsOfSymfony/FOSJsRoutingBundle


答:
If both arrays has the same size of cells, you can just do:

```<code>$index = array_rand($combined_alt_blur);
print $combined_alt_blur[$index];
print $combined_alt_normal[$index];
</code>```

Otherwise you can assign maybe a default value:

```<code>print isset($combined_alt_normal[$index]) ? $combined_alt_normal[$index] : "default";
</code>```

Title: How to get same number of item from two random arrays?

Body:
If both arrays has the same size of cells, you can just do:

$index = array_rand($combined_alt_blur);
print $combined_alt_blur[$index];
print $combined_alt_normal[$index];

Otherwise you can assign maybe a default value:

print isset($combined_alt_normal[$index]) ? $combined_alt_normal[$index] : "default";


问:
my android studio can`t find compile method(com.android.support.constraint:constraint-layout:1.0.0-beta4)
i have this problem in Android Studio and i added this in build.gradle file but i have that problem.

Error:(13, 0) Could not find method compile() for arguments [com.android.support.constraint:constraint-layout:1.0.0-beta4] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {

     repositories {
        google()
        jcenter()

     }
     dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        compile'com.android.support.constraint:constraint-layout:1.0.0-beta4'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
     }
    }

    allprojects {
     repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com'
        }
     }
    }

    task clean(type: Delete) {
      delete rootProject.buildDir
    }
</code>```

答:
Beta 4 is an old version. Try using 1.0.2 instead:

```<code>compile 'com.android.support.constraint:constraint-layout:1.0.2'
</code>```

Body:
i have this problem in Android Studio and i added this in build.gradle file but i have that problem.

Error:(13, 0) Could not find method compile() for arguments [com.android.support.constraint:constraint-layout:1.0.0-beta4] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {

     repositories {
        google()
        jcenter()

     }
     dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        compile'com.android.support.constraint:constraint-layout:1.0.0-beta4'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
     }
    }

    allprojects {
     repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com'
        }
     }
    }

    task clean(type: Delete) {
      delete rootProject.buildDir
    }

Body:
Beta 4 is an old version. Try using 1.0.2 instead:

compile 'com.android.support.constraint:constraint-layout:1.0.2'


问:
/usr/bin/codesign failed with exit code 1
I am attempting to deploy my first development iPhone app, and am running into some problems.  I have successfully went though the online Provisioning Assistant, but now I am stuck.  No matter what I do, I always get the following error.

/usr/bin/codesign failed with exit code 1

Anyone have any ideas why this is happening?

答:
Another reason,
Check your Developer account is connected with xCode


问:
Programmatically created window appears but doesn't respond to touch events
I'm creating my app without the MainWindow nib, and after updating to the new SDK, my app completely broke. In the main() function of main.m I have:

```<code>int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
</code>```

Here's the relevant bits of application:didFinishLaunchingWithOptions: in AppDelegate.m

```<code>window = [[UIWindow alloc] init];

tabBarController = [[UITabBarController alloc] init];

UINavigationController *nav = ...;
UITableViewController *table = ...;

tabBarController.viewControllers = [NSArray arrayWithObjects:nav, table, nil];

[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
</code>```

When the app launches, the tab bar is visible and so is the view in the first tab. However, all touch events are either not being registered or not being passed to the window itself. I subclassed UIWindow and set window to be an instance of it. In this subclass, I overrode the sendEvent: method to log to the console whenever it was called. Nothing is showing up. What am I doing wrong?

答:
You may try to modify the fourth parameter from "nil" to the application delegate name in main.c

For example
Modify UIApplicationMain(argc, argv, nil, nil) to
UIApplicationMain(argc, argv, nil, @"HelloWorldAppDelegate")

Body:
I'm creating my app without the MainWindow nib, and after updating to the new SDK, my app completely broke. In the main() function of main.m I have:

int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");

Here's the relevant bits of application:didFinishLaunchingWithOptions: in AppDelegate.m

window = [[UIWindow alloc] init];

tabBarController = [[UITabBarController alloc] init];

UINavigationController *nav = ...;
UITableViewController *table = ...;

tabBarController.viewControllers = [NSArray arrayWithObjects:nav, table, nil];

[window addSubview:tabBarController.view];
[window makeKeyAndVisible];

When the app launches, the tab bar is visible and so is the view in the first tab. However, all touch events are either not being registered or not being passed to the window itself. I subclassed UIWindow and set window to be an instance of it. In this subclass, I overrode the sendEvent: method to log to the console whenever it was called. Nothing is showing up. What am I doing wrong?


问:
Getting the coordinate pairs of a Path2D object in Java?
I have to get the coordinates of each set of coordinates in a Path2D object but I don't know how.  Previously we were using Polygons, so I was able to initialize two arrays of length Polygon.npoints and then set them to be the Polygon.xpoints and Polygon.ypoints arrays.  Now that we are using Path2D objects, I have no idea how to do this, because all I can seem to do is initialize a PathIterator, which takes an array as input and returns segments? Can somebody explain how to get all the coordinate pairs of a Path2D object?

答:
Below is an example how you can get all the segments and coordinate pairs of a
PathIterator:

You call the PathIterator's currentSegment method repeatedly.
On each call you get the coordinates of one segment.
Note especially that the number of coordinates depends on the segment type
(the return value you got from the currentSegment method).

```<code>public static void dump(Shape shape) {
    float[] coords = new float[6];
    PathIterator pathIterator = shape.getPathIterator(new AffineTransform());
    while (!pathIterator.isDone()) {
        switch (pathIterator.currentSegment(coords)) {
        case PathIterator.SEG_MOVETO:
            System.out.printf("move to x1=%f, y1=%f\n",
                    coords[0], coords[1]);
            break;
        case PathIterator.SEG_LINETO:
            System.out.printf("line to x1=%f, y1=%f\n",
                    coords[0], coords[1]);
            break;
        case PathIterator.SEG_QUADTO:
            System.out.printf("quad to x1=%f, y1=%f, x2=%f, y2=%f\n",
                    coords[0], coords[1], coords[2], coords[3]);
            break;
        case PathIterator.SEG_CUBICTO:
            System.out.printf("cubic to x1=%f, y1=%f, x2=%f, y2=%f, x3=%f, y3=%f\n",
                    coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]);
            break;
        case PathIterator.SEG_CLOSE:
            System.out.printf("close\n");
            break;
        }
        pathIterator.next();
    }
}
</code>```

You can use this method for dumping any Shape
(and hence also for its implementations like Rectangle, Polygon, Ellipse2D, Path2D, ...)

```<code>Shape shape = ...;
dump(shape);
</code>```

Body:
Below is an example how you can get all the segments and coordinate pairs of a
PathIterator:

You call the PathIterator's currentSegment method repeatedly.
On each call you get the coordinates of one segment.
Note especially that the number of coordinates depends on the segment type
(the return value you got from the currentSegment method).

public static void dump(Shape shape) {
    float[] coords = new float[6];
    PathIterator pathIterator = shape.getPathIterator(new AffineTransform());
    while (!pathIterator.isDone()) {
        switch (pathIterator.currentSegment(coords)) {
        case PathIterator.SEG_MOVETO:
            System.out.printf("move to x1=%f, y1=%f\n",
                    coords[0], coords[1]);
            break;
        case PathIterator.SEG_LINETO:
            System.out.printf("line to x1=%f, y1=%f\n",
                    coords[0], coords[1]);
            break;
        case PathIterator.SEG_QUADTO:
            System.out.printf("quad to x1=%f, y1=%f, x2=%f, y2=%f\n",
                    coords[0], coords[1], coords[2], coords[3]);
            break;
        case PathIterator.SEG_CUBICTO:
            System.out.printf("cubic to x1=%f, y1=%f, x2=%f, y2=%f, x3=%f, y3=%f\n",
                    coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]);
            break;
        case PathIterator.SEG_CLOSE:
            System.out.printf("close\n");
            break;
        }
        pathIterator.next();
    }
}

You can use this method for dumping any Shape
(and hence also for its implementations like Rectangle, Polygon, Ellipse2D, Path2D, ...)

Shape shape = ...;
dump(shape);


问:
How to push an object in an array in Mongoose (error)
I am making a route in a Node server using Mongoose and Mongo which stores a comment in the comments array in blogPost (I will post model code). When I try to execute the query it gives me the following error:
Postman error

These are my models and the route:

blogPost model

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'comment'
  }]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;
</code>```

comment model

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number

  // board: Board
});

// UserSchema.virtual('postCount').get(function(){
//   return this.posts.length;
// });

const Comment = mongoose.model('comment', CommentSchema);

module.exports = Comment;
</code>```

Route

```<code>routes.put('/blogPosts/:id/comment', function(req, res) {
    const blogPostId = req.param('id');
    const commentProps = req.body;

    BlogPost.findById(req.params.id)
        .then((blogPost) => {
          blogPost.comments.push(commentProps);
          blogPost.save();
        })
    .catch((error) => res.status(400).json(error))
});
</code>```

Any help is greatly appreciated.

答:
You don't want to push the entire comment into the comments array but just its _id. So something like this (untested):

```<code>// first save the comment
Comment.create(commentProps, function(err, comment) {
    if(err)
    {
      // save the world
    }
    else
    {
        BlogPost.update({ _id: req.param('id') }, { $push: { comments: comment._id } }, function(err, numberAffected, raw) { /*...*/ });
    });
</code>```

Body:
I am making a route in a Node server using Mongoose and Mongo which stores a comment in the comments array in blogPost (I will post model code). When I try to execute the query it gives me the following error:
Postman error

These are my models and the route:

blogPost model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'comment'
  }]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;

comment model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number

  // board: Board
});

// UserSchema.virtual('postCount').get(function(){
//   return this.posts.length;
// });

const Comment = mongoose.model('comment', CommentSchema);

module.exports = Comment;

Route

routes.put('/blogPosts/:id/comment', function(req, res) {
    const blogPostId = req.param('id');
    const commentProps = req.body;

    BlogPost.findById(req.params.id)
        .then((blogPost) => {
          blogPost.comments.push(commentProps);
          blogPost.save();
        })
    .catch((error) => res.status(400).json(error))
});

Any help is greatly appreciated.

Body:
You don't want to push the entire comment into the comments array but just its _id. So something like this (untested):

// first save the comment
Comment.create(commentProps, function(err, comment) {
    if(err)
    {
      // save the world
    }
    else
    {
        BlogPost.update({ _id: req.param('id') }, { $push: { comments: comment._id } }, function(err, numberAffected, raw) { /*...*/ });
    });


答:
Try following:</p>

```<code>getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl).map((response)=>{
        return response;
    })
}
</code>```

Title: Angular - convert HAL to JSON

Body:
The following service extracts category objects from a REST service which returns them in HAL format. Now I try to convert that response into JSON. For that I searched and tried different solutions, e.g. chariotsolutions or so. Some are based on Response from '@angular/http' which is deprecated and which I cannot make work.

How can I do the conversion?

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { Category } from './category';

@Injectable()
export class CategoryService {

  private categoriesUrl = 'http://localhost:8080/account/categories';

  constructor(private http: HttpClient) { }

  getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl);
  }

}

The response as HAL

{
  "_embedded": {
    "categories": [
      {
        "id": 1,
        "name": "hardware",
        "description": "comprises all computer hardware",
        "level": "FIRST",
        "_links": {
          "self": {
            "href": "http://localhost:8080/account/categories/1"
          },
          "categoryEntity": {
            "href": "http://localhost:8080/account/categories/1"
          }
        }
      },
      {
        "id": 2,
        "name": "hardware_notebook",
        "description": "all notebooks",
        "level": "SECOND",
        "_links": {
          "self": {
            "href": "http://localhost:8080/account/categories/2"
          },
          "categoryEntity": {
            "href": "http://localhost:8080/account/categories/2"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/account/categories{?page,size,sort}",
      "templated": true
    },
    "profile": {
      "href": "http://localhost:8080/account/profile/categories"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 8,
    "totalPages": 1,
    "number": 0
  }
}

Body:
Try following:

getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl).map((response)=>{
        return response;
    })
}


问:
React: passing parameters to a function in map
I am building a component that shows array of users in React using MaterialDesign's Table.

 Each row is generated by a map function:

```<code>let actions = this.props.rowButtons;
...
{this.props.tableData.map( (val, index) => (
                       <TableRow key={index}>
                         <TableRowColumn >{index}</TableRowColumn>
                         <TableRowColumn >{val.firstName}</TableRowColumn>
                         <TableRowColumn >{val.lastName}</TableRowColumn>
                         <TableRowColumn >{val.email}</TableRowColumn>
                         <TableRowColumn >
                            <ActionButtons actions={actions}/>
                         </TableRowColumn>
                       </TableRow>
))}
</code>```

<ActionButtons> component creates one or many buttons, and as an argument takes array of objects like [{type: string, onClick: function}, {type: string, onClick: function}, ... ] (one button for each object in array);
Parent component is sending such an array in this.props.rowButtons.

I want to pass val  as an argument to each onClick function to have something like

```<code>actions = [{type: "personButton", onClick: onClick(val)}, {type: '', onclick: someOtherfunction(val)}];
</code>```

答:
You have to modify the actions a bit. Try doing it following way.

```<code>modifyActions = (actions, val) => {
  return actions.map((a) => {
      return Object.assign({}, a, {onClick: () => a.onClick(val)})
  })
}

<ActionButtons actions={this.modifyActions(actions, val)})}/>
</code>```

Body:
I am building a component that shows array of users in React using MaterialDesign's Table.

 Each row is generated by a map function:

let actions = this.props.rowButtons;
...
{this.props.tableData.map( (val, index) => (
                       <TableRow key={index}>
                         <TableRowColumn >{index}</TableRowColumn>
                         <TableRowColumn >{val.firstName}</TableRowColumn>
                         <TableRowColumn >{val.lastName}</TableRowColumn>
                         <TableRowColumn >{val.email}</TableRowColumn>
                         <TableRowColumn >
                            <ActionButtons actions={actions}/>
                         </TableRowColumn>
                       </TableRow>
))}

<ActionButtons> component creates one or many buttons, and as an argument takes array of objects like [{type: string, onClick: function}, {type: string, onClick: function}, ... ] (one button for each object in array);
Parent component is sending such an array in this.props.rowButtons.

I want to pass val  as an argument to each onClick function to have something like

actions = [{type: "personButton", onClick: onClick(val)}, {type: '', onclick: someOtherfunction(val)}];

Body:
You have to modify the actions a bit. Try doing it following way.

modifyActions = (actions, val) => {
  return actions.map((a) => {
      return Object.assign({}, a, {onClick: () => a.onClick(val)})
  })
}

<ActionButtons actions={this.modifyActions(actions, val)})}/>


问:
Filter out powershell search based on characters
How can i filter out characters in powershell search after users in AD?</p>

```<code>Get-ADUser -Filter {Char-eq "E"} -SearchBase "DC=Test, DC=local"
</code>```

答:
Your question is not very specific but I´ll just try to explain the filter parameter in general. First a bit of documentation:

Filter

Specifies a query string that retrieves Active Directory objects. This
  string uses the PowerShell Expression Language syntax. The PowerShell
  Expression Language syntax provides rich type-conversion support for
  value types received by the Filter parameter. The syntax uses an
  in-order representation, which means that the operator is placed
  between the operand and the value. For more information about the
  Filter parameter, see about_ActiveDirectory_Filter.

In practice it works like this:

Get all users:

```<code>Get-ADUser -Filter *
</code>```

Get all users whose surname is "Smith"

```<code>Get-ADUser -Filter {sn -eq "Smith"}
</code>```

Get all users who have an e-mail address and a phone number

```<code>Get-ADUser -Filter {(mail -like "*") -and (telephonenumber -like "*")}
</code>```

Get all users whose firstname starts with an E

```<code>Get-ADUser -Filter {givenname -like "E*"}
</code>```

The supported operators are:

FilterOperators: "-eq" | "-le" | "-ge" | "-ne" | "-lt" | "-gt"| "-approx" | "-bor" | "-band" | "-recursivematch" | "-like" | "-notlike"

JoinOperators "-and" | "-or"

NotOperators "-not"

Hope that helps, here is a link to the full Documentation: Get-ADUser, about_ActiveDirectory_Filter

Body:
How can i filter out characters in powershell search after users in AD?

Get-ADUser -Filter {Char-eq "E"} -SearchBase "DC=Test, DC=local"

Body:
Your question is not very specific but I´ll just try to explain the filter parameter in general. First a bit of documentation:

Filter

Specifies a query string that retrieves Active Directory objects. This
  string uses the PowerShell Expression Language syntax. The PowerShell
  Expression Language syntax provides rich type-conversion support for
  value types received by the Filter parameter. The syntax uses an
  in-order representation, which means that the operator is placed
  between the operand and the value. For more information about the
  Filter parameter, see about_ActiveDirectory_Filter.

In practice it works like this:

Get all users:

Get-ADUser -Filter *

Get all users whose surname is "Smith"

Get-ADUser -Filter {sn -eq "Smith"}

Get all users who have an e-mail address and a phone number

Get-ADUser -Filter {(mail -like "*") -and (telephonenumber -like "*")}

Get all users whose firstname starts with an E

Get-ADUser -Filter {givenname -like "E*"}

The supported operators are:

FilterOperators: "-eq" | "-le" | "-ge" | "-ne" | "-lt" | "-gt"| "-approx" | "-bor" | "-band" | "-recursivematch" | "-like" | "-notlike"

JoinOperators "-and" | "-or"

NotOperators "-not"

Hope that helps, here is a link to the full Documentation: Get-ADUser, about_ActiveDirectory_Filter


问:
Creating separate table to keep track of a specific column using TIMESTAMP data type
I've a mysql table which has two columns changes frequently.
One is  "available"(mainly 0,1) & the other is  "notification_preference".
Now, I wanna create a "updated_at" column to keep track of of the changes of "available" column.

I've learnt that TIMESTAMP type updates automatically if a column of the corresponding row changes. I want to use "updated_at" column to keep track only of the "available" column.

So the question is, should I create a new table with "available" & "updated_at(TIMESTAMP)" or keep data in the same table and change the "updated_at" table manually?
The main table is the following :

...........................................

id                int

name              varchar

username          varchar

password          varchar

available         tinyint

updated_at        DATETIME

What I'm wanting to do is :

Main Table

...........................................

id                int

name              varchar

username          varchar

password          varchar

available         tinyint

updated_at        DATETIME

Another Table for available

...........................................

user_id

available         tinyint

updated_at        TIMESTAMP

which procedure is better?

There are other columns in the main table that might change sometimes, so I can't use TIMESTAMP for "updated_at" in the main table. Because if other columns of this table get updated, then "updated_at" will be updated too, but I don't want this.
Thanks in advance.

答:
You can use a trigger which will update the updated_at column only if the value in available has been changed:

```<code>create trigger mainTable_before_update before update on mainTable
for each row begin
    if new.available <> old.available
        then set new.updated_at = now();
    end if;
end
</code>```

For inserts you can still use DEFAULT CURRENT_TIMESTAMP in the CREATE statement:

```<code>updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
</code>```

As you will see in the Demo the column is not updated when we change the password. But it is updated when we change available.

Body:
You can use a trigger which will update the updated_at column only if the value in available has been changed:

create trigger mainTable_before_update before update on mainTable
for each row begin
    if new.available <> old.available
        then set new.updated_at = now();
    end if;
end

For inserts you can still use DEFAULT CURRENT_TIMESTAMP in the CREATE statement:

updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

As you will see in the Demo the column is not updated when we change the password. But it is updated when we change available.


问:
Zip function and going through lists that incorporates raw_input?
Can zip be used to go through question and answer variables that ask for raw input in the answer variable? </p>

答:
Yes, of course you can do something like this, but i wouldn't suggest it:

```<code>questions = ['Question 1? ', 'Question 2? ']
answers = [input(questions[0]), input(questions[1])]

zip_object = zip(questions, answers)
</code>```

The answers variable will be filled by your answers.

Body:
Yes, of course you can do something like this, but i wouldn't suggest it:

questions = ['Question 1? ', 'Question 2? ']
answers = [input(questions[0]), input(questions[1])]

zip_object = zip(questions, answers)

The answers variable will be filled by your answers.


问:
Alias templates or specialized derived classes?
```<code>template<typename T, int V>
class AwesomeClass    // [1]
{
public:

    AwesomeClass(T baseValue)
        : m_value(baseValue + V)
    {
    }

    T get() const
    {
        return m_value;
    }

private:

    T m_value;
};

#ifdef USE_ALIAS_TEMPLATES    // [2]

template<typename T>
using AwesomeClassWithOne = AwesomeClass<T, 1>;

template<typename T>
using AwesomeClassWithTwo = AwesomeClass<T, 2>;

#else    // [4]

template<typename T>
class AwesomeClassWithOne: public AwesomeClass<T, 1>
{
    using AwesomeClass<T, 1>::AwesomeClass;
};

template<typename T>
class AwesomeClassWithTwo: public AwesomeClass<T, 2>
{
    using AwesomeClass<T, 2>::AwesomeClass;
};

AwesomeClassWithOne(int) -> AwesomeClassWithOne<int>;
AwesomeClassWithTwo(int) -> AwesomeClassWithTwo<int>;

#endif

int main()
{
    AwesomeClassWithOne firstObj(20);    // [3]
    AwesomeClassWithTwo secondObj(20);

    return firstObj.get() + secondObj.get();
}
</code>```

I have a class, AwesomeClass [1], which takes two template parameters, typename T and int V. V is an internal detail that I don't want to expose to users of the class, so instead I want to provide aliases such as AwesomeClassWithOne and AwesomeClassWithTwo which take only T as a template parameter, and have V already bound to some value (1 and 2 respectively in my example).

Alias templates seemed to be appropriate for this [2]. However, as of C++17, it appears that argument deduction cannot be used with alias templates, so I can't do [3].

So I came up with an alternative [4] which involves creating new derived classes for each "alias" type I want, inheriting all the constructors from the base class, then creating deduction guides to make automatic deduction work (base class constructors don't seem to result in automatic deduction guides like normal constructors do; related question).

Does this seem like an appropriate workaround? Can I expect to see any weird side-effects compared to the alias template solution?

答:
It's a pity that C++17 doesn't accept deduction guides for type aliases.

But you can ever use the good old make-something way (std::make_pair(), std::make_tuple(), std::make_unique(), etc.).

By example: if you define, switching the order of template arguments, a makeAwesome() function as follows

```<code>template <int V, typename T>
AwesomeClass<T, V> makeAwesome (T && t)
 { return { std::forward<T>(t) };
</code>```

you can obtain an AwesomeClass<T, V> object, explicating V and deducing T, calling it as follows

```<code>auto firstObj = makeAwesome<1>(20);
</code>```

If you don't want expose to the user the integer V part, you can add

```<code>template <typename T>
auto makeAwesomeWithOne (T && t)
 { return makeAwesome<1>( std::forward<T>(t) ); }

template <typename T>
auto makeAwesomeWithTwo (T && t)
 { return makeAwesome<2>( std::forward<T>(t) ); }
</code>```

and in main() you can write

```<code>auto firstObj  = makeAwesomeWithOne(20);
auto secondObj = makeAwesomeWithTwo(20);
</code>```

I know that it's annoying to write a lot of makeAwesomeWith-number functions that are almost equals.

If the use of old C-style function macros doesn't scare you (they are distilled evil, IMHO, but in circumstances like this...) you can auto-magically create the makeAwesomeWith-number functions as follows

```<code>#define MakeAwesomeWith(Str, Num) \
   template <typename T> \
   auto makeAwesomeWith ## Str (T && t) \
    { return makeAwesome<Num>( std::forward<T>(t) ); }

MakeAwesomeWith(One, 1);
MakeAwesomeWith(Two, 2);
// ...
</code>```

The following is a full working (macro based) example

```<code>#include <iostream>
#include <utility>

template <typename T, int V>
class AwesomeClass
 {
   public:
      AwesomeClass (T baseValue) : m_value(baseValue + V)
       { }

      T get () const
       { return m_value; }

   private:
      T m_value;
 };

template <int V, typename T>
AwesomeClass<T, V> makeAwesome (T && t)
 { return { std::forward<T>(t) }; }

#define MakeAwesomeWith(Str, Num) \
   template <typename T> \
   auto makeAwesomeWith ## Str (T && t) \
    { return makeAwesome<Num>( std::forward<T>(t) ); }

MakeAwesomeWith(One, 1);
MakeAwesomeWith(Two, 2);

int main ()
 {
   auto firstObj  = makeAwesomeWithOne(20);
   auto secondObj = makeAwesomeWithTwo(20);

   std::cout << (firstObj.get() + secondObj.get()) << std::endl;
 }
</code>```

Body:
template<typename T, int V>
class AwesomeClass    // [1]
{
public:

    AwesomeClass(T baseValue)
        : m_value(baseValue + V)
    {
    }

    T get() const
    {
        return m_value;
    }

private:

    T m_value;
};

#ifdef USE_ALIAS_TEMPLATES    // [2]

template<typename T>
using AwesomeClassWithOne = AwesomeClass<T, 1>;

template<typename T>
using AwesomeClassWithTwo = AwesomeClass<T, 2>;

#else    // [4]

template<typename T>
class AwesomeClassWithOne: public AwesomeClass<T, 1>
{
    using AwesomeClass<T, 1>::AwesomeClass;
};

template<typename T>
class AwesomeClassWithTwo: public AwesomeClass<T, 2>
{
    using AwesomeClass<T, 2>::AwesomeClass;
};

AwesomeClassWithOne(int) -> AwesomeClassWithOne<int>;
AwesomeClassWithTwo(int) -> AwesomeClassWithTwo<int>;

#endif

int main()
{
    AwesomeClassWithOne firstObj(20);    // [3]
    AwesomeClassWithTwo secondObj(20);

    return firstObj.get() + secondObj.get();
}

I have a class, AwesomeClass [1], which takes two template parameters, typename T and int V. V is an internal detail that I don't want to expose to users of the class, so instead I want to provide aliases such as AwesomeClassWithOne and AwesomeClassWithTwo which take only T as a template parameter, and have V already bound to some value (1 and 2 respectively in my example).

Alias templates seemed to be appropriate for this [2]. However, as of C++17, it appears that argument deduction cannot be used with alias templates, so I can't do [3].

So I came up with an alternative [4] which involves creating new derived classes for each "alias" type I want, inheriting all the constructors from the base class, then creating deduction guides to make automatic deduction work (base class constructors don't seem to result in automatic deduction guides like normal constructors do; related question).

Does this seem like an appropriate workaround? Can I expect to see any weird side-effects compared to the alias template solution?

Body:
It's a pity that C++17 doesn't accept deduction guides for type aliases.

But you can ever use the good old make-something way (std::make_pair(), std::make_tuple(), std::make_unique(), etc.).

By example: if you define, switching the order of template arguments, a makeAwesome() function as follows

template <int V, typename T>
AwesomeClass<T, V> makeAwesome (T && t)
 { return { std::forward<T>(t) };

you can obtain an AwesomeClass<T, V> object, explicating V and deducing T, calling it as follows

auto firstObj = makeAwesome<1>(20);

If you don't want expose to the user the integer V part, you can add

template <typename T>
auto makeAwesomeWithOne (T && t)
 { return makeAwesome<1>( std::forward<T>(t) ); }

template <typename T>
auto makeAwesomeWithTwo (T && t)
 { return makeAwesome<2>( std::forward<T>(t) ); }

and in main() you can write

auto firstObj  = makeAwesomeWithOne(20);
auto secondObj = makeAwesomeWithTwo(20);

I know that it's annoying to write a lot of makeAwesomeWith-number functions that are almost equals.

If the use of old C-style function macros doesn't scare you (they are distilled evil, IMHO, but in circumstances like this...) you can auto-magically create the makeAwesomeWith-number functions as follows

#define MakeAwesomeWith(Str, Num) \
   template <typename T> \
   auto makeAwesomeWith ## Str (T && t) \
    { return makeAwesome<Num>( std::forward<T>(t) ); }

MakeAwesomeWith(One, 1);
MakeAwesomeWith(Two, 2);
// ...

The following is a full working (macro based) example

#include <iostream>
#include <utility>

template <typename T, int V>
class AwesomeClass
 {
   public:
      AwesomeClass (T baseValue) : m_value(baseValue + V)
       { }

      T get () const
       { return m_value; }

   private:
      T m_value;
 };

template <int V, typename T>
AwesomeClass<T, V> makeAwesome (T && t)
 { return { std::forward<T>(t) }; }

#define MakeAwesomeWith(Str, Num) \
   template <typename T> \
   auto makeAwesomeWith ## Str (T && t) \
    { return makeAwesome<Num>( std::forward<T>(t) ); }

MakeAwesomeWith(One, 1);
MakeAwesomeWith(Two, 2);

int main ()
 {
   auto firstObj  = makeAwesomeWithOne(20);
   auto secondObj = makeAwesomeWithTwo(20);

   std::cout << (firstObj.get() + secondObj.get()) << std::endl;
 }


问:
AppCompatRadioButton not shown
Since I want to use buttonTint on versions < 21, I need to switch from RadioButton to AppCompatRadioButton. Unfortunately the button is not shown on the device (Android 5.1). It's strange because the android:text of the AppCompatRadioButton works, so that means that the button basically works. Only the circle is not shown. Any ideas why? I also tried to set other color attributes which come with AppCompatRadioButton. It didn't work either. I also updated to the latest compatibility package, I moved the button inside the xml to another position, but nothing works.

This is the xml definition:

```<code><android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="onBillingRadioButtonClicked"
    android:text="@string/bronze_monthly"
    android:textColor="@color/black"
    android:textSize="@dimen/default_text_size"
    app:buttonTint="@color/black"
    app:colorAccent="@color/black"
    app:colorPrimary="@color/black"
    app:colorPrimaryDark="@color/black"/>
</code>```

答:
I figured out what was wrong:
Inside the Activity declaration in AndroidManifest, I set my own transparent theme which is used in other Activities too:

```<code><activity
    android:name=".domain.billing.BillingActivity"
    android:noHistory="true"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.Transparent">
</activity>
</code>```

This is from styles.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="Theme.Transparent" parent="android:Theme">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

<!--more styles -->
</resources>
</code>```

if I omit this line, it works:

```<code>android:theme="@style/Theme.Transparent"
</code>```

Title: AppCompatRadioButton not shown

Body:
Since I want to use buttonTint on versions < 21, I need to switch from RadioButton to AppCompatRadioButton. Unfortunately the button is not shown on the device (Android 5.1). It's strange because the android:text of the AppCompatRadioButton works, so that means that the button basically works. Only the circle is not shown. Any ideas why? I also tried to set other color attributes which come with AppCompatRadioButton. It didn't work either. I also updated to the latest compatibility package, I moved the button inside the xml to another position, but nothing works.

This is the xml definition:

<android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="onBillingRadioButtonClicked"
    android:text="@string/bronze_monthly"
    android:textColor="@color/black"
    android:textSize="@dimen/default_text_size"
    app:buttonTint="@color/black"
    app:colorAccent="@color/black"
    app:colorPrimary="@color/black"
    app:colorPrimaryDark="@color/black"/>

Body:
I figured out what was wrong:
Inside the Activity declaration in AndroidManifest, I set my own transparent theme which is used in other Activities too:

<activity
    android:name=".domain.billing.BillingActivity"
    android:noHistory="true"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.Transparent">
</activity>

This is from styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="Theme.Transparent" parent="android:Theme">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

<!--more styles -->
</resources>

if I omit this line, it works:

android:theme="@style/Theme.Transparent"