问:
SQL rules being ignored
I have two tables on a SQL database:

MODEL (ID_MODEL, MODEL, ID_manu, ID_CLASS) and CLASS ( ID_CLASS, CLASS)

They are linked using the ID_CLASS.

The query to delete information has a none rule, so it's supposed to give an error when I try to delete a row from CLASS, if the ID_CLASS is being used on the MODEL table.

But it's being ignored. It's deleting the CLASS from the CLASS table and the row on the MODEL table is removed from the DataGridView, but it's kept on the table.

The ID_CLASS options on MODELis a NOT NULL as you can see below:

```<code>CREATE TABLE [dbo].[MODEL] (
    [ID_MODEL] INT          IDENTITY (1, 1) NOT NULL,
    [MODEL]    VARCHAR (50) NOT NULL,
    [ID_manu]  INT          NOT NULL,
    [ID_CLASS] INT          NOT NULL,
    PRIMARY KEY CLUSTERED ([ID_MODEL] ASC),
    UNIQUE NONCLUSTERED ([MODEL] ASC)
);
</code>```

Even after deleting and recreating the relationship its still happening.

Also there are two other tables with a similar configuration (same rule and data type) and on that it's working as expected. It retrieves an error every time the delete query is run.

答:
You have to add foreign key on dbo.Model:</p>

```<code>alter table dbo.Model
add constraint FK_Model_Class foreign key (ID_Class) references dbo.Class(ID_Class);
</code>```

Title: SQL rules being ignored

Body:
I have two tables on a SQL database:

MODEL (ID_MODEL, MODEL, ID_manu, ID_CLASS) and CLASS ( ID_CLASS, CLASS)

They are linked using the ID_CLASS.

The query to delete information has a none rule, so it's supposed to give an error when I try to delete a row from CLASS, if the ID_CLASS is being used on the MODEL table.

But it's being ignored. It's deleting the CLASS from the CLASS table and the row on the MODEL table is removed from the DataGridView, but it's kept on the table.

The ID_CLASS options on MODELis a NOT NULL as you can see below:

CREATE TABLE [dbo].[MODEL] (
    [ID_MODEL] INT          IDENTITY (1, 1) NOT NULL,
    [MODEL]    VARCHAR (50) NOT NULL,
    [ID_manu]  INT          NOT NULL,
    [ID_CLASS] INT          NOT NULL,
    PRIMARY KEY CLUSTERED ([ID_MODEL] ASC),
    UNIQUE NONCLUSTERED ([MODEL] ASC)
);

Even after deleting and recreating the relationship its still happening.

Also there are two other tables with a similar configuration (same rule and data type) and on that it's working as expected. It retrieves an error every time the delete query is run.

Body:
You have to add foreign key on dbo.Model:

alter table dbo.Model
add constraint FK_Model_Class foreign key (ID_Class) references dbo.Class(ID_Class);


来源: stackexchange

问:
Design a data structure that use hash and support compare
I am looking for help with designing an algorithm that supports:

initiation(M) Given Set of M unique natural number initialize the data
  structure in O(f(n)) f is some polynomial function
   lookUP(x) given a natural number find if x in S
  in O(1). find Kth(k) return the kth largest number in S in O(1).

the question seemed to me quite easy when I tried to use hash to support O(1) operations, but then I recalled that hash tables does not support compare between elements, I know i can sort the array in O(n^2) and i finish.

Is there a much quicker solution for f(n) as polynomial O(f(n)) init?

答:
I know i can sort the array in O(n^2) and i finish.

Sorting can be done faster, in O(nlogn), where n is the size of your problem. An example of such an algorithm is Quicksort.

The data structure can be an array, where you sort it with cost O(nlogn). Then you can index it for the largest k-th element in O(1) time.

However, in order to search for any x, you will have to use Binary Search, which costs O(logn).

But your elements are unique. So, you could use an index array, where for example if your input was [1, 2, 3, 5], then your boolean index array would be [1, 1, 1, 0, 1], where 0 states that the number in that index is not present in your input. That way you could look up for every x at O(1) time.

But now the find the largest k-th element would require to go to the k-th index, check that slot, and if it's empty, then check the next slot, until you find a 1, meaning that this slot's number is present in our input. This will cost O(m), where m is the number of empty slots you will encounter after reaching the k-th index, which, on average, should be small, and can be assumed to be constant, yielding a time complexity of O(1).

ContentLicense: CC BY-SA 3.0


问:
Angularjs service doesn't work in run() method
I got a simple get and set service in my angular app, that stores data from a $http request, but for some reason it just doesn't seem to work in angular's run() method. I'm not sure what am doing wrong.

my service

```<code>app.factory('sessionService', function() {
    var user_info = {};

    return {
        set: function(value) {
            user_info = value;
        },
        get: function() {
            return user_info;
        }
    };
});
</code>```

my run method

```<code>app.run(['$rootScope', '$location', 'Auth', 'sessionService',
    function($rootScope, $location, Auth, sessionService) {

        var routespermission = ['/dashboard', '/create']; //route that require login
        $rootScope.$on('$routeChangeStart', function() {
            if (routespermission.indexOf($location.path()) != -1) {
                Auth.check({
                    type: 'checkSession'
                }).success(function(data) {
                    if (data.status === false) {
                        $location.path('/user/login');
                    } else {
                        sessionService.set(data);
                    }
                });
            }
        });
    }
]);
</code>```

trying to access the data in my controller

```<code>app.controller('dashboardCtrl', ['$scope', '$location', 'sessionService',
    function($scope, $location, sessionService) {

        $scope.user_info = sessionService.get();
        console.log($scope.user_info);

        $scope.create_review = function() {

        }

    }
]);
</code>```

when I console log the service in my controller, it return an empty object. I don't getany error, so not sure where i went wrong

答:
you should inject $route dependency in app.run for '$routeChangeStart' to work.

```<code>app.run(['$rootScope', '$location','$route', 'Auth', 'sessionService',
function($rootScope, $location,$route, Auth, sessionService) {

    var routespermission = ['/dashboard', '/create']; //route that require login
    $rootScope.$on('$routeChangeStart', function() {
        if (routespermission.indexOf($location.path()) != -1) {
            Auth.check({
                type: 'checkSession'
            }).success(function(data) {
                if (data.status === false) {
                    $location.path('/user/login');
                } else {
                    sessionService.set(data);
                }
            });
        }
    });
}
</code>```

]);

Body:
I got a simple get and set service in my angular app, that stores data from a $http request, but for some reason it just doesn't seem to work in angular's run() method. I'm not sure what am doing wrong.

my service

app.factory('sessionService', function() {
    var user_info = {};

    return {
        set: function(value) {
            user_info = value;
        },
        get: function() {
            return user_info;
        }
    };
});

my run method

app.run(['$rootScope', '$location', 'Auth', 'sessionService',
    function($rootScope, $location, Auth, sessionService) {

        var routespermission = ['/dashboard', '/create']; //route that require login
        $rootScope.$on('$routeChangeStart', function() {
            if (routespermission.indexOf($location.path()) != -1) {
                Auth.check({
                    type: 'checkSession'
                }).success(function(data) {
                    if (data.status === false) {
                        $location.path('/user/login');
                    } else {
                        sessionService.set(data);
                    }
                });
            }
        });
    }
]);

trying to access the data in my controller

app.controller('dashboardCtrl', ['$scope', '$location', 'sessionService',
    function($scope, $location, sessionService) {

        $scope.user_info = sessionService.get();
        console.log($scope.user_info);

        $scope.create_review = function() {

        }

    }
]);

when I console log the service in my controller, it return an empty object. I don't getany error, so not sure where i went wrong

Body:
you should inject $route dependency in app.run for '$routeChangeStart' to work.

app.run(['$rootScope', '$location','$route', 'Auth', 'sessionService',
function($rootScope, $location,$route, Auth, sessionService) {

    var routespermission = ['/dashboard', '/create']; //route that require login
    $rootScope.$on('$routeChangeStart', function() {
        if (routespermission.indexOf($location.path()) != -1) {
            Auth.check({
                type: 'checkSession'
            }).success(function(data) {
                if (data.status === false) {
                    $location.path('/user/login');
                } else {
                    sessionService.set(data);
                }
            });
        }
    });
}

]);


问:
Can't do matrix multiplication with tensorflow
In Tensorflow, I would like to do matrix multiplication using this code:

```<code>_X = np.array([[1, 2, 3], [4, 5, 6]])
_Y = np.array([[1, 1], [2, 2], [3, 3]])
X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)

res = tf.matmul(X, Y)
</code>```

However, I am getting this error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-29-37c04c70cff8> in <module>()
      4 Y = tf.convert_to_tensor(_Y)
      5
----> 6 res = tf.matmul(X, Y)

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, adjoint_a, adjoint_b, a_is_sparse, b_is_sparse, name)
   1799     else:
   1800       return gen_math_ops._mat_mul(
-> 1801           a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
   1802
   1803

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py in _mat_mul(a, b, transpose_a, transpose_b, name)
   1261   """
   1262   result = _op_def_lib.apply_op("MatMul", a=a, b=b, transpose_a=transpose_a,
-> 1263                                 transpose_b=transpose_b, name=name)
   1264   return result
   1265

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    588               _SatisfiesTypeConstraint(base_type,
    589                                        _Attr(op_def, input_arg.type_attr),
--> 590                                        param_name=input_name)
    591             attrs[input_arg.type_attr] = attr_value
    592             inferred_from[input_arg.type_attr] = input_name

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py in _SatisfiesTypeConstraint(dtype, attr_def, param_name)
     59           "allowed values: %s" %
     60           (param_name, dtypes.as_dtype(dtype).name,
---> 61            ", ".join(dtypes.as_dtype(x).name for x in allowed_list)))
     62
     63

TypeError: Value passed to parameter 'a' has DataType int64 not in list of allowed values: float16, float32, float64, int32, complex64, complex128
</code>```

Any idea what could be wrong with the code?

答:
Here is the docs for tf.matmul:

Both matrices must be of the same type. The supported types are:
  float16, float32, float64, int32, complex64, complex128.

Changing the data type to one of the supported eliminates the error.

```<code>_X = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
_Y = np.array([[1, 1], [2, 2], [3, 3]], dtype=np.int32)
X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)

res = tf.matmul(X, Y)

sess = tf.Session()
res.eval(session=sess)
#array([[14, 14],
#       [32, 32]], dtype=int32)
</code>```

Body:
In Tensorflow, I would like to do matrix multiplication using this code:

_X = np.array([[1, 2, 3], [4, 5, 6]])
_Y = np.array([[1, 1], [2, 2], [3, 3]])
X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)

res = tf.matmul(X, Y)

However, I am getting this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-29-37c04c70cff8> in <module>()
      4 Y = tf.convert_to_tensor(_Y)
      5
----> 6 res = tf.matmul(X, Y)

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, adjoint_a, adjoint_b, a_is_sparse, b_is_sparse, name)
   1799     else:
   1800       return gen_math_ops._mat_mul(
-> 1801           a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
   1802
   1803

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py in _mat_mul(a, b, transpose_a, transpose_b, name)
   1261   """
   1262   result = _op_def_lib.apply_op("MatMul", a=a, b=b, transpose_a=transpose_a,
-> 1263                                 transpose_b=transpose_b, name=name)
   1264   return result
   1265

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    588               _SatisfiesTypeConstraint(base_type,
    589                                        _Attr(op_def, input_arg.type_attr),
--> 590                                        param_name=input_name)
    591             attrs[input_arg.type_attr] = attr_value
    592             inferred_from[input_arg.type_attr] = input_name

/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py in _SatisfiesTypeConstraint(dtype, attr_def, param_name)
     59           "allowed values: %s" %
     60           (param_name, dtypes.as_dtype(dtype).name,
---> 61            ", ".join(dtypes.as_dtype(x).name for x in allowed_list)))
     62
     63

TypeError: Value passed to parameter 'a' has DataType int64 not in list of allowed values: float16, float32, float64, int32, complex64, complex128

Any idea what could be wrong with the code?

Body:
Here is the docs for tf.matmul:

Both matrices must be of the same type. The supported types are:
  float16, float32, float64, int32, complex64, complex128.

Changing the data type to one of the supported eliminates the error.

_X = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
_Y = np.array([[1, 1], [2, 2], [3, 3]], dtype=np.int32)
X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)

res = tf.matmul(X, Y)

sess = tf.Session()
res.eval(session=sess)
#array([[14, 14],
#       [32, 32]], dtype=int32)


问:
Add a Canvas Form Control in Drupal Custom Module
Im currently developing a module and I have this code in html:

```<code><canvas id="cnv" name="cnv" width="500" height="100"></canvas>
</code>```

I want it to add in my page using form controls but when I scan through Form API Reference , there's no canvas form control available. How to make it possible in Drupal? Any idea?

答:
You can also create a canvas using html_tag type. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21HtmlTag.php/class/HtmlTag/8.2.x.

Here is the code.

```<code>$form['mycanvas']=array(
      '#type' => 'html_tag',
      '#tag' => 'canvas',
      '#attributes' => array(
                    'id'=> 'cnv',
                    'name'=>'cnv',
                    'style'=>'border: 1px solid #000000;
                              width: 500;
                              height: 100;'
                            ),
      );
</code>```

Body:
Im currently developing a module and I have this code in html:

<canvas id="cnv" name="cnv" width="500" height="100"></canvas>

I want it to add in my page using form controls but when I scan through Form API Reference , there's no canvas form control available. How to make it possible in Drupal? Any idea?

Body:
You can also create a canvas using html_tag type. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21HtmlTag.php/class/HtmlTag/8.2.x.

Here is the code.

$form['mycanvas']=array(
      '#type' => 'html_tag',
      '#tag' => 'canvas',
      '#attributes' => array(
                    'id'=> 'cnv',
                    'name'=>'cnv',
                    'style'=>'border: 1px solid #000000;
                              width: 500;
                              height: 100;'
                            ),
      );


问:
Dealing with jumps/discontinuities in Modelica
I was wondering if anyone had any tips or tricks in terms of dealing with jumps/discontinuities in Modelica. I'm using OpenModelica, and a simplified example code for my problem is shown below.

```<code>model PowerGenerator
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;
equation
if (5 < time) and (time < 15) then P = 3;
  else P = 0;
  end if;
  der(E) = P;
end PowerGenerator;
</code>```

How can I make the jumps at 5 and 15 sec into continuous transitions, where the derivative of the slope is finite? I've tried the noEvent and smooth functions, but I haven't been able to make them do what I need.

Edit:
The issue in my main model is that these events induce chattering, and so I also need it to work in real-time. Also in my full model, the events are state events, and so the time is not known.

答:
The answer by Scott G is good, but it only works well if the change just depends on time. A more general solution is to use a low-pass filter:

```<code>model PowerGenerator
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;
  Modelica.Blocks.Continuous.LowpassButterworth lowpassButterworth(f=1)
    annotation (Placement(transformation(extent={{-40,20},{-20,40}})));
equation
  if (5 < time) and (time < 15) then
     P = 3;
  else
     P = 0;
  end if;
  lowpassButterworth.u=P;
  der(E) = lowpassButterworth.y;
end PowerGenerator;
</code>```

(I would recommend using connect-statements instead - but the above should also be legal Modelica.)

Body:
I was wondering if anyone had any tips or tricks in terms of dealing with jumps/discontinuities in Modelica. I'm using OpenModelica, and a simplified example code for my problem is shown below.

model PowerGenerator
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;
equation
if (5 < time) and (time < 15) then P = 3;
  else P = 0;
  end if;
  der(E) = P;
end PowerGenerator;

How can I make the jumps at 5 and 15 sec into continuous transitions, where the derivative of the slope is finite? I've tried the noEvent and smooth functions, but I haven't been able to make them do what I need.

Edit:
The issue in my main model is that these events induce chattering, and so I also need it to work in real-time. Also in my full model, the events are state events, and so the time is not known.

Body:
The answer by Scott G is good, but it only works well if the change just depends on time. A more general solution is to use a low-pass filter:

model PowerGenerator
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;
  Modelica.Blocks.Continuous.LowpassButterworth lowpassButterworth(f=1)
    annotation (Placement(transformation(extent={{-40,20},{-20,40}})));
equation
  if (5 < time) and (time < 15) then
     P = 3;
  else
     P = 0;
  end if;
  lowpassButterworth.u=P;
  der(E) = lowpassButterworth.y;
end PowerGenerator;

(I would recommend using connect-statements instead - but the above should also be legal Modelica.)


问:
JavaScript - Form validation loop through specific fields
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

```<code><form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>
</code>```

答:
Have you tried the jQuery validation plugin?

You can see a demo here.

ContentLicense: CC BY-SA 2.5

Body:
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

<form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>


问:
Display unique array entries and sum of related entry from separate array
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

```<code>var arr1 = [7012, 7013, 7015, 7012];
</code>```

Array 2:

```<code>var arr2 = [10, 20, 25, 10];
</code>```

Expected Output:

(first explanation was not great, changing this)

```<code>newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];
</code>```

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

```<code>var newArr = [...new Set(arr1)];
</code>```

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

答:
You can use map to replace the values of your unique array with the value in the corresponding position of arr2, and then use reduce to get the sum:</p>

```<code>const sum = [...new Set(arr1)].
  map( x => arr2[ arr1.indexOf( x ) ] ).
  reduce( ( a, b ) => a + b, 0 )
;
</code>```

Body:
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

var arr1 = [7012, 7013, 7015, 7012];

Array 2:

var arr2 = [10, 20, 25, 10];

Expected Output:

(first explanation was not great, changing this)

newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

var newArr = [...new Set(arr1)];

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

Body:
You can use map to replace the values of your unique array with the value in the corresponding position of arr2, and then use reduce to get the sum:

const sum = [...new Set(arr1)].
  map( x => arr2[ arr1.indexOf( x ) ] ).
  reduce( ( a, b ) => a + b, 0 )
;


问:
PHP - Outsource switch cases in different files
I want a switch-case instruction but outsource all the case-statements in diffenrent files.
Like this:

```<code><?php
switch ($a) {
    foreach (glob("/path/*.php") as $filename) {
            include $filename;
        }
}
</code>```

and in /path/ there are files like a.php and b.php with contents like

```<code><?php
case 1:
    echo "hello";
    break;
</code>```

How can I do this?

Edit:
I am using PHP7.1 if this is of interest.

答:
The only solution I found for this is to change the switch-case to some if-statements:

```<code>$a = $_GET['something'];
foreach (glob("/path/*.php") as $filename) {
    include $filename;
}
</code>```

And then in a.php

```<code>if ($a == 1) {
    echo "hello1";
}
</code>```

in b.php

```<code>if ($a == 2) {
    echo "hello2";
}
</code>```

and so on...

Body:
I want a switch-case instruction but outsource all the case-statements in diffenrent files.
Like this:

<?php
switch ($a) {
    foreach (glob("/path/*.php") as $filename) {
            include $filename;
        }
}

and in /path/ there are files like a.php and b.php with contents like

<?php
case 1:
    echo "hello";
    break;

How can I do this?

Edit:
I am using PHP7.1 if this is of interest.

Body:
The only solution I found for this is to change the switch-case to some if-statements:

$a = $_GET['something'];
foreach (glob("/path/*.php") as $filename) {
    include $filename;
}

And then in a.php

if ($a == 1) {
    echo "hello1";
}

in b.php

if ($a == 2) {
    echo "hello2";
}

and so on...


问:
MongoDB Aggregation Limit Lookup
I am using $lookup in PyMongo to successfully "join" two collections (this works). I am having a problem where the second collection I am joining in may exceed the BSON document size when it returns all of the records.

I am looking to use $limit to limit the number of records that are allowed to join under "match_docs" eg: 100 records maximum from "comments" per obj_id:

```<code>db.indicators.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "_id",
      "foreignField": "obj_id",
      "as": "match_docs"
    }
  }
])
</code>```

I've tried various types of $limit, and it seems to only limit the total number of results overall, not just for the join.

答:
I was able to figure it out.

$lookup -> $match -> $project

```<code>db.indicators.aggregate([{
    "$lookup": {
        "from": "comments"
        , "localField": "_id"
        , "foreignField": "obj_id"
        , "as": "match_docs"
    }
}, {
    "$match": {
        "match_docs": {
            "$exists": True
        }
    }
}, {
    "$project": {
        "match_docs_agg": {
            "$slice": ["$match_docs", 3]
        }
    }
}])
</code>```

Title: MongoDB Aggregation Limit Lookup

Body:
I am using $lookup in PyMongo to successfully "join" two collections (this works). I am having a problem where the second collection I am joining in may exceed the BSON document size when it returns all of the records.

I am looking to use $limit to limit the number of records that are allowed to join under "match_docs" eg: 100 records maximum from "comments" per obj_id:

db.indicators.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "_id",
      "foreignField": "obj_id",
      "as": "match_docs"
    }
  }
])

I've tried various types of $limit, and it seems to only limit the total number of results overall, not just for the join.

Body:
I was able to figure it out.

$lookup -> $match -> $project

db.indicators.aggregate([{
    "$lookup": {
        "from": "comments"
        , "localField": "_id"
        , "foreignField": "obj_id"
        , "as": "match_docs"
    }
}, {
    "$match": {
        "match_docs": {
            "$exists": True
        }
    }
}, {
    "$project": {
        "match_docs_agg": {
            "$slice": ["$match_docs", 3]
        }
    }
}])


问:
php 'ISSET' function not working. OR the code skips my if statements
The not working and i get the same error output as defined in the last else statement.

I am new to Php, please help me out. What am I doing wrong?

HERE IS THE CODE

```<code><form action="imagespace.php?groupid=<?php echo $_GET['groupid'] ;?>" method = "POST">
<input type="button" name="Up-Vote" value ="Up-Vote" class="up-votes" />
<input type="button" name="Down-Vote" value="Down-Vote" class="down-votes" />
</form>
<?php

$emailid=$_SESSION['emailid'];
$groupid = $_GET['groupid'];
$emailid = mysqli_real_escape_string($con,$emailid);
$groupid = mysqli_real_escape_string($con,$emailid);

if(isset($_POST['Up-Vote']))
    { echo ' trial';
    $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '1') ";
    $query_run = mysqli_query($con,$query);
    if($query_run)
    {echo 'upvoted';}
    }

else if(isset($_POST['Down-Vote']))
    {
        $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '0') ";
        $query_run = mysqli_query($con,$query);
        if($query_run)
        {echo 'downvoted';}
    }
else{
echo 'error' ;
}
}
?>

</body>
</html>
</code>```

答:
I can't seem to find a submit button in there. Try adding

```<code><input type="submit" />
</code>```

right before the closing </form>-tag. Then try if the error still occurs if you click on it.

Also, try using checkboxes/radio buttons instead of buttons. I don't know whether it is possible to do that with buttons.

Body:
The not working and i get the same error output as defined in the last else statement.

I am new to Php, please help me out. What am I doing wrong?

HERE IS THE CODE

<form action="imagespace.php?groupid=<?php echo $_GET['groupid'] ;?>" method = "POST">
<input type="button" name="Up-Vote" value ="Up-Vote" class="up-votes" />
<input type="button" name="Down-Vote" value="Down-Vote" class="down-votes" />
</form>
<?php

$emailid=$_SESSION['emailid'];
$groupid = $_GET['groupid'];
$emailid = mysqli_real_escape_string($con,$emailid);
$groupid = mysqli_real_escape_string($con,$emailid);

if(isset($_POST['Up-Vote']))
    { echo ' trial';
    $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '1') ";
    $query_run = mysqli_query($con,$query);
    if($query_run)
    {echo 'upvoted';}
    }

else if(isset($_POST['Down-Vote']))
    {
        $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '0') ";
        $query_run = mysqli_query($con,$query);
        if($query_run)
        {echo 'downvoted';}
    }
else{
echo 'error' ;
}
}
?>

Body:
I can't seem to find a submit button in there. Try adding

<input type="submit" />

right before the closing </form>-tag. Then try if the error still occurs if you click on it.

Also, try using checkboxes/radio buttons instead of buttons. I don't know whether it is possible to do that with buttons.


问:
Are there any good open source smalltalk implementations?
Do you know any good smalltalk implementations which meet the following criteria:

are open source (and free)

are enterprise ready - I can do commercial apps into it

works on os x

I'm asking this because I heard a lot about smalltalk, and I want to learn it - just for fun. But it seems to be hard to find the right tools and books for this language.

答: Gnu smalltalk</p>

Body: Gnu smalltalk


问:
Creating simple pages through variables
I'm trying to create a page that can allow users to customize there own specific pages, these pages will only have a few customization options such as text, color and layout of blocks. I haven't started a configuration page but i have began creating a template that the user will modify to suit their needs.

I would like to somehow get the information given by the user on the configuration page and then display it into parts of the other page. At the moment i don't know the best way to get that information and display in tags on the other page such as these tags.

  <?php  $GLOBALS['event1'] ?>

```

This is a snippet of code of a few ways I've tried to display the information sadly i haven't had any luck in getting the information and displaying it at the  same time.

I was thinking about trying to get information from the PHP configuration form and then turn it into a java script variable and display it into the page.

I would like your views on how to do this and whether there is a better way and how to do that.

答:
Zahir,

First, you have to store the information...

assuming you have this information already stored and have written the code that fetches the user information from the database:

You will need to echo out the values like so:

```<code><p><i class="fa fa-certificate fa-fw w3-margin-right w3-large" style="color: #582d37"></i><?php echo $cert; ?></p>
</code>```

IF you have yet to write the code for storing the information:

On the page where user fills out the form, have the form go to some page (could be the same page)--this page is specified in form tag's ACTION attribute.

All form data will be in $_POST; prior to making the call to the database for storing the form data, you must sanitize/validate it! (otherwise, your application will be vulnerable to attacks such as SQL Injection.

And then follow the step above.

Just some pointers to get you going... if you get more stuck write back.

Hope this helps,

-Rush

Title: Creating simple pages through variables

Body:
I'm trying to create a page that can allow users to customize there own specific pages, these pages will only have a few customization options such as text, color and layout of blocks. I haven't started a configuration page but i have began creating a template that the user will modify to suit their needs.

I would like to somehow get the information given by the user on the configuration page and then display it into parts of the other page. At the moment i don't know the best way to get that information and display in tags on the other page such as these tags.

  <?php  $GLOBALS['event1'] ?>

This is a snippet of code of a few ways I've tried to display the information sadly i haven't had any luck in getting the information and displaying it at the  same time.

I was thinking about trying to get information from the PHP configuration form and then turn it into a java script variable and display it into the page.

I would like your views on how to do this and whether there is a better way and how to do that.

Body:
Zahir,

First, you have to store the information...

assuming you have this information already stored and have written the code that fetches the user information from the database:

You will need to echo out the values like so:

<p><i class="fa fa-certificate fa-fw w3-margin-right w3-large" style="color: #582d37"></i><?php echo $cert; ?></p>

IF you have yet to write the code for storing the information:

On the page where user fills out the form, have the form go to some page (could be the same page)--this page is specified in form tag's ACTION attribute.

All form data will be in $_POST; prior to making the call to the database for storing the form data, you must sanitize/validate it! (otherwise, your application will be vulnerable to attacks such as SQL Injection.

And then follow the step above.

Just some pointers to get you going... if you get more stuck write back.

Hope this helps,

-Rush


问:
Sql procedure slow using 2 dates d1 and d2
I have 2 problems, first when i use 2 defined dates my request works but when i try to do this with two var which came from my C# code it doesnt work it's very slow. And then if i use a limit with those 2 vars it works untill 294 but at 295 it doesnt work i do not know why. There is my code. </p>

```<code>CREATE OR REPLACE FUNCTION prc_get_list_resa(d1 date, d2 date, p_id_resa integer, p_state character, p_id_clt integer, p_id_chauff integer, p_id_conv integer, p_id_fact integer, p_id_org integer)
  RETURNS refcursor AS
$BODY$
DECLARE
      ref refcursor;
    BEGIN
        OPEN ref FOR
          SELECT *
          FROM db_reservations res
          LEFT JOIN db_clients clt ON res.id_clt_resa = clt.id_clt
          LEFT JOIN db_organisations org ON res.id_org_resa = org.id_org
          LEFT JOIN db_chauffeurs chauff ON res.id_chauff_resa = chauff.id_chauff
          LEFT JOIN db_vehicules vehic ON res.id_vehic_resa = vehic.id_vehic
          LEFT JOIN db_type_transport ttransp ON res.id_type_transp_resa = ttransp.id_type_transp

          WHERE  res.date_dep_resa >= (select distinct d1 from db_reservations) and res.date_dep_resa < (select distinct d2 from db_reservations)
           and  ((res.id_resa        = p_id_resa)   or (p_id_resa = 0))
           and  ((res.id_org_resa    = p_id_org)    or (p_id_org = 0))
           and  ((res.id_chauff_resa = p_id_chauff) or (p_id_chauff = 0))
           and  ((res.id_clt_resa    = p_id_clt)    or (p_id_clt  = 0))
           and  ((res.id_conv_resa   = p_id_conv)   or (p_id_conv = 0))
           and  ((res.id_fact_resa   = p_id_fact)   or (p_id_fact = 0))
           and  ((res.etat_resa      = p_state)     or (p_state   = ''))

           order by id_org_resa,id_clt_resa, date_dep_resa,type_trajet asc limit 1000;
      RETURN ref ;
    END;
  $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION prc_get_list_resa(date, date, integer, character, integer, integer, integer, integer, integer)
  OWNER TO postgres;
</code>```

<p>The c# code : </p>

```<code>public static List<Reservation> ListReservations(string param, int p_id_resa, string p_state, int p_id_clt, int p_id_chauff, int p_id_conv, string p_deb_period, string p_fin_period, int p_id_fact, int p_id_pass, int p_id_org)
{
    string d1, d2;
    DateTime baseDate = DateTime.Today;

    var today = baseDate;
    var yesterday = baseDate.AddDays(-1);
    var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
    var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
    var lastWeekStart = thisWeekStart.AddDays(-7);
    var lastWeekEnd = thisWeekStart.AddSeconds(-1);
    var thisMonthStart = baseDate.AddDays(1 - baseDate.Day);
    var thisMonthEnd = thisMonthStart.AddMonths(1).AddSeconds(-1);
    var lastMonthStart = thisMonthStart.AddMonths(-1);
    var lastMonthEnd = thisMonthStart.AddSeconds(-1);
    if (param == "lastweek")
    {
        d1 = thisWeekStart.ToString("dd-MM-yyyy");
        d2 = thisWeekEnd.ToString("dd-MM-yyyy");
    }
    else if (param == "lastmonth")
    {
        d1 = thisMonthStart.ToString("dd-MM-yyyy");
        d2 = thisMonthEnd.ToString("dd-MM-yyyy");
    }
    else if (param == "today")
    {
        d1 = DateTime.Today.ToString("dd-MM-yyyy");
        d2 = DateTime.Today.ToString("dd-MM-yyyy");
    }
    else if (param == "all")
    {
        d1 = "01-01-1900";
        d2 = "01-01-2100";
    }
    else
    {
        d1 = p_deb_period;
        d2 = p_fin_period;
    }

    NpgsqlDataReader dr = null;
    List<Reservation> lst_reservation = new List<Reservation>();
    ApplicationConfig db = new ApplicationConfig();
    string cnx = db.getConnectionStringFromXML();
    NpgsqlConnection npgsqlcnx = new NpgsqlConnection(cnx);

    npgsqlcnx.Open();
    NpgsqlTransaction tran = npgsqlcnx.BeginTransaction();
    //  NpgsqlCommand command = new NpgsqlCommand("prc_get_reservations", npgsqlcnx);
    NpgsqlCommand command = new NpgsqlCommand("prc_get_list_resa", npgsqlcnx);

    command.CommandType = CommandType.StoredProcedure;

    if ((d1 != "") && (d1 != null))
    {
        command.Parameters.AddWithValue("@d1", DateTime.Parse(d1));
    }
    else
    {
        command.Parameters.AddWithValue("@d1", DateTime.Parse("01/01/1900"));
    }
    if ((d2 != "") && (d2 != null))
    {
        command.Parameters.AddWithValue("@d2", DateTime.Parse(d2));
        }
    else
    {
        command.Parameters.AddWithValue("@d2", DateTime.Parse("01/01/2100"));
    }

    command.Parameters.AddWithValue("@p_id_resa", p_id_resa);
    command.Parameters.AddWithValue("@p_state", p_state);
    command.Parameters.AddWithValue("@p_id_clt", p_id_clt);
    command.Parameters.AddWithValue("@p_id_chauff", p_id_chauff);
    command.Parameters.AddWithValue("@p_id_conv", p_id_conv);
    command.Parameters.AddWithValue("@p_id_fact", p_id_fact);
    command.Parameters.AddWithValue("@p_id_org", p_id_org);

    dr = command.ExecuteReader();

    int t = dr.FieldCount;
    lst_reservation = Reservations(dr);
    //    lst_reservation = Reservations(dr);
    npgsqlcnx.Close();
    return lst_reservation;
}
</code>```

答:
d1 and d2 must be declared as DateTime variables - don't store dates in strings. Especially when passing those dates to a database that expects a date rather than a string.

In all likelihood, you are passing a string to the database and the database is interpreting that string differently (e.g. is 1/2/2017 1st Feb or 2nd Jan?). By passing only dates to the database there is no ambiguity.

Thus instead of code like:

```<code>d1 = DateTime.Today.ToString("dd-MM-yyyy");
</code>```

you will use code like:

```<code>d1 = DateTime.Today;
</code>```

Also change this line:

```<code>WHERE  res.date_dep_resa >= (select distinct d1 from db_reservations) and res.date_dep_resa < (select distinct d2 from db_reservations)
</code>```

to:

```<code>WHERE  res.date_dep_resa >= d1 and res.date_dep_resa < d2
</code>```

Body:
I have 2 problems, first when i use 2 defined dates my request works but when i try to do this with two var which came from my C# code it doesnt work it's very slow. And then if i use a limit with those 2 vars it works untill 294 but at 295 it doesnt work i do not know why. There is my code.

CREATE OR REPLACE FUNCTION prc_get_list_resa(d1 date, d2 date, p_id_resa integer, p_state character, p_id_clt integer, p_id_chauff integer, p_id_conv integer, p_id_fact integer, p_id_org integer)
  RETURNS refcursor AS
$BODY$
DECLARE
      ref refcursor;
    BEGIN
        OPEN ref FOR
          SELECT *
          FROM db_reservations res
          LEFT JOIN db_clients clt ON res.id_clt_resa = clt.id_clt
          LEFT JOIN db_organisations org ON res.id_org_resa = org.id_org
          LEFT JOIN db_chauffeurs chauff ON res.id_chauff_resa = chauff.id_chauff
          LEFT JOIN db_vehicules vehic ON res.id_vehic_resa = vehic.id_vehic
          LEFT JOIN db_type_transport ttransp ON res.id_type_transp_resa = ttransp.id_type_transp

          WHERE  res.date_dep_resa >= (select distinct d1 from db_reservations) and res.date_dep_resa < (select distinct d2 from db_reservations)
           and  ((res.id_resa        = p_id_resa)   or (p_id_resa = 0))
           and  ((res.id_org_resa    = p_id_org)    or (p_id_org = 0))
           and  ((res.id_chauff_resa = p_id_chauff) or (p_id_chauff = 0))
           and  ((res.id_clt_resa    = p_id_clt)    or (p_id_clt  = 0))
           and  ((res.id_conv_resa   = p_id_conv)   or (p_id_conv = 0))
           and  ((res.id_fact_resa   = p_id_fact)   or (p_id_fact = 0))
           and  ((res.etat_resa      = p_state)     or (p_state   = ''))

           order by id_org_resa,id_clt_resa, date_dep_resa,type_trajet asc limit 1000;
      RETURN ref ;
    END;
  $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION prc_get_list_resa(date, date, integer, character, integer, integer, integer, integer, integer)
  OWNER TO postgres;

The c# code :

public static List<Reservation> ListReservations(string param, int p_id_resa, string p_state, int p_id_clt, int p_id_chauff, int p_id_conv, string p_deb_period, string p_fin_period, int p_id_fact, int p_id_pass, int p_id_org)
{
    string d1, d2;
    DateTime baseDate = DateTime.Today;

    var today = baseDate;
    var yesterday = baseDate.AddDays(-1);
    var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
    var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
    var lastWeekStart = thisWeekStart.AddDays(-7);
    var lastWeekEnd = thisWeekStart.AddSeconds(-1);
    var thisMonthStart = baseDate.AddDays(1 - baseDate.Day);
    var thisMonthEnd = thisMonthStart.AddMonths(1).AddSeconds(-1);
    var lastMonthStart = thisMonthStart.AddMonths(-1);
    var lastMonthEnd = thisMonthStart.AddSeconds(-1);
    if (param == "lastweek")
    {
        d1 = thisWeekStart.ToString("dd-MM-yyyy");
        d2 = thisWeekEnd.ToString("dd-MM-yyyy");
    }
    else if (param == "lastmonth")
    {
        d1 = thisMonthStart.ToString("dd-MM-yyyy");
        d2 = thisMonthEnd.ToString("dd-MM-yyyy");
    }
    else if (param == "today")
    {
        d1 = DateTime.Today.ToString("dd-MM-yyyy");
        d2 = DateTime.Today.ToString("dd-MM-yyyy");
    }
    else if (param == "all")
    {
        d1 = "01-01-1900";
        d2 = "01-01-2100";
    }
    else
    {
        d1 = p_deb_period;
        d2 = p_fin_period;
    }

    NpgsqlDataReader dr = null;
    List<Reservation> lst_reservation = new List<Reservation>();
    ApplicationConfig db = new ApplicationConfig();
    string cnx = db.getConnectionStringFromXML();
    NpgsqlConnection npgsqlcnx = new NpgsqlConnection(cnx);

    npgsqlcnx.Open();
    NpgsqlTransaction tran = npgsqlcnx.BeginTransaction();
    //  NpgsqlCommand command = new NpgsqlCommand("prc_get_reservations", npgsqlcnx);
    NpgsqlCommand command = new NpgsqlCommand("prc_get_list_resa", npgsqlcnx);

    command.CommandType = CommandType.StoredProcedure;

    if ((d1 != "") && (d1 != null))
    {
        command.Parameters.AddWithValue("@d1", DateTime.Parse(d1));
    }
    else
    {
        command.Parameters.AddWithValue("@d1", DateTime.Parse("01/01/1900"));
    }
    if ((d2 != "") && (d2 != null))
    {
        command.Parameters.AddWithValue("@d2", DateTime.Parse(d2));
        }
    else
    {
        command.Parameters.AddWithValue("@d2", DateTime.Parse("01/01/2100"));
    }

    command.Parameters.AddWithValue("@p_id_resa", p_id_resa);
    command.Parameters.AddWithValue("@p_state", p_state);
    command.Parameters.AddWithValue("@p_id_clt", p_id_clt);
    command.Parameters.AddWithValue("@p_id_chauff", p_id_chauff);
    command.Parameters.AddWithValue("@p_id_conv", p_id_conv);
    command.Parameters.AddWithValue("@p_id_fact", p_id_fact);
    command.Parameters.AddWithValue("@p_id_org", p_id_org);

    dr = command.ExecuteReader();

    int t = dr.FieldCount;
    lst_reservation = Reservations(dr);
    //    lst_reservation = Reservations(dr);
    npgsqlcnx.Close();
    return lst_reservation;
}

Body:
d1 and d2 must be declared as DateTime variables - don't store dates in strings. Especially when passing those dates to a database that expects a date rather than a string.

In all likelihood, you are passing a string to the database and the database is interpreting that string differently (e.g. is 1/2/2017 1st Feb or 2nd Jan?). By passing only dates to the database there is no ambiguity.

Thus instead of code like:

d1 = DateTime.Today.ToString("dd-MM-yyyy");

you will use code like:

d1 = DateTime.Today;

Also change this line:

WHERE  res.date_dep_resa >= (select distinct d1 from db_reservations) and res.date_dep_resa < (select distinct d2 from db_reservations)

to:

WHERE  res.date_dep_resa >= d1 and res.date_dep_resa < d2


问:
Tkinter, Add menu options in new window
so i am confused on how to add menu options to my windows... i clearly can make a menubar and know how to do that as you can see in my code. however, the way i have the windows change from one to another is affecting things because i have only 1 Tk.tk window. the rest of the program operates inside that window. I would like to be able to change the title and the menu for each window.

```<code>class start(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        tk.Tk.title(self, "Group Registration")

        menubar = tk.Menu(container)
        tk.Tk.config(self, menu=menubar)
        fileMenu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Exit", command=quit)

        for F in (begin, admin_main, members):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(begin)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()
        frame.event_generate("<<showframe>>")

class begin(tk.Frame):
    pass

class admin_main(tk.Frame):

    def __init__(self, parent, controller):

        self.bind("<<showframe>>", self.on_show_frame)

    def on_show_frame(self, event):

        menubar = Menu(self)
        fileMenu = Menu(menubar)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Create member list")#command=)
        fileMenu.add_command(label="Load member list")#command=)
        fileMenu.add_command(label="Email")#command=)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit")

        print"ok"

class members(tk.Frame):
    pass

app = start()
app.geometry("600x400")
app.mainloop()
</code>```

the classes are my new windows. this is just short version of code to show how windows operate...

(REVISED)
interpreter will print "ok" when page opens. there is no syntax with it revised again... however, i do not have my new menubar showing up.

答:
You are very close (except for all of the errors in the code in your question...)

However, assuming you can fix all of the errors, the only piece you're missing is to actually configure the main window to use the menubar that you've created.

You need to add a couple lines to tell the window about the menubar. You can get the window by calling winfo_toplevel(), and then you can configure that widget to have the menu:

```<code>def on_show_frame(self, event):
    menubar = tk.Menu(...)
    ...
    top = self.winfo_toplevel()
    top.configure(menu=menubar)
</code>```

Title: Tkinter, Add menu options in new window

Body:
so i am confused on how to add menu options to my windows... i clearly can make a menubar and know how to do that as you can see in my code. however, the way i have the windows change from one to another is affecting things because i have only 1 Tk.tk window. the rest of the program operates inside that window. I would like to be able to change the title and the menu for each window.

class start(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        tk.Tk.title(self, "Group Registration")

        menubar = tk.Menu(container)
        tk.Tk.config(self, menu=menubar)
        fileMenu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Exit", command=quit)

        for F in (begin, admin_main, members):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(begin)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()
        frame.event_generate("<<showframe>>")

class begin(tk.Frame):
    pass

class admin_main(tk.Frame):

    def __init__(self, parent, controller):

        self.bind("<<showframe>>", self.on_show_frame)

    def on_show_frame(self, event):

        menubar = Menu(self)
        fileMenu = Menu(menubar)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Create member list")#command=)
        fileMenu.add_command(label="Load member list")#command=)
        fileMenu.add_command(label="Email")#command=)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit")

        print"ok"

class members(tk.Frame):
    pass

app = start()
app.geometry("600x400")
app.mainloop()

the classes are my new windows. this is just short version of code to show how windows operate...

(REVISED)
interpreter will print "ok" when page opens. there is no syntax with it revised again... however, i do not have my new menubar showing up.

Body:
You are very close (except for all of the errors in the code in your question...)

However, assuming you can fix all of the errors, the only piece you're missing is to actually configure the main window to use the menubar that you've created.

You need to add a couple lines to tell the window about the menubar. You can get the window by calling winfo_toplevel(), and then you can configure that widget to have the menu:

def on_show_frame(self, event):
    menubar = tk.Menu(...)
    ...
    top = self.winfo_toplevel()
    top.configure(menu=menubar)


问:
Conditional Compilation and Objective-C/Xcode
So I am working on a learning project and I am trying to create a header file that contains a store of URL's so that you can just change a single flag to change from Debug to Production.  This is what I am trying to do with the compiler and it is clearly wrong.  I can't find any information on how to do this in Objective-C, so that's why I came here.

```<code>#define DEBUG 1
#if DEBUG
  NSString *URL = @"dev.myserver.com";
#else
  NSString *URL = @"myserver.com";
#endif

@interface GlobalURLRefrences : NSObject {
  //NSString *URL; removed this
}

//@property (nonatomic, retain) NSString *URL; removed this

@end
</code>```

Now I am not sure if I need to declare that as a property or not.  Also, once this is compiled properly, how to I access it from an outside class (of course after you #import the globalURL's class)  Any sort of guidance on the proper method of doing this would be greatly appreciated.

答:
I think this should work</p>

```<code>#define DEBUG 1
#if DEBUG
   #define URL = @"dev.myserver.com";
#else
   #define URL = @"myserver.com";
#endif
</code>```

Body:
So I am working on a learning project and I am trying to create a header file that contains a store of URL's so that you can just change a single flag to change from Debug to Production.  This is what I am trying to do with the compiler and it is clearly wrong.  I can't find any information on how to do this in Objective-C, so that's why I came here.

#define DEBUG 1
#if DEBUG
  NSString *URL = @"dev.myserver.com";
#else
  NSString *URL = @"myserver.com";
#endif

@interface GlobalURLRefrences : NSObject {
  //NSString *URL; removed this
}

//@property (nonatomic, retain) NSString *URL; removed this

@end

Now I am not sure if I need to declare that as a property or not.  Also, once this is compiled properly, how to I access it from an outside class (of course after you #import the globalURL's class)  Any sort of guidance on the proper method of doing this would be greatly appreciated.

Body:
I think this should work

#define DEBUG 1
#if DEBUG
   #define URL = @"dev.myserver.com";
#else
   #define URL = @"myserver.com";
#endif


问:
Changing the size of text boxes in forms (MS Access)
I created a form based on a query and want to customize the size of each text box. However, when I adjust the size of one it adjusts the size of all of them. Is there any way that I can make it stop doing that and just let me edit the size of each one individually?</p>

答: With the form in design mode, select the Arrange tab at the top, then click "remove" in the "Control Layout" pane to remove the selected textbox from the control group. </p>


问:
Closing all opened tabs except the first tab/main tab using webdriver
Can anyone tell me how to close all opened tabs except the first tab/main tab using webdriver?

I tried below, but it is closing all tabs including first tab as well.

```<code>public static void closeTabs() {
    String wh1=driver.getWindowHandle();
    String cwh=null;
    while(wh1!=cwh)
    {
    new Actions(driver).sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform();
    driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, Keys.TAB);
    cwh=driver.getWindowHandle();
    driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"w");
    }
}
</code>```

Please help me.

答:
I did the following to close all windows but the main one:</p>

```<code>// Find out which handle is the one of the main window
String mainWindow = driver.CurrentWindowHandle;

// Get a list of all windows, except the main window
driver.WindowHandles.Where(w => w != mainWindow).ToList()
    // For each window found
    .ForEach(w =>
    {
        // switch to the window
        driver.SwitchTo().Window(w);

        // close the window
        driver.Close();
    });

// At the end, come back to the main window
driver.SwitchTo().Window(mainWindow);
</code>```

Body:
Can anyone tell me how to close all opened tabs except the first tab/main tab using webdriver?

I tried below, but it is closing all tabs including first tab as well.

public static void closeTabs() {
    String wh1=driver.getWindowHandle();
    String cwh=null;
    while(wh1!=cwh)
    {
    new Actions(driver).sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform();
    driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, Keys.TAB);
    cwh=driver.getWindowHandle();
    driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"w");
    }
}

Please help me.

Body:
I did the following to close all windows but the main one:

// Find out which handle is the one of the main window
String mainWindow = driver.CurrentWindowHandle;

// Get a list of all windows, except the main window
driver.WindowHandles.Where(w => w != mainWindow).ToList()
    // For each window found
    .ForEach(w =>
    {
        // switch to the window
        driver.SwitchTo().Window(w);

        // close the window
        driver.Close();
    });

// At the end, come back to the main window
driver.SwitchTo().Window(mainWindow);


问:
How to set Session Variable without breaking header redirect PHP
I know for a fact that the one line where I set my session variable is preventing the header redirect for going off.  The question then becomes where/how I can set it without breaking the header redirect.

This is based off code from Microsoft Graph REST API:

```<code><?php
ob_start();

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$provider = array (
    'client_id' => '', //blank here for security reasons
    'client_secret' => '',
    'redirect_uri' => '', //blank here for security reasons
    'authority_url' => 'https://login.microsoftonline.com/common',
    'authorize_endpoint' => '/oauth2/v2.0/authorize',
    'token_endpoint' => '/oauth2/v2.0/token',
    'resource_id' => 'https://graph.microsoft.com',
    'sendmail_endpoint' => '/v1.0/me/sendmail',
    'scopes' => 'openid profile mail.send',
    'authorization_url' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
    'parameters' => '?client_id=xxxxxxx&response_type=code&redirect_uri=xxxx&response_mode=query&scope=openid profile mail.send&state=', //client id/redirect uri xx'ed here for security reason
);

if ($_SERVER['REQUEST_METHOD'] === 'GET' && !isset($_GET['code'])) {
    $_SESSION['state'] = Base64.encode(generateRandomString()); //this line caused the header to break
    header('Location: ' . $provider['authorization_url'].$provider['parameters'].$_SESSION['state']);
    exit();
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['code'])) {
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['state'])) {
        unset($_SESSION['state']);
        exit('State value does not match the one initially sent');
    }
}
</code>```

答:
My instinct would be to remove the conditional statement wrapped around session_start() and use that function call unconditionally.  I would also use session_write_close() immediately before the header() that redirects the browser.

You also want to change Base64.encode to PHP base64_encode() function.

Body:
I know for a fact that the one line where I set my session variable is preventing the header redirect for going off.  The question then becomes where/how I can set it without breaking the header redirect.

This is based off code from Microsoft Graph REST API:

<?php
ob_start();

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$provider = array (
    'client_id' => '', //blank here for security reasons
    'client_secret' => '',
    'redirect_uri' => '', //blank here for security reasons
    'authority_url' => 'https://login.microsoftonline.com/common',
    'authorize_endpoint' => '/oauth2/v2.0/authorize',
    'token_endpoint' => '/oauth2/v2.0/token',
    'resource_id' => 'https://graph.microsoft.com',
    'sendmail_endpoint' => '/v1.0/me/sendmail',
    'scopes' => 'openid profile mail.send',
    'authorization_url' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
    'parameters' => '?client_id=xxxxxxx&response_type=code&redirect_uri=xxxx&response_mode=query&scope=openid profile mail.send&state=', //client id/redirect uri xx'ed here for security reason
);

if ($_SERVER['REQUEST_METHOD'] === 'GET' && !isset($_GET['code'])) {
    $_SESSION['state'] = Base64.encode(generateRandomString()); //this line caused the header to break
    header('Location: ' . $provider['authorization_url'].$provider['parameters'].$_SESSION['state']);
    exit();
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['code'])) {
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['state'])) {
        unset($_SESSION['state']);
        exit('State value does not match the one initially sent');
    }
}


问:
Cakephp 3 save associations dose not work
I try to make a blog with articles and tags but for some reason my tags wont save when creating articles.
I did followed some ideas from official cake blog and from here but no luck for me .. Maybe something I do wrong and I dont see.

Tables for keywords

```<code>CREATE TABLE `keywords` (
  `id` int(11) NOT NULL,
  `article_id` int(11) DEFAULT NULL,
  `tag` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Table model
Keywords:

```<code>class KeywordsTable extends Table
{
......................
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('keywords');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->belongsTo('Article', [
            'foreignKey' => 'article_id',
            'joinType' => 'INNER'
        ]);
    }
....................
}
</code>```

Article

```<code>class ArticleTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('article');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);

        $this->hasMany('Keywords', [
            'foreignKey' => 'article_id'
        ]);
    }
......................................
}
</code>```

And here is my controller:

```<code>public function add()
{

        //$this->autoRender = false;
        $article = $this->Article->newEntity();

        if ($this->request->is('post')) {

        $article = $this->Article->patchEntity($article, $this->request->data, ['associated'=>['Keywords']]);
        echo "```";
        print_r($this->Article->save($article));
        die();
        }
}
```

<p>And this is the code I use in my form</p>

```<?= $this->Form->input('article[keywords][]', ['label'=>false, 'class' => 'form-control', 'placeholder' => 'keywords', 'templates' => ['inputContainer' => '{{content}}']]); ?>
```

So if any one could help me out I will appreciate.

答:
Ok, after 4 hours I managed to find the problem.
Problem was in my view form input.

It should have been article.0.tag instead of article[keywords][]
Changed that and all works now.

Regards

Body:
I try to make a blog with articles and tags but for some reason my tags wont save when creating articles.
I did followed some ideas from official cake blog and from here but no luck for me .. Maybe something I do wrong and I dont see.

Tables for keywords

CREATE TABLE `keywords` (
  `id` int(11) NOT NULL,
  `article_id` int(11) DEFAULT NULL,
  `tag` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table model
Keywords:

class KeywordsTable extends Table
{
......................
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('keywords');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->belongsTo('Article', [
            'foreignKey' => 'article_id',
            'joinType' => 'INNER'
        ]);
    }
....................
}

Article

class ArticleTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('article');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);

        $this->hasMany('Keywords', [
            'foreignKey' => 'article_id'
        ]);
    }
......................................
}

And here is my controller:

public function add()
{

        //$this->autoRender = false;
        $article = $this->Article->newEntity();

        if ($this->request->is('post')) {

        $article = $this->Article->patchEntity($article, $this->request->data, ['associated'=>['Keywords']]);
        echo "
";
        print_r($this->Article->save($article));
        die();
        }
}

And this is the code I use in my form

<?= $this->Form->input('article[keywords][]', ['label'=>false, 'class' => 'form-control', 'placeholder' => 'keywords', 'templates' => ['inputContainer' => '{{content}}']]); ?>

So if any one could help me out I will appreciate.


问:
Error getting all calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)" Swift 3
I have an app that is supposed to load a list of calendars into a pickerview. It works, but only after the app crashes and is opened again. I am not sure why it will not work on the initial opening of the app.

Calendar Permission Request:

```<code>func requestCalendarPermissions() {
eventInstance.requestAccess(to: .event, completion: {(accessGranted: Bool, error: Error?) in

    if accessGranted == true {
        print("Access Has Been Granted")
        }
    else {
        print("Change Settings to Allow Access")
    }
    })
}
</code>```

Checking the Permission Status:

```<code>func checkStatus() {
let currentStatus = EKEventStore.authorizationStatus(for: EKEntityType.event)

if currentStatus == EKAuthorizationStatus.notDetermined {
    requestCalendarPermissions()
}
else if currentStatus == EKAuthorizationStatus.authorized {
    print("Access Has Been Granted")
}
else if (currentStatus == EKAuthorizationStatus.denied) || (currentStatus == EKAuthorizationStatus.restricted){
    print("Access Has Been Denied")
}
}
</code>```

PickerView Code:

```<code>    func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return calendars.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return calendars[row].title
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    CalendarField.text = calendars[row].title
    calID = calendars[row].calendarIdentifier
}
</code>```

This error comes up:

Error getting all calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)"

The app finally crashes because it tries to fill the pickerView and there is no data to fill with. I do load the calendars.

But, for some reason this doesn't happen after the app crashes and is reopened.

Thanks

[Update]

Console out:

2016-11-26 18:04:23.856 PTF[98143:2347570] Error getting all
  calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)" Calendars
  Loaded 2016-11-26 18:04:23.869 PTF[98143:2347569] Error getting all
  calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)" Calendars
  Loaded

Access Has Been Granted 2016-11-26 18:04:25.954 PTF[98143:2347569]
  Error getting all calendars: Error Domain=EKCADErrorDomain Code=1013
  "(null)" Calendars Loaded

2016-11-26 18:04:46.620 PTF[98143:2347522] * Terminating app due to
  uncaught exception 'NSRangeException', reason: '* -[NSArray0
  objectAtIndex:]: index 0 beyond bounds for empty NSArray'
  *** First throw call stack: (     0   CoreFoundation                      0x000000010bb6634b __exceptionPreprocess + 171  1   libobjc.A.dylib

  0x000000010b5c721e objc_exception_throw + 48  2   CoreFoundation

  0x000000010bb7dddd -[__NSArray0 objectAtIndex:] + 93  3

  libswiftCore.dylib                  0x000000010d95311d
  _TFVs12_ArrayBuffer19_getElementSlowPathfSiPs9AnyObject_ + 125    4   libswiftCore.dylib                  0x000000010d953003
  _TFVs12_ArrayBuffer10getElementfTSi20wasNativeTypeCheckedSb_x + 147   5   libswiftCore.dylib                  0x000000010d963b8a
  _TFSag9subscriptFSix + 138    6   PTF                                 0x000000010af8df12
  _TFC3PTF19MainScreenTableView10pickerViewfTCSo12UIPickerView12didSelectRowSi11inComponentSi_T_
  + 226     7   PTF                                 0x000000010af8e10a _TToFC3PTF19MainScreenTableView10pickerViewfTCSo12UIPickerView12didSelectRowSi11inComponentSi_T_
  + 74  8   UIKit                               0x000000010c0d301d -[UIPickerView _sendSelectionChangedForComponent:notify:] + 104  9   UIKit                               0x000000010c0d326e -[UIPickerView
  _sendSelectionChangedFromTable:notify:] + 370     10  UIKit                               0x000000010c8a560d -[UIPickerTableView _scrollingFinished] + 187    11
  UIKit                               0x000000010c8a57fd
  -[UIPickerTableView scrollViewDidEndDecelerating:] + 30   12  UIKit                               0x000000010c1df821 -[UIScrollView(UIScrollViewInternal)
  _scrollViewDidEndDeceleratingForDelegate] + 91    13  UIKit                               0x000000010c1dc362 -[UIScrollView(UIScrollViewInternal)
  _stopScrollDecelerationNotify:] + 316     14  UIKit                               0x000000010c1dc5b9 -[UIScrollView(UIScrollViewInternal)
  _stopScrollingNotify:pin:tramplingDragFlags:] + 505   15  UIKit                               0x000000010c1d4503 -[UIScrollView _smoothScrollWithUpdateTime:] + 3304
    16  QuartzCore                          0x0000000113fa3bd5
  _ZN2CA7Display15DisplayLinkItem8dispatchEy + 57   17  QuartzCore                          0x0000000113fa3a95 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy +
  449   18  CoreFoundation                      0x000000010baf8964
  __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION + 20    19  CoreFoundation                      0x000000010baf85f3
  __CFRunLoopDoTimer + 1075     20  CoreFoundation                      0x000000010baf817a __CFRunLoopDoTimers + 250    21  CoreFoundation

  0x000000010baeff01 __CFRunLoopRun + 2065  22  CoreFoundation

  0x000000010baef494 CFRunLoopRunSpecific + 420     23  GraphicsServices

  0x000000011124aa6f GSEventRunModal + 161  24  UIKit

  0x000000010c0eff34 UIApplicationMain + 159    25  PTF

  0x000000010af9f36f main + 111     26  libdyld.dylib

  0x000000010f30368d start + 1 ) libc++abi.dylib: terminating with
  uncaught exception of type NSException

答: I've just run into this problem. After 'requestAccess' the documentation says to call 'reset' on the eventInstance. However even this did not get things working. However getting a new eventInstance did. I'm using objective c, so I release the EKEventStore object I was using and allocate a new one.</p>

Body:
I have an app that is supposed to load a list of calendars into a pickerview. It works, but only after the app crashes and is opened again. I am not sure why it will not work on the initial opening of the app.

Calendar Permission Request:

func requestCalendarPermissions() {
eventInstance.requestAccess(to: .event, completion: {(accessGranted: Bool, error: Error?) in

    if accessGranted == true {
        print("Access Has Been Granted")
        }
    else {
        print("Change Settings to Allow Access")
    }
    })
}

Checking the Permission Status:

func checkStatus() {
let currentStatus = EKEventStore.authorizationStatus(for: EKEntityType.event)

if currentStatus == EKAuthorizationStatus.notDetermined {
    requestCalendarPermissions()
}
else if currentStatus == EKAuthorizationStatus.authorized {
    print("Access Has Been Granted")
}
else if (currentStatus == EKAuthorizationStatus.denied) || (currentStatus == EKAuthorizationStatus.restricted){
    print("Access Has Been Denied")
}
}

PickerView Code:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return calendars.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return calendars[row].title
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    CalendarField.text = calendars[row].title
    calID = calendars[row].calendarIdentifier
}

This error comes up:

Error getting all calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)"

The app finally crashes because it tries to fill the pickerView and there is no data to fill with. I do load the calendars.

But, for some reason this doesn't happen after the app crashes and is reopened.

Thanks

[Update]

Console out:

2016-11-26 18:04:23.856 PTF[98143:2347570] Error getting all
  calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)" Calendars
  Loaded 2016-11-26 18:04:23.869 PTF[98143:2347569] Error getting all
  calendars: Error Domain=EKCADErrorDomain Code=1013 "(null)" Calendars
  Loaded

Access Has Been Granted 2016-11-26 18:04:25.954 PTF[98143:2347569]
  Error getting all calendars: Error Domain=EKCADErrorDomain Code=1013
  "(null)" Calendars Loaded

2016-11-26 18:04:46.620 PTF[98143:2347522] * Terminating app due to
  uncaught exception 'NSRangeException', reason: '* -[NSArray0
  objectAtIndex:]: index 0 beyond bounds for empty NSArray'
  *** First throw call stack: (     0   CoreFoundation                      0x000000010bb6634b __exceptionPreprocess + 171  1   libobjc.A.dylib

  0x000000010b5c721e objc_exception_throw + 48  2   CoreFoundation

  0x000000010bb7dddd -[__NSArray0 objectAtIndex:] + 93  3

  libswiftCore.dylib                  0x000000010d95311d
  _TFVs12_ArrayBuffer19_getElementSlowPathfSiPs9AnyObject_ + 125    4   libswiftCore.dylib                  0x000000010d953003
  _TFVs12_ArrayBuffer10getElementfTSi20wasNativeTypeCheckedSb_x + 147   5   libswiftCore.dylib                  0x000000010d963b8a
  _TFSag9subscriptFSix + 138    6   PTF                                 0x000000010af8df12
  _TFC3PTF19MainScreenTableView10pickerViewfTCSo12UIPickerView12didSelectRowSi11inComponentSi_T_
  + 226     7   PTF                                 0x000000010af8e10a _TToFC3PTF19MainScreenTableView10pickerViewfTCSo12UIPickerView12didSelectRowSi11inComponentSi_T_
  + 74  8   UIKit                               0x000000010c0d301d -[UIPickerView _sendSelectionChangedForComponent:notify:] + 104  9   UIKit                               0x000000010c0d326e -[UIPickerView
  _sendSelectionChangedFromTable:notify:] + 370     10  UIKit                               0x000000010c8a560d -[UIPickerTableView _scrollingFinished] + 187    11
  UIKit                               0x000000010c8a57fd
  -[UIPickerTableView scrollViewDidEndDecelerating:] + 30   12  UIKit                               0x000000010c1df821 -[UIScrollView(UIScrollViewInternal)
  _scrollViewDidEndDeceleratingForDelegate] + 91    13  UIKit                               0x000000010c1dc362 -[UIScrollView(UIScrollViewInternal)
  _stopScrollDecelerationNotify:] + 316     14  UIKit                               0x000000010c1dc5b9 -[UIScrollView(UIScrollViewInternal)
  _stopScrollingNotify:pin:tramplingDragFlags:] + 505   15  UIKit                               0x000000010c1d4503 -[UIScrollView _smoothScrollWithUpdateTime:] + 3304
    16  QuartzCore                          0x0000000113fa3bd5
  _ZN2CA7Display15DisplayLinkItem8dispatchEy + 57   17  QuartzCore                          0x0000000113fa3a95 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy +
  449   18  CoreFoundation                      0x000000010baf8964
  __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION + 20    19  CoreFoundation                      0x000000010baf85f3
  __CFRunLoopDoTimer + 1075     20  CoreFoundation                      0x000000010baf817a __CFRunLoopDoTimers + 250    21  CoreFoundation

  0x000000010baeff01 __CFRunLoopRun + 2065  22  CoreFoundation

  0x000000010baef494 CFRunLoopRunSpecific + 420     23  GraphicsServices

  0x000000011124aa6f GSEventRunModal + 161  24  UIKit

  0x000000010c0eff34 UIApplicationMain + 159    25  PTF

  0x000000010af9f36f main + 111     26  libdyld.dylib

  0x000000010f30368d start + 1 ) libc++abi.dylib: terminating with
  uncaught exception of type NSException


问:
npm: How to install all dependencies at once
I installed eslint and when running command npm run lint then every time it asks to install all dependencies one by one. Is there any command option to install all once rather than running npm run lint all the time?

package.json

```<code>{
  "private": true,
  "devDependencies": {
    "gulp": "3.9.0",
    "laravel-elixir-livereload": "1.1.2",
    "babel-eslint": "4.1.1",
    "eslint": "1.3.1",
    "eslint-config-airbnb": "0.0.8",
    "eslint-plugin-react": "3.3.1",
    "laravel-elixir-eslint": "1.0.0"
  },
  "dependencies": {
    "laravel-elixir": "3.2.6",
    "bootstrap-sass": "3.3.5",
    "jquery": "2.1.4"
  },
  "scripts": {
    "lint": "./node_modules/.bin/eslint resources/assets/js/"
  }
}
</code>```

答: use npm install , It will read the top of your gulpfile an install all dependencies listed</p>

Body:
I installed eslint and when running command npm run lint then every time it asks to install all dependencies one by one. Is there any command option to install all once rather than running npm run lint all the time?

package.json

{
  "private": true,
  "devDependencies": {
    "gulp": "3.9.0",
    "laravel-elixir-livereload": "1.1.2",
    "babel-eslint": "4.1.1",
    "eslint": "1.3.1",
    "eslint-config-airbnb": "0.0.8",
    "eslint-plugin-react": "3.3.1",
    "laravel-elixir-eslint": "1.0.0"
  },
  "dependencies": {
    "laravel-elixir": "3.2.6",
    "bootstrap-sass": "3.3.5",
    "jquery": "2.1.4"
  },
  "scripts": {
    "lint": "./node_modules/.bin/eslint resources/assets/js/"
  }
}


问:
building blog using react.js and express.js
I am a web developer tries to learn React.js. I am thinking about a blog for my first React project. Based on articles and tutorials I have read in the past few days, I am thinking about to use Node.js, Express.js and MongoDB for my server side and React.js for the front-end. Before I start, I want to be clear on few questions I have.

Are those enough to build a blog? Can React.js be used for UI without other template library such as Handlebars?? I have seen few articles using both React and Template engine and confused if I am going to need another template engine.

Can I use Json as communication method(Restful API) between the UI and the server?

答: Yes for all. But I suggest to use Redus(or Flax) to control all states.</p>


问:
TFS api not validating the credentials
I have the following code on my windows form application:

```<code>        // Connect to server
        var tfs = new TeamFoundationServer(tfsServer, credentials);
        try
        {
            tfs.EnsureAuthenticated();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        };
</code>```

This is working. The problem is TeamFoundationServer is an obsolete class.

The TeamFoundationServer class is obsolete. Use the TfsTeamProjectCollection or TfsConfigurationServer classes to talk to a 2010 Team Foundation Server.
In order to talk to a 2005 or 2008 Team Foundation Server use the TfsTeamProjectCollection class.

I am using the below code now but it doesn't validate my credentials. What did I do wrong here?

```<code>        NetworkCredential credentials = new NetworkCredential(username, password, domain);

        MyCredentials credentials = new MyCredentials(username, password, domain);
        TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsServer), credentials);
        try
        {
            tfs.EnsureAuthenticated();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
</code>```

This is the MyCrendentials class:

```<code>    private class MyCredentials : ICredentialsProvider
    {
        private NetworkCredential credentials;
        #region ICredentialsProvider Members
        public MyCredentials(string user, string domain, string password)
        {
            credentials = new NetworkCredential(user, password, domain);
        }

        public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
        {
            return credentials;
        }

        public void NotifyCredentialsAuthenticated(Uri uri)
        {
            throw new NotImplementedException();
        }

        #endregion
     }
</code>```

Thanks in advance!

答:
I know it's an old question, but I was asking the same question at one point.</p>

```<code>NetworkCredential credentials = NetworkCredential("User", "Password", "Domain");
TfsConfigurationServer tfs = new TfsConfigurationServer(new Uri("Address"), credentials);
tfs.Authenticate();
</code>```

Title: TFS api not validating the credentials

Body:
I have the following code on my windows form application:

        // Connect to server
        var tfs = new TeamFoundationServer(tfsServer, credentials);
        try
        {
            tfs.EnsureAuthenticated();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        };

This is working. The problem is TeamFoundationServer is an obsolete class.

The TeamFoundationServer class is obsolete. Use the TfsTeamProjectCollection or TfsConfigurationServer classes to talk to a 2010 Team Foundation Server.
In order to talk to a 2005 or 2008 Team Foundation Server use the TfsTeamProjectCollection class.

I am using the below code now but it doesn't validate my credentials. What did I do wrong here?

        NetworkCredential credentials = new NetworkCredential(username, password, domain);

        MyCredentials credentials = new MyCredentials(username, password, domain);
        TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsServer), credentials);
        try
        {
            tfs.EnsureAuthenticated();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

This is the MyCrendentials class:

    private class MyCredentials : ICredentialsProvider
    {
        private NetworkCredential credentials;
        #region ICredentialsProvider Members
        public MyCredentials(string user, string domain, string password)
        {
            credentials = new NetworkCredential(user, password, domain);
        }

        public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
        {
            return credentials;
        }

        public void NotifyCredentialsAuthenticated(Uri uri)
        {
            throw new NotImplementedException();
        }

        #endregion
     }

Thanks in advance!

Body:
I know it's an old question, but I was asking the same question at one point.

NetworkCredential credentials = NetworkCredential("User", "Password", "Domain");
TfsConfigurationServer tfs = new TfsConfigurationServer(new Uri("Address"), credentials);
tfs.Authenticate();


问:
selecting count, percentage and compare in mysql
I have a MYSQL database that has two tables.

The first one called movies_interaction with the following parameters: movie_id, watcher_id, movie_duration.
the second table is movies_additional with the following parameters: movie_id and movie_length

What I need is to connect these two tables by which I need to retrieve the movies which was watched more than once AND more than 60% of its duration for each user.

This is so far what I wrote, but I know its wrong, so don't take that on me please.

```<code>SELECT watcher_id, COUNT(*)
AS video_count FROM movie_interaction
GROUP BY movie_id HAVING COUNT(*) >= 2 AND
movies_interaction.movie_duration *100 / movies_additional.movie_length >= 60
</code>```

the fourth line of the code is where I need help!

Result can look like this: watcher_id1 = 9, watcher_id2 = 13...etc.

Thank you very much.

答:
I'm not exactly sure on you need but I think that way look like that.

```<code>SELECT A.movie_id, COUNT(I.watcher_id) AS video_count
FROM movie_interaction I
INNER JOIN movie_additional A ON A.movie_id = I.movie_id AND
                                 I.movie_duration / A.movie_length >= 0.60
GROUP BY A.movie_id
HAVING COUNT(I.watcher_id) >= 2
</code>```

This will give you a list of movies watched more than one time for more that 60>%

Body:
I have a MYSQL database that has two tables.

The first one called movies_interaction with the following parameters: movie_id, watcher_id, movie_duration.
the second table is movies_additional with the following parameters: movie_id and movie_length

What I need is to connect these two tables by which I need to retrieve the movies which was watched more than once AND more than 60% of its duration for each user.

This is so far what I wrote, but I know its wrong, so don't take that on me please.

SELECT watcher_id, COUNT(*)
AS video_count FROM movie_interaction
GROUP BY movie_id HAVING COUNT(*) >= 2 AND
movies_interaction.movie_duration *100 / movies_additional.movie_length >= 60

the fourth line of the code is where I need help!

Result can look like this: watcher_id1 = 9, watcher_id2 = 13...etc.

Thank you very much.

Body:
I'm not exactly sure on you need but I think that way look like that.

SELECT A.movie_id, COUNT(I.watcher_id) AS video_count
FROM movie_interaction I
INNER JOIN movie_additional A ON A.movie_id = I.movie_id AND
                                 I.movie_duration / A.movie_length >= 0.60
GROUP BY A.movie_id
HAVING COUNT(I.watcher_id) >= 2

This will give you a list of movies watched more than one time for more that 60>%


问:
ImageView larger than the screen as a background
Hello I have a ImageView(background) which's height should correspond to the screen height, the width on the other hand should be left intact.

Before this was done like this

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="match_parent">

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

    <ImageView
        android:id="@+id/songDetails_songImage"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:contentDescription="@string/songDetails_cd_songCover"
        app:srcCompat="@drawable/default_song_cover" />

</HorizontalScrollView>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
...
</code>```

This worked fine - the image view occupies whole background and the user can scroll right or left to see the whole image.

My goal is to animate the scroll, to do that I need to get rid of the horizontal view(to prevent user from scrolling) but whenever I change the HorizontalScrollView to Frame/Relative layouts(with the width set to wrap_content) the image view is scaled down to fit the screen.

Is there a way to keep the imageView width intact(with height matching that of the screen) so that it would remain bigger than the device screen?(without cropping)

I could then use custom animation to scroll right.

I have looked at similar questions but I wasn't able to find anything that would work in this case.

答:
What you could do is to try to override the onTouchListener for the HorizontalScrollView.

For example, something like this:

```<code>scrollView.setOnTouchListener(new OnTouch());

private class OnTouch implements OnTouchListener
{
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    return true;
    }
}
</code>```

This would disable  the user from scrolling the HorizontalScrollView while you could probably still scroll it programmatically.

Body:
Hello I have a ImageView(background) which's height should correspond to the screen height, the width on the other hand should be left intact.

Before this was done like this

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="match_parent">

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

    <ImageView
        android:id="@+id/songDetails_songImage"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:contentDescription="@string/songDetails_cd_songCover"
        app:srcCompat="@drawable/default_song_cover" />

</HorizontalScrollView>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
...

This worked fine - the image view occupies whole background and the user can scroll right or left to see the whole image.

My goal is to animate the scroll, to do that I need to get rid of the horizontal view(to prevent user from scrolling) but whenever I change the HorizontalScrollView to Frame/Relative layouts(with the width set to wrap_content) the image view is scaled down to fit the screen.

Is there a way to keep the imageView width intact(with height matching that of the screen) so that it would remain bigger than the device screen?(without cropping)

I could then use custom animation to scroll right.

I have looked at similar questions but I wasn't able to find anything that would work in this case.

Body:
What you could do is to try to override the onTouchListener for the HorizontalScrollView.

For example, something like this:

scrollView.setOnTouchListener(new OnTouch());

private class OnTouch implements OnTouchListener
{
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    return true;
    }
}

This would disable  the user from scrolling the HorizontalScrollView while you could probably still scroll it programmatically.


问:
iPage "No input file specified." on /admin page
I'm having this problem my app which is build in codeigniter 2.14 was working fine in my localhost using xammp but when i migrated it to my hosting server which is iPage.com i can no longer access my dashboard it prompts a No input specified error.</p>

```<code>Options +FollowSymlinks -MultiViews -Indexes

<IfModule mod_rewrite.c>

 RewriteEngine on
 RewriteBase /

 # If the user types "index.php" or "admin.php".
 RewriteCond $1 !^(index\.php|admin\.php|images|robots\.txt)

 # If the user types just "admin".
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^admin$ admin\.php [L,QSA]

 # If the user enter in any admin section, like "admin/section".
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^admin\/(.*)$ admin\.php/$1 [L,QSA]

 # If the user types any site section, like "site/section".
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index\.php/$1 [L,QSA]

</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>
</code>```

答:
Just add the following to the .htaccess file :

```<code>DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
</code>```

Body:
I'm having this problem my app which is build in codeigniter 2.14 was working fine in my localhost using xammp but when i migrated it to my hosting server which is iPage.com i can no longer access my dashboard it prompts a No input specified error.

Options +FollowSymlinks -MultiViews -Indexes

<IfModule mod_rewrite.c>

 RewriteEngine on
 RewriteBase /

 # If the user types "index.php" or "admin.php".
 RewriteCond $1 !^(index\.php|admin\.php|images|robots\.txt)

 # If the user types just "admin".
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^admin$ admin\.php [L,QSA]

 # If the user enter in any admin section, like "admin/section".
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^admin\/(.*)$ admin\.php/$1 [L,QSA]

 # If the user types any site section, like "site/section".
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index\.php/$1 [L,QSA]

</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

Body:
Just add the following to the .htaccess file :

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]


问:
PHP Online file analyzing
I'm looking for some tutorial on how from a webapplication upload a file and while uploading analyzing it.

I mean a user chooses a file from his computer on a web app, the file is excel. After choosing elaborate it the file is analyzed and some stuff is done, once the work is complete the user is redirect to  a webapp with the results.

I need just some hints on where to start investigating.

Many thanks!

答:
There are a number of libraries available for accessing the data in an Excel workbook, including my own PHPExcel which can read both .xls and .xlsx files. exactly how to transfer data from the workbook to a database depends on the content of the workbook, but basically you need to iterate through each row of a worksheet and determine its cell content, then build a SQL statement to insert that cell content into your database.

You definitely need the file to be uploaded in its entirety before you try reading it though.

Title: PHP Online file analyzing