问:
VB.NET Get direction from one point to another
I need this function to work in order to continue progress with my simple scrolling shooter game.

```<code>Public Function GetDirection(origin As Point, target As Point) As Single
    'do some trigonometry here
    Return Direction
End Function
</code>```

Normally I would insert these parameters: GetDirection(player_point, MousePosition)

And use them in this context:

```<code>Dim direction As Single = GetDirection(player_point, MousePosition)
Dim blt_increment_x As Single = Math.Sin(direction)
Dim blt_increment_y As Single = Math.Cos(direction)
</code>```

Now these variables can be used to move my bullet entity:

```<code>blt_point.X += blt_increment_x
blt_point.Y += blt_increment_y
</code>```

All I need is the code for this GetDirection() function. Currently I have no idea where to start, and I set it to constantly return 0. I am using VB.NET. Thanks! :)

For those wondering, here's a screenshot of my game, very reminiscent of diep.io :)

答:
You should use Math.Atan2 method. I'm not a VB developer but I think you can convert following pseudo-code into VB:

```<code>direction = Math.Atan2(target.Y - origin.Y, target.X - origin.X)
</code>```

But looking into your code and noticing that you will use Math.Sin and Math.Cos just in the next line, the whole idea makes very little sense. Direction of the movement is specified by differences in X and Y coordinates. If you want to have a constand speed, your code could be something like this

```<code>dX = target.X - origin.X
dY = target.Y - origin.Y
len = Math.Sqrt(dX*dX + dY*dY)
blt_increment_x = Speed * dX / len
blt_increment_y = Speed * dY / len
</code>```

Body:
I need this function to work in order to continue progress with my simple scrolling shooter game.

Public Function GetDirection(origin As Point, target As Point) As Single
    'do some trigonometry here
    Return Direction
End Function

Normally I would insert these parameters: GetDirection(player_point, MousePosition)

And use them in this context:

Dim direction As Single = GetDirection(player_point, MousePosition)
Dim blt_increment_x As Single = Math.Sin(direction)
Dim blt_increment_y As Single = Math.Cos(direction)

Now these variables can be used to move my bullet entity:

blt_point.X += blt_increment_x
blt_point.Y += blt_increment_y

All I need is the code for this GetDirection() function. Currently I have no idea where to start, and I set it to constantly return 0. I am using VB.NET. Thanks! :)

For those wondering, here's a screenshot of my game, very reminiscent of diep.io :)

Body:
You should use Math.Atan2 method. I'm not a VB developer but I think you can convert following pseudo-code into VB:

direction = Math.Atan2(target.Y - origin.Y, target.X - origin.X)

But looking into your code and noticing that you will use Math.Sin and Math.Cos just in the next line, the whole idea makes very little sense. Direction of the movement is specified by differences in X and Y coordinates. If you want to have a constand speed, your code could be something like this

dX = target.X - origin.X
dY = target.Y - origin.Y
len = Math.Sqrt(dX*dX + dY*dY)
blt_increment_x = Speed * dX / len
blt_increment_y = Speed * dY / len


来源: stackexchange

问:
How to assign public port to port 5900 in docker-compose
I have below YAML file :

seleniumhub:

image: selenium/hub

ports:
 - 4444:4444
```

<p>firefoxnode:</p>

<pre class="lang-yaml prettyprint-override"><code>image: selenium/node-firefox-debug

ports:
 - 4577

links:
 - seleniumhub:hub

expose:
 - "5900"
</code>```

chromenode:

image : selenium/node-chrome-debug

ports:
 - 4578

links:
 - seleniumhub:hub

expose:
 - "5900"
```

<hr>

<p>docker ps:</p>

```time="2017-04-01T17:57:44+03:00" level=info msg="Unable to use system certificate pool: crypto/x509: system root pool is not available on Windows"

CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                               NAMES
9d2ccb193b54        selenium/node-firefox-debug   "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32785->4577/tcp   dockercompose_firefoxnode_1
4be6223fe043        selenium/node-chrome-debug    "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32784->4578/tcp   dockercompose_chromenode_1
7d95d3e73016        selenium/hub                  "/opt/bin/entry_po..."   7 seconds ago       Up 6 seconds        0.0.0.0:4444->4444/tcp              dockercompose_seleniumhub_1
```

<hr>

<p>But whenever I run below command in Docker quick start terminal:</p>

```docker port 9d2ccb193b54 5900
```

I got below:

Error: No public port '5900/tcp' published for 9d2ccb193b54

and I'm not able to connect to the node machines through VNC

答:
For exposing ports the syntax is:

```<code>ports:
  - "host:container"
</code>```

In your case:

```<code>image: selenium/node-firefox-debug

ports:
 - 4577
 - "5900:5900"

links:
 - seleniumhub:hub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have below YAML file :

seleniumhub:

image: selenium/hub

ports:
 - 4444:4444

firefoxnode:

image: selenium/node-firefox-debug

ports:
 - 4577

links:
 - seleniumhub:hub

expose:
 - "5900"

chromenode:

image : selenium/node-chrome-debug

ports:
 - 4578

links:
 - seleniumhub:hub

expose:
 - "5900"

docker ps:

time="2017-04-01T17:57:44+03:00" level=info msg="Unable to use system certificate pool: crypto/x509: system root pool is not available on Windows"

CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                               NAMES
9d2ccb193b54        selenium/node-firefox-debug   "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32785->4577/tcp   dockercompose_firefoxnode_1
4be6223fe043        selenium/node-chrome-debug    "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32784->4578/tcp   dockercompose_chromenode_1
7d95d3e73016        selenium/hub                  "/opt/bin/entry_po..."   7 seconds ago       Up 6 seconds        0.0.0.0:4444->4444/tcp              dockercompose_seleniumhub_1

But whenever I run below command in Docker quick start terminal:

docker port 9d2ccb193b54 5900

I got below:

Error: No public port '5900/tcp' published for 9d2ccb193b54

and I'm not able to connect to the node machines through VNC

Body:
For exposing ports the syntax is:

ports:
  - "host:container"

In your case:

image: selenium/node-firefox-debug

ports:
 - 4577
 - "5900:5900"

links:
 - seleniumhub:hub

ContentLicense: CC BY-SA 4.0


问:
How to make new file inherit permission?
I am using CS50 appliance(Ubuntu).
My php function adds images in the imgs folder of public.
But each time after addition I have to manually change the permission of the newly added file for it to be view-able in my webpage.
Is there any way for me to set the default permission of any file being added to the folder imgs as 644?</p>

答:
```<code>sudo chmod 777 yourFloderName/*
</code>```

Body: sudo chmod 777 yourFloderName/*


问:
How do I switch rows and columns in a 2D array?
I am working on a code that will create a visual Sierpinski triangle to 3D print, and in order for it to work I have to use a Pascal triangle algorithm that will create an array so I can use to tell my algorithm that will create my triangles where not to put triangles.

Anyway the problem is, that my code that arranges the triangles creates the triangles by column instead of by row like the Pascal algorithm does so I am just trying to do a quick fix by having a subroutine that rearranges the Pascal array. I am just stumped on how to do it since I am not sure how to avoid index out of range errors.

This is the code that creates the array for Pascal's triangle.

TL:DR I am trying to make an rearrange an array where rows are the columns and columns are the rows

```<code>def pascal(n):
    """Prints out n rows of Pascal's triangle."""
    row = [1]
    global array
    array = [[0 for x in range(int(n))] for y in range(int(n))]
    array[0]=row
    k = [0]
    for x in range(int(max(n,0)-1)):
       row=[l+r for l,r in zip(row+k,k+row)]
       array[x+1]=row
    return 1
</code>```

This is the output of printing the array. I just want the rows to be columns and columns to be rows

[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]
```

<p>Here is the full code if you are curious about the project, but it requires <code>rhinoscriptsyntax</code> to make the model.</p>

```import rhinoscriptsyntax as rhino
import math

obj = rhino.GetObject("Select object to transform", preselect=True)
scale = 3
n=math.pow(3,scale)
def pascal(n):
   """Prints out n rows of Pascal's triangle."""
   row = [1]
   global array
   array = [[0 for x in range(int(n))] for y in range(int(n))]
   array[0]=row
   k = [0]
   for x in range(int(max(n,0)-1)):
      row=[l+r for l,r in zip(row+k,k+row)]
      array[x+1]=row
   return 1
pascal(math.pow(2,scale))
print array
def remakePascal():
    pass
my_horizontalVector = [[1,0,0,6],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

my_tsfm = [[1,0,0,0],  #identity
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

def makeTriangle(scale,obj):
    w=1/scale
    h=1/scale
    tsfm= [[w,0,0,0],   #scale about origin
            [0,h,0,0],
            [0,0,1,0],
            [0,0,0,1]]
    output= rhino.XformMultiply(my_tsfm,tsfm)
    new_obj=rhino.TransformObject(obj,output,copy=True)
    return new_obj
def placeObj(i):
    my_moveUpVector = [[1,0,0,(3/scale)*i],
           [0,1,0,(4/scale)*i],
           [0,0,1,0],
           [0,0,0,1]]
    vector = rhino.XformMultiply(my_tsfm,my_moveUpVector)
    return vector
n=0
for i in range(int(math.pow(2,scale))):
    if(i>0):
       hPlace=rhino.XformMultiply(my_tsfm,my_horizontalVector)
       obj = rhino.TransformObject(obj,hPlace)
    factor = int(math.pow(2,scale))-n
    for j in range(factor):
        if():
            pass
        else:
            Vertobj=makeTriangle(scale,obj)
            tsfm = rhino.TransformObject(Vertobj,placeObj(j),copy=True)
    n=n+1
```

答:
You can transpose the rows and columns after matching length of each rows with max row and filling with zeros.

Working code as below. numpy_fillna function sourced from this SO post.

```<code>import numpy as np
x = [[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]

a = np.array(x)

def numpy_fillna(data):
    # Get lengths of each row of data
    lens = np.array([len(i) for i in data])

    # Mask of valid places in each row
    mask = np.arange(lens.max()) < lens[:,None]

    # Setup output array and put elements from data into masked positions
    out = np.zeros(mask.shape, dtype=data.dtype)
    out[mask] = np.concatenate(data)
    return out
</code>```

Result

```<code>>>> numpy_fillna(a).T
array([[1, 1, 1, 1, 1, 1, 1, 1],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 0, 1, 3, 6, 10, 15, 21],
       [0, 0, 0, 1, 4, 10, 20, 35],
       [0, 0, 0, 0, 1, 5, 15, 35],
       [0, 0, 0, 0, 0, 1, 6, 21],
       [0, 0, 0, 0, 0, 0, 1, 7],
       [0, 0, 0, 0, 0, 0, 0, 1]], dtype=object)
>>>
</code>```

Body:
I am working on a code that will create a visual Sierpinski triangle to 3D print, and in order for it to work I have to use a Pascal triangle algorithm that will create an array so I can use to tell my algorithm that will create my triangles where not to put triangles.

Anyway the problem is, that my code that arranges the triangles creates the triangles by column instead of by row like the Pascal algorithm does so I am just trying to do a quick fix by having a subroutine that rearranges the Pascal array. I am just stumped on how to do it since I am not sure how to avoid index out of range errors.

This is the code that creates the array for Pascal's triangle.

TL:DR I am trying to make an rearrange an array where rows are the columns and columns are the rows

def pascal(n):
    """Prints out n rows of Pascal's triangle."""
    row = [1]
    global array
    array = [[0 for x in range(int(n))] for y in range(int(n))]
    array[0]=row
    k = [0]
    for x in range(int(max(n,0)-1)):
       row=[l+r for l,r in zip(row+k,k+row)]
       array[x+1]=row
    return 1

This is the output of printing the array. I just want the rows to be columns and columns to be rows

[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]

Here is the full code if you are curious about the project, but it requires rhinoscriptsyntax to make the model.

import rhinoscriptsyntax as rhino
import math

obj = rhino.GetObject("Select object to transform", preselect=True)
scale = 3
n=math.pow(3,scale)
def pascal(n):
   """Prints out n rows of Pascal's triangle."""
   row = [1]
   global array
   array = [[0 for x in range(int(n))] for y in range(int(n))]
   array[0]=row
   k = [0]
   for x in range(int(max(n,0)-1)):
      row=[l+r for l,r in zip(row+k,k+row)]
      array[x+1]=row
   return 1
pascal(math.pow(2,scale))
print array
def remakePascal():
    pass
my_horizontalVector = [[1,0,0,6],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

my_tsfm = [[1,0,0,0],  #identity
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

def makeTriangle(scale,obj):
    w=1/scale
    h=1/scale
    tsfm= [[w,0,0,0],   #scale about origin
            [0,h,0,0],
            [0,0,1,0],
            [0,0,0,1]]
    output= rhino.XformMultiply(my_tsfm,tsfm)
    new_obj=rhino.TransformObject(obj,output,copy=True)
    return new_obj
def placeObj(i):
    my_moveUpVector = [[1,0,0,(3/scale)*i],
           [0,1,0,(4/scale)*i],
           [0,0,1,0],
           [0,0,0,1]]
    vector = rhino.XformMultiply(my_tsfm,my_moveUpVector)
    return vector
n=0
for i in range(int(math.pow(2,scale))):
    if(i>0):
       hPlace=rhino.XformMultiply(my_tsfm,my_horizontalVector)
       obj = rhino.TransformObject(obj,hPlace)
    factor = int(math.pow(2,scale))-n
    for j in range(factor):
        if():
            pass
        else:
            Vertobj=makeTriangle(scale,obj)
            tsfm = rhino.TransformObject(Vertobj,placeObj(j),copy=True)
    n=n+1

Body:
You can transpose the rows and columns after matching length of each rows with max row and filling with zeros.

Working code as below. numpy_fillna function sourced from this SO post.

import numpy as np
x = [[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]

a = np.array(x)

def numpy_fillna(data):
    # Get lengths of each row of data
    lens = np.array([len(i) for i in data])

    # Mask of valid places in each row
    mask = np.arange(lens.max()) < lens[:,None]

    # Setup output array and put elements from data into masked positions
    out = np.zeros(mask.shape, dtype=data.dtype)
    out[mask] = np.concatenate(data)
    return out

Result

>>> numpy_fillna(a).T
array([[1, 1, 1, 1, 1, 1, 1, 1],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 0, 1, 3, 6, 10, 15, 21],
       [0, 0, 0, 1, 4, 10, 20, 35],
       [0, 0, 0, 0, 1, 5, 15, 35],
       [0, 0, 0, 0, 0, 1, 6, 21],
       [0, 0, 0, 0, 0, 0, 1, 7],
       [0, 0, 0, 0, 0, 0, 0, 1]], dtype=object)
>>>


问:
type error : Cannot read value 'name' of undefined
I'm working with Angularjs and firebase to create an app that is a task timer. I create the firebase object and all works fine except when I try to log task.newTask to the console. Here's a bit of my code (please note this is not all the code):

```<code>//HTML
<aside id="sidebar">
    <section id="widget_1">
        <h2 class="titles">Task History:</h2>
        <input id="text-field" type="text" ng-model="taskText" />
        <input id="task-button" type="button" value="Add Task" ng-click="addTask()" />
    </section>

    <section id="widget_2">
        <h2 class="titles">Task List:</h2>
        <table>
            <tr ng-repeat="task in timer_tasks | orderBy: '-taskText'">
                <td>{{ task.taskText }}</td>
            </tr>
        </table>
    </section>
</aside>

//Controller:
(function() {
'use strict'

function HomeCtrl($scope, $firebaseArray, $interval) {
    console.log('I see you home controller ... you are loaded sir!!!')

    var timerRef = firebase.database().ref().child('timer_tasks');
    $scope.timer_tasks = $firebaseArray(timerRef);

    $scope.addTask = function () {
        $scope.timer_tasks.$add({
            taskText: $scope.taskText,
            newTask: true
        }).then(function (timerRef) {
            $scope.taskText = '';
        });
    };

console.log(task.newTask);
</code>```

On page load the error comes up at console.log(task.newTask);

Any help would be great. Thanks in advance!

答:
If i'm understood correctly, you need to retrieve textbook value in controller which will build $scope.timer_tasks and later can be retrieved back to view in ng-repeat.

view

```<code><aside id="sidebar">
   <section id="widget_1">
     <h4 class="titles">Task History:</h4>
       <input id="text-field" type="text" ng-model="taskText" />
       <input id="task-button"
        type="button"
        value="Add Task"
        ng-click="addTask(taskText)"/>
  </section>
</aside>
</code>```

Script

```<code>myApp.controller('myCtrl', function($scope) {
    $scope.addTask = function (value) {
      console.log(" clicked : "+value);
    };
});
</code>```

All i did was bind the value upon addTask click from ng-model to ng-click and as you can see now you have that value in addTask function.

Body:
I'm working with Angularjs and firebase to create an app that is a task timer. I create the firebase object and all works fine except when I try to log task.newTask to the console. Here's a bit of my code (please note this is not all the code):

//HTML

Task History:

        <input id="text-field" type="text" ng-model="taskText" />
        <input id="task-button" type="button" value="Add Task" ng-click="addTask()" />

Task List:

                {{ task.taskText }}

//Controller:
(function() {
'use strict'

function HomeCtrl($scope, $firebaseArray, $interval) {
    console.log('I see you home controller ... you are loaded sir!!!')

    var timerRef = firebase.database().ref().child('timer_tasks');
    $scope.timer_tasks = $firebaseArray(timerRef);

    $scope.addTask = function () {
        $scope.timer_tasks.$add({
            taskText: $scope.taskText,
            newTask: true
        }).then(function (timerRef) {
            $scope.taskText = '';
        });
    };

console.log(task.newTask);

On page load the error comes up at console.log(task.newTask);

Any help would be great. Thanks in advance!

Body:
If i'm understood correctly, you need to retrieve textbook value in controller which will build $scope.timer_tasks and later can be retrieved back to view in ng-repeat.

view

<aside id="sidebar">
   <section id="widget_1">
     <h4 class="titles">Task History:</h4>
       <input id="text-field" type="text" ng-model="taskText" />
       <input id="task-button"
        type="button"
        value="Add Task"
        ng-click="addTask(taskText)"/>
  </section>
</aside>

Script

myApp.controller('myCtrl', function($scope) {
    $scope.addTask = function (value) {
      console.log(" clicked : "+value);
    };
});

All i did was bind the value upon addTask click from ng-model to ng-click and as you can see now you have that value in addTask function.


问:
What is the right way to work with InnoDBs lack of 2nd col auto_increment support?
I am using Mysql 5.1. Because I need transactions I wanted to switch a database from MyISAM to InnoDB, but then I learned I can't because I have a primary key that contains two columns (businessunitID and invoiceID) while one (invoiceID) being an auto increment column:

```<code>CREATE TABLE invoice (invoiceID INT auto_increment, businessunitID
INT(2), date DATETIME, PRIMARY KEY (businessunitID, invoiceID));
</code>```

This design makes sense, because there are businessunits (like branches) and each has its own set of issued invoices with an ordinal number (invoiceID) where it is not allowed that a number in between is missing.

There are enough answers on stackoverflow that it does not work with InnoDB:

What is wrong with this mysql query?

But my question is: What should I do? Do I really have to migrate very basic database logic to program logic making the application much less failure proof? It is just right to define auto increment at a database level, you'll never know from where the data populating the database could all come from. (Here is an article adressing this: http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx - 100% agree.)

So is there another solution I still can get my desired behaviour with InnoDB?

答:
If I had to do this (continue using the MyISAM AUTO_INCREMENT behavior but using InnoDB tables)

One option I would consider is continuing to use MyISAM tables to generate the AUTO_INCREMENT values, exercising that functionality from a BEFORE INSERT trigger on the InnoDB table.

First, I'd remove the AUTO_INCREMENT attribute from the invoiceID column on the new InnoDB table ...

```<code>CREATE TABLE invoice
( invoiceID      INT
, businessunitID INT(2)
, date           DATETIME
, PRIMARY KEY (businessunitID, invoiceID)
) ENGINE=InnoDB;
</code>```

Next, create a MyISAM table that has the AUTO_INCREMENT property. We only need the two columns in the primary key, we don't need any of the other columns.

```<code>CREATE TABLE invoice_autoincrement
( invoiceID      INT AUTO_INCREMENT
, businessunitID INT(2)
, PRIMARY KEY (businessunitID, invoiceID)
) ENGINE=MyISAM;
</code>```

Then we can create a BEFORE INSERT trigger. As a rudimentary starting point, something like this:

```<code>DELIMITER $$

CREATE TRIGGER invoice_bi
BEFORE INSERT ON invoice
FOR EACH ROW
BEGIN
   DECLARE li_invoiceid INT DEFAULT NULL;
   IF NEW.invoiceID IS NULL OR NEW.invoiceID = 0 THEN
      INSERT INTO invoice_autoincrement
      ( invoiceID
      , businessunitID
      ) VALUES
      ( NEW.invoiceID
      , NEW.businessunitID
      );
      SELECT LAST_INSERT_ID() INTO li_invoiceid ;
      SET NEW.invoiceID = li_invoiceid ;
   END IF;
END$$

DELIMITER ;
</code>```

There's likely more that needs to be added to the trigger to appropriately handle error conditions; if sql_mode doesn't includes NO_AUTO_VALUE_ON_ZERO, then we only need to handle the NULL value and not the zero value...

```<code>IF NEW.invoiceID IS NULL THEN
</code>```

We also need to consider that the INSERT into the MyISAM table won't be rolled back if the transaction rolls back.

We don't necessarily need to keep every row we insert into the MyISAM table; we only really need the row with the highest (maximum) invoiceID for each businessunitID.

As batch maintenance approach to keeping the MyISAM table trimmed...

```<code>DELETE t.*
  FROM invoice_autoincrement t
    -- anti-join exclude
  LEFT
  JOIN ( SELECT r.businessunitID
              , MAX(r.invoiceid) AS max_invoiceID
           FROM invoice_autoincrement r
          GROUP BY r.businessunitID
       ) s
    ON s.businessunitID = t.businessunitID
   AND s.max_invoiceID  = t.invoiceID
 WHERE s.businessunitID IS NULL
</code>```

If we want to keep the MyISAM table trimmed from within BEFORE INSERT trigger, following a successful insert to the MyISAM table, and after we've retrieve the LAST_INCREMENT_ID() value... we can execute a DELETE including predicates on businesunitID.

We could repeat the same batch logic, for just the NEW.businessunitID

```<code>      DELETE t.*
        FROM invoice_autoincrement t
          -- anti-join exclude
        LEFT
        JOIN ( SELECT r.businessunitID
                    , MAX(r.invoiceid) AS max_invoiceID
                 FROM invoice_autoincrement r
                WHERE r.businessunitID =   NEW.businessunitID
                GROUP BY r.businessunitID
             ) s
          ON s.businessunitID = t.businessunitID
         AND s.max_invoiceID  = t.invoiceID
       WHERE s.businessunitID IS NULL
         AND t.businessunitID =    NEW.businessunitID
      ;
</code>```

Or we can do a simpler DELETE, removing rows for that one businessunitID that have invoiceID less than the auto_increment value we just retrieved...

```<code>      DELETE q.*
        FROM invoice_autoincrement q
       WHERE q.businessunitID = NEW.businessunitID
         AND q.invoiceID      < NEW.invoiceID
      ;
</code>```

That's an alternative I would consider.

Body:
I am using Mysql 5.1. Because I need transactions I wanted to switch a database from MyISAM to InnoDB, but then I learned I can't because I have a primary key that contains two columns (businessunitID and invoiceID) while one (invoiceID) being an auto increment column:

CREATE TABLE invoice (invoiceID INT auto_increment, businessunitID
INT(2), date DATETIME, PRIMARY KEY (businessunitID, invoiceID));

This design makes sense, because there are businessunits (like branches) and each has its own set of issued invoices with an ordinal number (invoiceID) where it is not allowed that a number in between is missing.

There are enough answers on stackoverflow that it does not work with InnoDB:

What is wrong with this mysql query?

But my question is: What should I do? Do I really have to migrate very basic database logic to program logic making the application much less failure proof? It is just right to define auto increment at a database level, you'll never know from where the data populating the database could all come from. (Here is an article adressing this: http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx - 100% agree.)

So is there another solution I still can get my desired behaviour with InnoDB?

Body:
If I had to do this (continue using the MyISAM AUTO_INCREMENT behavior but using InnoDB tables)

One option I would consider is continuing to use MyISAM tables to generate the AUTO_INCREMENT values, exercising that functionality from a BEFORE INSERT trigger on the InnoDB table.

First, I'd remove the AUTO_INCREMENT attribute from the invoiceID column on the new InnoDB table ...

CREATE TABLE invoice
( invoiceID      INT
, businessunitID INT(2)
, date           DATETIME
, PRIMARY KEY (businessunitID, invoiceID)
) ENGINE=InnoDB;

Next, create a MyISAM table that has the AUTO_INCREMENT property. We only need the two columns in the primary key, we don't need any of the other columns.

CREATE TABLE invoice_autoincrement
( invoiceID      INT AUTO_INCREMENT
, businessunitID INT(2)
, PRIMARY KEY (businessunitID, invoiceID)
) ENGINE=MyISAM;

Then we can create a BEFORE INSERT trigger. As a rudimentary starting point, something like this:

DELIMITER $$

CREATE TRIGGER invoice_bi
BEFORE INSERT ON invoice
FOR EACH ROW
BEGIN
   DECLARE li_invoiceid INT DEFAULT NULL;
   IF NEW.invoiceID IS NULL OR NEW.invoiceID = 0 THEN
      INSERT INTO invoice_autoincrement
      ( invoiceID
      , businessunitID
      ) VALUES
      ( NEW.invoiceID
      , NEW.businessunitID
      );
      SELECT LAST_INSERT_ID() INTO li_invoiceid ;
      SET NEW.invoiceID = li_invoiceid ;
   END IF;
END$$

DELIMITER ;

There's likely more that needs to be added to the trigger to appropriately handle error conditions; if sql_mode doesn't includes NO_AUTO_VALUE_ON_ZERO, then we only need to handle the NULL value and not the zero value...

IF NEW.invoiceID IS NULL THEN

We also need to consider that the INSERT into the MyISAM table won't be rolled back if the transaction rolls back.

We don't necessarily need to keep every row we insert into the MyISAM table; we only really need the row with the highest (maximum) invoiceID for each businessunitID.

As batch maintenance approach to keeping the MyISAM table trimmed...

DELETE t.*
  FROM invoice_autoincrement t
    -- anti-join exclude
  LEFT
  JOIN ( SELECT r.businessunitID
              , MAX(r.invoiceid) AS max_invoiceID
           FROM invoice_autoincrement r
          GROUP BY r.businessunitID
       ) s
    ON s.businessunitID = t.businessunitID
   AND s.max_invoiceID  = t.invoiceID
 WHERE s.businessunitID IS NULL

If we want to keep the MyISAM table trimmed from within BEFORE INSERT trigger, following a successful insert to the MyISAM table, and after we've retrieve the LAST_INCREMENT_ID() value... we can execute a DELETE including predicates on businesunitID.

We could repeat the same batch logic, for just the NEW.businessunitID

      DELETE t.*
        FROM invoice_autoincrement t
          -- anti-join exclude
        LEFT
        JOIN ( SELECT r.businessunitID
                    , MAX(r.invoiceid) AS max_invoiceID
                 FROM invoice_autoincrement r
                WHERE r.businessunitID =   NEW.businessunitID
                GROUP BY r.businessunitID
             ) s
          ON s.businessunitID = t.businessunitID
         AND s.max_invoiceID  = t.invoiceID
       WHERE s.businessunitID IS NULL
         AND t.businessunitID =    NEW.businessunitID
      ;

Or we can do a simpler DELETE, removing rows for that one businessunitID that have invoiceID less than the auto_increment value we just retrieved...

      DELETE q.*
        FROM invoice_autoincrement q
       WHERE q.businessunitID = NEW.businessunitID
         AND q.invoiceID      < NEW.invoiceID
      ;

That's an alternative I would consider.


问:
Scaling worker pools in vert.x
I'm writing a clustered Vert.x application which uses, in its entry point, a pool of worker-verticles. These verticles are iterating endlessly, asking for tasks to execute, from a central persistent queue.
This type of verticles is, of course, a worker-verticle, running in its own dedicated worker-pool.

I want to scale up and down the number of this verticles according the the number of pending tasks in the queue, but since a worker-pool has a constant size, I have no idea how to achieve such a behavior.

Is there any best-practice in which I could scale up and down the clustered worker-pool?

Furthermore - I'd like to add more VMs to my cluster as the total load on the system grows. Is there a built-in cluster-autoscaling support in vert.x?

Thanks

答:
I don't think it is possible to re-scale the worker pool size via a vertx api, but the worker pool is just a standard FixedThreadPool executor service.  You can replace that executor service with another instance.  Look into the various Executor services that Java has and see if it fits your need.

See this post about changing the ExecutorService : multithreading within vertx

Title: Scaling worker pools in vert.x


问:
PHP: object is NULL right after creation
We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

```<code>class MyLocaleWrapper extends SomeOtherClass {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            debug(self::$system);
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion(self::$system->rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower(self::$system->rfcName);
            }
            …

# in another file:
class SomeOtherClass {
    …
    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
    …

# in yet another file:
MyLocaleWrapper::getSystemLocale();
</code>```

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?

答:
Thanks for all the updates.  (see extensive comments above on original post).

Unfortunately, I'm as stumped as you are -- everything looks fine with that code.

Either

you've found some rather obscure bug in php, or...

the symptoms are tricking you into thinking the problem is in one place, when it's actually somewhere else, or...

we're all missing something in that code that should be obvious to a bunch of seasoned php developers.  ;-)

If it were my production system to deal with, I'd probably comment out the return NULL in the constructor, and let it run in production for a while.  That return shouldn't cause any problems, but it's the only strange thing I can see here.

Sorry I can't help more than that. Please come back and let us know if you figure it out.

ContentLicense: CC BY-SA 2.5

Body:
We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

class MyLocaleWrapper extends SomeOtherClass {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            debug(self::$system);
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion(self::$system->rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower(self::$system->rfcName);
            }
            …

# in another file:
class SomeOtherClass {
    …
    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
    …

# in yet another file:
MyLocaleWrapper::getSystemLocale();

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?


问:
Protractor Failed: browser.findElements(...).all is not a function
First time trying to e2e test my AngularJS application.

I have an ul with the class 'meta'. The ul has a couple of li's.
I want to grab the first li and compare that to a string.

```<code>var duration = browser.findElements(by.className('meta')).all(by.tagName('li')).get(1);
</code>```

But when running the test i keep getting the error:  Failed: browser.findElements(...).all is not a function.

I already tried findElement and findElements and keep getting the same error.

I stumbled upon this previous question: Selecting second anchor element within lists using protractor. But it didn't help me.

答:
The currently accepted answer is correct in terms of what you should be using, but here is why your code did not work.

Protractor, as you may know, wraps the WebDriverJS - selenium javascript bindings. On top of what is there, it adds a lot of convenient concepts like ElementFinder or ElementArrayFinder or the browser object.

Protractor also provides you a way to call the pure WebDriverJS functions and methods directly, like, for example, it allows to use findElement() or findElements() on the browser object.

In your case, the browser.findElements(by.className('meta')) would return an array of WebElements which is a pure WebDriverJS concept. Note, this is not an ElementArrayFinder instance, you are not at the Protractor territory at this point.

Now, you are trying to call .all() function on this array of elements and it obviously fails.

The Protractor way of doing this would be:

```<code>var duration = $$('.meta li').first();
</code>```

Or, you can even get away with a single selector:

```<code>var duration = $('.meta li:first-of-type');
</code>```

Related reading:

Protractor Syntax vs WebDriverJS Syntax

Body:
First time trying to e2e test my AngularJS application.

I have an ul with the class 'meta'. The ul has a couple of li's.
I want to grab the first li and compare that to a string.

var duration = browser.findElements(by.className('meta')).all(by.tagName('li')).get(1);

But when running the test i keep getting the error:  Failed: browser.findElements(...).all is not a function.

I already tried findElement and findElements and keep getting the same error.

I stumbled upon this previous question: Selecting second anchor element within lists using protractor. But it didn't help me.

Body:
The currently accepted answer is correct in terms of what you should be using, but here is why your code did not work.

Protractor, as you may know, wraps the WebDriverJS - selenium javascript bindings. On top of what is there, it adds a lot of convenient concepts like ElementFinder or ElementArrayFinder or the browser object.

Protractor also provides you a way to call the pure WebDriverJS functions and methods directly, like, for example, it allows to use findElement() or findElements() on the browser object.

In your case, the browser.findElements(by.className('meta')) would return an array of WebElements which is a pure WebDriverJS concept. Note, this is not an ElementArrayFinder instance, you are not at the Protractor territory at this point.

Now, you are trying to call .all() function on this array of elements and it obviously fails.

The Protractor way of doing this would be:

var duration = $$('.meta li').first();

Or, you can even get away with a single selector:

var duration = $('.meta li:first-of-type');

Related reading:

Protractor Syntax vs WebDriverJS Syntax


问:
No route matches [POST] "/account/new"
I'm trying to create a new account. but for some reason I'm getting this error when trying to submit the form No route matches [POST] "/account/new". Here is my form_for:

```<code><%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
</code>```

ROUTES

```<code>account_index GET    /account(.:format)                                      account#index
                                  POST   /account(.:format)                                      account#create
                      new_account GET    /account/new(.:format)                                  account#new
                     edit_account GET    /account/:id/edit(.:format)                             account#edit
                          account GET    /account/:id(.:format)                                  account#show
                                  PATCH  /account/:id(.:format)                                  account#update
                                  PUT    /account/:id(.:format)                                  account#update
                                  DELETE /account/:id(.:format)                                  account#destroy
</code>```

ROUTES.RB

```<code>resources :account
</code>```

ACCOUNT CONTROLLER:

```<code>class AccountController < ApplicationController
  def new
    @account = Account.new
  end

  def create
    binding.pry
    interactor = CreateAccount.call(
      params: account_params,
      user: current_user
    )

    if interactor.success?
      redirect_to pages_dashboard_path
    else
      render :new
    end
  end

  private

  def account_params
    params.require(:account).permit(:name)
  end
end
</code>```

NEW.HTML.ERB

```<code><div class="plans">
  <h1>New Account Plan</h1>

  <%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
    <div class="plans__trial">
      <h3>Trial</h3>
      <p>1 Worker</p>
      <p>1 Assignment</p>

      <p class="price">Price: Free</p>

      <label>
        <%= form.submit "Select", name: "trial", class: "button" %>
      </label>
    </div>

    <div class="plans__tier-1">
      <h3>Tier 1</h3>
      <p>Unlimited Workers</p>
      <p>Unlimited Assignments</p>

      <p class="price">Price: $9.00</p>

      <label>
        <input type="radio" required  />
        <a href="" class="button">Select</a>
      </label>
    </div>

    <div class="cc-fields">
      <%= render partial: "shared/cc-fields" %>
    </div>
    <%= form.submit name: "tier_1" %>
  <% end %>
</div>
</code>```

What am I doing wrong. Should it hit the create action? It's not currently.

答:
Try change this code in routes.rb

resources :account

to:

resources :accounts

then you can use this code

<%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

Title: No route matches [POST] "/account/new"

Body:
I'm trying to create a new account. but for some reason I'm getting this error when trying to submit the form No route matches [POST] "/account/new". Here is my form_for:

<%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

ROUTES

account_index GET    /account(.:format)                                      account#index
                                  POST   /account(.:format)                                      account#create
                      new_account GET    /account/new(.:format)                                  account#new
                     edit_account GET    /account/:id/edit(.:format)                             account#edit
                          account GET    /account/:id(.:format)                                  account#show
                                  PATCH  /account/:id(.:format)                                  account#update
                                  PUT    /account/:id(.:format)                                  account#update
                                  DELETE /account/:id(.:format)                                  account#destroy

ROUTES.RB

resources :account

ACCOUNT CONTROLLER:

class AccountController < ApplicationController
  def new
    @account = Account.new
  end

  def create
    binding.pry
    interactor = CreateAccount.call(
      params: account_params,
      user: current_user
    )

    if interactor.success?
      redirect_to pages_dashboard_path
    else
      render :new
    end
  end

  private

  def account_params
    params.require(:account).permit(:name)
  end
end

NEW.HTML.ERB

New Account Plan

  <%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

Trial

1 Worker

1 Assignment

Price: Free

        <%= form.submit "Select", name: "trial", class: "button" %>

Tier 1

Unlimited Workers

Unlimited Assignments

Price: $9.00

        <input type="radio" required  />
        Select

      <%= render partial: "shared/cc-fields" %>

    <%= form.submit name: "tier_1" %>
  <% end %>

What am I doing wrong. Should it hit the create action? It's not currently.


问:
How to skip login in cakephp 2.6.7?
I have an old cakephp application which requires login. I was working with the tables in phpmyadmin and I accidentally deleted the user login/password entry from the table. Now I am not able to login in the cakephp application. I tried to create a login entry in the table but I am not sure how to insert a password in it. it is not working with plain text password. I guess, app is looking for encrypted password which I don't know how to add to the table.

Either I need to disable the login from the cakephp application code and direct the user straight to the main page of the app
Or I need to encrypt the password correctly and insert it in the table.

Please help!  I am not sure how to achieve either of these solutions.

答:
Go to your Users Controller and add the actions you need to create and save a new user:

```<code>$this->Auth->allow('display','save');
</code>```

so, you'll be able to anter to that controller actions without any login.

Title: How to skip login in cakephp 2.6.7?

Body:
Go to your Users Controller and add the actions you need to create and save a new user:

$this->Auth->allow('display','save');

so, you'll be able to anter to that controller actions without any login.


问:
ActiveReports always prints last page when NewPage is set to "After"
I have an ActiveReports file with the NewPage property set to "After" in the Detail Section of my report.  Every time I print, I get an extra page at the end of the report.  How can I prevent this from happening?

The only extra page is the last page.  So I'm pretty sure this is not an issue about page margins.

答: I solved this by making heights = 0 on all subsequent sections, including the Report Footer. </p>


问:
Input Validation for Vectors C++
I'm having a problem with the input validation of my do-while loop. My do-while loop only validates every other input

Here's an example:

```<code>Please Enter Grade 1: 101 (It does not accept input)

Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 1: 101 (It accapts this input)

Please Enter Grade 2: 101 (It does not accept input)

Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 2: 101 (It accapts this input)
</code>```

Here's My Code:

```<code>for(vector<double>::size_type i = 0; i < 15; i++)
  {
    do
    {
         cout << "Please Enter Grade "<< i + 1 <<": " << flush;
            cin >> gradesVector[i];
        }
        while(gradesVector[i] < 0.0 && gradesVector[i] > 100.0);
        {
            cout << "Invalid Rage. Please Enter Range 0-100:\n";
                cout << "Please Enter Grade "<< i + 1 <<": " << flush;
                    cin >> gradesVector[i];
         }
}
</code>```

答:
The statement while(gradesVector > 0.0 && gradesVector <= 100.0) is trying to check if the entire vector is greater than 0 or less than 100, which doesn't really make sense.  You want to do something like while(gradesVector[i] > 0.0 && gradesVector[i] <= 100.0) (just make sure i is in the correct scope).

Edit: just get rid of the do-while loop and only use a for-loop.  Inside the for-loop, add an if-statement: if(gradesVector[i] > 0.0 && gradesVector[i] <= 100.0).  If the validation fails, use a break statement to exit the for-loop.

Title: Input Validation for Vectors C++

Body:
I'm having a problem with the input validation of my do-while loop. My do-while loop only validates every other input

Here's an example:

Please Enter Grade 1: 101 (It does not accept input)

Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 1: 101 (It accapts this input)

Please Enter Grade 2: 101 (It does not accept input)

Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 2: 101 (It accapts this input)

Here's My Code:

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    do
    {
         cout << "Please Enter Grade "<< i + 1 <<": " << flush;
            cin >> gradesVector[i];
        }
        while(gradesVector[i] < 0.0 && gradesVector[i] > 100.0);
        {
            cout << "Invalid Rage. Please Enter Range 0-100:\n";
                cout << "Please Enter Grade "<< i + 1 <<": " << flush;
                    cin >> gradesVector[i];
         }
}


问:
How to write to OS system log in Java?
Mac OS has an application called Console, which contains logged messages, errors, and faults. I believe the Windows equivalent is Event Viewer. I'd imagine there is one on Linux as well, but I don't know anything about it or where it is.

Is it possible to get a message from Java output to a system log like this? I'm writing a GUI-based application, so there is nothing running from the command line. The standard System.out or System.err probably won't be of much use in this case, unless I'm missing something.

I have written a simple logging service for my application that writes to a dedicated log file, but I want to have some kind of failsafe in case an I/O error occurs while attempting to write to this file.

I know the IDE will display output via System.out and System.err just fine, but this is for if the end-user encounters a problem like this.

As an example: I've written "codeless language modules" for the application TextWrangler on the Mac. These modules are read by TW at application startup, and if there is an error while processing them, errors get logged and can be viewed in the Mac Console application.

答:
You can redirect System.out to a log file, and Mac's Console app is the default viewer for files ending in ".log".

One way this is commonly done is with a shell script that would invoke your Java program.  In this Java 7 example, the output of invoking the main class MyClass is redirected to mylogfile.log.  Everything that's written with System.out will be in mylogfile.log.

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

for a in /path/to/my/jars/*
do
CLASSPATH=$CLASSPATH:$a
done

java -Xms128M -Xmx128M -XX:MaxPermSize=128M -cp ${CLASSPATH} com.example.package.MyClass >> mylogfile.log
</code>```

Title: How to write to OS system log in Java?

Body:
You can redirect System.out to a log file, and Mac's Console app is the default viewer for files ending in ".log".

One way this is commonly done is with a shell script that would invoke your Java program.  In this Java 7 example, the output of invoking the main class MyClass is redirected to mylogfile.log.  Everything that's written with System.out will be in mylogfile.log.

#!/bin/bash

for a in /path/to/my/jars/*
do
CLASSPATH=$CLASSPATH:$a
done

java -Xms128M -Xmx128M -XX:MaxPermSize=128M -cp ${CLASSPATH} com.example.package.MyClass >> mylogfile.log


问:
std::ofstream, check if file exists before writing
I am implementing file saving functionality within a Qt application using C++.

I am looking for a way to check to see if the selected file already exists before writing to it, so that I can prompt a warning to the user.

I am using an std::ofstream and I am not looking for a Boost solution.

答: Try ::stat() (declared in <sys/stat.h>)

Body: Try ::stat() (declared in <sys/stat.h>)


问:
Is SchemaCrawler broken when using its API?
I am refering the doc in http://sualeh.github.io/SchemaCrawler/how-to.html#api
But I never get what I want. The tables returned is always empty.</p>

```<code>final Connection connection = ... // Get a MYSQL connection;
final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
options.setSchemaInfoLevel(SchemaInfoLevelBuilder.maximum());
options.setTableInclusionRule(new IncludeAll());
options.setTableNamePattern("*");

final Catalog catalog = SchemaCrawlerUtility.getCatalog(connection, options);

for (final Schema schema: catalog.getSchemas())
{
    Collection<Table> tables = catalog.getTables(schema);
    //
    // The size of tables is always 0
    //
    System.out.println(tables);
}
</code>```

答:
You should not set the table name pattern, so please remove the following line:

options.setTableNamePattern("*");

Sualeh Fatehi, SchemaCrawler

Body:
I am refering the doc in http://sualeh.github.io/SchemaCrawler/how-to.html#api
But I never get what I want. The tables returned is always empty.

final Connection connection = ... // Get a MYSQL connection;
final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
options.setSchemaInfoLevel(SchemaInfoLevelBuilder.maximum());
options.setTableInclusionRule(new IncludeAll());
options.setTableNamePattern("*");

final Catalog catalog = SchemaCrawlerUtility.getCatalog(connection, options);

for (final Schema schema: catalog.getSchemas())
{
    Collection
 tables = catalog.getTables(schema);
    //
    // The size of tables is always 0
    //
    System.out.println(tables);
}


问:
Else if statement ending program
I've attempted to write a function yes that confirms if the user wants to exit the program. If the user enters 'Y' or 'y' it exits successfully and if the user enters an invalid input it also exits successfully however, if the user enters 'N' or 'n' it will return them to the menu, but any further input will simply end the program. I've tried a do while loop as well, but was met with similar issues. Here's my code:

```<code>void GroceryInventorySystem(void) {
    int menuSelection;
    int exitSelection;

    welcome();
    printf("\n");

    while (menuSelection != 0)
    {
        menuSelection = menu();
        switch (menuSelection)
    {
        case 1:
        printf("List Items under construction!\n");
        pause();
        break;

        case 2:
        printf("Search Items under construction!\n");
        pause();
        break;

        case 3:
        printf("Checkout Item under construction!\n");
        pause();
        break;

        case 4:
        printf("Stock Item under construction!\n");
        pause();
        break;

        case 5:
        printf("Add/Update Item under construction!\n");
        pause();
        break;

        case 6:
        printf("Delete Item under construction!\n");
        pause();
        break;

        case 7:
        printf("Search by name under construction!\n");
        pause();
        break;

        default:
        printf("Exit the program? (Y)es/(N)o: ");
        exitSelection = yes();
        break;
        }
    }
}

int yes(void) {
        char YN;
        begin:;

        scanf("%c", &YN);
        flushKeyboard();

        if (YN == 'Y' || YN == 'y') {
        }

        else if (YN == 'N' || YN == 'n') {
        menu();
        }

        else {
            printf("Only (Y)es or (N)o are acceptable: ");
            goto begin;
        }
}

int menu(void) {
    int option;
    int firstSelection = 0;
    int lastSelection = 7;
    printf("\n1- List all items\n");
    printf("2- Search by SKU\n");
    printf("3- Checkout an item\n");
    printf("4- Stock an item\n");
    printf("5- Add new item or update item\n");
    printf("6- Delete item\n");
    printf("7- Search by name\n");
    printf("0- Exit program\n");
    printf("> ");
    option = getIntLimited(firstSelection, lastSelection);
    return option;
}
</code>```

I can provide the rest of the code if necessary.

答:
Looking through what your code does, this is what occurs when the program is run and someone selects menu option '0':

menu() returns 0 and is assigned to menuselection

the exit case executes and yes() is run

here the user selects 'N' and menu() is called again

menu() returns whatever option is selected and nothing is done with it

run() reaches end of execution for which behaviour is undefined

while loop ends and executes again with menuselection still 0

When you execute your case for exit, you need to signal to your while loop that the user has changed their mind.

Title: Else if statement ending program

Body:
I've attempted to write a function yes that confirms if the user wants to exit the program. If the user enters 'Y' or 'y' it exits successfully and if the user enters an invalid input it also exits successfully however, if the user enters 'N' or 'n' it will return them to the menu, but any further input will simply end the program. I've tried a do while loop as well, but was met with similar issues. Here's my code:

void GroceryInventorySystem(void) {
    int menuSelection;
    int exitSelection;

    welcome();
    printf("\n");

    while (menuSelection != 0)
    {
        menuSelection = menu();
        switch (menuSelection)
    {
        case 1:
        printf("List Items under construction!\n");
        pause();
        break;

        case 2:
        printf("Search Items under construction!\n");
        pause();
        break;

        case 3:
        printf("Checkout Item under construction!\n");
        pause();
        break;

        case 4:
        printf("Stock Item under construction!\n");
        pause();
        break;

        case 5:
        printf("Add/Update Item under construction!\n");
        pause();
        break;

        case 6:
        printf("Delete Item under construction!\n");
        pause();
        break;

        case 7:
        printf("Search by name under construction!\n");
        pause();
        break;

        default:
        printf("Exit the program? (Y)es/(N)o: ");
        exitSelection = yes();
        break;
        }
    }
}

int yes(void) {
        char YN;
        begin:;

        scanf("%c", &YN);
        flushKeyboard();

        if (YN == 'Y' || YN == 'y') {
        }

        else if (YN == 'N' || YN == 'n') {
        menu();
        }

        else {
            printf("Only (Y)es or (N)o are acceptable: ");
            goto begin;
        }
}

int menu(void) {
    int option;
    int firstSelection = 0;
    int lastSelection = 7;
    printf("\n1- List all items\n");
    printf("2- Search by SKU\n");
    printf("3- Checkout an item\n");
    printf("4- Stock an item\n");
    printf("5- Add new item or update item\n");
    printf("6- Delete item\n");
    printf("7- Search by name\n");
    printf("0- Exit program\n");
    printf("> ");
    option = getIntLimited(firstSelection, lastSelection);
    return option;
}

I can provide the rest of the code if necessary.


问:
Swift playground: get ViewController to call presentViewController
I would like to play with UIAlertController in Playground. Is it possible to get the ViewController from XCPlaygroundPage - to be able to call presentViewController?</p>

答:
You can set the liveView to your Window after presenting, to avoid the warning.

```<code>import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
let window = UIWindow()
let viewController = UIViewController()
window.rootViewController = viewController
window.makeKeyAndVisible()

let alert = UIAlertController(title: "title here", message: "message here", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "action here", style: .default, handler: nil))
viewController.present(alert, animated: true, completion: nil)
PlaygroundPage.current.liveView = window
</code>```

Result:

Body:
You can set the liveView to your Window after presenting, to avoid the warning.

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
let window = UIWindow()
let viewController = UIViewController()
window.rootViewController = viewController
window.makeKeyAndVisible()

let alert = UIAlertController(title: "title here", message: "message here", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "action here", style: .default, handler: nil))
viewController.present(alert, animated: true, completion: nil)
PlaygroundPage.current.liveView = window

Result:


问:
How to call from C# to CEFSharp that run a web page using react
I have created a c# app that embed CEFSharp. From C#, I can call a javascript function using cefsharp.ExecuteScriptAsync.
e.g. in javsscript, I have a function showAlertFromClient(msg)
from c#, I can call this Javascript function using

cefsharp.ExecuteScriptAsync("showAlertFromClient('Hi from C#');");

However, the web page is done using React and I have no idea on how to expose a function in react where I can call it from c#.

e.g. of react, index.js
import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    ReactDOM.render(
        <App/>, document.getElementById('root'));

So do I expose a JS function e.g. showAlertFromClient() in React where I can call if from c#?
Anyone have any idea how to achieve that? Thanks

答:
Create a new.js file and add your method(showAlertFromClient) in this file. Call this function like

```<code>cefsharp.ExecuteScriptAsync("showAlertFromClient('Hi from C#');");
</code>```

Include this file in head of index.html.

inside your method use window.anyname('anything'.):

```<code>showAlertFromClient('Hi from C#'){
   window.updateUi('Hi from C#');
</code>```

}

In component of react.js

```<code>componentWillMount() {
window.updateUi= (data) => {
  this.setState({
    newData: data
  });
}
</code>```

Body:
Create a new.js file and add your method(showAlertFromClient) in this file. Call this function like

cefsharp.ExecuteScriptAsync("showAlertFromClient('Hi from C#');");

Include this file in head of index.html.

inside your method use window.anyname('anything'.):

showAlertFromClient('Hi from C#'){
   window.updateUi('Hi from C#');

}

In component of react.js

componentWillMount() {
window.updateUi= (data) => {
  this.setState({
    newData: data
  });
}


问:
Are there no built in C# GUI Layouts?
I'm used to the GUI frameworks in Java as well as the QT GUI framework, and I'm used to the various layout managers. It doesn't seem that C# has any layout managers built in, or am I missing something?

2 Year Later Edit

I just want to point out to any readers of this question that in hind-sight, my question was misplaced. With proper anchoring and docking of child controls, having a need for the layout managers of Java and QT4 is nearly non-existent.

答:
Both WPF and Windows Forms provide layout capabilities (WPF is just much better at it).

You can achieve moderately complex layouts in Windows Forms too by utilizing the Dock and Anchor properties of controls. Personally I learned what can be achieved and how through Petzold's book on WinForms. If you don't have access to that book, read this short article.

Title: Are there no built in C# GUI Layouts?


问:
Parsing JSON with ruby
I have a probem when I parse file like this all works

{"StumbleUpon":0,"Reddit":0,"Facebook":{"total_count":19227,"comment_count":0,"share_count":19227},"LinkedIn":27}

my code:

```<code>module SocialShares
  class Sharedcount < Base
    def shares!
      response = RestClient.get(url)
      JSON.parse(response)['Facebook']["share_count"] || 0
    end

  private

    def url
      "https://free.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.secrets.socialshared_api_key}"
    end
  end
end
</code>```

And when I parse this i have error TypeError: no implicit conversion of String into Integer

file:
{"StumbleUpon":0,"Reddit":0,"Facebook":0,"LinkedIn":0}

答:
That second structure doesn't have the necessary structure to navigate it that way. You need to approach this more cautiously:

```<code>def shares!
  response = RestClient.get(url)

  data = JSON.parse(response)

  data['Facebook'].is_a?(Hash) && data['Facebook']["share_count"] || 0
end
</code>```

You can also do this in Ruby 2.4 or later:

```<code>  data.dig('Facebook', 'share_count').to_i
</code>```

Title: Parsing JSON with ruby

Body:
I have a probem when I parse file like this all works

{"StumbleUpon":0,"Reddit":0,"Facebook":{"total_count":19227,"comment_count":0,"share_count":19227},"LinkedIn":27}

my code:

module SocialShares
  class Sharedcount < Base
    def shares!
      response = RestClient.get(url)
      JSON.parse(response)['Facebook']["share_count"] || 0
    end

  private

    def url
      "https://free.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.secrets.socialshared_api_key}"
    end
  end
end

And when I parse this i have error TypeError: no implicit conversion of String into Integer

file:
{"StumbleUpon":0,"Reddit":0,"Facebook":0,"LinkedIn":0}

Body:
That second structure doesn't have the necessary structure to navigate it that way. You need to approach this more cautiously:

def shares!
  response = RestClient.get(url)

  data = JSON.parse(response)

  data['Facebook'].is_a?(Hash) && data['Facebook']["share_count"] || 0
end

You can also do this in Ruby 2.4 or later:

  data.dig('Facebook', 'share_count').to_i


问:
Change keyboard shortcut to "Run Script" in Atom IDE
In the "Script" package, The keyboard shortcut to "Run Script" is shift+ctrl+b.
Does anyone know how to change this to a custom shortcut?

I have script 3.14.1 installed in Atom (with Windows 10 64bit)

答:
go to "Settings", "Packages", find the "script" package and click "Settings".

at the top, select "View Code" button.

In the new window that pops up, expand the "keymaps" folder and open the "script.cson" file.

Find the shortcut for 'script:run' (line 15) and type in your preferred shortcut.

Save the file.

That's it!


问:
Use of " for(string str: tmp) " in c++?
I came accross this for(string str: tmp) s.insert(str) in a C++ code for LCS and I don't know what it means. I saw it used in Java. Can it be written in any other way in C++?

答:
This is know as a for-each. It'll iterate over the different elements of a data structure (for instance, a list, a vector, a set, ...), allowing you to perform some operations on each elements. If you want to use it in c++ you will have to use c++11, but you can reach a similar behavior with an iterator based for loop.

Going with your for (string str : tmp) s.insert(str), here is a small description of each parts of the expression. tmp is the data structure over which you want to iterate. string str is the declaration that will be called for each elements in the data structure. The type declared should reflect what is in the data structure. This str variable will give you access to the data structure's item in the loop's "body". The last part of the expression s.insert(str) is the loop's "body" as in any regular for loop, but the coder chose to put it on the same line as the for.

In short, that loop inserts all the strings contained in tmp inside an object s with an insert method, probably another data structure.

Title: Use of " for(string str: tmp) " in c++?


问:
create child using mkdir with variable
I have the path /home/folder/test set as variable $1

I want to make a directory using mkdir, I think, that will be in a new folder but has the same name as the last child folder.  So for example I want to make a folder called /home/folder2/test.

Is this something that I should be using xargs for?  I'm not too experience with shell commands, so I'm pretty confused how to get this done.

答:
Assuming a UNIX-like operating system, if you have a string /home/folder/test and you want the last part of it, you can simply use basename to get that:

```<code>pax> str="/home/folder/test"
pax> base="$(basename $str)"
pax> echo "${base}"
test
</code>```

Once you have that, you can use it to make another directory:

```<code>pax> mkdir -p "/home/folder2/${base}"
pax> ls -al "/home/folder2/test"
total 0
drwxr-xr-x 2 pax pax  6 Apr  2 04:19 .
drwxrwxrwx 1 pax pax 49 Apr  2 04:19 ..
</code>```

Title: create child using mkdir with variable

Body:
Assuming a UNIX-like operating system, if you have a string /home/folder/test and you want the last part of it, you can simply use basename to get that:

pax> str="/home/folder/test"
pax> base="$(basename $str)"
pax> echo "${base}"
test

Once you have that, you can use it to make another directory:

pax> mkdir -p "/home/folder2/${base}"
pax> ls -al "/home/folder2/test"
total 0
drwxr-xr-x 2 pax pax  6 Apr  2 04:19 .
drwxrwxrwx 1 pax pax 49 Apr  2 04:19 ..


问:
Windows Home Server backup solution
I admit this is not strictly a programming question, although I do use my WHS as a source repository server for home projects, and I'm guessing many other coders here do as well.

Does anyone have a recommendation for a good backup solution for the non-fileshare portion of Windows Home Server?  All the WHS backups I've seen handle the fileshares, but none of the system files or other administrative stuff on the box.

Thanks,
  Andy

答: iDrive is Great and free under 2 gigs </p>

OwnerDisplayName: AndrewCr

Title: Windows Home Server backup solution

Body: iDrive is Great and free under 2 gigs

OwnerDisplayName: Chris


答:
Try this:

```<code>int main() {
   vector<double> gradesVector(15);
   for(vector<double>::size_type i = 0; i < 15; i++) {
       do {
            cout << "Please Enter Grade "<< i + 1 <<": " << flush;
            cin >> gradesVector[i];
       } while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
   }
}
</code>```

Title: Input Validation for Vectors C++

Body:
Try this:

int main() {
   vector<double> gradesVector(15);
   for(vector<double>::size_type i = 0; i < 15; i++) {
       do {
            cout << "Please Enter Grade "<< i + 1 <<": " << flush;
            cin >> gradesVector[i];
       } while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
   }
}


问:
Authorize 3rd Party App to Access User Data from Laravel App
I want to allow third party apps to access user data from my laravel application. But I am bit confuse how this process actually work.

I have installed laravel passport and its working fine. So what I am trying to do is:
3rd party app which has a unique client_id and secret can access any user data if user authenticate using his username and password.

I have used passport for user authentication for mobile devices. But accessing other user data, I am not sure if its possible with passport or not.

答:
Have a read through issuing access tokens: https://laravel.com/docs/5.4/passport#issuing-access-tokens. They give you in details all you need to get going. Though you will have to develop your own interface to allow your users to manage the clients they gave access to.

Once user gives access to  a 3rd party, they will then have access to that user's data because they will be part of the user's clients.

You should also watch this laracast https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/13


问:
Do I need Indicators for Regression with Categorical Variables?
It is always said that we need to create predictor variables for categorical values in order to the regression. I made a test, by creating first a predictor column of 1, 2, 3s for a five-layered categorical variable. Then, I ran the same model, without the predictor column, but with the categorical column itself.

In conclusion, the coefficients are different; however, their relative importance and effect on the y-value are the same. Moreover R-squared and p-value numbers are exactly the same in these two cases. So, do I have to create the predictor variable, or is R smart enough to do it automatically?

```<code>for(i in 1:74)
{
  if(travel$accommodation[i] == "Hotel")
  {
    travel$pred_hotel[i] <- 1
  }

  if(travel$accommodation[i] == "Airbnb")
  {
    travel$pred_hotel[i] <- 2
  }

  if(travel$accommodation[i] == "Hostel")
  {
    travel$pred_hotel[i] <- 3
  }

  if(travel$accommodation[i] == "With friend/family")
  {
    travel$pred_hotel[i] <- 4
  }

  if(travel$accommodation[i] == "Other")
  {
    travel$pred_hotel[i] <- 5
  }
}

travel$pred_hotel <- as.factor(travel$pred_hotel)
</code>```

Then:

```<code>msf <- lm(ticket_events_money ~ museum_fee + nationality +
    ticket_events_frequency + accommodation + line + activity_1 +
    locals + vacation_days, data = travel[-1, ])

mm <- lm(ticket_events_money ~ museum_fee + nationality +
    ticket_events_frequency + pred_hotel + line + activity_1 +
    locals + vacation_days, data = travel[-1, ])

summary(msf)
summary(mm)
</code>```

答:
The problem is, you originally have a character column accommodation. Your new variable pred_hotel is a factor. Function lm automatically converts character covariate into factor. In your test, the only difference will be in factor levels; all the rest is the same. If you want to see difference, remove the as.factor line.

Another common failure is as in the following minimal, reproducible example.

```<code>dat <- data.frame(y = rnorm(20), x = rep(letters[1:2], 10), stringsAsFactors = FALSE)
m1 <- lm(y ~ x, dat)

dat$x[dat$x == 'a'] <- 1
dat$x[dat$x == 'b'] <- 2
class(dat$x)    # still a character column!!
m2 <- lm(y ~ x, dat)
</code>```

But you will see difference, if you use real numeric:

```<code>dat$x <- as.numeric(dat$x)
m3 <- lm(y ~ x, dat)
</code>```

Body:
It is always said that we need to create predictor variables for categorical values in order to the regression. I made a test, by creating first a predictor column of 1, 2, 3s for a five-layered categorical variable. Then, I ran the same model, without the predictor column, but with the categorical column itself.

In conclusion, the coefficients are different; however, their relative importance and effect on the y-value are the same. Moreover R-squared and p-value numbers are exactly the same in these two cases. So, do I have to create the predictor variable, or is R smart enough to do it automatically?

for(i in 1:74)
{
  if(travel$accommodation[i] == "Hotel")
  {
    travel$pred_hotel[i] <- 1
  }

  if(travel$accommodation[i] == "Airbnb")
  {
    travel$pred_hotel[i] <- 2
  }

  if(travel$accommodation[i] == "Hostel")
  {
    travel$pred_hotel[i] <- 3
  }

  if(travel$accommodation[i] == "With friend/family")
  {
    travel$pred_hotel[i] <- 4
  }

  if(travel$accommodation[i] == "Other")
  {
    travel$pred_hotel[i] <- 5
  }
}

travel$pred_hotel <- as.factor(travel$pred_hotel)

Then:

msf <- lm(ticket_events_money ~ museum_fee + nationality +
    ticket_events_frequency + accommodation + line + activity_1 +
    locals + vacation_days, data = travel[-1, ])

mm <- lm(ticket_events_money ~ museum_fee + nationality +
    ticket_events_frequency + pred_hotel + line + activity_1 +
    locals + vacation_days, data = travel[-1, ])

summary(msf)
summary(mm)

Body:
The problem is, you originally have a character column accommodation. Your new variable pred_hotel is a factor. Function lm automatically converts character covariate into factor. In your test, the only difference will be in factor levels; all the rest is the same. If you want to see difference, remove the as.factor line.

Another common failure is as in the following minimal, reproducible example.

dat <- data.frame(y = rnorm(20), x = rep(letters[1:2], 10), stringsAsFactors = FALSE)
m1 <- lm(y ~ x, dat)

dat$x[dat$x == 'a'] <- 1
dat$x[dat$x == 'b'] <- 2
class(dat$x)    # still a character column!!
m2 <- lm(y ~ x, dat)

But you will see difference, if you use real numeric:

dat$x <- as.numeric(dat$x)
m3 <- lm(y ~ x, dat)


问:
Kohana v3 routes - multiple optional parameters
I'm setting up a search system which has urls eg. all parameters are optional and there are 15 possible params in total

```<code>http://example.com/search/key1-value/key2-value/key3-value/key13-value/key15-value
</code>```

Is there a better way to set up the route than this?

```<code>Route::set('search', 'search(/<param1>(/<param2>(/<param3>(/<param4>(/<param5>(/<param6>(/<param7>(/<param8>(/<param9>(/<param10>(/<param11>(/<param12>(/<param13>(/<param14>(/<param15>)))))))))))))))')
        ->defaults(array(
        'controller' => 'search',
        'action'     => 'index',
));
</code>```

I would then test for them in the controller and parse them to a neat array.  Is there any way to specify a route with any number of optional /key-value/ parameters?

EDIT

I noticed the request object has a nice parameter array already -- this leads me back to the Route::set question.. is there a way to phrase it allowing any number of parameters without the ugly ...(/<param14>(/<param15>))))))))... nesting?

答:
```<code>Route::set('search', 'search(/<params>/)',array('params'=>'\.*'))
        ->defaults(array(
        'controller' => 'search',
        'action'     => 'index',
));
</code>```

tried?

Body:
I'm setting up a search system which has urls eg. all parameters are optional and there are 15 possible params in total

http://example.com/search/key1-value/key2-value/key3-value/key13-value/key15-value

Is there a better way to set up the route than this?

Route::set('search', 'search(/<param1>(/<param2>(/<param3>(/<param4>(/<param5>(/<param6>(/<param7>(/<param8>(/<param9>(/<param10>(/<param11>(/<param12>(/<param13>(/<param14>(/<param15>)))))))))))))))')
        ->defaults(array(
        'controller' => 'search',
        'action'     => 'index',
));

I would then test for them in the controller and parse them to a neat array.  Is there any way to specify a route with any number of optional /key-value/ parameters?

EDIT

I noticed the request object has a nice parameter array already -- this leads me back to the Route::set question.. is there a way to phrase it allowing any number of parameters without the ugly ...(/<param14>(/<param15>))))))))... nesting?

Body:
Route::set('search', 'search(/<params>/)',array('params'=>'\.*'))
        ->defaults(array(
        'controller' => 'search',
        'action'     => 'index',
));

tried?


问:
Linked list - insert
I am trying to insert elements of a file in a linked list, I used two functions, one that loads and which inserts, the function loads is running, apparently, in the correct way, however the function insert is initiating the implementation and does not end, testing i noticed that she manages to enter the first 3 lines of the file, but does not complete correctly the insertion, as the code is long, it follows, that part of it problems:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define RECS_PATIO 2

struct Rec_Emp {
    char nome_rec[10];
    int uso_rec;
    int taxa_rec;
/*    struct Rec_Emp *prox; */
};

typedef struct Rec_Emp recuperadora;

struct Patio {
    char iden_patio;
    int capacidade;
    struct Patio *prox;
    struct Rec_Emp *lista[RECS_PATIO];
};

typedef struct Patio patio;

void insere_patio (patio *cabeca, patio *novo) {
    patio *p = cabeca;

    while (p->prox != NULL)
        p = p->prox;
    novo->prox = p->prox;
    p->prox = novo;

}

void carrega_patio (patio *pa, patio p, recuperadora r1, recuperadora r2) {
    patio *pt = pa;
    FILE *f;

    f = fopen ("portorec.txt", "rt");

    if (f == NULL) {
        printf ("Problema na abertura do arquivo");
        return;
    }

    while (!feof(f)) {
        fscanf (f, "%d %c %s %s %d %d %d %d", &p.capacidade, &p.iden_patio, r1.nome_rec, r2.nome_rec, &r1.uso_rec, &r2.uso_rec, &r1.taxa_rec, &r2.taxa_rec);

        p.lista[0] = &r1;
        p.lista[1] = &r2;
        insere_patio(pt, &p);

    }
    fclose(f);
}

int main {

patio *PT;
    PT = malloc(sizeof(patio));
    PT->prox = NULL;
    patio pat;
    recuperadora rec1, rec2;
    carrega_patio(PT, pat, rec1, rec2);
}
</code>```

File

```<code>600000 A REC01 - 0 -1 6000 -1
600000 B REC01 REC03 0 0 6000 8000
600000 C REC02 REC03 0 0 6000 8000
600000 D REC02 - 0 -1 6000 -1
2400000 E ER01 ER02 0 0 8000 8000
2400000 F REC04 ER01 0 0 8000 8000
2400000 G REC04 - 0 -1 8000 -1
2400000 H REC05 - 0 -1 8000 -1
2400000 I REC05 - 0 -1 8000 -1
2400000 J  ER02 - 0 -1 8000 -1
</code>```

答:
In main, you declare patio pat as an automatic variable (allocated on the stack). Automatic variables are not initialized by default, so you are getting whatever random garbage happens to be on the stack as the value for pat.prox. I expect your list insert is chasing random garbage pointers throughout memory, looking for p->prox == NULL.

In addition, you are not dynamically allocating your memory in carrega_patio. The parameters patio p, recuperadora r1, recuperadora r2 are all structures, but those structures are going to be reused every time through your loop.

Imagine filling out a paper form with 1 line of this data. And then starting from the top of the same paper form and filling out the exact same form with a different line of this data. And then again, and again.

Because you are not separately allocating memory, you can't create a list. You need to call malloc() or calloc() to allocate a "new piece of paper" for each record.

Try something like this (note: not tested):
    #include
    #include

```<code>typedef const char * FILESPEC;

typedef struct rec_emp {
    #define RE_NOME_DIM 10

    int      re_taxa;
    int      re_uso;
    char     re_nome[RE_NOME_DIM];
} REC_EMP;

typedef struct patio {
    #define PA_LISTA_DIM 2

    struct patio *pa_prox;
    int     pa_capacidade;
    char    pa_iden;
    REC_EMP pa_lista[PA_LISTA_DIM];   /* NOTE: structs, NOT pointers */

    #define pare(pa,n) ((pa)->pa_lista[(n)])
} PATIO;

PATIO *
patio_novinho()
{
    PATIO * p = calloc(1, sizeof (PATIO));
    return p;
}

void
patio_insere(cabeca, novo)
    PATIO * cabeca;
    PATIO * novo;
{
    while (cabeca->pa_prox) {
        cabeca = cabeca->pa_prox;
    }
    novo->pa_prox = cabeca->pa_prox;
    cabeca->pa_prox = novo;
}

void
patio_carrega(cabeca, arquivo)
    PATIO * cabeca;
    FILESPEC arquivo;
{
    FILE *fp = fopen(arquivo, "rt");

    if (fp == NULL) {
        perror("patio_carrega: Problema na abertura do arquivo");
        exit(1);
    }

    while (!feof(fp) && !ferror(fp)) {

        PATIO * pa = patio_novinho();

        fscanf(fp, "%d %c %s %s %d %d %d %d",
            &pa->pa_capacidade,
            &pa->pa_iden,
            pare(pa,0).re_nome,
            pare(pa,1).re_nome,
            &(pare(pa,0).re_uso),
            &(pare(pa,1).re_uso),
            &(pare(pa,0).re_taxa),
            &(pare(pa,1).re_taxa)
        );

        patio_insere(cabeca, pa);

    }

    fclose(fp);
}

int
main()
{
    PATIO * cabeca = patio_novinho();
    patio_carrega(cabeca, "portorec.txt");

    /* more stuff here */
    exit(0);
}
</code>```

Title: Linked list - insert

Body:
I am trying to insert elements of a file in a linked list, I used two functions, one that loads and which inserts, the function loads is running, apparently, in the correct way, however the function insert is initiating the implementation and does not end, testing i noticed that she manages to enter the first 3 lines of the file, but does not complete correctly the insertion, as the code is long, it follows, that part of it problems:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define RECS_PATIO 2

struct Rec_Emp {
    char nome_rec[10];
    int uso_rec;
    int taxa_rec;
/*    struct Rec_Emp *prox; */
};

typedef struct Rec_Emp recuperadora;

struct Patio {
    char iden_patio;
    int capacidade;
    struct Patio *prox;
    struct Rec_Emp *lista[RECS_PATIO];
};

typedef struct Patio patio;

void insere_patio (patio *cabeca, patio *novo) {
    patio *p = cabeca;

    while (p->prox != NULL)
        p = p->prox;
    novo->prox = p->prox;
    p->prox = novo;

}

void carrega_patio (patio *pa, patio p, recuperadora r1, recuperadora r2) {
    patio *pt = pa;
    FILE *f;

    f = fopen ("portorec.txt", "rt");

    if (f == NULL) {
        printf ("Problema na abertura do arquivo");
        return;
    }

    while (!feof(f)) {
        fscanf (f, "%d %c %s %s %d %d %d %d", &p.capacidade, &p.iden_patio, r1.nome_rec, r2.nome_rec, &r1.uso_rec, &r2.uso_rec, &r1.taxa_rec, &r2.taxa_rec);

        p.lista[0] = &r1;
        p.lista[1] = &r2;
        insere_patio(pt, &p);

    }
    fclose(f);
}

int main {

patio *PT;
    PT = malloc(sizeof(patio));
    PT->prox = NULL;
    patio pat;
    recuperadora rec1, rec2;
    carrega_patio(PT, pat, rec1, rec2);
}

File

600000 A REC01 - 0 -1 6000 -1
600000 B REC01 REC03 0 0 6000 8000
600000 C REC02 REC03 0 0 6000 8000
600000 D REC02 - 0 -1 6000 -1
2400000 E ER01 ER02 0 0 8000 8000
2400000 F REC04 ER01 0 0 8000 8000
2400000 G REC04 - 0 -1 8000 -1
2400000 H REC05 - 0 -1 8000 -1
2400000 I REC05 - 0 -1 8000 -1
2400000 J  ER02 - 0 -1 8000 -1

Body:
In main, you declare patio pat as an automatic variable (allocated on the stack). Automatic variables are not initialized by default, so you are getting whatever random garbage happens to be on the stack as the value for pat.prox. I expect your list insert is chasing random garbage pointers throughout memory, looking for p->prox == NULL.

In addition, you are not dynamically allocating your memory in carrega_patio. The parameters patio p, recuperadora r1, recuperadora r2 are all structures, but those structures are going to be reused every time through your loop.

Imagine filling out a paper form with 1 line of this data. And then starting from the top of the same paper form and filling out the exact same form with a different line of this data. And then again, and again.

Because you are not separately allocating memory, you can't create a list. You need to call malloc() or calloc() to allocate a "new piece of paper" for each record.

Try something like this (note: not tested):
    #include
    #include

typedef const char * FILESPEC;

typedef struct rec_emp {
    #define RE_NOME_DIM 10

    int      re_taxa;
    int      re_uso;
    char     re_nome[RE_NOME_DIM];
} REC_EMP;

typedef struct patio {
    #define PA_LISTA_DIM 2

    struct patio *pa_prox;
    int     pa_capacidade;
    char    pa_iden;
    REC_EMP pa_lista[PA_LISTA_DIM];   /* NOTE: structs, NOT pointers */

    #define pare(pa,n) ((pa)->pa_lista[(n)])
} PATIO;

PATIO *
patio_novinho()
{
    PATIO * p = calloc(1, sizeof (PATIO));
    return p;
}

void
patio_insere(cabeca, novo)
    PATIO * cabeca;
    PATIO * novo;
{
    while (cabeca->pa_prox) {
        cabeca = cabeca->pa_prox;
    }
    novo->pa_prox = cabeca->pa_prox;
    cabeca->pa_prox = novo;
}

void
patio_carrega(cabeca, arquivo)
    PATIO * cabeca;
    FILESPEC arquivo;
{
    FILE *fp = fopen(arquivo, "rt");

    if (fp == NULL) {
        perror("patio_carrega: Problema na abertura do arquivo");
        exit(1);
    }

    while (!feof(fp) && !ferror(fp)) {

        PATIO * pa = patio_novinho();

        fscanf(fp, "%d %c %s %s %d %d %d %d",
            &pa->pa_capacidade,
            &pa->pa_iden,
            pare(pa,0).re_nome,
            pare(pa,1).re_nome,
            &(pare(pa,0).re_uso),
            &(pare(pa,1).re_uso),
            &(pare(pa,0).re_taxa),
            &(pare(pa,1).re_taxa)
        );

        patio_insere(cabeca, pa);

    }

    fclose(fp);
}

int
main()
{
    PATIO * cabeca = patio_novinho();
    patio_carrega(cabeca, "portorec.txt");

    /* more stuff here */
    exit(0);
}


问:
PHP show return from python script
I am unable to get php to show full results of my python script, only the last basic print statement is printed. What am I doing wrong here? Why is the php not showing the output from the python script?

php

```<code>$result = exec('python list.py');
echo $result;
</code>```

list.py

```<code>import subprocess

print "start"

a = subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
a.wait()
result_str = a.stdout.read()
print result_str

print "stop"
</code>```

the command line output for that python script is as below

```<code>start
...filename
...filename
...etc...etc

stop
</code>```

The php output from executing the python script is only

stop

Thank you

答:
exec will always return the last line from the result of the command. So, if you need to get every line of output from the command executed. Then, you need to write as below :

```<code>$result = exec('python list.py', $ouput);
print_r($output)
</code>```

As per exec documentation

```<code>string exec ( string $command [, array &$output [, int &$return_var ]] )
</code>```

If the output argument is present, then the specified array will be
  filled with every line of output from the command. Trailing
  whitespace, such as \n, is not included in this array. Note that if
  the array already contains some elements, exec() will append to the
  end of the array. If you do not want the function to append elements,
  call unset() on the array before passing it to exec().

Title: PHP show return from python script

Body:
I am unable to get php to show full results of my python script, only the last basic print statement is printed. What am I doing wrong here? Why is the php not showing the output from the python script?

php

$result = exec('python list.py');
echo $result;

list.py

import subprocess

print "start"

a = subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
a.wait()
result_str = a.stdout.read()
print result_str

print "stop"

the command line output for that python script is as below

start
...filename
...filename
...etc...etc

stop

The php output from executing the python script is only

stop

Thank you

Body:
exec will always return the last line from the result of the command. So, if you need to get every line of output from the command executed. Then, you need to write as below :

$result = exec('python list.py', $ouput);
print_r($output)

As per exec documentation

string exec ( string $command [, array &$output [, int &$return_var ]] )

If the output argument is present, then the specified array will be
  filled with every line of output from the command. Trailing
  whitespace, such as \n, is not included in this array. Note that if
  the array already contains some elements, exec() will append to the
  end of the array. If you do not want the function to append elements,
  call unset() on the array before passing it to exec().


问:
Make image fill div completely without stretching
I have large images of varying dimensions that need to completely fill 240px by 300px containers in both dimensions. Here is what I got right now, which only works for one dimension:

http://jsfiddle.net/HsE6H/

HTML

```<code><div class="container">
    <img src="http://placehold.it/300x1500">
</div>
<div class="container">
    <img src="http://placehold.it/1500x300">
</div
</code>```

CSS

```<code>.container {
height: 300px;
width: 240px;
background-color: red;
float: left;
overflow: hidden;
margin: 20px;
}

img {
max-width: 100%;
height: auto;
}
</code>```

The proportions should stay the same. Essentially, wide images should be cut off in width, while high images need to be cut off in height. So just zooming in as much as is needed to fill the container.

Not sure why I can't get it to work, do I need JavaScript for this?

Edit: To be clear. I need everything red on the fiddle gone. The images coming in are dynamic, therefore I can't use background-images. I'm open to using JavaScript. Thanks! :)

答:
The following solution is very short and clean if you need to insert img tag into div tag:

.container, .container img
{
 max-height: 300px;
 max-width: 240px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Try to open every image into another page you will notice that originals are all different sized but none is streched, just zoomed:
<p></p>

<div class="container"><img src="https://www.gentoo.org/assets/img/screenshots/surface.png" /></div>
<p></p>
<div class="container"><img src="https://cdn.pixabay.com/photo/2011/03/22/22/25/winter-5701_960_720.jpg" /></div>
<p></p>
<div class="container"><img src="https://cdn.arstechnica.net/wp-content/uploads/2009/11/Screenshot-gnome-shell-overview.png" /></div>
<p></p>
<div class="container"><img src="http://i.imgur.com/OwFSTIw.png" /></div>
<p></p>
<div class="container"><img src="https://www.gentoo.org/assets/img/screenshots/surface.png" /></div>
<p></p>
<div class="container"><img src="https://freebsd.kde.org/img/screenshots/uk_maximignatenko_kde420-1.png" /></div>
<p></p>
<div class="container"><img src="https://i.ytimg.com/vi/9mrOgkYje0s/maxresdefault.jpg" /></div>
<p></p>
<div class="container"><img src="https://upload.wikimedia.org/wikipedia/commons/5/59/Linux_screenshot.jpg" /></div>
<p></p></code>```

Also, if you don't need to use a div you can just write an even shorter css:

```<code> img
    {
        max-height: 300px;
        max-width: 240px;
    }
</code>```

Body:
I have large images of varying dimensions that need to completely fill 240px by 300px containers in both dimensions. Here is what I got right now, which only works for one dimension:

http://jsfiddle.net/HsE6H/

HTML

</div

CSS

.container {
height: 300px;
width: 240px;
background-color: red;
float: left;
overflow: hidden;
margin: 20px;
}

img {
max-width: 100%;
height: auto;
}

The proportions should stay the same. Essentially, wide images should be cut off in width, while high images need to be cut off in height. So just zooming in as much as is needed to fill the container.

Not sure why I can't get it to work, do I need JavaScript for this?

Edit: To be clear. I need everything red on the fiddle gone. The images coming in are dynamic, therefore I can't use background-images. I'm open to using JavaScript. Thanks! :)

Body:
The following solution is very short and clean if you need to insert img tag into div tag:

.container, .container img
{
 max-height: 300px;
 max-width: 240px;
}

Try to open every image into another page you will notice that originals are all different sized but none is streched, just zoomed:
<p></p>

<div class="container"><img src="https://www.gentoo.org/assets/img/screenshots/surface.png" /></div>
<p></p>
<div class="container"><img src="https://cdn.pixabay.com/photo/2011/03/22/22/25/winter-5701_960_720.jpg" /></div>
<p></p>
<div class="container"><img src="https://cdn.arstechnica.net/wp-content/uploads/2009/11/Screenshot-gnome-shell-overview.png" /></div>
<p></p>
<div class="container"><img src="http://i.imgur.com/OwFSTIw.png" /></div>
<p></p>
<div class="container"><img src="https://www.gentoo.org/assets/img/screenshots/surface.png" /></div>
<p></p>
<div class="container"><img src="https://freebsd.kde.org/img/screenshots/uk_maximignatenko_kde420-1.png" /></div>
<p></p>
<div class="container"><img src="https://i.ytimg.com/vi/9mrOgkYje0s/maxresdefault.jpg" /></div>
<p></p>
<div class="container"><img src="https://upload.wikimedia.org/wikipedia/commons/5/59/Linux_screenshot.jpg" /></div>
<p></p>

Also, if you don't need to use a div you can just write an even shorter css:

 img
    {
        max-height: 300px;
        max-width: 240px;
    }


问:
Printing sorted dictionary keys along with sorted values
I am sorting a dictionary based on a particular value which is 3rd element on the list(in values) by using:

```<code>print sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]
</code>```

How can I also display the keys to which those sorted values correspond to ?

Thank you for looking.

答:
Use items instead of keys:

```<code>print(sorted(dict.items(), key=lambda item: item[1][2], reverse=True)[:3])
</code>```

or save sorted keys, and use that to get items:

```<code>keys = sorted(dict, key=lambda key: dict[k][2], reverse=True)[:3]
items = [(key, dict[key]) for key in keys]
print(items)
</code>```

if you want values seaparately:

```<code>keys = sorted(dict, key=lambda k: dict[k][2], reverse=True)[:3]
values = [dict[key] for key in keys]
</code>```

BTW, don't use dict as a variable name; it shadows built-in function/type dict.

Body:
I am sorting a dictionary based on a particular value which is 3rd element on the list(in values) by using:

print sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]

How can I also display the keys to which those sorted values correspond to ?

Thank you for looking.

Body:
Use items instead of keys:

print(sorted(dict.items(), key=lambda item: item[1][2], reverse=True)[:3])

or save sorted keys, and use that to get items:

keys = sorted(dict, key=lambda key: dict[k][2], reverse=True)[:3]
items = [(key, dict[key]) for key in keys]
print(items)

if you want values seaparately:

keys = sorted(dict, key=lambda k: dict[k][2], reverse=True)[:3]
values = [dict[key] for key in keys]

BTW, don't use dict as a variable name; it shadows built-in function/type dict.


问:
Giraph, Hadoop, Spark and Cassandra
Is it possible for me to use Giraph if I have Spark clusters and Cassandra but no Hadoop clusters?

Currently, I am using GraphX and would like to use Giraph instead. Is this possible considering that I have Spark clusters and am using Cassandra?

答:
I have only limited experience with Giraph from years ago, and I never tried using it outside of a Hadoop cluster. But it looks like what you want is at least technically possible if not necessarily easy.

This code is the companion to Practical Graph Analytics with Apache Giraph. As you can see, it requires Hadoop in the classpath for DoubleWritable and Text, for example, but it does nothing with a Hadoop cluster. Instead, it works with in-memory arrays. It looks like all you need to do is implement compute in the BasicComputation class to do whatever you need with Cassandra as long as you keep Hadoop around as a dependency to help satisfy the type boundaries for BasicComputation.

I never found Giraph terribly intuitive, but hopefully you can make this unconventional setup work.

Title: Giraph, Hadoop, Spark and Cassandra