问:
MySQL - Retrieving the record with the maximum value
I've a table like below on my MySQL database:

```<code>employee
-------------------------
id    name    num
1     Jack    1
2     John    1
3     Jack    2
4     Steve   1
5     Jack    3
6     Steve   2
7     Carol   1
</code>```

The thing I want to do is to retrieve names with the highest "num" value.

For example:

```<code>5     Jack    3
</code>```

There more than one records named Jack but I want to get the one with the maximum "num" value.

I've tried to use the query below:

```<code>SELECT MAX(num),id,name FROM `employee`
</code>```

But it returns the id and name of first record (first "Jack") but the num of the latest.

```<code>MAX(num)    id     num
-----------------------
3           1      Jack
</code>```

Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.

```<code>SELECT num,id,name FROM `employee` order by num desc
</code>```

This query will also return all the records including the smaller ones.

```<code>id    name    num
-------------------------
3     5       Jack
2     3       Jack
2     6       Steve
1     1       Jack
1     2       John
1     4       Steve
1     7       Carol
</code>```

When I try to group by name, it returns the records grouped by name but again only the small records.

The both of the queries below give the same result:

```<code>SELECT num,id,name FROM `employee` group by name order by num desc

SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc
</code>```

Again, it groups with only the first and smallest records.

```<code>id  name    num
1   Jack    1
2   John    1
4   Steve   1
7   Carol   1
</code>```

答:
Simply add a LIMIT 1 clause to your query like

```<code>SELECT num,id,name FROM `employee` order by num desc LIMIT 1
</code>```

Edit:

OK, I misunderstood your original question. The following lists each name with the highest num value:

```<code>SELECT a.* FROM employee a
INNER JOIN (
  SELECT name na, MAX(num) nu FROM employee
  GROUP BY name ) b ON na=name AND nu=num
</code>```

See here for a demo: http://rextester.com/MOL28087

Body:
I've a table like below on my MySQL database:

employee
-------------------------
id    name    num
1     Jack    1
2     John    1
3     Jack    2
4     Steve   1
5     Jack    3
6     Steve   2
7     Carol   1

The thing I want to do is to retrieve names with the highest "num" value.

For example:

5     Jack    3

There more than one records named Jack but I want to get the one with the maximum "num" value.

I've tried to use the query below:

SELECT MAX(num),id,name FROM `employee`

But it returns the id and name of first record (first "Jack") but the num of the latest.

MAX(num)    id     num
-----------------------
3           1      Jack

Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.

SELECT num,id,name FROM `employee` order by num desc

This query will also return all the records including the smaller ones.

id    name    num
-------------------------
3     5       Jack
2     3       Jack
2     6       Steve
1     1       Jack
1     2       John
1     4       Steve
1     7       Carol

When I try to group by name, it returns the records grouped by name but again only the small records.

The both of the queries below give the same result:

SELECT num,id,name FROM `employee` group by name order by num desc

SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc

Again, it groups with only the first and smallest records.

id  name    num
1   Jack    1
2   John    1
4   Steve   1
7   Carol   1

Body:
Simply add a LIMIT 1 clause to your query like

SELECT num,id,name FROM `employee` order by num desc LIMIT 1

Edit:

OK, I misunderstood your original question. The following lists each name with the highest num value:

SELECT a.* FROM employee a
INNER JOIN (
  SELECT name na, MAX(num) nu FROM employee
  GROUP BY name ) b ON na=name AND nu=num

See here for a demo: http://rextester.com/MOL28087


来源: stackexchange

问:
SQL Null: Preferred way of distinguishing between unknown and no value
Suppose I have a simple table such as:

```<code>CREATE TABLE authors (
    id INT PRIMARY KEY,
    name VARCHAR(40),
    born DATE,
    died DATE
);
</code>```

Both the born and died dates are optional, so they can contain NULL.

Presumably authors who haven’t been born yet, won’t make it into the table, so the obvious way to interpret NULL would be that the date is unknown.

However, there is some ambiguity with the died date. A null could imply that the date is unknown, or that the author has yet to die.

What is the preferred way allow for both an unknown date and an event which has not yet occurred?

For what it’s worth, I routinely use PostgreSQL, MySQL/MariaDB and SQL Server, so this question isn’t specific to a particular DBMS.

答: One way to handle this would be to add a new column deceased which indicates whether or not a given author has expired.  This frees your died date field from being responsible for whether an author has died.  Under this design, if an author has not yet died (deceased is false), then we don't care about the date of death.  And if an author has died, then a NULL value would only mean that the date really is unknown.

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a simple table such as:

CREATE TABLE authors (
    id INT PRIMARY KEY,
    name VARCHAR(40),
    born DATE,
    died DATE
);

Both the born and died dates are optional, so they can contain NULL.

Presumably authors who haven’t been born yet, won’t make it into the table, so the obvious way to interpret NULL would be that the date is unknown.

However, there is some ambiguity with the died date. A null could imply that the date is unknown, or that the author has yet to die.

What is the preferred way allow for both an unknown date and an event which has not yet occurred?

For what it’s worth, I routinely use PostgreSQL, MySQL/MariaDB and SQL Server, so this question isn’t specific to a particular DBMS.


问:
Error Generating OpenAPI doc using the endpoint-framework-tools (unclear documentation)
(Intro)

I am undergoing some tutorials on google cloud endpoint using the google documentation. I have managed to run my first API but i am having an error generating an OpenAPI document using the endpoint-framework-tools

(Question/Issue)

Long story short, I am having an "unclear" error while trying to generate the OpenAPI document of my google cloud endpoint project.
Official google docs (here) states the below method to generate the file:

```<code>  endpoints-framework-tools-2.0.0-beta.11/bin/endpoints-framework-tools\
 get-openapi-doc \
  --hostname=YOUR-PROJECT-ID.appspot.com \
  --war=target/echo-1.0-SNAPSHOT \
  com.example.echo.Echo
</code>```

They do not specify what is "com.eample.echo.Echo".
Trying to run the command by replacing com.example by my package path I am receiving the below confusing error.

```<code>Error:  co.mydomain.eliokhattar.myapplication.backend.MyEndpoint
</code>```

replacing the above package by any other package still gives the same error.

Can any one advise or provide a clear tutorial on how to use this endpoints-framework-tool?

答:
I have figured out the issue, and it was related to the fact that i was not mentionning the -classpath parameter when invoking endpoint framework.
The below command worked fine.

```<code>endpoints-framework-tools-2.0.0-beta.11/bin/endpoints-framework-tools \
 get-openapi-doc \
 --hostname=iccloudendpoint.appspot.com \
 --war=/Users/eliokhattar/endpints-test/IcExteranlTutorialDemo/icSysBackend/src/main/webapp \
 --classpath=/Users/eliokhattar/endpints-test/IcExteranlTutorialDemo/icSysBackend/build/classes/main/ co.mydomain.eliokhattar.myapplication.backend.MyEndpoint
</code>```

On the other hand i am having a different unrelated error now.

Body:
(Intro)

I am undergoing some tutorials on google cloud endpoint using the google documentation. I have managed to run my first API but i am having an error generating an OpenAPI document using the endpoint-framework-tools

(Question/Issue)

Long story short, I am having an "unclear" error while trying to generate the OpenAPI document of my google cloud endpoint project.
Official google docs (here) states the below method to generate the file:

  endpoints-framework-tools-2.0.0-beta.11/bin/endpoints-framework-tools\
 get-openapi-doc \
  --hostname=YOUR-PROJECT-ID.appspot.com \
  --war=target/echo-1.0-SNAPSHOT \
  com.example.echo.Echo

They do not specify what is "com.eample.echo.Echo".
Trying to run the command by replacing com.example by my package path I am receiving the below confusing error.

Error:  co.mydomain.eliokhattar.myapplication.backend.MyEndpoint

replacing the above package by any other package still gives the same error.

Can any one advise or provide a clear tutorial on how to use this endpoints-framework-tool?

Body:
I have figured out the issue, and it was related to the fact that i was not mentionning the -classpath parameter when invoking endpoint framework.
The below command worked fine.

endpoints-framework-tools-2.0.0-beta.11/bin/endpoints-framework-tools \
 get-openapi-doc \
 --hostname=iccloudendpoint.appspot.com \
 --war=/Users/eliokhattar/endpints-test/IcExteranlTutorialDemo/icSysBackend/src/main/webapp \
 --classpath=/Users/eliokhattar/endpints-test/IcExteranlTutorialDemo/icSysBackend/build/classes/main/ co.mydomain.eliokhattar.myapplication.backend.MyEndpoint

On the other hand i am having a different unrelated error now.


问:
How to use doctrine or symfony pager with different column selected from multiple table?
How can I implement pagination using Doctrine_Pager or sfDoctrinePager while my query selects multiple columns from two or more tables ?

Edit1:

Ok, now I figured out that it can be done how Nathan has described below! I got confused as I couldn't retrieve certain data from the query! Let me describe it below:

This is my pager query:

```<code>        $pager = new sfDoctrinePager('sfGuardUser', '5');

        $q = Doctrine_Query::create()
                        ->select('u.id, u.username,  p.org_name,  g.name, l.status')
                        ->from('sfGuardUser u')
                        ->leftJoin('u.Profile p')
                        ->leftJoin('u.Groups g')
                        ->leftJoin('u.LicensedVendors l')
                        ->where('g.name = \'client\'');

        $pager->setQuery($q);
        $pager->setPage($request->getParameter('page', 1));
        $pager->init();
</code>```

Now in my Template I can retrieve my sfGuardUser and Profile data like this:

```<code> foreach ($pager->getResults() as $data) {

            echo $data->username ;  //outputs 'username' from sfGuardUser table
            echo '<br />' ;
            echo $data->Profile->org_name ; //outputs 'Organization name' from sfGuardUserProfile table

}
</code>```

I was wrongly trying to retrieve the profile data by $data->org_name and not $data->Profile->org_name! Now its working for this part correctly, but there is still an issue !

I am still unable to retrieve the Groups & LicensedVendors data using $data->Groups->name or $data->LicensedVendors->status ! It does not show any error or any value either! looks like it outputs an empty string. Shouldn't it get the value just like Profile data ?
But when I hydrate the query by setting:

$q->setHydrationMode(Doctrine_Core::HYDRATE_SCALAR);

I can retrieve all data through:

```<code>foreach ($pager->getResults() as $data) {

      echo $data['u_username'];
      echo $data['p_org_name'];
      echo $data['g_name'];
      echo $data['l_status'];
}
</code>```

How to get those data without setting **Doctrine_Core::HYDRATE_SCALAR** ? Where I'm doing wrong for retrieving those Groups and LicensedVendors table data?

Here is the schema definition of the tables described above:

```<code>License:
  actAs: [Timestampable]
  tableName: licenses
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    status:
      type: enum
      values: ['approved','pending_admin','pending_client','pending_vendor','rejected']
      default: 'pending'
    client_id:
      type: integer(8)
      notnull: true
    vendor_id:
      type: integer(8)
      notnull: true
    product_desc:
      type: clob(16777215)
    supplier_name:
      type: string(80)
    other_desc:
      type: string(50)
    financial_statement:
      type: clob
  relations:
    VendorUser:
      class: sfGuardUser
      local: client_id
      foreign: id
      foreignAlias: LicensedVendors
      onDelete: cascade
      foreignType: many
      owningSide: true
    ClientUser:
      class: sfGuardUser
      local: vendor_id
      foreign: id
      foreignAlias: LicensedClients
      onDelete: cascade
      foreignType: many
      owningSide: true

sfGuardUser:
      actAs: [Timestampable]
      columns:
        first_name: string(255)
        last_name: string(255)
        email_address:
          type: string(255)
          notnull: true
          unique: true
        username:
          type: string(128)
          notnull: true
          unique: true
        algorithm:
          type: string(128)
          default: sha1
          notnull: true
        salt: string(128)
        password: string(128)
        is_active:
          type: boolean
          default: 1
        is_super_admin:
          type: boolean
          default: false
        last_login:
          type: timestamp
      indexes:
        is_active_idx:
          fields: [is_active]
      relations:
        Groups:
          class: sfGuardGroup
          local: user_id
          foreign: group_id
          refClass: sfGuardUserGroup
          foreignAlias: Users

sfGuardUserProfile:
  actAs:
    Timestampable: ~
  columns:
    user_id:
      type: integer
      notnull: true
    email:
      type: string(80)
      notnull: true
      unique: true
    email_new:
      type: string(80)
      unique: true
    firstname:
      type: string(30)
    lastname:
      type: string(70)
    org_name:
      type: string(80)
      notnull: true

  relations:
    User:
      class: sfGuardUser
      foreign: id
      local: user_id
      type: one
      onDelete: cascade
      foreignType: one
      foreignAlias: Profile

sfGuardGroup:
  actAs: [Timestampable]
  columns:
    name:
      type: string(255)
      unique: true
    description: string(1000)
  relations:
    Users:
      class: sfGuardUser
      refClass: sfGuardUserGroup
      local: group_id
      foreign: user_id
      foreignAlias: Groups
</code>```

Edit2: I posted my new issues which I described in first edit as a separate question here !

答:
Yeah, what greg0ire said.  This documentation is a bit old, but it shows what you'd need with Propel in the old days.  Updating to Doctrine would be like,

```<code>public function executeList ()
{
  $pager = new sfDoctrinePager('Comment', 2);

  $q = Doctrine_Core::getTable('Comment')
    ->createQuery('c')
    ->where('c.author = ?', 'Steve')
    ->leftJoin('c.Article a')
    ->andWhere('a.content LIKE ?', '%enjoy%')
    ->orderBy('c.created_at ASC');

  $pager->setQuery($q);
  $pager->setPage($request->getParameter('page', 1));
  $pager->init();

  $this->pager = $pager;
}
</code>```

This blog post, "Symfony doctrine pager for two tables" has a more extended/convoluted example.  Oh, looks like that was the author's answer to his own SO question.

ContentLicense: CC BY-SA 2.5

Body:
How can I implement pagination using Doctrine_Pager or sfDoctrinePager while my query selects multiple columns from two or more tables ?

Edit1:

Ok, now I figured out that it can be done how Nathan has described below! I got confused as I couldn't retrieve certain data from the query! Let me describe it below:

This is my pager query:

        $pager = new sfDoctrinePager('sfGuardUser', '5');

        $q = Doctrine_Query::create()
                        ->select('u.id, u.username,  p.org_name,  g.name, l.status')
                        ->from('sfGuardUser u')
                        ->leftJoin('u.Profile p')
                        ->leftJoin('u.Groups g')
                        ->leftJoin('u.LicensedVendors l')
                        ->where('g.name = \'client\'');

        $pager->setQuery($q);
        $pager->setPage($request->getParameter('page', 1));
        $pager->init();

Now in my Template I can retrieve my sfGuardUser and Profile data like this:

 foreach ($pager->getResults() as $data) {

            echo $data->username ;  //outputs 'username' from sfGuardUser table
            echo '
' ;
            echo $data->Profile->org_name ; //outputs 'Organization name' from sfGuardUserProfile table

}

I was wrongly trying to retrieve the profile data by $data->org_name and not $data->Profile->org_name! Now its working for this part correctly, but there is still an issue !

I am still unable to retrieve the Groups & LicensedVendors data using $data->Groups->name or $data->LicensedVendors->status ! It does not show any error or any value either! looks like it outputs an empty string. Shouldn't it get the value just like Profile data ?
But when I hydrate the query by setting:

$q->setHydrationMode(Doctrine_Core::HYDRATE_SCALAR);

I can retrieve all data through:

foreach ($pager->getResults() as $data) {

      echo $data['u_username'];
      echo $data['p_org_name'];
      echo $data['g_name'];
      echo $data['l_status'];
}

How to get those data without setting **Doctrine_Core::HYDRATE_SCALAR** ? Where I'm doing wrong for retrieving those Groups and LicensedVendors table data?

Here is the schema definition of the tables described above:

License:
  actAs: [Timestampable]
  tableName: licenses
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    status:
      type: enum
      values: ['approved','pending_admin','pending_client','pending_vendor','rejected']
      default: 'pending'
    client_id:
      type: integer(8)
      notnull: true
    vendor_id:
      type: integer(8)
      notnull: true
    product_desc:
      type: clob(16777215)
    supplier_name:
      type: string(80)
    other_desc:
      type: string(50)
    financial_statement:
      type: clob
  relations:
    VendorUser:
      class: sfGuardUser
      local: client_id
      foreign: id
      foreignAlias: LicensedVendors
      onDelete: cascade
      foreignType: many
      owningSide: true
    ClientUser:
      class: sfGuardUser
      local: vendor_id
      foreign: id
      foreignAlias: LicensedClients
      onDelete: cascade
      foreignType: many
      owningSide: true

sfGuardUser:
      actAs: [Timestampable]
      columns:
        first_name: string(255)
        last_name: string(255)
        email_address:
          type: string(255)
          notnull: true
          unique: true
        username:
          type: string(128)
          notnull: true
          unique: true
        algorithm:
          type: string(128)
          default: sha1
          notnull: true
        salt: string(128)
        password: string(128)
        is_active:
          type: boolean
          default: 1
        is_super_admin:
          type: boolean
          default: false
        last_login:
          type: timestamp
      indexes:
        is_active_idx:
          fields: [is_active]
      relations:
        Groups:
          class: sfGuardGroup
          local: user_id
          foreign: group_id
          refClass: sfGuardUserGroup
          foreignAlias: Users

sfGuardUserProfile:
  actAs:
    Timestampable: ~
  columns:
    user_id:
      type: integer
      notnull: true
    email:
      type: string(80)
      notnull: true
      unique: true
    email_new:
      type: string(80)
      unique: true
    firstname:
      type: string(30)
    lastname:
      type: string(70)
    org_name:
      type: string(80)
      notnull: true

  relations:
    User:
      class: sfGuardUser
      foreign: id
      local: user_id
      type: one
      onDelete: cascade
      foreignType: one
      foreignAlias: Profile

sfGuardGroup:
  actAs: [Timestampable]
  columns:
    name:
      type: string(255)
      unique: true
    description: string(1000)
  relations:
    Users:
      class: sfGuardUser
      refClass: sfGuardUserGroup
      local: group_id
      foreign: user_id
      foreignAlias: Groups

Edit2: I posted my new issues which I described in first edit as a separate question here !

Body:
Yeah, what greg0ire said.  This documentation is a bit old, but it shows what you'd need with Propel in the old days.  Updating to Doctrine would be like,

public function executeList ()
{
  $pager = new sfDoctrinePager('Comment', 2);

  $q = Doctrine_Core::getTable('Comment')
    ->createQuery('c')
    ->where('c.author = ?', 'Steve')
    ->leftJoin('c.Article a')
    ->andWhere('a.content LIKE ?', '%enjoy%')
    ->orderBy('c.created_at ASC');

  $pager->setQuery($q);
  $pager->setPage($request->getParameter('page', 1));
  $pager->init();

  $this->pager = $pager;
}

This blog post, "Symfony doctrine pager for two tables" has a more extended/convoluted example.  Oh, looks like that was the author's answer to his own SO question.


问:
Cannot access JSON object property in JavaScript
I have a json object

```<code>alert(typeof object)
//Output
Object
</code>```

which returns the following string after

```<code>alert(JSON.stringify(object));

//Output object

[{
"locationId":"8",
"locationTypeId":"0",
"locationTitle":"Alberta Prices",
"locationAddress":"Alberta, Canada",
"locationStatus":"0",
"locationLatitude":"53.9332706",
"locationLongitude":"116.5765035",
"googleLocationId":"ChIJtRkkqIKyCVMRno6bQJpHqbA",
"lastModified":"2017-06-04 03:59:02",
"locationType":"SPORT",
"userId":"4"
}]
</code>```

When I am trying to access any property of the object, I get 'Undefined';

```<code>alert(object.locationId);

//Output
Undefined
</code>```

答:
You get undefined because you are trying to access locationId on an Array which clearly does not exist.

If you want to access a given item's locationId you have to access the array by index and then its property.

```<code>console.log(object[0].locationId); //8
</code>```

Body:
I have a json object

alert(typeof object)
//Output
Object

which returns the following string after

alert(JSON.stringify(object));

//Output object

[{
"locationId":"8",
"locationTypeId":"0",
"locationTitle":"Alberta Prices",
"locationAddress":"Alberta, Canada",
"locationStatus":"0",
"locationLatitude":"53.9332706",
"locationLongitude":"116.5765035",
"googleLocationId":"ChIJtRkkqIKyCVMRno6bQJpHqbA",
"lastModified":"2017-06-04 03:59:02",
"locationType":"SPORT",
"userId":"4"
}]

When I am trying to access any property of the object, I get 'Undefined';

alert(object.locationId);

//Output
Undefined

Body:
You get undefined because you are trying to access locationId on an Array which clearly does not exist.

If you want to access a given item's locationId you have to access the array by index and then its property.

console.log(object[0].locationId); //8


问:
How to efficiently get an adjacency list for a spherical Voronoi diagram?
I want to generate an adjacency list for the regions of a spherical Voronoi diagram. I am using the SphericalVoronoi class from SciPy so the only information I can use is the centers and vertices of the diagram.

The best thing I've come up with is checking for every pair of regions if they have a common vertex (vor is the instance of SphericalVoronoi):

```<code>def adjacent(vor, reg1, reg2):
    for i in vor.vertices[reg1]:
        if i in vor.vertices[reg2]: return True
    return False

adjacencies = [[] for i in range(len(vor.regions))]
for i in range(npoints):
    for j in range(i,npoints):
        if adjacent(vor,vor.regions[i],vor.regions[j]):
            adjacencies[i].append(j)
            adjacencies[j].append(i)
</code>```

Is there a more efficient way to do this?

答:
It is more efficient to find for each vertex regions it is in, and use that information to find which regions are neighbours.

Something like:

```<code># Vertex - region adjacencies
vert2region = defaultdict(list)
for i, region in enumerate(vor.regions):
  for v in region:
    vert2region[v].append(i)

# Region - region adjacencies
adjacencies = defaultdict(set)  # set is important not to have same adjacency twice
for v, regions in vert2region.items():
  for r1, r2 in itertools.combinations(regions, 2):
    adjacencies[r1].add(r2)
    adjacencies[r2].add(r1)
</code>```

Body:
I want to generate an adjacency list for the regions of a spherical Voronoi diagram. I am using the SphericalVoronoi class from SciPy so the only information I can use is the centers and vertices of the diagram.

The best thing I've come up with is checking for every pair of regions if they have a common vertex (vor is the instance of SphericalVoronoi):

def adjacent(vor, reg1, reg2):
    for i in vor.vertices[reg1]:
        if i in vor.vertices[reg2]: return True
    return False

adjacencies = [[] for i in range(len(vor.regions))]
for i in range(npoints):
    for j in range(i,npoints):
        if adjacent(vor,vor.regions[i],vor.regions[j]):
            adjacencies[i].append(j)
            adjacencies[j].append(i)

Is there a more efficient way to do this?

Body:
It is more efficient to find for each vertex regions it is in, and use that information to find which regions are neighbours.

Something like:

# Vertex - region adjacencies
vert2region = defaultdict(list)
for i, region in enumerate(vor.regions):
  for v in region:
    vert2region[v].append(i)

# Region - region adjacencies
adjacencies = defaultdict(set)  # set is important not to have same adjacency twice
for v, regions in vert2region.items():
  for r1, r2 in itertools.combinations(regions, 2):
    adjacencies[r1].add(r2)
    adjacencies[r2].add(r1)


问:
css transitions "triggers" on browser resize
I can't figure out how to avoid css transitions to execute, when you go from mobile first to desktop via media query.

I would like to have and transition on hover, but also when you hover out on a svg logo etc. I have a smaller logo for mobile, and larger for desktop. But the transition effects the new width and triggers a hover transition aswell.

Any idea how you can void transitions to "execute" when new style via a media query gets applied.

I have made an example with my issue.

http://jsfiddle.net/yw2L2u7s/

```<code><div class="logo"></div>

.logo {
    width:100px;
    height:100px;
    background: red;
}
@media only screen and (min-width: 525px) {
    .logo {
        width:200px;
        height:200px;
        background: blue;
    }

    .logo:hover {
        background: yellow;
    }

    .logo {
        -webkit-transition: ease 0.5s;
        -moz-transition: ease 0.5s;
        -ms-transition: ease 0.5s;
        -o-transition: ease 0.5s;
        transition: ease 0.5s;
    }
}
</code>```

答:
I had the same issue and finally found a fix.

This one should work:

```<code>$(document).ready(function(){
   window.onresize = resizePage;
   resizePage();
});
function resizePage(){
    var width = (window.innerWidth > 0) ? window.innerWidth : document.documentElement.clientWidth;
    if(width >= 525 && width <= 526){ // your page breakpoint happens probably between 525px and 526px width at this range we gonna disable the transition temporarily
        $(".logo").css( "transition-property", "none" ); // temporarily disable the transition on .logo
    }
    else{
        $(".logo").css( "transition-property", "" ) // else restore the actual transition
    }
}
</code>```

Note: if you want to temporarily disable all transitions at the breakpoint range, you can use the * selector, which selects all elements.

```<code>$("*").css( "transition-property", "none" );
</code>```

Body:
I can't figure out how to avoid css transitions to execute, when you go from mobile first to desktop via media query.

I would like to have and transition on hover, but also when you hover out on a svg logo etc. I have a smaller logo for mobile, and larger for desktop. But the transition effects the new width and triggers a hover transition aswell.

Any idea how you can void transitions to "execute" when new style via a media query gets applied.

I have made an example with my issue.

http://jsfiddle.net/yw2L2u7s/

.logo {
    width:100px;
    height:100px;
    background: red;
}
@media only screen and (min-width: 525px) {
    .logo {
        width:200px;
        height:200px;
        background: blue;
    }

    .logo:hover {
        background: yellow;
    }

    .logo {
        -webkit-transition: ease 0.5s;
        -moz-transition: ease 0.5s;
        -ms-transition: ease 0.5s;
        -o-transition: ease 0.5s;
        transition: ease 0.5s;
    }
}

Body:
I had the same issue and finally found a fix.

This one should work:

$(document).ready(function(){
   window.onresize = resizePage;
   resizePage();
});
function resizePage(){
    var width = (window.innerWidth > 0) ? window.innerWidth : document.documentElement.clientWidth;
    if(width >= 525 && width <= 526){ // your page breakpoint happens probably between 525px and 526px width at this range we gonna disable the transition temporarily
        $(".logo").css( "transition-property", "none" ); // temporarily disable the transition on .logo
    }
    else{
        $(".logo").css( "transition-property", "" ) // else restore the actual transition
    }
}

Note: if you want to temporarily disable all transitions at the breakpoint range, you can use the * selector, which selects all elements.

$("*").css( "transition-property", "none" );

ContentLicense: CC BY-SA 4.0


问:
Comparing Java enum members: == or equals()?
I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used .equals(), e.g.

```<code>public useEnums(SomeEnum a)
{
    if(a.equals(SomeEnum.SOME_ENUM_VALUE))
    {
        ...
    }
    ...
}
</code>```

However, I just came across some code that uses the equals operator == instead of .equals():

```<code>public useEnums2(SomeEnum a)
{
    if(a == SomeEnum.SOME_ENUM_VALUE)
    {
        ...
    }
    ...
}
</code>```

Which operator is the one I should be using?

答:
In short, both have pros and cons.

On one hand, it has advantages to use ==, as described in the other answers.

On the other hand, if you for any reason replace the enums with a different approach (normal class instances), having used == bites you. (BTDT.)

Body:
I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used .equals(), e.g.

public useEnums(SomeEnum a)
{
    if(a.equals(SomeEnum.SOME_ENUM_VALUE))
    {
        ...
    }
    ...
}

However, I just came across some code that uses the equals operator == instead of .equals():

public useEnums2(SomeEnum a)
{
    if(a == SomeEnum.SOME_ENUM_VALUE)
    {
        ...
    }
    ...
}

Which operator is the one I should be using?


问:
How does Node.js convert your code to events?
When you first run your Node program, how/what is the first event supplied to the event loop? Is your program like a top-level callback that is being executed the entire time? (And I would assume this top-level callback is usually "server.listen()"?)</p>

答:
I think this question is just based on some missunderstanding. So lets start with the bascis:

I've been kind of thinking of Node in terms of a Task Queue of Runnables, which may be the problem.

Yes. NodeJS has nothing todo with a task qeue that is filled by the code you supply. The qeue is filled up by requests/timers and other stuff. Your code just provides methods, to handle such tasks.

I'm confused about whether the event loop exists outside of the "main" script (or entry point) being ran, or if the event loop runs the "main" script itself

The first one. The js is parsed first, when the code exits, the event loop starts.

```<code>//parse + execute the js
while(true){}
//this code never enters the event loop as the global scope js is blocking
</code>```

how/what is the first event supplied to the event loop?

We dont know. It may be a timer, a user request, a file ready, etc.

Lets have a look at an example code:

```<code>//on start this js is parsed, qeue, heap and the global object are constructed
//a function is stored on the global object
function log(){
 console.log("Hi, im logged");
}

//the function pointer of log is pushed to the qeue
process.nextTick(log);

 //a hardware timer is initialised
setTimeout(log,1000);
//the parser ends, nodejs enters the event loop
</code>```

At first, the js is parsed. After that, our global object contains a function log, and our Task qeue looks like this:

```<code>qeue=[ log ] //was added trough process.nextTick
</code>```

In the background, theres a hardware timer running, that will finish somewhen.

Now the JS engine enters the event loop. The event loop processes the qeue. So it looks like sth like this (pseudocode):

```<code>while(true){
  execute(qeue.shift())
}
</code>```

So our log is called the first time, then our qeue is empty and the event loop will stop/ do some background tasks.

After one second, the timer finishes and pushes log onto the qeue:

```<code>function timer_finishes(){
  qeue.push(log);
}
</code>```

So now our qeue contains another function to execute.

Normally the qeue is full of finished timers to execute, requests to answer and file read/write successes to handle.

Body:
I think this question is just based on some missunderstanding. So lets start with the bascis:

I've been kind of thinking of Node in terms of a Task Queue of Runnables, which may be the problem.

Yes. NodeJS has nothing todo with a task qeue that is filled by the code you supply. The qeue is filled up by requests/timers and other stuff. Your code just provides methods, to handle such tasks.

I'm confused about whether the event loop exists outside of the "main" script (or entry point) being ran, or if the event loop runs the "main" script itself

The first one. The js is parsed first, when the code exits, the event loop starts.

//parse + execute the js
while(true){}
//this code never enters the event loop as the global scope js is blocking

how/what is the first event supplied to the event loop?

We dont know. It may be a timer, a user request, a file ready, etc.

Lets have a look at an example code:

//on start this js is parsed, qeue, heap and the global object are constructed
//a function is stored on the global object
function log(){
 console.log("Hi, im logged");
}

//the function pointer of log is pushed to the qeue
process.nextTick(log);

 //a hardware timer is initialised
setTimeout(log,1000);
//the parser ends, nodejs enters the event loop

At first, the js is parsed. After that, our global object contains a function log, and our Task qeue looks like this:

qeue=[ log ] //was added trough process.nextTick

In the background, theres a hardware timer running, that will finish somewhen.

Now the JS engine enters the event loop. The event loop processes the qeue. So it looks like sth like this (pseudocode):

while(true){
  execute(qeue.shift())
}

So our log is called the first time, then our qeue is empty and the event loop will stop/ do some background tasks.

After one second, the timer finishes and pushes log onto the qeue:

function timer_finishes(){
  qeue.push(log);
}

So now our qeue contains another function to execute.

Normally the qeue is full of finished timers to execute, requests to answer and file read/write successes to handle.


问:
JMS Persistent delivery mode
I am learning JMS and came across this statement: http://docs.oracle.com/javaee/1.3/jms/tutorial/1_3_1-fcs/doc/advanced.html#1023387

The PERSISTENT delivery mode, the default, instructs the JMS provider
  to take extra care to ensure that a message is not lost in transit in
  case of a JMS provider failure. A message sent with this delivery mode
  is logged to stable storage when it is sent.

If JMS Provider failure occurs then how the JMS Provider can ensure that a message is not lost?

What does it mean that:

"A message sent with this delivery mode is logged to stable storage when it is sent."

Please help me in understanding the JMS concept here.

答:
You can do a simple test to understand the concept. Refer the tutorial here on how to create producer and consumer.

You will see producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
Change it to producer.setDeliveryMode(DeliveryMode.PERSISTENT);

Now create two classes. One which calls only Producers and one only consumer.

public class AppOnlyProduce {
    public static void thread(Runnable runnable, boolean daemon) {
        Thread brokerThread = new Thread(runnable);
        brokerThread.setDaemon(daemon);
        brokerThread.start();
    }
    public static void main(String[] args) throws InterruptedException {
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldProducer(), false);
    }
}

public class AppOnlyConsumer {
    public static void thread(Runnable runnable, boolean daemon) {
        Thread brokerThread = new Thread(runnable);
        brokerThread.setDaemon(daemon);
        brokerThread.start();
    }
    public static void main(String[] args) throws InterruptedException {
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldConsumer(), false);
    }
}

First run AppOnlyProduce. It will create two messages. Now run AppOnlyConsumer it will read two messages.
Now change back the line to producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

Again run AppOnlyProduce. It will create two messages. Now run AppOnlyConsumer You will see that it waits for sometime for message and they say Received: null

In first case mode was persistent. So though Java program ended messages were persisted and made available when JMS started (this time by consumer)

In second case mode was not persistent. So messages vanished as soon as program ended.

Title: JMS Persistent delivery mode


问:
Is Login and Sign Up put together secure?
Haven't begun writing any code, so this is not language specific.
In many websites when you click login, there will be another link down the bottom to sign up if you don't have an account.

I have an idea for a login page where you enter your email, and in the background (without any reloading), it checks whether that email is linked to an account.

If you do not have an account it adds all the relevant fields (DOB, name, confirm password). But if it detects you do have an account, it will just leave the single password field.

The question is:
Is this secure having these two pages built into one, and is there any main reason most websites have the two login and s

答:
It is secure to put both forms (sign in and sing up) on the same page, or alternatively to put both operations in the same form.

The only security issue it produces is that malicious users would know whether or not a specific username exists in your website, and that way it would be a little bit easier for them to break into a random account, but it is relatively not such a big deal. I wouldn't take it into account in terms of security.

Nevertheless, the main issue regarding having both sing in and sign up in the same form is a UX issue. It might be confusing for the user what the purpose of the form is. Having a clear sign up page is crucial in order not to loose potential customers.

Anyway, in order to make your sign-up and sign-in forms secured, you should learn all the following topics: TLS, XSS, CSRF, JWT, Clickjacing, Challenge-Response authentication, SQL injenction, replay attack, Captcha, Encryption and Salting, as well as keeping track with the new vulnerabilities that are getting published.


问:
Using EventAggregator (or something else - IoC maybe) with MEF
I am currently building an MEF project so I can learn how to use it in practical applications. I have successfully imported a DataHandler module to provide database connections and other centralized database operations.

Now I am thinking about a way to provide methods to other imported modules. For instance, if a Security Module requires a connection to a database, it would be able to request a database connection. Now, I have a way for a module to detect if a DataHandler is available as the Host application makes that public. So I am wondering if there were a way to use EventAggregator to publish a type of event where the subscriber (Security Module) simply fires an event and gets a DbConnection object in return.

If EventAggregator is the answer, I could use some hints as to how. Keep in mind that I am still researching...not just asking for teh codez. If there is a better solution out there, I am interested in options.

I am currently reviewing this post by Denis Vuyka

Edit

EventAggregator looks like it might not be the right tool to use. Is there some sort of loosely coupled messaging that I can implement in my Host app? Is a Service locator or Command pattern something that can be implemented?

答:
It sounds like you are looking for a Service Locator, not an EventAggregator.

But why request services through a service locator if you already injecting those services with MEF? If you need to acquire services later at run-time, you can inject a Lazy<T> or a factory instead.


问:
I have already installed pynotify, still getting error no module named pynotify
I have already installed pynotify using :

```<code>pip install py-notify
</code>```

When I re-run this it shows :

Requirement already satisfied (use --upgrade to upgrade).

I also tried :

```<code>pip install --upgrade py-notify
</code>```

but it shows :

Requirement already up-to-date.

Below is my simple code to show desktop notification using pynotify.

```<code>import pynotify
pynotify.init("Basic")

n = pynotify.Notification("Title", "Some sample content")
n.show()
</code>```

What should I do now to run below code correctly?

答:
There's a names conflict with pynotify.

I had installed pynotify from PIP using:

```<code>sudo pip install pynotify
</code>```

Since that was the wrong choice, I removed it with:

```<code>sudo pip uninstall pynotify
</code>```

And then installed the expected pynotify using:

```<code>sudo apt install python-notify
</code>```

Body:
I have already installed pynotify using :

pip install py-notify

When I re-run this it shows :

Requirement already satisfied (use --upgrade to upgrade).

I also tried :

pip install --upgrade py-notify

but it shows :

Requirement already up-to-date.

Below is my simple code to show desktop notification using pynotify.

import pynotify
pynotify.init("Basic")

n = pynotify.Notification("Title", "Some sample content")
n.show()

What should I do now to run below code correctly?

Body:
There's a names conflict with pynotify.

I had installed pynotify from PIP using:

sudo pip install pynotify

Since that was the wrong choice, I removed it with:

sudo pip uninstall pynotify

And then installed the expected pynotify using:

sudo apt install python-notify


答:
Try accessing like this object[0].locationId.
You object is an array not just a single object. Hope it clears it.

Title: Cannot access JSON object property in JavaScript


问:
Image Button not displaying, On click is working
I am working on Android studio, with an xml that displays a comment like in Facebook. My issue is that one of the buttons, the comment_more_options button, is not showing up in my actual device run, on the emulator provided with Android Studio, but does show up in my xml preview. However, when I click where the button should be, in the app run, the menu that is attached to it displays properly. What am I doing wrong? </p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_gravity="left|center_vertical"
            android:layout_margin="12dp"
            android:layout_weight="0.26"
            app:srcCompat="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:gravity="bottom|left"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginBottom="6dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="2dp"
                android:layout_weight="1"
                android:gravity="top|left"
                android:text="Handle" />

        </LinearLayout>

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="left"
            android:layout_margin="1dp"
            android:layout_weight="0.50"
            android:background="@android:color/transparent"
            android:visibility="visible"
            app:srcCompat="@drawable/ic_more_vert_black_24dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/enter_comment"
        android:textSize="18sp" />

</LinearLayout>
</code>```

答:
#. Add attribute android:weightSum="1.76" to child LinearLayout.

#. Instead of using app:srcCompat="@drawable/ic_more_vert_black_24dp", use attribute android:src="@drawable/ic_more_vert_black_24dp".

Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1.76">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_gravity="left|center_vertical"
            android:layout_margin="12dp"
            android:layout_weight="0.26"
            android:src="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:gravity="bottom|left"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginBottom="6dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="2dp"
                android:layout_weight="1"
                android:gravity="top|left"
                android:text="Handle" />

        </LinearLayout>

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="left"
            android:layout_margin="1dp"
            android:layout_weight="0.50"
            android:background="@android:color/transparent"
            android:visibility="visible"
            android:src="@drawable/ic_more_vert_black_24dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Enter Comment"
        android:textSize="18sp" />

</LinearLayout>
</code>```

You can also use RelativeLayout. Here is an example:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_margin="12dp"
            android:src="@mipmap/ic_launcher" />

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:background="@android:color/transparent"
            android:visibility="visible"
            android:src="@drawable/ic_camera" />

        <LinearLayout
            android:id="@+id/layout_middle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_toRightOf="@+id/comment_profile_picture"
            android:layout_toLeftOf="@+id/comment_more_options"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_centerVertical="true">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginTop="2dp"
                android:text="Handle" />

        </LinearLayout>
    </RelativeLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Enter Comment"
        android:textSize="18sp" />

</LinearLayout>
</code>```

OUTPUT:

Hope this will help~

Body:
I am working on Android studio, with an xml that displays a comment like in Facebook. My issue is that one of the buttons, the comment_more_options button, is not showing up in my actual device run, on the emulator provided with Android Studio, but does show up in my xml preview. However, when I click where the button should be, in the app run, the menu that is attached to it displays properly. What am I doing wrong?

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_gravity="left|center_vertical"
            android:layout_margin="12dp"
            android:layout_weight="0.26"
            app:srcCompat="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:gravity="bottom|left"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginBottom="6dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="2dp"
                android:layout_weight="1"
                android:gravity="top|left"
                android:text="Handle" />

        </LinearLayout>

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="left"
            android:layout_margin="1dp"
            android:layout_weight="0.50"
            android:background="@android:color/transparent"
            android:visibility="visible"
            app:srcCompat="@drawable/ic_more_vert_black_24dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/enter_comment"
        android:textSize="18sp" />

</LinearLayout>

Body:
#. Add attribute android:weightSum="1.76" to child LinearLayout.

#. Instead of using app:srcCompat="@drawable/ic_more_vert_black_24dp", use attribute android:src="@drawable/ic_more_vert_black_24dp".

Try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1.76">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_gravity="left|center_vertical"
            android:layout_margin="12dp"
            android:layout_weight="0.26"
            android:src="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:gravity="bottom|left"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginBottom="6dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="2dp"
                android:layout_weight="1"
                android:gravity="top|left"
                android:text="Handle" />

        </LinearLayout>

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="left"
            android:layout_margin="1dp"
            android:layout_weight="0.50"
            android:background="@android:color/transparent"
            android:visibility="visible"
            android:src="@drawable/ic_more_vert_black_24dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Enter Comment"
        android:textSize="18sp" />

</LinearLayout>

You can also use RelativeLayout. Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_margin="12dp"
            android:src="@mipmap/ic_launcher" />

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:background="@android:color/transparent"
            android:visibility="visible"
            android:src="@drawable/ic_camera" />

        <LinearLayout
            android:id="@+id/layout_middle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_toRightOf="@+id/comment_profile_picture"
            android:layout_toLeftOf="@+id/comment_more_options"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_centerVertical="true">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginTop="2dp"
                android:text="Handle" />

        </LinearLayout>
    </RelativeLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Enter Comment"
        android:textSize="18sp" />

</LinearLayout>

OUTPUT:

Hope this will help~


问:
Script to Find Copies of Files in Powershell
I am trying to make a script in PowerShell that analyzes recursevily a directory and gets all hashes MD5 from all files and from all files inside any directories inside the 1st one given.

After that, I want to compare all the hashes between each other to see which one is a copy, and then give an option to delete these copies or not.

At the moment I have this:

```<code>$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse
$someFilePath = $UserInput
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
$hash
</code>```

The main problem is in the hash part, that I get an error in calling the "ReadAllBytes".

I also am doubting if creating an array so when I compare the hashes, if they are equal, put the copies in an array, so then deleting them is "easier".

What do you think? (I am also not sure if I am using right the "SomeFilePath", MD5 nor Hash).

答:
If targeting PowerShell 5.1 on Windows 10, I'd use the Get-FileHash cmdlet and then group them by hash using the Group-Object cmdlet:

```<code>$UserInput = Read-Host
$DuplicateFiles = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $DuplicateFiles)
{
    Write-Host "These files share hash $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
}
</code>```

Body:
I am trying to make a script in PowerShell that analyzes recursevily a directory and gets all hashes MD5 from all files and from all files inside any directories inside the 1st one given.

After that, I want to compare all the hashes between each other to see which one is a copy, and then give an option to delete these copies or not.

At the moment I have this:

$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse
$someFilePath = $UserInput
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
$hash

The main problem is in the hash part, that I get an error in calling the "ReadAllBytes".

I also am doubting if creating an array so when I compare the hashes, if they are equal, put the copies in an array, so then deleting them is "easier".

What do you think? (I am also not sure if I am using right the "SomeFilePath", MD5 nor Hash).

Body:
If targeting PowerShell 5.1 on Windows 10, I'd use the Get-FileHash cmdlet and then group them by hash using the Group-Object cmdlet:

$UserInput = Read-Host
$DuplicateFiles = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $DuplicateFiles)
{
    Write-Host "These files share hash $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
}


问:
Django PostgreSQL setting with separated credential file?
I want to migrate my django's database from MySQL to PostgreSQL.
Previously I've used database configuration options just like this example from Django website.

The MySQL engine on database setting has options: 'read_default_file', so I can separate my database credential on external file.

Now I'm ready to switch to PostgreSQL with psycopg2 engine, but I can't find the similar options like read_default_file.

Is there any solution for this?

Or may be I should change to other database engine of PostgreSQL which has this options? Thanks

答:
read_default_file is purely a mysql thing. It cannot be used for postgresql. The closest equivalent in postgresql is the .pgpass file which is a file that needs to be created in the home directory of the user running the psql client. That defines the user's password.

When you are using django in development creating a file in your your home directory would do the trick. But in production you are not supposed to run the django dev server. Production WSGI servers run under restricted user accounts that may not have a home directory. In that case you need to use the PGPASSFILE environment variable to tell django where to look for the password.


问:
How to open a file in pandas
Having difficulty opening a csv file in pandas, I have tried:

```<code>data = pd.read_csv("/home/me/Programming/data/sample.csv")
</code>```

That did not work, so I tried:

```<code>import os
cwd = os.getcwd()

data = pd.read_csv(cwd + "sample.csv")
</code>```

and that doesn't work either, just says that file does not exist, but it's there in the file manager clear as day.

答:
os.getcwd() return the current working directory without trailing path separtor.

You should use os.path.join instead of + to correctly join paths:

```<code>import os

cwd = os.getcwd()
data = pd.read_csv(os.path.join(cwd, 'sample.csv'))
</code>```

BTW, there's no need to specify full path of current working directory; just specify sample.csv should be enough:

```<code>data = pd.read_csv("sample.csv")
</code>```

Make sure the file sample.csv is in the current working directory.

Title: How to open a file in pandas

Body:
Having difficulty opening a csv file in pandas, I have tried:

data = pd.read_csv("/home/me/Programming/data/sample.csv")

That did not work, so I tried:

import os
cwd = os.getcwd()

data = pd.read_csv(cwd + "sample.csv")

and that doesn't work either, just says that file does not exist, but it's there in the file manager clear as day.

Body:
os.getcwd() return the current working directory without trailing path separtor.

You should use os.path.join instead of + to correctly join paths:

import os

cwd = os.getcwd()
data = pd.read_csv(os.path.join(cwd, 'sample.csv'))

BTW, there's no need to specify full path of current working directory; just specify sample.csv should be enough:

data = pd.read_csv("sample.csv")

Make sure the file sample.csv is in the current working directory.


问:
CreateFile fails with error ERROR_SHARING_VIOLATION
Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.

I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.

Here is my code:

```<code>void FileHandle::open(const char* fileName, FILE_MODE mode)
{
    if (m_bIsOpen)
        close();

    HANDLE fh = NULL;

    DWORD dwDesiredAccess  = GENERIC_READ;
    DWORD dwShareMode = FILE_SHARE_READ;
    DWORD dwCreationDisposition = OPEN_EXISTING;

    switch (mode)
    {
    case FILE_READ:
        break;

    case FILE_WRITE:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = CREATE_ALWAYS;
        break;

    case FILE_APPEND:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = OPEN_ALWAYS;
        break;

    default:
        throw gcException(ERR_INVALID, "The mode was invalid");
        break;
    }

    fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);

    if (!fh || fh == INVALID_HANDLE_VALUE)
        throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));

    m_hFileHandle = fh;
    m_bIsOpen = true;

    if (mode == FILE_APPEND)
    {
        DWORD high = 0;
        DWORD low = GetFileSize(fh, &high);

        uint64 pos = (((uint64)high)<<32) + (uint64)low;
        seek(pos);
    }
}
</code>```

Am i doing something wrong or is there an issue with the api?

Edit:
Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE

答:
Is there anti-virus on the machine? Sometimes an AV's (or other software that monitors files) operations and timing can cause sharing conflicts.

This is particularly true if you're opening an existing file for exclusive access (this would be the case for the FILE_WRITE and FILE_APPEND cases if the file already exists).

Body:
Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.

I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.

Here is my code:

void FileHandle::open(const char* fileName, FILE_MODE mode)
{
    if (m_bIsOpen)
        close();

    HANDLE fh = NULL;

    DWORD dwDesiredAccess  = GENERIC_READ;
    DWORD dwShareMode = FILE_SHARE_READ;
    DWORD dwCreationDisposition = OPEN_EXISTING;

    switch (mode)
    {
    case FILE_READ:
        break;

    case FILE_WRITE:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = CREATE_ALWAYS;
        break;

    case FILE_APPEND:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = OPEN_ALWAYS;
        break;

    default:
        throw gcException(ERR_INVALID, "The mode was invalid");
        break;
    }

    fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);

    if (!fh || fh == INVALID_HANDLE_VALUE)
        throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));

    m_hFileHandle = fh;
    m_bIsOpen = true;

    if (mode == FILE_APPEND)
    {
        DWORD high = 0;
        DWORD low = GetFileSize(fh, &high);

        uint64 pos = (((uint64)high)<<32) + (uint64)low;
        seek(pos);
    }
}

Am i doing something wrong or is there an issue with the api?

Edit:
Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE


问:
Filter array of multibyte strings ending in a specific letter and conditionally mutate the retained strings
A now write this function for my script. It works well type but a little slows down. Consider the function and if you have options for optimally ask me to help.

Here is my code:

```<code>function izada($array) {
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") == 2) {
            $result[] = str_replace("ӣ ", "ӣ, ", $value);
        }
        if(mb_substr($value, -1) !== "ӣ") {
            unset($array[$key]);
        }
        if(substr_count($value, "ӣ") == 2) {
            unset($array[$key]);
        }
        $array = array_filter(array_unique(array_merge($array, $result)));
    }
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") > 2 || substr_count($value, "ӣ") < 1) {
            unset($array[$key]);
        }
    }
    return $array;
}
</code>```

Input and function call:

```<code>$array = array (
  "забони тоҷикӣ",
  "хуҷандӣ бӯстонӣ",
  "Тоҷикистон Ватанам",
  "Ғафуровӣ Мичуринӣ Савхозӣ",
  "Конверторӣ хуруфҳо"
);

$array = izada($array);

echo"```";
print_r($array);
echo"```";
</code>```

Result must be:

```<code>Array (
  [0] => забони тоҷикӣ
  [1] => хуҷандӣ, бӯстонӣ
)
</code>```

答:
All the array_merge and array_unique are taking up unnecessary resources. Instead of trying to alter the original array, why not create an output array and fill it with the data you want?

There are also several redundant conditions - you are checking for the same thing several times. From what I understood, this is what you want:

Return all strings where ӣ is present once or twice, either at the end or twice anywhere. If it is present twice, add a coma.

So you could simplify it like

```<code>function izada($array) {
  $ret = [];
  foreach($array as $string){
      if (substr_count($string, "ӣ") >= 1 && substr_count($string, "ӣ") <= 2) {
          if(substr_count($string, "ӣ") == 2) {
              $ret[] = str_replace("ӣ ", "ӣ, ",$string);
          }
          else if (mb_substr($string, -1) == "ӣ") {
              $ret[] = $string;
          }
      }
  }
  return $ret;
</code>```

}

Body:
A now write this function for my script. It works well type but a little slows down. Consider the function and if you have options for optimally ask me to help.

Here is my code:

function izada($array) {
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") == 2) {
            $result[] = str_replace("ӣ ", "ӣ, ", $value);
        }
        if(mb_substr($value, -1) !== "ӣ") {
            unset($array[$key]);
        }
        if(substr_count($value, "ӣ") == 2) {
            unset($array[$key]);
        }
        $array = array_filter(array_unique(array_merge($array, $result)));
    }
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") > 2 || substr_count($value, "ӣ") < 1) {
            unset($array[$key]);
        }
    }
    return $array;
}

Input and function call:

$array = array (
  "забони тоҷикӣ",
  "хуҷандӣ бӯстонӣ",
  "Тоҷикистон Ватанам",
  "Ғафуровӣ Мичуринӣ Савхозӣ",
  "Конверторӣ хуруфҳо"
);

$array = izada($array);

echo"
";
print_r($array);
echo"
";

Result must be:

Array (
  [0] => забони тоҷикӣ
  [1] => хуҷандӣ, бӯстонӣ
)

Body:
All the array_merge and array_unique are taking up unnecessary resources. Instead of trying to alter the original array, why not create an output array and fill it with the data you want?

There are also several redundant conditions - you are checking for the same thing several times. From what I understood, this is what you want:

Return all strings where ӣ is present once or twice, either at the end or twice anywhere. If it is present twice, add a coma.

So you could simplify it like

function izada($array) {
  $ret = [];
  foreach($array as $string){
      if (substr_count($string, "ӣ") >= 1 && substr_count($string, "ӣ") <= 2) {
          if(substr_count($string, "ӣ") == 2) {
              $ret[] = str_replace("ӣ ", "ӣ, ",$string);
          }
          else if (mb_substr($string, -1) == "ӣ") {
              $ret[] = $string;
          }
      }
  }
  return $ret;

}


问:
Current Time Update MySQL Query
I am trying to update my field with current time during update query but its not working for some reason. My field Time is datetime type and Default set as Current Time stamp. I need update that time when I update one other field.
My Query is like this and working fine without update time

```<code>mysql_query("update tbl_quotes set quote_status='0' where id=".$_REQUEST['up_dea']."");
</code>```

I have tried to update my time field with below query but its not updating....

```<code>mysql_query("update tbl_quotes set quote_status='0',Time=getDate() where id=".$_REQUEST['up_dea']."");
</code>```

Let me know if someone know what is wrong with this...

Thanks

答:
Alter your table with:

```<code>ALTER TABLE table_name
MODIFY datetime_column DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
</code>```

This way, every time when a record is updated, its timestamp will be updated.

Title: Current Time Update MySQL Query

Body:
I am trying to update my field with current time during update query but its not working for some reason. My field Time is datetime type and Default set as Current Time stamp. I need update that time when I update one other field.
My Query is like this and working fine without update time

mysql_query("update tbl_quotes set quote_status='0' where id=".$_REQUEST['up_dea']."");

I have tried to update my time field with below query but its not updating....

mysql_query("update tbl_quotes set quote_status='0',Time=getDate() where id=".$_REQUEST['up_dea']."");

Let me know if someone know what is wrong with this...

Thanks

Body:
Alter your table with:

ALTER TABLE table_name
MODIFY datetime_column DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

This way, every time when a record is updated, its timestamp will be updated.


问:
How to make my random generated div appear inside container div?
HTML

```<code>    <div id="container">
        <div id="wrapper">

        </div>
        <span id = "waveNum">Current Wave: 0</span>
        <input type = "button" value = "Start Game" onclick = "startGame()"></input>
    </div>

    <script src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script src="main.js"></script>
  </body>
</code>```

Javascript

```<code>var keyArray = [];
var currentWave = 1;

var player;
var player2;
function initiate(){
    player = new createPlayer(150,50,"player1","relative","blue");
    player2 = new createPlayer(150,0,"player2","relative","green");
}

function startGame() {
    point();
}

function createPlayer(l,t,id,pos,color){
    this.speed = 3;
    this.width = 25;
    this.height = 25;
    this.left = l;
    this.top = t;
    this.id = id;
    this.model = $("<div id=" + id + "/>")
        .css({"backgroundColor":color,"height":this.height,"width":this.width,
            "left":this.left,"top":this.top,"position":pos})

  $('#wrapper').append($(this.model));
}

function point(){
  leftP = parseInt(Math.random()*970);
  topP = parseInt(Math.random()*580);
  $points = $("<div class=point/>")
    .css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
        "top":0,"position":"relative"})
  $('#wrapper').append($points)
}

function update(){
  //left
    if(keyArray[65]){
        var newLeft = parseInt(player.left)-player.speed+"px"
        player.left = newLeft;
        document.getElementById(player.id).style.left = newLeft;
    }
    //right
    if(keyArray[68]){
        var newLeft = parseInt(player.left)+player.speed+"px"
        player.left = newLeft;
        document.getElementById(player.id).style.left = newLeft;
    }
    //up
    if(keyArray[87]){
        var newTop = parseInt(player.top)-player.speed+"px"
        player.top = newTop;
        document.getElementById(player.id).style.top = newTop;
    }
    //down
    if(keyArray[83]){
        var newTop = parseInt(player.top)+player.speed+"px"
        player.top = newTop;
        document.getElementById(player.id).style.top = newTop;
    }

  //player2
    //left
    if(keyArray[37]){
        var newLeft = parseInt(player2.left)-player2.speed+"px"
        player2.left = newLeft;
        document.getElementById(player2.id).style.left = newLeft;
    }
    //right
    if(keyArray[39]){
        var newLeft = parseInt(player2.left)+player2.speed+"px"
        player2.left = newLeft;
        document.getElementById(player2.id).style.left = newLeft;
    }
    //up
    if(keyArray[38]){
        var newTop = parseInt(player2.top)-player2.speed+"px"
        player2.top = newTop;
        document.getElementById(player2.id).style.top = newTop;
    }
    //down
    if(keyArray[40]){
        var newTop = parseInt(player2.top)+player2.speed+"px"
        player2.top = newTop;
        document.getElementById(player2.id).style.top = newTop;
    }
    blockade();
    requestAnimationFrame(update);
}

function blockade(){
    var elemLeft = parseInt($('#wrapper').css('left'));
    var elemWidth = parseInt($('#wrapper').css('width'));
    var elemTop= parseInt($('#wrapper').css('height'));
  //blocks players from moving outside of game
    if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
        player.left = elemWidth - player.width - 2;
    }
    if(parseInt(player.top) + player.height >= elemTop){
        player.top = elemTop - player.height - 2;
    }
    if(parseInt(player.top) < 3){
        player.top = 3;
    }
    if(parseInt(player.left) < 3){
        player.left = 3;
    }
    if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
        player2.left = elemWidth - player2.width - 2;
    }
    if(parseInt(player2.top) + player2.height >= elemTop){
        player2.top = elemTop - player2.height - 2;
    }
    if(parseInt(player2.top) < 3){
        player2.top = 3;
    }
    if(parseInt(player2.left) < 3){
        player2.left = 3;
    }
}

window.onkeydown = function(page){
    keyArray[page.keyCode] = page.type === 'keydown';
}
    window.onkeyup = function(page){
        keyArray[page.keyCode] = page.type === 'keydown'
}
</code>```

CSS

```<code>html, body {margin: 0; height: 100%; overflow: hidden}

#container{
    width:80%;
    height:60%;
    display: block;
    text-align:center;
    margin: 0 auto;
}
#wrapper{
    left:0px;
    width:1000px; /* 100% */
    height:600px;
    border:1px solid lime;
    margin:0 auto;
    background-color:black;
}

#player1, .point {
    float: left;
    clear: both;
}
body{
    background-color:black;
}
#waveNum{
    color:white;
    font-size:200%;
}

.point {
    overflow: auto;
}
</code>```

So currently I need my point() function to generate a random div within the
 which it is but after a few different spawns, does not stay within the wrapper div eventually. It seems like the container of the point() seems to be shifting down. The more that is generated the more often it appears to the bottom and outside of the container.

Eventually my idea is for all of them to have the same top and left original positions in that way I could use my player and player2 to touch them (match left and top positions) and make them disappear like they are being collected like points. I also cant get them to have the same origin point. I think these issues might be related

答:
Try adding absolute positioning to your wrapper div and relative positioning to the container div:

```<code>#container {
  position: relative;
}

#wrapper {
  position: absolute;
  top: 0;
  left: 0;
}
</code>```

This takes the div out of normal flow from the rest of the document.

See here for more explanations on why this works.

Body:
HTML

        Current Wave: 0
        <input type = "button" value = "Start Game" onclick = "startGame()"></input>

Javascript

var keyArray = [];
var currentWave = 1;

var player;
var player2;
function initiate(){
    player = new createPlayer(150,50,"player1","relative","blue");
    player2 = new createPlayer(150,0,"player2","relative","green");
}

function startGame() {
    point();
}

function createPlayer(l,t,id,pos,color){
    this.speed = 3;
    this.width = 25;
    this.height = 25;
    this.left = l;
    this.top = t;
    this.id = id;
    this.model = $("
")
        .css({"backgroundColor":color,"height":this.height,"width":this.width,
            "left":this.left,"top":this.top,"position":pos})

  $('#wrapper').append($(this.model));
}

function point(){
  leftP = parseInt(Math.random()*970);
  topP = parseInt(Math.random()*580);
  $points = $("
")
    .css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
        "top":0,"position":"relative"})
  $('#wrapper').append($points)
}

function update(){
  //left
    if(keyArray[65]){
        var newLeft = parseInt(player.left)-player.speed+"px"
        player.left = newLeft;
        document.getElementById(player.id).style.left = newLeft;
    }
    //right
    if(keyArray[68]){
        var newLeft = parseInt(player.left)+player.speed+"px"
        player.left = newLeft;
        document.getElementById(player.id).style.left = newLeft;
    }
    //up
    if(keyArray[87]){
        var newTop = parseInt(player.top)-player.speed+"px"
        player.top = newTop;
        document.getElementById(player.id).style.top = newTop;
    }
    //down
    if(keyArray[83]){
        var newTop = parseInt(player.top)+player.speed+"px"
        player.top = newTop;
        document.getElementById(player.id).style.top = newTop;
    }

  //player2
    //left
    if(keyArray[37]){
        var newLeft = parseInt(player2.left)-player2.speed+"px"
        player2.left = newLeft;
        document.getElementById(player2.id).style.left = newLeft;
    }
    //right
    if(keyArray[39]){
        var newLeft = parseInt(player2.left)+player2.speed+"px"
        player2.left = newLeft;
        document.getElementById(player2.id).style.left = newLeft;
    }
    //up
    if(keyArray[38]){
        var newTop = parseInt(player2.top)-player2.speed+"px"
        player2.top = newTop;
        document.getElementById(player2.id).style.top = newTop;
    }
    //down
    if(keyArray[40]){
        var newTop = parseInt(player2.top)+player2.speed+"px"
        player2.top = newTop;
        document.getElementById(player2.id).style.top = newTop;
    }
    blockade();
    requestAnimationFrame(update);
}

function blockade(){
    var elemLeft = parseInt($('#wrapper').css('left'));
    var elemWidth = parseInt($('#wrapper').css('width'));
    var elemTop= parseInt($('#wrapper').css('height'));
  //blocks players from moving outside of game
    if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
        player.left = elemWidth - player.width - 2;
    }
    if(parseInt(player.top) + player.height >= elemTop){
        player.top = elemTop - player.height - 2;
    }
    if(parseInt(player.top) < 3){
        player.top = 3;
    }
    if(parseInt(player.left) < 3){
        player.left = 3;
    }
    if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
        player2.left = elemWidth - player2.width - 2;
    }
    if(parseInt(player2.top) + player2.height >= elemTop){
        player2.top = elemTop - player2.height - 2;
    }
    if(parseInt(player2.top) < 3){
        player2.top = 3;
    }
    if(parseInt(player2.left) < 3){
        player2.left = 3;
    }
}

window.onkeydown = function(page){
    keyArray[page.keyCode] = page.type === 'keydown';
}
    window.onkeyup = function(page){
        keyArray[page.keyCode] = page.type === 'keydown'
}

CSS

html, body {margin: 0; height: 100%; overflow: hidden}

#container{
    width:80%;
    height:60%;
    display: block;
    text-align:center;
    margin: 0 auto;
}
#wrapper{
    left:0px;
    width:1000px; /* 100% */
    height:600px;
    border:1px solid lime;
    margin:0 auto;
    background-color:black;
}

#player1, .point {
    float: left;
    clear: both;
}
body{
    background-color:black;
}
#waveNum{
    color:white;
    font-size:200%;
}

.point {
    overflow: auto;
}

So currently I need my point() function to generate a random div within the
 which it is but after a few different spawns, does not stay within the wrapper div eventually. It seems like the container of the point() seems to be shifting down. The more that is generated the more often it appears to the bottom and outside of the container.

Eventually my idea is for all of them to have the same top and left original positions in that way I could use my player and player2 to touch them (match left and top positions) and make them disappear like they are being collected like points. I also cant get them to have the same origin point. I think these issues might be related

Body:
Try adding absolute positioning to your wrapper div and relative positioning to the container div:

#container {
  position: relative;
}

#wrapper {
  position: absolute;
  top: 0;
  left: 0;
}

This takes the div out of normal flow from the rest of the document.

See here for more explanations on why this works.


问:
characters in for loop printing out too far away from values
I am very new to java and for loops. I would like my code to print out this

```<code>Andy      **
Kristy    **********
Amy       ***** `
</code>```

But my I am getting this instead

```<code>Andy          **
Kristy          **********
Amy          *****
</code>```

How do I change my for loop to stop the spacing from the names being this way? Thank you.

```<code>public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}
</code>```

答:
If you are using Java 8 you can use String::join like this :

```<code>public static void drawChart(String name, int age) {
    String spaces = String.join("", Collections.nCopies(20 - name.length(), " "));
    String stars = String.join("", Collections.nCopies(age, "*"));
    System.out.println(name + spaces + stars);
}
</code>```

Body:
I am very new to java and for loops. I would like my code to print out this

Andy      **
Kristy    **********
Amy       ***** `

But my I am getting this instead

Andy          **
Kristy          **********
Amy          *****

How do I change my for loop to stop the spacing from the names being this way? Thank you.

public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}

Body:
If you are using Java 8 you can use String::join like this :

public static void drawChart(String name, int age) {
    String spaces = String.join("", Collections.nCopies(20 - name.length(), " "));
    String stars = String.join("", Collections.nCopies(age, "*"));
    System.out.println(name + spaces + stars);
}


问:
Html change div content
I'm having a struggle. It's not one of these questions how to do it but more like how to do that better.

What im trying to achieve

Also I want to load rest into content when clicking on nav's

My question is what's "proper" or correct approach to do it without making a mess in a code.

How I done it so far

```<code><li><a class="navelement" data-url="resources/web/loadit.html" href="#">navbar A</a></li>
</code>```

And used jquery

```<code>$(document).ready(function(){
$('.navelement').click(function(e){
    e.preventDefault;
    $('#content').load($(this).data('url'));
});
$('.navelement:eq(0)').click();
</code>```

});

I like this approach but I need to execute ajax rest call each time I change navbar.

Second approach I can think off is to hide/show in css div's. Any tip will be appreaciated.

答:
What I suggest to you is , first load all your html nav in the content and hide them (adding class) , also set foreach generated div a custom class (by example I added the index of nav element ) , with this you'll prevent multiple ajax loading ( only once ).

then , after clicking on  each nav just show it's content by refering to the generated class by example (nav1 ,nav2, nav 3)

Please find bellow a working snippet

$(function() {
  $(".navelement").each(function(index, elm) {
    if ($(elm).data("url")) {
      var navElment = $("
").load($(elm).data("url"));

      $("#content").append(navElment);

      $(elm).on("click", function() {
        $(".navdiv").addClass("hidden");
        $(".navdiv.nav" + index).removeClass("hidden");
      })
    }

  })

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}

ul li {
  display: inline;
  padding:5px;
}</code>```

navbar A

navbar B

navbar C

```

Title: Html change div content

Body:
I'm having a struggle. It's not one of these questions how to do it but more like how to do that better.

What im trying to achieve

Also I want to load rest into content when clicking on nav's

My question is what's "proper" or correct approach to do it without making a mess in a code.

How I done it so far

navbar A

And used jquery

$(document).ready(function(){
$('.navelement').click(function(e){
    e.preventDefault;
    $('#content').load($(this).data('url'));
});
$('.navelement:eq(0)').click();

});

I like this approach but I need to execute ajax rest call each time I change navbar.

Second approach I can think off is to hide/show in css div's. Any tip will be appreaciated.

Body:
What I suggest to you is , first load all your html nav in the content and hide them (adding class) , also set foreach generated div a custom class (by example I added the index of nav element ) , with this you'll prevent multiple ajax loading ( only once ).

then , after clicking on  each nav just show it's content by refering to the generated class by example (nav1 ,nav2, nav 3)

Please find bellow a working snippet

$(function() {
  $(".navelement").each(function(index, elm) {
    if ($(elm).data("url")) {
      var navElment = $("<div class='navdiv nav" + index + " hidden'>").load($(elm).data("url"));

      $("#content").append(navElment);

      $(elm).on("click", function() {
        $(".navdiv").addClass("hidden");
        $(".navdiv.nav" + index).removeClass("hidden");
      })
    }

  })

})

.hidden {
  display: none;
}

ul li {
  display: inline;
  padding:5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a class="navelement" data-url="https://httpbin.org/get?text=navAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" href="#">navbar A</a></li>
  <li><a class="navelement" data-url="https://httpbin.org/get?text=navBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" href="#">navbar B</a></li>
  <li><a class="navelement" data-url="https://httpbin.org/get?text=navCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" href="#">navbar C</a></li>
</ul>
<div id="content">

</div>


问:
SQLite insert into table using the id from an inner insert
I'm trying to insert a parent and child at the same time.

My idea is to insert the parent, get the id using SELECT last_insert_rowid() AS [Id] and use this id to insert the child

I can get each part of this working independently but not as a whole. This is what I currently have:

```<code>INSERT INTO ParentTable (Col1)
VALUES( 'test')
SELECT last_insert_rowid() AS [Id]
</code>```

The above works - so far so good. Now I want to use the result of this in the child insert. This is what I have:

```<code>INSERT INTO ChildTable (col1, col2, ParentId)
VALUES( 1, 2, SELECT Id FROM (
    INSERT INTO ParentTable (Col1)
    VALUES( 'test')
    SELECT last_insert_rowid() AS [Id]
);
</code>```

I get this error:

near "SELECT": syntax error:

Can anyone point me in the right direction?

答:
You can't use INSERT in SELECT statement. You should first insert and then use last inserted id:

```<code>INSERT INTO ParentTable (Col1) VALUES( 'test');

INSERT INTO ChildTable (col1, col2, ParentId)
    VALUES(1,2, (SELECT last_insert_rowid()));
</code>```

Since you want to insert many records with parent ID, here is a workaround:

```<code>BEGIN TRANSACTION;
CREATE TEMPORARY TABLE IF NOT EXISTS temp(id integer);
DELETE FROM temp;
INSERT INTO ParentTable (Col1) VALUES( 'test');
INSERT INTO temp SELECT last_insert_rowid();
INSERT INTO ChildTable (col1, col2, ParentId)
    VALUES(1,2, (SELECT id FROM temp LIMIT 1));
.............
COMMIT;
DROP TABLE temp;
</code>```

Or you can create a permanent table to this effect.

Body:
I'm trying to insert a parent and child at the same time.

My idea is to insert the parent, get the id using SELECT last_insert_rowid() AS [Id] and use this id to insert the child

I can get each part of this working independently but not as a whole. This is what I currently have:

INSERT INTO ParentTable (Col1)
VALUES( 'test')
SELECT last_insert_rowid() AS [Id]

The above works - so far so good. Now I want to use the result of this in the child insert. This is what I have:

INSERT INTO ChildTable (col1, col2, ParentId)
VALUES( 1, 2, SELECT Id FROM (
    INSERT INTO ParentTable (Col1)
    VALUES( 'test')
    SELECT last_insert_rowid() AS [Id]
);

I get this error:

near "SELECT": syntax error:

Can anyone point me in the right direction?

Body:
You can't use INSERT in SELECT statement. You should first insert and then use last inserted id:

INSERT INTO ParentTable (Col1) VALUES( 'test');

INSERT INTO ChildTable (col1, col2, ParentId)
    VALUES(1,2, (SELECT last_insert_rowid()));

Since you want to insert many records with parent ID, here is a workaround:

BEGIN TRANSACTION;
CREATE TEMPORARY TABLE IF NOT EXISTS temp(id integer);
DELETE FROM temp;
INSERT INTO ParentTable (Col1) VALUES( 'test');
INSERT INTO temp SELECT last_insert_rowid();
INSERT INTO ChildTable (col1, col2, ParentId)
    VALUES(1,2, (SELECT id FROM temp LIMIT 1));
.............
COMMIT;
DROP TABLE temp;

Or you can create a permanent table to this effect.


问:
Google Drive C# Exception fired 'Application not found'

Error shown in screenshot - please help me.

答:
Try to use
new[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile }

Instead of just "Scopes"