问:
3D pointer seg error
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

```<code>int ***grid;
    grid=new int **[number];
</code>```

then I want to assign the 2D arrays to the 3D construct

```<code>for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);
</code>```

with

```<code>int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}
</code>```

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

```<code>printf("%d",grid[1][1][1]);
</code>```

What is my mistake?

Best,
  Hannes

答:
To clear out the memory allocated for grid, you can't do the whole NxN matrix with one memset, it isn't contiguous memory.  Since each row is allocated as a separate memory block, you need to clear them individually.

```<code>for(i=0;i<600;i++) {
    grid[i]=new int[600];
    memset(grid[i], 0, sizeof(int) * 600);
}
</code>```

The 600 value should be a named constant, and not a hardcoded number.

And grid does not need to be a static variable.

Title: 3D pointer seg error

Body:
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

int ***grid;
    grid=new int **[number];

then I want to assign the 2D arrays to the 3D construct

for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);

with

int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

printf("%d",grid[1][1][1]);

What is my mistake?

Best,
  Hannes

Body:
To clear out the memory allocated for grid, you can't do the whole NxN matrix with one memset, it isn't contiguous memory.  Since each row is allocated as a separate memory block, you need to clear them individually.

for(i=0;i<600;i++) {
    grid[i]=new int[600];
    memset(grid[i], 0, sizeof(int) * 600);
}

The 600 value should be a named constant, and not a hardcoded number.

And grid does not need to be a static variable.


来源: stackexchange

问:
Comparing two char* and two char[ ] strings in C
```<code>#include <stdio.h>

int main(){
    char a[] = "bar";
    char b[] = "bar";
    printf("%d\n", (a==b));

    char* x = "bar";
    char* y = "bar";
    printf("%d\n", (x==y));
 }
</code>```

Output :

```<code>0
1
</code>```

I know we can't compare C char arrays using the == operator as it compares memory locations, but why does it work in the second case ?

答:
In the first case, as you defined two arrays, the compiler allocated two separate storage for them, so a and b are not equal.

But, for the second case, as you initialized two pointers with the same string literal, the compiler found them the same string, and point the two pointers into the same address which is the start address of that string literal ("bar").
However, as @David said, this is not happened necessarily, and in some situation, removing some optimization, or based on some compiler, x and y might not be the same.

ContentLicense: CC BY-SA 3.0

Body:
#include <stdio.h>

int main(){
    char a[] = "bar";
    char b[] = "bar";
    printf("%d\n", (a==b));

    char* x = "bar";
    char* y = "bar";
    printf("%d\n", (x==y));
 }

Output :

0
1

I know we can't compare C char arrays using the == operator as it compares memory locations, but why does it work in the second case ?


问:
How can I remove all old related items in an array list when I insert a new item? i.e. Cube 1 removed when adding Cube 2
```<code>String[] total = new String[] {
  };

final List<String> total_list = new ArrayList<String>(Arrays.asList(total));
</code>```

I add the total string 1 by 1 by pressing a button

```<code>total_list.add(newstring);
</code>```

So, my array will be like this:

```<code>ArrayList {"Cube 1", "Cube 2", "Cube 3", "Square 1", "Square 2", "Square 3" ...}
</code>```

How to delete the prior inserted data?

So when I add data array Cube 3 all data with Cube 1, Cube 2 will be deleted, and the other same too, Square 1, Square 2 will be deleted when I insert Square 3.

答:
Well, assuming all your items are like <name><white-space><index> and case-sensitive and assuming you list doesn't contain anything else, use this method to insert new items into it:

```<code>void addReplace(ArrayList<String> a, String s) {
    String name = s.split("\\s")[0];
    for (int i = a.size()-1; i >= 0; i--) {
        String item = a.get(i);
        if (item.startsWith(name))
            a.remove(i);
    }
}
</code>```

But I recommend you to change data storage strategy, depending of what you need in real. Looks like you need to store some index for string keys. Try to looking at sets and maps.

Body:
String[] total = new String[] {
  };

final List<String> total_list = new ArrayList<String>(Arrays.asList(total));

I add the total string 1 by 1 by pressing a button

total_list.add(newstring);

So, my array will be like this:

ArrayList {"Cube 1", "Cube 2", "Cube 3", "Square 1", "Square 2", "Square 3" ...}

How to delete the prior inserted data?

So when I add data array Cube 3 all data with Cube 1, Cube 2 will be deleted, and the other same too, Square 1, Square 2 will be deleted when I insert Square 3.

Body:
Well, assuming all your items are like <name><white-space><index> and case-sensitive and assuming you list doesn't contain anything else, use this method to insert new items into it:

void addReplace(ArrayList<String> a, String s) {
    String name = s.split("\\s")[0];
    for (int i = a.size()-1; i >= 0; i--) {
        String item = a.get(i);
        if (item.startsWith(name))
            a.remove(i);
    }
}

But I recommend you to change data storage strategy, depending of what you need in real. Looks like you need to store some index for string keys. Try to looking at sets and maps.


问:
Recognise pose of object (IBM Watson)
I was wondering whether it was possible to recognise if an object is in a desired pose with some visual recognition tools (in particular, I was hoping to use IBM Watson services). For instance, I need to check if a cylinder is in the desired position relatively to other objects near it. Hence, given enough features in the environment around the cylinder, would this be possible?

Sorry, but I am really new to visual recognition field and I still need to learn lots of things. Also, I haven't been able to find anything online regarding this issue.
Thank you!

答:
whether it was possible to recognise if an object is in a desired pose with some visual recognition tools

Yes, you can train a custom classifier in Watson Visual Recognition, just by giving it example images.

It cannot solve every problem in this space of pose classification, but depending on what type of object and what pose, and the surrounding environment, it could solve a lot of them.  To say, for instance, if we are looking at the frontal or rear view of a car is pretty easy if the car is the main thing in the scene.  You would just need to give it a few dozen examples.

This is how to train a custom classifier: https://console.bluemix.net/docs/services/visual-recognition/tutorial-custom-classifier.html#creating-a-custom-classifier

Keep in mind, it can only be trained to recognize distinct classes you have given examples of, such as "upright cylinder" vs. "cylinder laying on its side".  It would not report a continuously varying output like "37 degree rotated" cylinder.

The best approach is try it out experimentally.  There is also a demo GUI you can train https://visual-recognition-demo.ng.bluemix.net/train without an API key (though your classifier would not persist) and a GUI training tool (requires API key, so your classifier would persist): https://watson-visual-recognition.ng.bluemix.net/

Title: Recognise pose of object (IBM Watson)


问:
Convert query into cakePHP find statement
Can any one help me to convert this query into CakePHP find statement

```<code>SELECT
    SUM(ISNULL(tg_prd_value,0)) as total,MAX(tblMarketingArea.mkt_Area_ID) as mkt_Area_ID,MAX(tblMarketingArea.mkt_Area) as mkt_Area
FROM
    tblTarget right outer join
    tblMarketingArea on (tblMarketingArea.mkt_Area_ID = tblTarget.tg_area_id and tblTarget.tg_month = 1 and tblTarget.tg_year = 2011)
where tblMarketingArea.isDeleted!=1
GROUP BY
    tblMarketingArea.mkt_Area_ID order by tblMarketingArea.mkt_Area_ID
</code>```

i have "Target" and "MarketingArea" model.(I know the tablenames are not according to the cakephp convention but i have to use these names). Since i am using sql server i created Synonyms for the tables according to the cake convension

model MarketingArea (marketing_area.php)

```<code>class MarketingArea extends AppModel{
   var $name='MarketingArea';
   var $primaryKey='mkt_Area_ID';
 }
</code>```

i have tried this binding

```<code>$this->bindModel(array(
        'hasMany' => array(
            'Target' => array(
                'foreignKey' => 'tg_area_id',
                'conditions' => array(
                    'tg_month' => 1,
                    'tg_year' => 2011
                    )
                                 )
                          )
                     )
                );
</code>```

But still i am facing problem with SUM(tg_prd_value)

thankz in advace.

答: Unless there is some special reason for using the find method, I would simply create a model method and use query() to execute the SQL statement. And if month and year are parameters, make sure they are integers to avoid an SQL injection attack.

ContentLicense: CC BY-SA 2.5

Body:
Can any one help me to convert this query into CakePHP find statement

SELECT
    SUM(ISNULL(tg_prd_value,0)) as total,MAX(tblMarketingArea.mkt_Area_ID) as mkt_Area_ID,MAX(tblMarketingArea.mkt_Area) as mkt_Area
FROM
    tblTarget right outer join
    tblMarketingArea on (tblMarketingArea.mkt_Area_ID = tblTarget.tg_area_id and tblTarget.tg_month = 1 and tblTarget.tg_year = 2011)
where tblMarketingArea.isDeleted!=1
GROUP BY
    tblMarketingArea.mkt_Area_ID order by tblMarketingArea.mkt_Area_ID

i have "Target" and "MarketingArea" model.(I know the tablenames are not according to the cakephp convention but i have to use these names). Since i am using sql server i created Synonyms for the tables according to the cake convension

model MarketingArea (marketing_area.php)

class MarketingArea extends AppModel{
   var $name='MarketingArea';
   var $primaryKey='mkt_Area_ID';
 }

i have tried this binding

$this->bindModel(array(
        'hasMany' => array(
            'Target' => array(
                'foreignKey' => 'tg_area_id',
                'conditions' => array(
                    'tg_month' => 1,
                    'tg_year' => 2011
                    )
                                 )
                          )
                     )
                );

But still i am facing problem with SUM(tg_prd_value)

thankz in advace.


问:
low priority and high priority implicits in scala
In following code from Scala's puzzlers, it seems that there is no conflict in implicits because TestAlarmHandler is more specific. I didn't understand the explanation though. Why is TestAlarmHandler is more specific than DefaultAlarmHandler?

```<code>object Scanner {
  trait Console { def display(item: String) }
  trait AlarmHandler extends (() => Unit)
  def scanItem(item: String)(implicit c: Console) {
    c.display(item)
  }
  def hitAlarmButton()(implicit ah: AlarmHandler) { ah() }
}

class OperatingMode {
  implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println(s"Found a ${item}") }
  }
  implicit val DefaultAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("ALARM! ALARM!") }
  }
}
object NormalMode extends OperatingMode
object TestMode extends OperatingMode {
  override implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println("Found a detonator") }
  }
  implicit val TestAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("Test successful. Well done!") }
  }
}
import NormalMode._
scala> Scanner scanItem "knife"
Found a knife
scala> Scanner.hitAlarmButton()
ALARM! ALARM!
import TestMode._
scala> Scanner scanItem "shoe"
Found a detonator
scala> Scanner.hitAlarmButton()
Test successful. Well done!
</code>```

答:
TestAlarmHandler is more specific than DefaultAlaramHandler because TestAlarmHandler is defined in an anonymous class which is derived from class OperatingMode defining DefaultAlarmHandler.

Formally, the Scala Language Specification specifies how to handle a case when more than one eligible arguments are found, as follows (note that both TestAlarmHandler and DefaultAlarmHandler are eligible because they have been imported by import TestMode._):

If there are several eligible arguments which match the implicit parameter's type, a most specific one will be chosen using the rules of static overloading resolution.

Section 6.26.3 Overloading Resolution defines the concept of being more specific in terms of the concept of relative weight:

The relative weight of an alternative A over an alternative B is a number from 0 to 2, defined as the sum of

1 if A is as specific as B, 0 otherwise, and

1 if A is defined in a class or object which is derived from the class or object defining B, 0 otherwise.

The relative weight of TestAlarmHandler over DefaultAlarmHandler is 1 while that of DefaultAlarmHandler over TestAlarmHandler is 0. Note that TestAlarmHandler is defined in an anonymous class which is derived from class OperatingMode defining DefaultAlarmHandler. The first rule is of concern when resolving method overloading, but not relevant here.

An alternative A is more specific than an alternative B if the relative weight of A over B is greater than the relative weight of B over A.

TestAlarmHandler is more specific than DefaultAlaramHandler because the relative weight TestAlarmHandler over DefaultAlarmHandler is greater than that of the inverse.

Body:
In following code from Scala's puzzlers, it seems that there is no conflict in implicits because TestAlarmHandler is more specific. I didn't understand the explanation though. Why is TestAlarmHandler is more specific than DefaultAlarmHandler?

object Scanner {
  trait Console { def display(item: String) }
  trait AlarmHandler extends (() => Unit)
  def scanItem(item: String)(implicit c: Console) {
    c.display(item)
  }
  def hitAlarmButton()(implicit ah: AlarmHandler) { ah() }
}

class OperatingMode {
  implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println(s"Found a ${item}") }
  }
  implicit val DefaultAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("ALARM! ALARM!") }
  }
}
object NormalMode extends OperatingMode
object TestMode extends OperatingMode {
  override implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println("Found a detonator") }
  }
  implicit val TestAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("Test successful. Well done!") }
  }
}
import NormalMode._
scala> Scanner scanItem "knife"
Found a knife
scala> Scanner.hitAlarmButton()
ALARM! ALARM!
import TestMode._
scala> Scanner scanItem "shoe"
Found a detonator
scala> Scanner.hitAlarmButton()
Test successful. Well done!


问:
AngularJS pre-fill input fields based on data from controller
I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

```<code><div ng-app="app" ng-controller="MainCtrl">
    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>
</div>
</code>```

and

```<code>angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });
</code>```

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

答:
you need to create your object like this</p>

```<code>$scope.widget = {
         title: 'abc',
          content: 'test'
};
</code>```

Body:
I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>

and

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

Body:
you need to create your object like this

$scope.widget = {
         title: 'abc',
          content: 'test'
};


问:
Pair items in two lists
i have two lists:

```<code>foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']
</code>```

The result i want is

```<code>('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]
</code>```

Here follows my codes:

```<code>zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

or,

```<code>zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

How to solve such a problem?

答:
Yeah as said before, assuming '3.enterain.py' is mispelled, you can try this:

```<code>foocpy = foo.copy()

zoo = [(f, b) for f, b in product(foo, bar) if f in b and not foocpy.remove(f)]
zoo+= [(f, f) for f in foocpy]

del foocpy
</code>```

Otherwise, implement your own comparison check instead of using in.

Title: Pair items in two lists

Body:
i have two lists:

foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']

The result i want is

('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]

Here follows my codes:

zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

or,

zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

How to solve such a problem?

Body:
Yeah as said before, assuming '3.enterain.py' is mispelled, you can try this:

foocpy = foo.copy()

zoo = [(f, b) for f, b in product(foo, bar) if f in b and not foocpy.remove(f)]
zoo+= [(f, f) for f in foocpy]

del foocpy

Otherwise, implement your own comparison check instead of using in.


问:
TypeError: input expected at most 1 arguments, got 3 (Rock, paper, scissors game)
Keep getting this syntax error

TypeError: input expected at most 1 arguments, got 3

Does anyone know how to fix this?

```<code>from random import randint
from tkinter import *

po = ["Rock", "Paper", "Scissors"]

player = False
cpu = po[randint(0, 2)]

while player == False:
    player = input("Rock", "Paper", "Scissors?")
    if player == computer:
        print("Tie")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
        else:
            print("You win!", player, "smashes", computer)
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cuts", player)
        else:
            print("You win!", player, "covers", computer)
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose!", computer, "smashes", player)
        else:
            print("You win!", player, "cut", computer)
    else:
        print("That's not a valid play. Check your spelling!")

    player = False
    computer = po[randint(0,2)]
</code>```

答:
You're misusing input. The argument passed to it is merely the prompt presented, and thus can only be a single string.

```<code>player = input("Rock, Paper, Scissors?")
</code>```

Is probably more like what you want.

Body:
Keep getting this syntax error

TypeError: input expected at most 1 arguments, got 3

Does anyone know how to fix this?

from random import randint
from tkinter import *

po = ["Rock", "Paper", "Scissors"]

player = False
cpu = po[randint(0, 2)]

while player == False:
    player = input("Rock", "Paper", "Scissors?")
    if player == computer:
        print("Tie")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
        else:
            print("You win!", player, "smashes", computer)
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cuts", player)
        else:
            print("You win!", player, "covers", computer)
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose!", computer, "smashes", player)
        else:
            print("You win!", player, "cut", computer)
    else:
        print("That's not a valid play. Check your spelling!")

    player = False
    computer = po[randint(0,2)]

Body:
You're misusing input. The argument passed to it is merely the prompt presented, and thus can only be a single string.

player = input("Rock, Paper, Scissors?")

Is probably more like what you want.


问:
how to use cookies in javascript and html?
my question is I took one form like register form and fill al fields like first name, last name,address, check boxes  also used then when submit at final i want it to display those data in new page. Here I want code only in javascript and html. Is their possible please help me........... and send code and guide lines </p>

答:
I suggest you don't use cookies any more, you can take advantage of the new HTML5 specifications and you can use the so called "localStorage" feature.

I recommend that you use jquery and it's magnificent plugins. A good example in this case is http://plugins.jquery.com/project/html5Storage , in wich case you could just do something like :

```
$('#formId')
  .children('input')
  .each(function(){
     $.Storage.set(
        $(this).attr('name'),
        $(this).val()
     );
  });
```

then,if you want to load the saved values , you will do something like :

```
$('#formId')
  .children('input')
  .each(function(){
     $(this).val($.Storage.get($(this).attr('name')));
  });
```

If tou want full browser compatibility , you should probably go with the cookie implementation,
but localStorage is supported by webkit based browsers, firefox, opera and IE 8 :), so it's only a matter of old browsers compatibility.

Body:
I suggest you don't use cookies any more, you can take advantage of the new HTML5 specifications and you can use the so called "localStorage" feature.

I recommend that you use jquery and it's magnificent plugins. A good example in this case is http://plugins.jquery.com/project/html5Storage , in wich case you could just do something like :

$('#formId')
  .children('input')
  .each(function(){
     $.Storage.set(
        $(this).attr('name'),
        $(this).val()
     );
  });

then,if you want to load the saved values , you will do something like :

$('#formId')
  .children('input')
  .each(function(){
     $(this).val($.Storage.get($(this).attr('name')));
  });

If tou want full browser compatibility , you should probably go with the cookie implementation,
but localStorage is supported by webkit based browsers, firefox, opera and IE 8 :), so it's only a matter of old browsers compatibility.


问:
ReactJS difference between stateful and stateless
I am trying to understand the exact difference between React's stateful and stateless components. Ok, stateless components just do something, but remember nothing, while stateful components may do the same, but they remember stuff within this.state. That's the theory.

But now, checking on how to show this using code, I have a little trouble making the difference. Am I right with the following two examples? The only difference really is the definition of the getInitialState function.

Example of a stateless component:

```<code>var React = require('react');

var Header = React.createClass({
    render: function() {
        return(
            <img src={'mypicture.png'} />
        );
    }
});

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

Example of a stateful component:

```<code>var React = require('react');

var Header = React.createClass({

    getInitialState: function() {
        return {
            someVariable: "I remember something"
        };
    },

    render: function() {
        return(
            <img src={'mypicture.png'} />
        );
    }
});

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

答:
In a simple definition it can be explained as

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component and if behaviour is independent of its state then it can be a stateless component.

When something is “stateful”, it is a central point that stores information in memory about the app/component’s state.
When something is “stateless”, it calculates its internal state but it never directly mutates it.

The stateless components are sometimes referred as dumb components

The main advantage  stateless over stateful component is scalability and reusability.

Now you can check the example components in @Davin Tryon Answer

Body:
I am trying to understand the exact difference between React's stateful and stateless components. Ok, stateless components just do something, but remember nothing, while stateful components may do the same, but they remember stuff within this.state. That's the theory.

But now, checking on how to show this using code, I have a little trouble making the difference. Am I right with the following two examples? The only difference really is the definition of the getInitialState function.

Example of a stateless component:

var React = require('react');

var Header = React.createClass({
    render: function() {
        return(

        );
    }
});

module.exports = Header;

Example of a stateful component:

var React = require('react');

var Header = React.createClass({

    getInitialState: function() {
        return {
            someVariable: "I remember something"
        };
    },

    render: function() {
        return(

        );
    }
});

module.exports = Header;

ContentLicense: CC BY-SA 4.0


问:
Comparing two lists using the greater than or less than operator
I noticed a piece of code recently directly comparing two lists of integers like so:

```<code>a = [10,3,5, ...]
b = [5,4,3, ...,]
if a > b:
     ...
</code>```

which seemed a bit peculiar, but I imagined it would return True if all of list_a's elements are larger then list_b's and False if each element is equal or list_b's elements are larger then list_a's. So I tested it:

```<code>>>> a=[3,3,3,3]
>>> b=[4,4,4,4]
>>> a>b
False
>>> b>a
True
</code>```

Ok that works. As does:

```<code>>>> b = [1,1,1,1]
>>> a = [1,1,1,1]
>>> a>b
False
>>> b>a
False
</code>```

but when it gets more fuzzy:

```<code>>>> a=[1,1,3,1]
>>> b=[1,3,1,1]
>>> a>b
False
>>> b>a
True
</code>```

or:

```<code>>>> a=[1,3,1,1]
>>> b=[1,1,3,3]
>>> a>b
True
>>> b>a
False
</code>```

the results are a bit stranger. What is python actually doing? It seems that it's returning the result in favour of the first list in which the left most element is greater then the corresponding?

答:
Since I didn't find the explanation of list/tuple comparison using "lexicographical ordering" particularly illuminating at first, here's an attempt to explain it "in my own words". First, here are some example lists that are referred to in the explanation below:

```<code>a = [1, 2, 3]
b = [1, 2, 10]
c = [1, 2, 3, 100]
d = [1, 2, 3]
e = [1, 2, 3, 4, 'a']
f = ['a', 'b', 'c']
</code>```

The pair of items at each index are compared in turn. So, comparing a to b will result in 1 being compared to 1, 2 being compared to 2, and 3 being compared to 10.

The comparison of pairs will stop when either an unequal pair of items is found or--if the lists are different lengths--the end of the shorter list is reached.

For example, when comparing a and b, comparisons will stop when 3 and 10 are compared. When comparing b and c, comparisons will stop when 10 and 3 are compared.

As soon as an unequal pair is found, the overall result is the result of comparing the unequal items. This applies whether the lists are the same length or not--for example, list b is greater than list c because the 100 in c never comes into play.

For example, when comparing a to b, the overall result will be the result of comparing 3 to 10. a  True because 3 is less than 10. a > b -> False because 3 is not greater than 10. a == b -> False because 3 does not equal 10.

If one of the lists is shorter and its N items are equal to the first N items of the longer list, as with a and c, the shorter list will be considered less than the longer list (so a is less than c).

Two lists will compare as equal only if they're the same length and all pairs of items compare as equal.

Note about types: if the items in a pair aren't comparable, the comparison will fail with a TypeError as usual. For example, comparing list a to f will fail when 1 is compared to 'a'. But also note that lists d and e can be compared since the 'a' in e is never compared to anything in d.

Body:
I noticed a piece of code recently directly comparing two lists of integers like so:

a = [10,3,5, ...]
b = [5,4,3, ...,]
if a > b:
     ...

which seemed a bit peculiar, but I imagined it would return True if all of list_a's elements are larger then list_b's and False if each element is equal or list_b's elements are larger then list_a's. So I tested it:

>>> a=[3,3,3,3]
>>> b=[4,4,4,4]
>>> a>b
False
>>> b>a
True

Ok that works. As does:

>>> b = [1,1,1,1]
>>> a = [1,1,1,1]
>>> a>b
False
>>> b>a
False

but when it gets more fuzzy:

>>> a=[1,1,3,1]
>>> b=[1,3,1,1]
>>> a>b
False
>>> b>a
True

or:

>>> a=[1,3,1,1]
>>> b=[1,1,3,3]
>>> a>b
True
>>> b>a
False

the results are a bit stranger. What is python actually doing? It seems that it's returning the result in favour of the first list in which the left most element is greater then the corresponding?

Body:
Since I didn't find the explanation of list/tuple comparison using "lexicographical ordering" particularly illuminating at first, here's an attempt to explain it "in my own words". First, here are some example lists that are referred to in the explanation below:

a = [1, 2, 3]
b = [1, 2, 10]
c = [1, 2, 3, 100]
d = [1, 2, 3]
e = [1, 2, 3, 4, 'a']
f = ['a', 'b', 'c']

The pair of items at each index are compared in turn. So, comparing a to b will result in 1 being compared to 1, 2 being compared to 2, and 3 being compared to 10.

The comparison of pairs will stop when either an unequal pair of items is found or--if the lists are different lengths--the end of the shorter list is reached.

For example, when comparing a and b, comparisons will stop when 3 and 10 are compared. When comparing b and c, comparisons will stop when 10 and 3 are compared.

As soon as an unequal pair is found, the overall result is the result of comparing the unequal items. This applies whether the lists are the same length or not--for example, list b is greater than list c because the 100 in c never comes into play.

For example, when comparing a to b, the overall result will be the result of comparing 3 to 10. a < b -> True because 3 is less than 10. a > b -> False because 3 is not greater than 10. a == b -> False because 3 does not equal 10.

If one of the lists is shorter and its N items are equal to the first N items of the longer list, as with a and c, the shorter list will be considered less than the longer list (so a is less than c).

Two lists will compare as equal only if they're the same length and all pairs of items compare as equal.

Note about types: if the items in a pair aren't comparable, the comparison will fail with a TypeError as usual. For example, comparing list a to f will fail when 1 is compared to 'a'. But also note that lists d and e can be compared since the 'a' in e is never compared to anything in d.


问:
cakephp3 load plugin for special prefix
I have Cakephp 3 application and i want to load this plugin and the event listener below it just for admin prefix. ( not the entire project ) .

how can i achive this?

this is my

config/bootstrap.php

where i load this plugin . (I load these at end of the file )

```<code>...

Plugin::load('Josegonzalez/Upload');

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());
</code>```

i want these to line only run on admin prefix

答:
Quoting cakephp plugin docs https://book.cakephp.org/3.0/en/plugins.html#plugin-routes

You can also load plugin routes in your application’s routes list. Doing this provides you more control on how plugin routes are loaded and allows you to wrap plugin routes in additional scopes or prefixes.

So you can do

```<code>  Router::scope('/', function ($routes) {
       // Connect other routes.
        $routes->scope('/admin', function ($routes) {
        $routes->loadPlugin('Josegonzalez/Upload');
       });
       });
</code>```

For your event listener,  load it inside plugin bootstrap configuration

```<code>    // inside plugin bootstra.php
    \Cake\Event\EventManager::instance()->on(new
     \App\Controller\Event\AppEventListener());
</code>```

Title: cakephp3 load plugin for special prefix

Body:
I have Cakephp 3 application and i want to load this plugin and the event listener below it just for admin prefix. ( not the entire project ) .

how can i achive this?

this is my

config/bootstrap.php

where i load this plugin . (I load these at end of the file )

...

Plugin::load('Josegonzalez/Upload');

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());

i want these to line only run on admin prefix

Body:
Quoting cakephp plugin docs https://book.cakephp.org/3.0/en/plugins.html#plugin-routes

You can also load plugin routes in your application’s routes list. Doing this provides you more control on how plugin routes are loaded and allows you to wrap plugin routes in additional scopes or prefixes.

So you can do

  Router::scope('/', function ($routes) {
       // Connect other routes.
        $routes->scope('/admin', function ($routes) {
        $routes->loadPlugin('Josegonzalez/Upload');
       });
       });

For your event listener,  load it inside plugin bootstrap configuration

    // inside plugin bootstra.php
    \Cake\Event\EventManager::instance()->on(new
     \App\Controller\Event\AppEventListener());


问:
C# instantiating class object & adding to List
How can I create new instance of Country which uses 3 variables firstParam, secondParam, thirdParam for its constructor and add to a List countryList?

The 3 variables are being read from .txt and split on the ,
Afghanistan,Kabul,30419928
Albania,Tirana,2821977

My 3 split variables firstParam, secondParam, thirdParam contain the right information. I think I am making a syntax mistake when I add to the countryList because debug mode stepping through the variables load the right info but when I try a foreach on the countryList I get the output "countries.country".

```<code>    List<Country> countryList = new List<Country>();

        foreach (string line in lines)
        {
            string[] criteria = line.Split(',');

            string firstParam = "";
            string secondParam = "";
            int thirdParam = 1;

            firstParam = criteria[0];
            secondParam = criteria[1];
            thirdParam = Convert.ToInt32(criteria[2]);

            countryList.Add(new Country(firstParam, secondParam, thirdParam));

        }
</code>```

I ran out of ideas and not sure what else to try I am trying to learn more about composition but hoping someone can nudge me along.
thank you.

答:
Try this to verify your code is working the way you want it to:

```<code>List<Country> countryList = new List<Country>();

foreach (string line in lines)
{
    string[] criteria = line.Split(',');

    countryList.Add(new Country(criteria[0],
                                criteria[1],
                                Convert.ToInt32(criteria[2]))
}

Console.WriteLine($"Countries in countryList: {countryList.Count}.");

foreach ( Country country in countryList)
{
    Console.WriteLine($"Name: {country.Name}, Capital: {country.Capital}, Population: {country.Population}.");
}
</code>```

You may need to insert your own names for the fields of your Country class instead of Name, Capital, and Population.

Body:
How can I create new instance of Country which uses 3 variables firstParam, secondParam, thirdParam for its constructor and add to a List countryList?

The 3 variables are being read from .txt and split on the ,
Afghanistan,Kabul,30419928
Albania,Tirana,2821977

My 3 split variables firstParam, secondParam, thirdParam contain the right information. I think I am making a syntax mistake when I add to the countryList because debug mode stepping through the variables load the right info but when I try a foreach on the countryList I get the output "countries.country".

    List<Country> countryList = new List<Country>();

        foreach (string line in lines)
        {
            string[] criteria = line.Split(',');

            string firstParam = "";
            string secondParam = "";
            int thirdParam = 1;

            firstParam = criteria[0];
            secondParam = criteria[1];
            thirdParam = Convert.ToInt32(criteria[2]);

            countryList.Add(new Country(firstParam, secondParam, thirdParam));

        }

I ran out of ideas and not sure what else to try I am trying to learn more about composition but hoping someone can nudge me along.
thank you.

Body:
Try this to verify your code is working the way you want it to:

List<Country> countryList = new List<Country>();

foreach (string line in lines)
{
    string[] criteria = line.Split(',');

    countryList.Add(new Country(criteria[0],
                                criteria[1],
                                Convert.ToInt32(criteria[2]))
}

Console.WriteLine($"Countries in countryList: {countryList.Count}.");

foreach ( Country country in countryList)
{
    Console.WriteLine($"Name: {country.Name}, Capital: {country.Capital}, Population: {country.Population}.");
}

You may need to insert your own names for the fields of your Country class instead of Name, Capital, and Population.


问:
Handlebars, how to create layout for sub page using Node and express
I'm currently working on a simple CMS. I have some basic layout set up for each page like that:

```<code>app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
</code>```

I have some pages and I would like to setup sublayout for those pages.
For example.
Each page need to have root layout but gallery/all, gallery/new etc. need its own sublayout. How can I do it?

solution :

I found a solution for this. Instead of using layout use handlebar partials

答:
You can use other layout: 'gallery_all_layout' in router:</p>

```<code>res.render('gallery/all', {
    pageTitle: 'Gallery List',
    layout: 'gallery_all_layout'; //place it the same folder defaultLayout 'layout'
    ...
});
</code>```

Body:
I'm currently working on a simple CMS. I have some basic layout set up for each page like that:

app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');

I have some pages and I would like to setup sublayout for those pages.
For example.
Each page need to have root layout but gallery/all, gallery/new etc. need its own sublayout. How can I do it?

solution :

I found a solution for this. Instead of using layout use handlebar partials

Body:
You can use other layout: 'gallery_all_layout' in router:

res.render('gallery/all', {
    pageTitle: 'Gallery List',
    layout: 'gallery_all_layout'; //place it the same folder defaultLayout 'layout'
    ...
});


问:
How to get the word under the cursor in Windows?
I want to create a application which gets the word under the cursor (not only for text fields), but I can't find how to do that. Using OCR is pretty hard. The only thing I've seen working is the Deskperience components. They support a 'native' way, but I they cost a lot. Now I'm trying to figure out what is this 'native' way (maybe somehow of hooking). Any help will be appreciated.

EDIT:
I found a way, but it gets only the whole text of the control. Any idea how to get only the word under the cursor from the whole text?

答:
On recent versions of Windows, the recommended way to gather information from one application to another (if you don't own the targeted application of course) is to use the UI Automation technology.
Wikipedia is pretty good for more information on this: Microsoft UI Automation

Basically, UI automation will use all necessary means to gather what can be gathered

Here is a small console application code that will spy the UI of other apps. Run it and move the mouse over to different applications. Each application has a different support for various "UI automation patterns". For example, there is the Value pattern and the Text pattern as demonstrated here.

```<code>static void Main(string[] args)
{
    do
    {
        System.Drawing.Point mouse = System.Windows.Forms.Cursor.Position; // use Windows forms mouse code instead of WPF
        AutomationElement element = AutomationElement.FromPoint(new System.Windows.Point(mouse.X, mouse.Y));
        if (element == null)
        {
            // no element under mouse
            return;
        }

        Console.WriteLine("Element at position " + mouse + " is '" + element.Current.Name + "'");

        object pattern;
        // the "Value" pattern is supported by many application (including IE & FF)
        if (element.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
        {
            ValuePattern valuePattern = (ValuePattern)pattern;
            Console.WriteLine(" Value=" + valuePattern.Current.Value);
        }

        // the "Text" pattern is supported by some applications (including Notepad)and returns the current selection for example
        if (element.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
        {
            TextPattern textPattern = (TextPattern)pattern;
            foreach(TextPatternRange range in textPattern.GetSelection())
            {
                Console.WriteLine(" SelectionRange=" + range.GetText(-1));
            }
        }
        Thread.Sleep(1000);
        Console.WriteLine(); Console.WriteLine();
    }
    while (true);
}
</code>```

UI automation is actually supported by Internet Explorer and Firefox, but not by Chrome to my knowledge. See this link: When will Google Chrome be accessible?

Now, this is just the beginning of work for you :-), because:

Most of the time, all this has heavy security implication. Using this technology (or direct Windows technology such as WindowFromPoint) will require sufficient rights to do so (such as being an administrator). And I don't think DExperience has any way to overcome these limitations, unless they install a kernel driver on the computer.

Some applications will not expose anything to anyone, even with proper rights. For example, if I'm writing a banking application, I don't want you to spy on what my application will display :-). Other applications such as Outlook with DRM will not expose anything for the same reasons.

Only the UI automation Text pattern support can give more information (like the word) than just the whole text. Alas, this specific pattern is not supported by IE nor FF even if they support UI automation globally.

So, if all this does not work for you, you will have to dive deeper and use OCR or Shape recognition techniques. Even with this, there will be some cases where you won't be able to do it at all (because of security rights).

Body:
On recent versions of Windows, the recommended way to gather information from one application to another (if you don't own the targeted application of course) is to use the UI Automation technology.
Wikipedia is pretty good for more information on this: Microsoft UI Automation

Basically, UI automation will use all necessary means to gather what can be gathered

Here is a small console application code that will spy the UI of other apps. Run it and move the mouse over to different applications. Each application has a different support for various "UI automation patterns". For example, there is the Value pattern and the Text pattern as demonstrated here.

static void Main(string[] args)
{
    do
    {
        System.Drawing.Point mouse = System.Windows.Forms.Cursor.Position; // use Windows forms mouse code instead of WPF
        AutomationElement element = AutomationElement.FromPoint(new System.Windows.Point(mouse.X, mouse.Y));
        if (element == null)
        {
            // no element under mouse
            return;
        }

        Console.WriteLine("Element at position " + mouse + " is '" + element.Current.Name + "'");

        object pattern;
        // the "Value" pattern is supported by many application (including IE & FF)
        if (element.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
        {
            ValuePattern valuePattern = (ValuePattern)pattern;
            Console.WriteLine(" Value=" + valuePattern.Current.Value);
        }

        // the "Text" pattern is supported by some applications (including Notepad)and returns the current selection for example
        if (element.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
        {
            TextPattern textPattern = (TextPattern)pattern;
            foreach(TextPatternRange range in textPattern.GetSelection())
            {
                Console.WriteLine(" SelectionRange=" + range.GetText(-1));
            }
        }
        Thread.Sleep(1000);
        Console.WriteLine(); Console.WriteLine();
    }
    while (true);
}

UI automation is actually supported by Internet Explorer and Firefox, but not by Chrome to my knowledge. See this link: When will Google Chrome be accessible?

Now, this is just the beginning of work for you :-), because:

Most of the time, all this has heavy security implication. Using this technology (or direct Windows technology such as WindowFromPoint) will require sufficient rights to do so (such as being an administrator). And I don't think DExperience has any way to overcome these limitations, unless they install a kernel driver on the computer.

Some applications will not expose anything to anyone, even with proper rights. For example, if I'm writing a banking application, I don't want you to spy on what my application will display :-). Other applications such as Outlook with DRM will not expose anything for the same reasons.

Only the UI automation Text pattern support can give more information (like the word) than just the whole text. Alas, this specific pattern is not supported by IE nor FF even if they support UI automation globally.

So, if all this does not work for you, you will have to dive deeper and use OCR or Shape recognition techniques. Even with this, there will be some cases where you won't be able to do it at all (because of security rights).


问:
React Hot Loader seems to work but doesn't update. [babel-preset-env]
I tried to set up a minimal project which utilises the newest versions of Webpack, React, Babel and React Hot Loader.
I have the same issue as described here. However the only difference is that I am using (beside solely the stuff mentioned above) babel-preset-env instead of babel-preset-es2015, thus the fix does not apply for me.

In short: Everything works, React Hot Loader detects changes but the components are not rerendered and the changes are not applied to the website.

You can find the complete project here. (yarn install/yarn start should get it started) You can reproduce the behaviour by changing the testString in /components/App.js and saving the file.

What am I doing wrong?

webpack.config.js

```<code>var webpack = require('webpack')

module.exports = {
    entry: [
      'react-hot-loader/patch',
      './src/index.js'
    ],
    output: {
        path: __dirname + '/dist',
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
      extensions: ['*', '.js', '.jsx']
    },
    module: {
        rules: [
            {
              test: /\.js$/,
              exclude: /(node_modules)/,
              use: {
                loader: 'babel-loader',
              }
            }
          ]
    },
    devServer: {
      contentBase: './dist',
      hot: true
    },
    plugins: [
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
      ]

}
</code>```

.babelrc

```<code>{
    "presets": [
      "react",
      [ "env", {
        "targets": {
          "browsers": "> 10%"
        }
      }]
    ],
    "plugins": ["react-hot-loader/babel"]
  }
</code>```

index.js

```<code>import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from '../components/App'

const render = Component => {
    ReactDOM.render(
      <AppContainer>
        <Component />
      </AppContainer>,
      document.getElementById('app'),
    )
  }

render(App)

if (module.hot) {
const NextApp = require('../components/App').default
module.hot.accept('../components/App', () => { render(NextApp) })
}
</code>```

package.json

```<code>{
  "name": "minimal-react",
  "version": "0.1.0",
  "description": "minimal react",
  "main": "index.js",
  "repository": "https://github.com/PeterKey/minimal-react.git",
  "dependencies": {
    "path": "^0.12.7",
    "react": "^16.1.1",
    "react-dom": "^16.1.1",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "react-hot-loader": "^3.1.3"
  },
  "scripts": {
    "start": "webpack-dev-server --progress --colors --config ./webpack.config.js"
  }
}
</code>```

答:
Okay I realised that I simply need to set the {"modules": false} property for the "env" preset the same way as for the "es2015" preset.

.babelrc

```<code>{
"presets": [
  "react",
  [ "env", {
    "modules": false,
    "targets": {
      "browsers": "> 10%"
    }
  }]
],
"plugins": ["react-hot-loader/babel"]
</code>```

}

Body:
I tried to set up a minimal project which utilises the newest versions of Webpack, React, Babel and React Hot Loader.
I have the same issue as described here. However the only difference is that I am using (beside solely the stuff mentioned above) babel-preset-env instead of babel-preset-es2015, thus the fix does not apply for me.

In short: Everything works, React Hot Loader detects changes but the components are not rerendered and the changes are not applied to the website.

You can find the complete project here. (yarn install/yarn start should get it started) You can reproduce the behaviour by changing the testString in /components/App.js and saving the file.

What am I doing wrong?

webpack.config.js

var webpack = require('webpack')

module.exports = {
    entry: [
      'react-hot-loader/patch',
      './src/index.js'
    ],
    output: {
        path: __dirname + '/dist',
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
      extensions: ['*', '.js', '.jsx']
    },
    module: {
        rules: [
            {
              test: /\.js$/,
              exclude: /(node_modules)/,
              use: {
                loader: 'babel-loader',
              }
            }
          ]
    },
    devServer: {
      contentBase: './dist',
      hot: true
    },
    plugins: [
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
      ]

}

.babelrc

{
    "presets": [
      "react",
      [ "env", {
        "targets": {
          "browsers": "> 10%"
        }
      }]
    ],
    "plugins": ["react-hot-loader/babel"]
  }

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from '../components/App'

const render = Component => {
    ReactDOM.render(
      <AppContainer>
        <Component />
      </AppContainer>,
      document.getElementById('app'),
    )
  }

render(App)

if (module.hot) {
const NextApp = require('../components/App').default
module.hot.accept('../components/App', () => { render(NextApp) })
}

package.json

{
  "name": "minimal-react",
  "version": "0.1.0",
  "description": "minimal react",
  "main": "index.js",
  "repository": "https://github.com/PeterKey/minimal-react.git",
  "dependencies": {
    "path": "^0.12.7",
    "react": "^16.1.1",
    "react-dom": "^16.1.1",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "react-hot-loader": "^3.1.3"
  },
  "scripts": {
    "start": "webpack-dev-server --progress --colors --config ./webpack.config.js"
  }
}

Body:
Okay I realised that I simply need to set the {"modules": false} property for the "env" preset the same way as for the "es2015" preset.

.babelrc

{
"presets": [
  "react",
  [ "env", {
    "modules": false,
    "targets": {
      "browsers": "> 10%"
    }
  }]
],
"plugins": ["react-hot-loader/babel"]

}


答:
It seems that you never really give the person a chance to input wether rock, paper, or scissors, you should probably do something along the lines of

```<code>player = str(input("Rock, Paper, or Scissors?"))
</code>```

That way player is assigned to whichever the player chooses

Title: TypeError: input expected at most 1 arguments, got 3 (Rock, paper, scissors game)

Body:
It seems that you never really give the person a chance to input wether rock, paper, or scissors, you should probably do something along the lines of

player = str(input("Rock, Paper, or Scissors?"))

That way player is assigned to whichever the player chooses


问:
How to make gray margins when using max-width in CSS
I want a page that has a max-width and a footer, and set the margins gray to set out the main part of the page if the window is bigger than the max-width. Also, I have a fixed footer at the bottom.

I set the background color gray, then the color of the main content white, and set up the margins, which works except when the height of the main divs don't take up all the space to the footer, then I get a big block of gray in this unused area.

The goal is gray margins for space beyond 1024px, all the way down to the footer, irrespective if the main divs take up all the space or not.

Here is what I have:

```<code><style>
body {
    background-color: gray;
    max-width:800px;
    margin: 0 auto;
}
#main {
    background-color: white;
}
#footer {
    text-align: center;
    max-width: 800px;
    background-color: white;
    position: fixed;
    bottom: 0px;
    width: 100%;
    margin: 0 auto;
}
</style>
<div id='main'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis tortor a nisl rhoncus, vitae aliquet lectus sodales.
</div>
<div id="footer">Footer Goes Here</div>
</code>```

Which gives this. You can see the gray between the #main and #footer

Any suggestions?

答:
If I have clearly understood your requirements then You wish to have gray margin left and right side of your main content when the width is more than 800px. You should set the proper height of main content. Calculate the viewport height and set it as the main content height. Check the below code or jsfiddle example.

body {
    background-color: gray;
    max-width:800px;
    margin: 0 auto;
}
#main {
    background-color: white;
   height: calc(100vh - 50px);
}
#footer {
    text-align: center;
    max-width: 800px;
    background-color: white;
    position: fixed;
    bottom: 0px;
    width: 100%;
    margin: 0 auto;
    height:50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='main'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis tortor a nisl rhoncus, vitae aliquet lectus sodales.
</div>
<div id="footer">Footer Goes Here</div></code>```

You may wish to change the height of your footer and accordingly change the value in height calculation of main content. I have set it 50px just for example.

To test it, please resize the browser window to see the gray margin (the jsfiddle's browser section is also re-sizable If you want to test there).

Note - If you also have header height in px, you will have to include that value too in the main content height calculation.

Body:
I want a page that has a max-width and a footer, and set the margins gray to set out the main part of the page if the window is bigger than the max-width. Also, I have a fixed footer at the bottom.

I set the background color gray, then the color of the main content white, and set up the margins, which works except when the height of the main divs don't take up all the space to the footer, then I get a big block of gray in this unused area.

The goal is gray margins for space beyond 1024px, all the way down to the footer, irrespective if the main divs take up all the space or not.

Here is what I have:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis tortor a nisl rhoncus, vitae aliquet lectus sodales.

Footer Goes Here

Which gives this. You can see the gray between the #main and #footer

Any suggestions?

Body:
If I have clearly understood your requirements then You wish to have gray margin left and right side of your main content when the width is more than 800px. You should set the proper height of main content. Calculate the viewport height and set it as the main content height. Check the below code or jsfiddle example.

body {
    background-color: gray;
    max-width:800px;
    margin: 0 auto;
}
#main {
    background-color: white;
   height: calc(100vh - 50px);
}
#footer {
    text-align: center;
    max-width: 800px;
    background-color: white;
    position: fixed;
    bottom: 0px;
    width: 100%;
    margin: 0 auto;
    height:50px;
}

<div id='main'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis tortor a nisl rhoncus, vitae aliquet lectus sodales.
</div>
<div id="footer">Footer Goes Here</div>

You may wish to change the height of your footer and accordingly change the value in height calculation of main content. I have set it 50px just for example.

To test it, please resize the browser window to see the gray margin (the jsfiddle's browser section is also re-sizable If you want to test there).

Note - If you also have header height in px, you will have to include that value too in the main content height calculation.


问:
Join loop on multiple files, filling empty fields
I have 28 files I'd like to join on column 1, keeping all results from both files with each iterative join, and filling empty columns with 0. There are two columns total. The expected input and output for the first 3 files:

File1

```<code>a   1
b   2
c   1
d   4
</code>```

File2

```<code>a   2
b   3

</code>```

File3

```<code>c   2
d   2
e   1

</code>```

joined

```<code>a   1   2   0
b   2   3   0
c   1   0   2
d   4   0   2
e   0   0   1
</code>```

I've written out the entire join using a pipe on my actual files, and it works but is obviously messy. I've shortened it with ellipses here for clarity:

```<code>join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 2.2 -1 1 -2 1 *D3-E-N-1*/*matrix.txt.cut *D3-E-N-2*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 2.2 -1 1 -2 1 - *D3-E-N-3*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 2.2 -1 1 -2 1 - *D3-E-N-4*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 1.5 2.2 -1 1 -2 1 - *D3-E-N-5*/*matrix.txt.cut | ... > final.matrix.txt
</code>```

I know this can be looped to add the new fields, but I'm new to programming and loops are not my forte. I've tried this (from here bash join multiple files with empty replacement (-e option)):

```<code>i=3
orderl='0,1.2'
orderr=',2.2'
for k in UNITAS*/*seq_cut
do
    if [ -a final.results ]
    then
        join -a1 -a2 -e "0" -o "$orderl$orderr" final.results $k  > tmp.res
        orderl="$orderl,1.$i"
        i=$((i+1))
        mv tmp.res final.results
    else
        cp $k final.results
    fi
done
</code>```

which gives me the error

[: too many arguments

[: too many arguments

cp: overwrite ‘final.results’?

Does anyone have suggestions on a script to recursively join files, or a program better suited for this task?

Much appreciated!

答:
Just use R and you can change the desired extension as necessary:

Here are the files I used as an example:

f1.txt

```<code>a 1
b 4
c 6
e 3
</code>```

f2.txt

```<code>c 1
d 4
f 5
z 3
</code>```

f3.txt

```<code>a 1
b 4
c 5
e 7
g 12
</code>```

R code:

```<code>#!/bin/env/Rscript

ext='.ext' #can alter this to desired extension
files <- list.files(pattern=ext) #get name of files in a directory
listOfFiles <- lapply(files, function(x){ read.table(x, row.names=1) } )

#The big reduction of all the files into a table
tbl <- Reduce(function(...) data.frame(merge(..., all = T, by = 0), row.names=1), listOfFiles)

tbl[is.na(tbl)] <- 0 #set all NA vals to 0
colnames(tbl) <- files #set the columns to the corresponding filenames (optional)
tbl #print out the table
</code>```

Output:

```<code>  f1.ext f2.ext f3.ext
a      1      0      1
b      4      0      4
c      6      1      5
d      0      4      0
e      3      0      7
f      0      5      0
g      0      0     12
z      0      3      0
</code>```

Body:
I have 28 files I'd like to join on column 1, keeping all results from both files with each iterative join, and filling empty columns with 0. There are two columns total. The expected input and output for the first 3 files:

File1

a   1
b   2
c   1
d   4

File2

a   2
b   3

File3

c   2
d   2
e   1

joined

a   1   2   0
b   2   3   0
c   1   0   2
d   4   0   2
e   0   0   1

I've written out the entire join using a pipe on my actual files, and it works but is obviously messy. I've shortened it with ellipses here for clarity:

join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 2.2 -1 1 -2 1 *D3-E-N-1*/*matrix.txt.cut *D3-E-N-2*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 2.2 -1 1 -2 1 - *D3-E-N-3*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 2.2 -1 1 -2 1 - *D3-E-N-4*/*matrix.txt.cut | join -t $'\t' -a 1 -a 2 -e '0' -o 0 1.2 1.3 1.4 1.5 2.2 -1 1 -2 1 - *D3-E-N-5*/*matrix.txt.cut | ... > final.matrix.txt

I know this can be looped to add the new fields, but I'm new to programming and loops are not my forte. I've tried this (from here bash join multiple files with empty replacement (-e option)):

i=3
orderl='0,1.2'
orderr=',2.2'
for k in UNITAS*/*seq_cut
do
    if [ -a final.results ]
    then
        join -a1 -a2 -e "0" -o "$orderl$orderr" final.results $k  > tmp.res
        orderl="$orderl,1.$i"
        i=$((i+1))
        mv tmp.res final.results
    else
        cp $k final.results
    fi
done

which gives me the error

[: too many arguments

[: too many arguments

cp: overwrite ‘final.results’?

Does anyone have suggestions on a script to recursively join files, or a program better suited for this task?

Much appreciated!

Body:
Just use R and you can change the desired extension as necessary:

Here are the files I used as an example:

f1.txt

a 1
b 4
c 6
e 3

f2.txt

c 1
d 4
f 5
z 3

f3.txt

a 1
b 4
c 5
e 7
g 12

R code:

#!/bin/env/Rscript

ext='.ext' #can alter this to desired extension
files <- list.files(pattern=ext) #get name of files in a directory
listOfFiles <- lapply(files, function(x){ read.table(x, row.names=1) } )

#The big reduction of all the files into a table
tbl <- Reduce(function(...) data.frame(merge(..., all = T, by = 0), row.names=1), listOfFiles)

tbl[is.na(tbl)] <- 0 #set all NA vals to 0
colnames(tbl) <- files #set the columns to the corresponding filenames (optional)
tbl #print out the table

Output:

  f1.ext f2.ext f3.ext
a      1      0      1
b      4      0      4
c      6      1      5
d      0      4      0
e      3      0      7
f      0      5      0
g      0      0     12
z      0      3      0


问:
How to get method name automatically in Code Snippet in C# 4.0
I am developing an application in ASP.Net 4.0 with C# where I am doing logging and tracing using Microsoft's Enterprise Lib. My problem is that almost in every function , as per my company guidline, where there is interaction with database or some critical business rules , use tracing, in this format.

```<code>try
{
_traceLog.clear();
_traceLog.AppendLine("XYZ method started: XYZ()");

_traceLog.AppendLine("XYZ method completed: XYZ()");
}
catch(Exception ex)
{
 _userException.CreateExceptionLog(ex);
}
finally
{
 _userException.CreateTraceLog(_traceLog.ToString());
}
</code>```

So what i want is to convert it as a code snippet that will automatically detect the current method, say in above case we have XYZ().

Please help me. Also tell me the way to add this to intellisense. Right now i am able create .snippet file and uses insert snippet from context menu.

UPdate

I think i am not clear to you guys. Let me make more clear. i have an code snippet

```<code><CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>
                TL
            </Title>
        </Header>
        <Snippet>
            <Code Language="CSharp">
                <![CDATA[ try
            {
                _traceLog.Clear();
                _traceLog.AppendLine("");   // here in side the append line i want to get name of method under which i am placing code snippet.
                _traceLog.AppendLine("");
            }
            catch (Exception ex)
            {

                _userExceptionLog.CreateExceptionLog(ex);
            }
            finally
            {
                _userExceptionLog.CreateTraceLog(_traceLog.ToString());
            }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
</code>```

For example if my method is

```<code>void XYZ()
{
  // when i insert snippet here , the snippet will automatically detect
</code>```

that this snippet is going to be placed under XYZ function.

```<code>try
                {
                    _traceLog.Clear();
                    _traceLog.AppendLine("XYZ started: XYZ()");
</code>```

// here in side the append line i want to get name of method under
which i am placing code snippet.

```<code>                _traceLog.AppendLine("XYZ completed: XYZ()");
                }
                catch (Exception ex)
                {

                    _userExceptionLog.CreateExceptionLog(ex);
                }
                finally
                {
                    _userExceptionLog.CreateTraceLog(_traceLog.ToString());
                }

}
</code>```

Is this possible? or I have to enter it manually or any other short way?

答: MethodInfo.GetCurrentMethod().Name will give you the name of the currently executing method. Caveat: anonymous methods will give you garbage as name.

Body:
I am developing an application in ASP.Net 4.0 with C# where I am doing logging and tracing using Microsoft's Enterprise Lib. My problem is that almost in every function , as per my company guidline, where there is interaction with database or some critical business rules , use tracing, in this format.

try
{
_traceLog.clear();
_traceLog.AppendLine("XYZ method started: XYZ()");

_traceLog.AppendLine("XYZ method completed: XYZ()");
}
catch(Exception ex)
{
 _userException.CreateExceptionLog(ex);
}
finally
{
 _userException.CreateTraceLog(_traceLog.ToString());
}

So what i want is to convert it as a code snippet that will automatically detect the current method, say in above case we have XYZ().

Please help me. Also tell me the way to add this to intellisense. Right now i am able create .snippet file and uses insert snippet from context menu.

UPdate

I think i am not clear to you guys. Let me make more clear. i have an code snippet

<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet">
    <CodeSnippet Format="1.0.0">

            <Title>
                TL
            </Title>

        <Snippet>

                <![CDATA[ try
            {
                _traceLog.Clear();
                _traceLog.AppendLine("");   // here in side the append line i want to get name of method under which i am placing code snippet.
                _traceLog.AppendLine("");
            }
            catch (Exception ex)
            {

                _userExceptionLog.CreateExceptionLog(ex);
            }
            finally
            {
                _userExceptionLog.CreateTraceLog(_traceLog.ToString());
            }]]>

        </Snippet>
    </CodeSnippet>
</CodeSnippets>

For example if my method is

void XYZ()
{
  // when i insert snippet here , the snippet will automatically detect

that this snippet is going to be placed under XYZ function.

try
                {
                    _traceLog.Clear();
                    _traceLog.AppendLine("XYZ started: XYZ()");

// here in side the append line i want to get name of method under
which i am placing code snippet.

                _traceLog.AppendLine("XYZ completed: XYZ()");
                }
                catch (Exception ex)
                {

                    _userExceptionLog.CreateExceptionLog(ex);
                }
                finally
                {
                    _userExceptionLog.CreateTraceLog(_traceLog.ToString());
                }

}

Is this possible? or I have to enter it manually or any other short way?


问:
Embedding a JavaScript canvas into the python TKinter
I am trying to embed a JavaScript canvas into the python Tkinter. I hope when I opened the GUI I will see the Javascript canvas already on the interface, is it possible to just import the JavaScript codes directly into the python script? Thank you.</p>

答: No, there is no way to use javascript to draw in a Tkinter canvas. </p>


问:
Getting specific date with timezone in Java
I am getting a little crazy with date and time libraries in Java. Basically what I need is to get two String dates, the first one corresponds to the previous day in Australia time (taking into account daylight time) with a specific hour (will come as a parameter) and with the following date format: "yyyy-MM-dd'T'HH:mm:ss.SSS zzz".

Consider I will receive the time as a string like the following: "180000". So if today is Nov-17 in Australia, I will need to get the following String:

```<code>"2017-11-16T18:00:00.000 AEDT"
</code>```

And the second string date I need is the same day as today in au time:

```<code>"2017-11-17T18:00:00.000 AEDT"
</code>```

I am not able to use JDK 8, I must use JDK 7.

I tried different ways but I am not getting what I need. Any suggestion will be great.

答:
I saw your comment that you cannot use Java 8, you must use JDK 7. At the same time, especially for not quite trivial run-of-the-mill operations like yours, java.time, the modern Java date and time API that came out with Java 8 in 2014 is so much nicer to work with. Fortunately the modern API has been backported to Java 6 and 7 too, in the ThreeTen Backport (that’s ThreeTen for JSR-310, where the API was first described). So I encourage you to get the backport and start coding:

```<code>    ZoneId australianTime = ZoneId.of("Australia/Sydney");
    DateTimeFormatter receivedTimeFormat = DateTimeFormatter.ofPattern("HHmmss");
    DateTimeFormatter neededDateTimeFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS zzz",
                                          Locale.forLanguageTag("en-AU"));
    LocalDate today = LocalDate.now(australianTime);
    LocalDate yesterday = today.minusDays(1);
    String receivedTimeString = "180000";
    LocalTime time = LocalTime.parse(receivedTimeString, receivedTimeFormat);
    String previousDayAtTime = yesterday.atTime(time)
            .atZone(australianTime)
            .format(neededDateTimeFormatter);
    System.out.println(previousDayAtTime);
</code>```

When I ran this snippet today, it printed the requested output for yesterday:

```<code>2017-11-16T18:00:00.000 AEDT
</code>```

I trust you to do similarly for today.

Since you had AEDT in your requested result, I picked Australia/Sydney as time zone over Australia/Darwin or other Australian options.

Using the backport is also the futureproof solution: you will need the backport only until one day you upgrade to Java 8 or later (Java 9 is out already). When upgrading, simply change your import statement from  org.threeten.bp to java.time.

Body:
I am getting a little crazy with date and time libraries in Java. Basically what I need is to get two String dates, the first one corresponds to the previous day in Australia time (taking into account daylight time) with a specific hour (will come as a parameter) and with the following date format: "yyyy-MM-dd'T'HH:mm:ss.SSS zzz".

Consider I will receive the time as a string like the following: "180000". So if today is Nov-17 in Australia, I will need to get the following String:

"2017-11-16T18:00:00.000 AEDT"

And the second string date I need is the same day as today in au time:

"2017-11-17T18:00:00.000 AEDT"

I am not able to use JDK 8, I must use JDK 7.

I tried different ways but I am not getting what I need. Any suggestion will be great.

Body:
I saw your comment that you cannot use Java 8, you must use JDK 7. At the same time, especially for not quite trivial run-of-the-mill operations like yours, java.time, the modern Java date and time API that came out with Java 8 in 2014 is so much nicer to work with. Fortunately the modern API has been backported to Java 6 and 7 too, in the ThreeTen Backport (that’s ThreeTen for JSR-310, where the API was first described). So I encourage you to get the backport and start coding:

    ZoneId australianTime = ZoneId.of("Australia/Sydney");
    DateTimeFormatter receivedTimeFormat = DateTimeFormatter.ofPattern("HHmmss");
    DateTimeFormatter neededDateTimeFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS zzz",
                                          Locale.forLanguageTag("en-AU"));
    LocalDate today = LocalDate.now(australianTime);
    LocalDate yesterday = today.minusDays(1);
    String receivedTimeString = "180000";
    LocalTime time = LocalTime.parse(receivedTimeString, receivedTimeFormat);
    String previousDayAtTime = yesterday.atTime(time)
            .atZone(australianTime)
            .format(neededDateTimeFormatter);
    System.out.println(previousDayAtTime);

When I ran this snippet today, it printed the requested output for yesterday:

2017-11-16T18:00:00.000 AEDT

I trust you to do similarly for today.

Since you had AEDT in your requested result, I picked Australia/Sydney as time zone over Australia/Darwin or other Australian options.

Using the backport is also the futureproof solution: you will need the backport only until one day you upgrade to Java 8 or later (Java 9 is out already). When upgrading, simply change your import statement from  org.threeten.bp to java.time.


问:
Troubles installing mysqlclient with pip3
I'm trying to set up a python 3.6 environment with Django. The installation instructions say I should install mysqlclient to be able to connect to mySQL. I get this:

```<code>dennis@django:~$ sudo -H pip3 install mysqlclient
Collecting mysqlclient
  Using cached mysqlclient-1.3.10.tar.gz
    Complete output from command python setup.py egg_info:
    /bin/sh: 1: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup_posix.py", line 44, in get_config
        libs = mysql_config("libs_r")
      File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup_posix.py", line 26, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    OSError: mysql_config not found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4jiw3hvk/mysqlclient/
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

mySQL is properly installed. What should be in the mysql_config file?
When I try to upgrade pip3 I get this:

```<code>dennis@django:~$ sudo -H pip3 install --upgrade pip3
Collecting pip3
  Could not find a version that satisfies the requirement pip3 (from versions: )
No matching distribution found for pip3
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

After installing mysqlclient with pip3, I noticed that the module was installed in the python3.5 directory instead of in the python3.6 directory so when I tried to import the MySQLdb module running python3.6, it was not found

```<code>dennis@django:~/python_db$ python
Python 3.6.0+ (default, Feb  4 2017, 11:11:46)
[GCC 5.4.1 20161202] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'MySQLdb'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'MySQLdb'
>>>
</code>```

I then reran using python 3.5 and it was found. How do I install modules using pip3 into the 3.6 directory?

答:
If you're running MAMP on OSX, do this:</p>

```<code>export PATH=$PATH:/Applications/MAMP/Library/bin
</code>```

Body:
I'm trying to set up a python 3.6 environment with Django. The installation instructions say I should install mysqlclient to be able to connect to mySQL. I get this:

dennis@django:~$ sudo -H pip3 install mysqlclient
Collecting mysqlclient
  Using cached mysqlclient-1.3.10.tar.gz
    Complete output from command python setup.py egg_info:
    /bin/sh: 1: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup_posix.py", line 44, in get_config
        libs = mysql_config("libs_r")
      File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup_posix.py", line 26, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    OSError: mysql_config not found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4jiw3hvk/mysqlclient/
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

mySQL is properly installed. What should be in the mysql_config file?
When I try to upgrade pip3 I get this:

dennis@django:~$ sudo -H pip3 install --upgrade pip3
Collecting pip3
  Could not find a version that satisfies the requirement pip3 (from versions: )
No matching distribution found for pip3
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

After installing mysqlclient with pip3, I noticed that the module was installed in the python3.5 directory instead of in the python3.6 directory so when I tried to import the MySQLdb module running python3.6, it was not found

dennis@django:~/python_db$ python
Python 3.6.0+ (default, Feb  4 2017, 11:11:46)
[GCC 5.4.1 20161202] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'MySQLdb'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'MySQLdb'
>>>

I then reran using python 3.5 and it was found. How do I install modules using pip3 into the 3.6 directory?

Body:
If you're running MAMP on OSX, do this:

export PATH=$PATH:/Applications/MAMP/Library/bin


问:
Facebook key hash doesn't work
I sent a new version of my app to Google Play and the key hash changed. I used Ionic package to generate the apk.

When I try to connect with Facebook on app, I receive the following error:

Invalid key hash. The key hash ***** does not match any stored key hashes. Configure your app key hashes at https://developers.facebook....

The problem is that the hash is configured on Facebook and I checked this a lot of times.

答:
"invalid key hash. the key {your_key} hash does not match any stored key hashes. configured your app key hashes release apk".

Just copy {your_key} into "key hash" of facebook console and save.

Title: Facebook key hash doesn't work


问:
Shell script diamond
The question is: Using Shell script programming, create a script that asks the user to enter a number and then prints the following shape. The number of rows is double the columns and user input determine the size of the diamond.

```<code>                *
               * *
              * * *
             * * * *
            * * * * *
           * * * * * *
          * * * * * * *
         * * * * * * * *
          * * * * * * *
           * * * * * *
            * * * * *
             * * * *
              * * *
               * *
                *
</code>```

I've been trying this for days. Any help would bee awesome

答:
I have written the following code for you, I hope that it helps you:

```<code>#!/usr/bin/env bash

#get the first argument passed to your script and assign it to STAR_NUMBER_MAX,
#if it is empty -> default value will be 0
readonly STAR_NUMBER_MAX="${1:-0}"

#check if your STAR_NUMBER_MAX is a number
re='^[0-9]+$'
if ! [[ $STAR_NUMBER_MAX =~ $re ]] ; then
   echo "error: your column_size is not a number" >&2; exit 1
fi
#variable that will be used to compute the number of stars to display per line
star_number=0
#variable that will be used in order to know if we have reached the max amount of stars
test_star_max=0
for i in `seq 1 $((2*STAR_NUMBER_MAX +1))`;
do
    #print the spaces
    for j in `seq $star_number $STAR_NUMBER_MAX`
    do
        echo -n " "
    done
    #print the stars
    for j in `seq 1 $star_number`;
    do
        if (( star_number == STAR_NUMBER_MAX )); then
            test_star_max=1
        fi
        echo -n "*"
    done
    #print the remaining stars
    for j in `seq 2 $star_number`;
    do
        echo -n "*"
    done
    if (( test_star_max == 0 )); then
        star_number=$((star_number + 1));
    else
        star_number=$((star_number - 1));
    fi
    echo ""
done
</code>```

The result of the script is you described.

Title: Shell script diamond

Body:
The question is: Using Shell script programming, create a script that asks the user to enter a number and then prints the following shape. The number of rows is double the columns and user input determine the size of the diamond.

                *
               * *
              * * *
             * * * *
            * * * * *
           * * * * * *
          * * * * * * *
         * * * * * * * *
          * * * * * * *
           * * * * * *
            * * * * *
             * * * *
              * * *
               * *
                *

I've been trying this for days. Any help would bee awesome

Body:
I have written the following code for you, I hope that it helps you:

#!/usr/bin/env bash

#get the first argument passed to your script and assign it to STAR_NUMBER_MAX,
#if it is empty -> default value will be 0
readonly STAR_NUMBER_MAX="${1:-0}"

#check if your STAR_NUMBER_MAX is a number
re='^[0-9]+$'
if ! [[ $STAR_NUMBER_MAX =~ $re ]] ; then
   echo "error: your column_size is not a number" >&2; exit 1
fi
#variable that will be used to compute the number of stars to display per line
star_number=0
#variable that will be used in order to know if we have reached the max amount of stars
test_star_max=0
for i in `seq 1 $((2*STAR_NUMBER_MAX +1))`;
do
    #print the spaces
    for j in `seq $star_number $STAR_NUMBER_MAX`
    do
        echo -n " "
    done
    #print the stars
    for j in `seq 1 $star_number`;
    do
        if (( star_number == STAR_NUMBER_MAX )); then
            test_star_max=1
        fi
        echo -n "*"
    done
    #print the remaining stars
    for j in `seq 2 $star_number`;
    do
        echo -n "*"
    done
    if (( test_star_max == 0 )); then
        star_number=$((star_number + 1));
    else
        star_number=$((star_number - 1));
    fi
    echo ""
done

The result of the script is you described.


问:
ios background ping every minute
I have looked at some posts within this domain (e.g. iOS background fetch custom interval) and I am concluding that what I need to do is not possible.

I have an external device communicating to ios over bluetooth (NFC chip card reader). The external device goes to sleep if not pinged every minute (59 seconds).
When the app is in the foreground I  can manage the pinging. When in the background I want to continue to ping. Is this impossible?
The ping operation is fast; it is just to send a message and I dont need a response back to ios.

(What works really well is the opposite, bluetooth communication can flow from the device to ios from the background. That is done via UIBackgroundModes in Info.plist to bluetooth-peripheral.)

Please note that I am feeding the iphone from external power in the application here. It is an industrial application; and the normal iphone usecase is not applicable.

答:
Short answer, no. The best iOS offers is back ground fetch. But there is no guarantee when background delegate method is called. You can specify a timespan as a guide but it primarily based on how often the app is accessed.

https://www.raywenderlich.com/143128/background-modes-tutorial-getting-started

Title: ios background ping every minute


问:
cant create create-service in Cloud Foundry
Start read the cloud-native-java book.
Where according to guide. Try to create service using the command:

```<code>cf create-service p-mysql 100mb bootcamp-customers-mysql
</code>```

in result i have an error:
**Service offering p-mysql not found**

What is the wrong ?

答: You can always run cf marketplace to see what services are available to you. p-mysql is the service created by the MySQL Tile for Pivotal Cloud Foundry and as was mentioned in the comments, is not available in PWS or other hosted CF offerings.

Body:
Start read the cloud-native-java book.
Where according to guide. Try to create service using the command:

cf create-service p-mysql 100mb bootcamp-customers-mysql

in result i have an error:
**Service offering p-mysql not found**

What is the wrong ?


问:
Django - Pass a list item's id/pk to the view with jQuery ajax
Here is my code, shortened for brevity.

HTML Template

```<code>{% for question in questions %}
    <div class="upvote"></div>
{% endfor %}

# lots of code later...

<script>
    $(".upvote").click(function(){
        $.ajax({
            type: "POST",
            url: "{% url 'upvote_for_question' %}",
            data: {
                'question': question
            },
            }
        })
    })
</script>
</code>```

My
 element is an upvote button for a question (think Stack Overflow's upvote button).  As the code shows, every question in question_list has an upvote button.

My question is, when the user presses an upvote button, how do I pass the associated question's pk/id to the view?

答:
You could first give each div a unique id:

```<code>{% for question in questions %}
    <div class="upvote" id="button-{{ question.pk}}"></div>
{% endfor %}
</code>```

Then pass that in the post data:

```<code>data: {
    'question': $(this).attr('id')
},
</code>```

Body:
Here is my code, shortened for brevity.

HTML Template

{% for question in questions %}

{% endfor %}

# lots of code later...

My
 element is an upvote button for a question (think Stack Overflow's upvote button).  As the code shows, every question in question_list has an upvote button.

My question is, when the user presses an upvote button, how do I pass the associated question's pk/id to the view?

Body:
You could first give each div a unique id:

{% for question in questions %}
    <div class="upvote" id="button-{{ question.pk}}"></div>
{% endfor %}

Then pass that in the post data:

data: {
    'question': $(this).attr('id')
},


问:
JavaScript: Why does closure only happen if I assign the return function to a variable?
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

```<code>function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3
</code>```

答:
Each time you call counter()(), it creates a new function and a new closure.
So the result is always 0.

On the contrary, when var createClosure = counter(); is executed, a function and closure are created and saved in the variable createClosure. Next time when you call createClosure(), the saved one is invoked and the created closure is used. Therefore the results are 0, 1, 2, 3, ...

Body:
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3


问:
Reading a particular column in csv file using numpy in python
How to read string column only using numpy in python?

csv file:

```<code>1,2,3,"Hello"
3,3,3,"New"
4,5,6,"York"
</code>```

How to get array like:

```<code>["Hello","york","New"]
</code>```

without using pandas and sklearn.

答:
```<code>import numpy
fname = 'sample.csv'
csv = numpy.genfromtxt(fname, dtype=str, delimiter=",")
names = csv[:,-1]
print(names)
</code>```

Choosing the data type
The main way to control how the sequences of strings we have read from the file are converted to other types is to set the dtype argument. Acceptable values for this argument are:

a single type, such as dtype=float. The output will be 2D with the given dtype, unless a name has been associated with each column with the use of the names argument (see below). Note that dtype=float is the default for genfromtxt.
a sequence of types, such as dtype=(int, float, float).
a comma-separated string, such as dtype="i4,f8,|U3".
a dictionary with two keys 'names' and 'formats'.
a sequence of tuples (name, type), such as dtype=[('A', int), ('B', float)].
an existing numpy.dtype object.
the special value None. In that case, the type of the columns will be determined from the data itself (see below).

When dtype=None, the type of each column is determined iteratively from its data. We start by checking whether a string can be converted to a boolean (that is, if the string matches true or false in lower cases); then whether it can be converted to an integer, then to a float, then to a complex and eventually to a string. This behavior may be changed by modifying the default mapper of the StringConverter class.

The option dtype=None is provided for convenience. However, it is significantly slower than setting the dtype explicitly.

Body:
How to read string column only using numpy in python?

csv file:

1,2,3,"Hello"
3,3,3,"New"
4,5,6,"York"

How to get array like:

["Hello","york","New"]

without using pandas and sklearn.

Body:
import numpy
fname = 'sample.csv'
csv = numpy.genfromtxt(fname, dtype=str, delimiter=",")
names = csv[:,-1]
print(names)

Choosing the data type
The main way to control how the sequences of strings we have read from the file are converted to other types is to set the dtype argument. Acceptable values for this argument are:

a single type, such as dtype=float. The output will be 2D with the given dtype, unless a name has been associated with each column with the use of the names argument (see below). Note that dtype=float is the default for genfromtxt.
a sequence of types, such as dtype=(int, float, float).
a comma-separated string, such as dtype="i4,f8,|U3".
a dictionary with two keys 'names' and 'formats'.
a sequence of tuples (name, type), such as dtype=[('A', int), ('B', float)].
an existing numpy.dtype object.
the special value None. In that case, the type of the columns will be determined from the data itself (see below).

When dtype=None, the type of each column is determined iteratively from its data. We start by checking whether a string can be converted to a boolean (that is, if the string matches true or false in lower cases); then whether it can be converted to an integer, then to a float, then to a complex and eventually to a string. This behavior may be changed by modifying the default mapper of the StringConverter class.

The option dtype=None is provided for convenience. However, it is significantly slower than setting the dtype explicitly.