问:
python dask dataframes - concatenate groupby.apply output to a single data frame
I am using dask dataframe.groupby().apply()
and get a dask series as a return value.
I am each group to a list triplets such as (a,b,1) and wish then to turn all the triplets into a single dask data frame

I am using this code in the end of the mapping function to return the triplets as a dask df

```<code>#assume here that trips is a generator for tripletes such as you would produce from itertools.product([l1,l2,l3])
trip = list(itertools.chain.from_iterable(trip))
df = pd.DataFrame.from_records(trip)
return dd.from_pandas(df,npartitions=1)
</code>```

then when I try to use something similar to pandas concat with dask concatenate

Assume the result of the apply function is the variable result.
I am trying to use
import dask.dataframe as dd
dd.concat(result, axis=0

and get the error

raise TypeError("dfs must be a list of DataFrames/Series objects")
  TypeError: dfs must be a list of DataFrames/Series objects

But when I check for the type of result using

```<code>print type(result)
</code>```

I get

output: class 'dask.dataframe.core.Series'

What is the proper way to apply a function over groups of dask groupby object and get all the results into one dataframe?

Thanks

edit:--------------------------------------------------------------
in order to produce the use case, assume this fake data generation

```<code>import random
import pandas as pd
import dask.dataframe as dd
people = [[random.randint(1,3), random.randint(1,3), random.randint(1,3)] for i in range(1000)]
ddf = dd.from_pandas(pd.DataFrame.from_records(people, columns=["first name", "last name", "cars"]), npartitions=1)
</code>```

Now my mission is to group people by first and last name (e.g all the people with same first name & first last name) and than I need to get a new dask data frame which will contain how many cars each group had.

Assume that the apply function can return either a series of lists of tuples e.g [(name,name,cars count),(name,name,cars count)] or a data frame with the same columns - name, name, car count.

Yes, I know that particular use case can be solved in another way, but please trust me, my use case is more complex. But i can not share the data and can not generate any similar data. so let's use a dummy data :-)

The challenge is to connect all the results of the apply into a single dask data frame (pandas data frame will be a problem here, data will not fit in memory - so transitions via a pandas data frame will be a problem)

答:
For your edit:</p>

```<code>In [8]: ddf.groupby(['first name', 'last name']).cars.count().compute()
Out[8]:
first name  last name
1           1            107
            2            107
            3            110
2           1            117
            2            120
            3             99
3           1            119
            2            103
            3            118
Name: cars, dtype: int64
</code>```

Body:
I am using dask dataframe.groupby().apply()
and get a dask series as a return value.
I am each group to a list triplets such as (a,b,1) and wish then to turn all the triplets into a single dask data frame

I am using this code in the end of the mapping function to return the triplets as a dask df

#assume here that trips is a generator for tripletes such as you would produce from itertools.product([l1,l2,l3])
trip = list(itertools.chain.from_iterable(trip))
df = pd.DataFrame.from_records(trip)
return dd.from_pandas(df,npartitions=1)

then when I try to use something similar to pandas concat with dask concatenate

Assume the result of the apply function is the variable result.
I am trying to use
import dask.dataframe as dd
dd.concat(result, axis=0

and get the error

raise TypeError("dfs must be a list of DataFrames/Series objects")
  TypeError: dfs must be a list of DataFrames/Series objects

But when I check for the type of result using

print type(result)

I get

output: class 'dask.dataframe.core.Series'

What is the proper way to apply a function over groups of dask groupby object and get all the results into one dataframe?

Thanks

edit:--------------------------------------------------------------
in order to produce the use case, assume this fake data generation

import random
import pandas as pd
import dask.dataframe as dd
people = [[random.randint(1,3), random.randint(1,3), random.randint(1,3)] for i in range(1000)]
ddf = dd.from_pandas(pd.DataFrame.from_records(people, columns=["first name", "last name", "cars"]), npartitions=1)

Now my mission is to group people by first and last name (e.g all the people with same first name & first last name) and than I need to get a new dask data frame which will contain how many cars each group had.

Assume that the apply function can return either a series of lists of tuples e.g [(name,name,cars count),(name,name,cars count)] or a data frame with the same columns - name, name, car count.

Yes, I know that particular use case can be solved in another way, but please trust me, my use case is more complex. But i can not share the data and can not generate any similar data. so let's use a dummy data :-)

The challenge is to connect all the results of the apply into a single dask data frame (pandas data frame will be a problem here, data will not fit in memory - so transitions via a pandas data frame will be a problem)

Body:
For your edit:

In [8]: ddf.groupby(['first name', 'last name']).cars.count().compute()
Out[8]:
first name  last name
1           1            107
            2            107
            3            110
2           1            117
            2            120
            3             99
3           1            119
            2            103
            3            118
Name: cars, dtype: int64


来源: stackexchange

问:
Why use hashed CSS stylesheet and Javascript file names?
When looking deeply at the code of some most popular websites, I've seen many times that, CSS and JavaScript file name are like this,

```<code><link type="text/css" rel="stylesheet" href="//sample.com/css/css__k3sYInttBtNNuJgtPSyqaYy9vVxS4qTZLrfs1ujQB9g__SH_QaIH3bnSp3nOw8n8afhszfHJlxVt51qRlrrrOnk0__fBOuweRojwN82z7EY4v-sVsMwU_P_vZSaU3fmyho6Do.css" media="all" />

<script type="text/javascript" src="//sample.com/js/js__-V23Vc4PVahQcqfyxss_rmNogErBARnPCvI7oPXC0qQ__O-yO5Gg8pRRaefl4d0X9qXUJTOSHq0yazxF-4tJCU_k__fBOuweRojwN82z7EY4v-sVsMwU_P_vZSaU3fmyho6Do.js"></script>
</code>```

It seems like that file names has been hashed and I don't know what is the reason. So I've got following problems.

What is the purpose of using this kind of method?

I've seen Very complex folder names also. Why is that?

Are there any security concerns?

Can we dynamically change file/folder names using PHP for maximum security?

I am little new to this area.

答:
You can assume that these file/folder names are not what the developers are working with during the development phase, but rather an artifact of the files' build process. JavaScript and CSS is often built into a single file from several source files, involving more or less compilation/transpilation and bundling steps.

The reason why you would want the filename to be/include a hash of the file is that this forces a cache invalidation whenever the file changes. Static files can be cached by the browser, server, and a number of other agents in-between. This is fine as long as the file does not change. However, when a new release is published, the user should be served this new version. If the file name of the resource changes, the browser will always request the new version of the file from the server, rather than using a cached version.

You should not rely on complex file names like this as a security/authorization feature. The file names are referenced in the app's index file and thus known to the end user. Also, security by obscurity is generally a bad idea.

ContentLicense: CC BY-SA 3.0

Body:
When looking deeply at the code of some most popular websites, I've seen many times that, CSS and JavaScript file name are like this,

<link type="text/css" rel="stylesheet" href="//sample.com/css/css__k3sYInttBtNNuJgtPSyqaYy9vVxS4qTZLrfs1ujQB9g__SH_QaIH3bnSp3nOw8n8afhszfHJlxVt51qRlrrrOnk0__fBOuweRojwN82z7EY4v-sVsMwU_P_vZSaU3fmyho6Do.css" media="all" />

It seems like that file names has been hashed and I don't know what is the reason. So I've got following problems.

What is the purpose of using this kind of method?

I've seen Very complex folder names also. Why is that?

Are there any security concerns?

Can we dynamically change file/folder names using PHP for maximum security?

I am little new to this area.


问:
AWS javascript SDK Kinesis getShardIterator Error: UnexpectedParameter: Unexpected key 'Timestamp' found in params
I am using the aws-sdk(version 2.1.8) to get records out from Kinesis. This is within a node Lambda function. Trying to use ShardIteratorType: AT_TIMESTAMP. I supply a Timestamp in the params object

```<code>const AWS = require("aws-sdk");
const kinesis = new AWS.Kinesis({ region: 'us-east-1' });
var params = {
    ShardId: shard.ShardId, /* required */
    ShardIteratorType: 'AT_TIMESTAMP', /* required */
    StreamName: process.env.STREAM_NAME, /* required */
    Timestamp: new Date(2017, 11, 08, 14, 32, 51)
};

kinesis.getShardIterator(params, function (err, data) {
    if (err) {
        return defer.reject(err);
    }
    defer.resolve(data);
});
</code>```

But I get this error: Unexpected key 'Timestamp' found in params.  Checked google, SO, and aws forums, to no avail. I am following the documentation from AWS: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html#getShardIterator-property

Here are the logs from the Lambda function where I use getShardIterator

```<code>2017-11-08T15:53:13.551Z    ec3ef291-c49c-11e7-ad35-473206669891    SHARD
ITERATOR TYPE:  AT_TIMESTAMP
2017-11-08T15:53:13.551Z    ec3ef291-c49c-11e7-ad35-473206669891
TIMESTAMP:  2017-12-08T14:32:51.000Z
</code>```

ShardIteratorTypes LATEST and TRIM_HORIZON work fine. It is only when I try to use AT_TIMESTAMP that the issue occurs.

答:
I found what was going on. The aws-sdk is taking the Timestamp value and multiplying it by 1000. This is insane - nowhere is this mentioned in the docs, where it simply states

The timestamp of the data record from which to start reading. Used with shard iterator type AT_TIMESTAMP. A timestamp is the Unix epoch date with precision in milliseconds

Therefore, using this

Timestamp: 1510673368611

will fail, even though it is a valid timestamp in milliseconds. You have to divide by 1000

Timestamp: 1510673368.611

This was pretty infuriating to discover. Just validate the value I send, don't alter it and then validate the result. Or, you know, MENTION THAT THIS HAPPENS IN THE DOCS.

Body:
I am using the aws-sdk(version 2.1.8) to get records out from Kinesis. This is within a node Lambda function. Trying to use ShardIteratorType: AT_TIMESTAMP. I supply a Timestamp in the params object

const AWS = require("aws-sdk");
const kinesis = new AWS.Kinesis({ region: 'us-east-1' });
var params = {
    ShardId: shard.ShardId, /* required */
    ShardIteratorType: 'AT_TIMESTAMP', /* required */
    StreamName: process.env.STREAM_NAME, /* required */
    Timestamp: new Date(2017, 11, 08, 14, 32, 51)
};

kinesis.getShardIterator(params, function (err, data) {
    if (err) {
        return defer.reject(err);
    }
    defer.resolve(data);
});

But I get this error: Unexpected key 'Timestamp' found in params.  Checked google, SO, and aws forums, to no avail. I am following the documentation from AWS: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html#getShardIterator-property

Here are the logs from the Lambda function where I use getShardIterator

2017-11-08T15:53:13.551Z    ec3ef291-c49c-11e7-ad35-473206669891    SHARD
ITERATOR TYPE:  AT_TIMESTAMP
2017-11-08T15:53:13.551Z    ec3ef291-c49c-11e7-ad35-473206669891
TIMESTAMP:  2017-12-08T14:32:51.000Z

ShardIteratorTypes LATEST and TRIM_HORIZON work fine. It is only when I try to use AT_TIMESTAMP that the issue occurs.


问:
Worse is better. Is there an example?
Is there a widely-used algorithm that has time complexity worse than that of another known algorithm but it is a better choice in all practical situations (worse complexity but better otherwise)?

An acceptable answer might be in a form:

There are algorithms A and B that
  have O(N**2) and O(N) time
  complexity correspondingly, but B
  has such a big constant that it has no
  advantages over A for inputs less
  then a number of atoms in the
  Universe.

Examples highlights from the answers:

Simplex algorithm -- worst-case is exponential time  -- vs. known polynomial-time algorithms for convex optimization problems.

A naive median of medians algorithm -- worst-case O(N**2) vs. known O(N) algorithm.

Backtracking regex engines -- worst-case exponential vs. O(N) Thompson NFA -based engines.

All these examples exploit worst-case vs. average scenarios.

Are there examples that do not rely on the difference between the worst case vs. average case scenario?

Related:

The Rise of ``Worse is Better''. (For the purpose of this question the "Worse is Better" phrase is used in a narrower (namely -- algorithmic time-complexity) sense than in the article)

Python's Design Philosophy:

The ABC group strived for perfection.
  For example, they used tree-based data
  structure algorithms that were proven
  to be optimal for asymptotically large
  collections (but were not so great for
  small collections).

This example would be the answer if there were no computers capable of storing these large collections (in other words large is not large enough in this case).

Coppersmith–Winograd algorithm for square matrix multiplication is a good example (it is the fastest (2008) but it is inferior to worse algorithms). Any others?
From the wikipedia article: "It is not used in practice because it only provides an advantage for matrices so large that they cannot be processed by modern hardware (Robinson 2005)."

答:
This example would be the answer if there were no computers capable of storing these large collections.

Presumably the size of the collection was 641K.

When working in the technical computing group for BAE SYSTEMS, which looked after structural and aerodynamic code for various aircraft, we had a codebase going back at least 25 years (and a third of the staff had been there that long).

Many of the algorithms were optimised for performance on a 16bit mainframe, rather than for scalability. These optimisations were entirely appropriate for 1970s hardware, but performed poorly on larger datasets on the 32 and 64 bit systems which replaced it. If you're choosing something with worse scalability which works better on the hardware you are currently working on, be aware that this is an optimisation, and it may not apply in the future. At the time those 1970s routines were written, data size we put into them in the 2000s was not practical. Unfortunately, trying to extract a clear algorithm from those codes which then could be implemented to suit modern hardware was not trivial.

Short of boiling the oceans, what counts as 'all practical situations' is often a time dependent variable.

OwnerDisplayName: J.F. Sebastian

ContentLicense: CC BY-SA 2.5

Title: Worse is better. Is there an example?

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Pete Kirkham

LastEditorDisplayName: Pete Kirkham


问:
Keeping pages inside an iframe
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?</p>

```<code>if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}
</code>```

答:
Yes it is possible, there are several methods of anti-frame busting including disabling JS in a frame (sandboxing, designMode). All described in Limitations of OWASP:Defending_with_Frame_Breaking_Scripts.

Generally use it only with intranet or restricted access site. If you expose site publicly with such tricks you may expect blacklisting by Google or others.

Title: Keeping pages inside an iframe

Body:
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?

if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}


问:
Azure microservices for message transaction
I want to achieve microservices architecture. I've converted my XML message into json. I am going to split the message based on micro services and each microservices will deserialize few json content and store few fields in a object. Then I am going to group all objects from various microservices again in a single object to move for further process.

How to achieve this? i just want to do it with function app.

答:
One approach would be to Azure Service Bus(es) and Web Jobs (under web apps). Unprocessed JSON or XML could exist as messages in a particular queue. You can then use continual web jobs (under Azure Web Apps) to monitor the bus. Use C# in a Web Job to monitor and then parse your message as needed, and then put the results into another bus (or one bus with multiple queues). Another web job can process that bus. Etc., etc...

In this model, you can stitch together a nice SOA workflow.

Good luck, Dhivakar!


问:
Tsql: CHARINDEX and REPLACE Dosn't recognize special character (Unicode-8207)
Given the following variable:

```<code>declare @str nvarchar(50) = 'abc'
</code>```

between 'a' and 'b' there is a hidden character which is: nchar(8207)

therefore:

```<code>select len(@str) --4
</code>```

and:

```<code>select unicode(SUBSTRING(@str,2,1)) --8207
</code>```

my problem is that I have many such records, and I have to find all these characters and delete them.

I'm trying find by CHARINDEX or REPLACE but it just does not recognize this character:

```<code>select CHARINDEX(Nchar(unicode(8207)),@str) --0
select REPLACE (@str , Nchar(unicode(8207)), '1') --abc
</code>```

答:
It seems that REPLACE() does indeed not work.
Looks like you will need to use STUFF()

```<code>DECLARE @Moo NVARCHAR(50) = CONCAT('a', NCHAR(8207), 'b', 'c')

SELECT   @Moo
        ,LEN(@Moo)
        ,LEN(STUFF(@moo, 2, 1, ''))
        ,STUFF(@moo, 2, 1, '')
</code>```

However, this leaves you with having to know the locations of the offending unprintable characters. A WHILE loop or Tally table might serve you well here.

Body:
Given the following variable:

declare @str nvarchar(50) = 'abc'

between 'a' and 'b' there is a hidden character which is: nchar(8207)

therefore:

select len(@str) --4

and:

select unicode(SUBSTRING(@str,2,1)) --8207

my problem is that I have many such records, and I have to find all these characters and delete them.

I'm trying find by CHARINDEX or REPLACE but it just does not recognize this character:

select CHARINDEX(Nchar(unicode(8207)),@str) --0
select REPLACE (@str , Nchar(unicode(8207)), '1') --abc

Body:
It seems that REPLACE() does indeed not work.
Looks like you will need to use STUFF()

DECLARE @Moo NVARCHAR(50) = CONCAT('a', NCHAR(8207), 'b', 'c')

SELECT   @Moo
        ,LEN(@Moo)
        ,LEN(STUFF(@moo, 2, 1, ''))
        ,STUFF(@moo, 2, 1, '')

However, this leaves you with having to know the locations of the offending unprintable characters. A WHILE loop or Tally table might serve you well here.


问:
Indices of n largest values in lower triangular region of a NumPy array
I have a numpy cosine similarity matrix. I want to find the indices of the n largest values, but exclude the 1.0's on the diagonals and only for the lower triangular region in it.

```<code>similarities = [[ 1.          0.18898224  0.16903085]
 [ 0.18898224  1.          0.67082039]
 [ 0.16903085  0.67082039  1.        ]]
</code>```

In this case, if I want the two highest values, I would want it to return [1, 0] and [2, 1].

I have tried using argpartition but this does not return what I'm looking for

```<code>n_select = 1
most_similar = (-similarities).argpartition(n_select, axis=None)[:n_select]
</code>```

How can I get the n highest values excluding the diagonal 1's and also exclude the upper triangular elements?

答:
Remember that the diagonal elements of a square matrix have a unique property: i+j=n, where n is matrix dimension.
Then, you can just find the n + number of (diagonal elements) max elements of the array and then iterate through them and exclude the tuples  (i,j) where i+j=n.
Hope it helps!</p>

Body:
I have a numpy cosine similarity matrix. I want to find the indices of the n largest values, but exclude the 1.0's on the diagonals and only for the lower triangular region in it.

similarities = [[ 1.          0.18898224  0.16903085]
 [ 0.18898224  1.          0.67082039]
 [ 0.16903085  0.67082039  1.        ]]

In this case, if I want the two highest values, I would want it to return [1, 0] and [2, 1].

I have tried using argpartition but this does not return what I'm looking for

n_select = 1
most_similar = (-similarities).argpartition(n_select, axis=None)[:n_select]

How can I get the n highest values excluding the diagonal 1's and also exclude the upper triangular elements?


问:
Constructing PeriodIndex from two int64 columns
The docs on pandas.PeriodIndex give the following example for construction:

>>> idx = PeriodIndex(year=year_arr, quarter=q_arr)

And specify the types for those two parameters:

year : int, array, or Series, default None

month : int, array, or Series, default None

But I'm running into a TypeError trying to use this type of construction.

```<code>import numpy as np
import pandas as pd

# (Year, Month) MultiIndex'd DataFrame
idx = pd.MultiIndex.from_product(([2017, 2016], range(1, 13)))
df = pd.DataFrame(np.random.randn(24, 2), index=idx, columns=['a', 'b'])

print(df.head())
               a         b
2017 1  0.406534 -0.516329
     2 -0.687286 -0.066606
     3  1.493217  0.539294
     4  2.069313  0.415216
     5 -0.212414 -1.375707

# Seems to mimic the construction example from the docs above:
pd.PeriodIndex(year=df.index.get_level_values(0),
               month=df.index.get_level_values(1))
# TypeError: expected string or bytes-like object

# Same issue even if I specify inputs as NumPy arrays or lists
pd.PeriodIndex(year=df.index.get_level_values(0).values,
               month=df.index.get_level_values(1).values)
pd.PeriodIndex(year=df.index.get_level_values(0).tolist(),
               month=df.index.get_level_values(1).tolist())
</code>```

Bonus question: can I unpack the levels of a MultiIndex?  Presently I have

```<code>year, month = list(zip(*df.index.get_values()))
</code>```

Is there a prescribed method to get an iterable from the index's levels?

Working in: pandas 0.20.3.

Body:
The docs on pandas.PeriodIndex give the following example for construction:

>>> idx = PeriodIndex(year=year_arr, quarter=q_arr)

And specify the types for those two parameters:

year : int, array, or Series, default None

month : int, array, or Series, default None

But I'm running into a TypeError trying to use this type of construction.

import numpy as np
import pandas as pd

# (Year, Month) MultiIndex'd DataFrame
idx = pd.MultiIndex.from_product(([2017, 2016], range(1, 13)))
df = pd.DataFrame(np.random.randn(24, 2), index=idx, columns=['a', 'b'])

print(df.head())
               a         b
2017 1  0.406534 -0.516329
     2 -0.687286 -0.066606
     3  1.493217  0.539294
     4  2.069313  0.415216
     5 -0.212414 -1.375707

# Seems to mimic the construction example from the docs above:
pd.PeriodIndex(year=df.index.get_level_values(0),
               month=df.index.get_level_values(1))
# TypeError: expected string or bytes-like object

# Same issue even if I specify inputs as NumPy arrays or lists
pd.PeriodIndex(year=df.index.get_level_values(0).values,
               month=df.index.get_level_values(1).values)
pd.PeriodIndex(year=df.index.get_level_values(0).tolist(),
               month=df.index.get_level_values(1).tolist())

Bonus question: can I unpack the levels of a MultiIndex?  Presently I have

year, month = list(zip(*df.index.get_values()))

Is there a prescribed method to get an iterable from the index's levels?

Working in: pandas 0.20.3.

Body:
You can get this to work by explicitly specifying the frequency string and passing in lists/tuples:

In [10]: pd.PeriodIndex(year=df.index.get_level_values(0).tolist(),
    ...:                month=df.index.get_level_values(1).tolist(), freq='M')
    ...:
Out[10]:
PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06',
             '2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12',
             '2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06',
             '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'],
            dtype='period[M]', freq='M')

Or alternatively unpacking with zip:

In [11]: pd.PeriodIndex(year,month=zip(*df.index.get_values()), freq='M')
Out[11]:
PeriodIndex(['2017-01', '2017-01', '2017-01', '2017-01', '2017-01', '2017-01',
             '2017-01', '2017-01', '2017-01', '2017-01', '2017-01', '2017-01',
             '2016-01', '2016-01', '2016-01', '2016-01', '2016-01', '2016-01',
             '2016-01', '2016-01', '2016-01', '2016-01', '2016-01', '2016-01'],
            dtype='period[M]', freq='M')

Not sure why it isn't working with an Index or numpy array.  Probably a bug.


问:
Emacs buffer-local font
For all my tasks I use URW Chancery L font in Emacs. But for some tasks,
like org-mode tables, shell or sunrise-commander, I would like to set mono-width font.
So, my question, how can I do it? All I found about it is set-default-font, which is not what I want.

答:
Did you try to customize org-table ?

You can modify it with org-menu > Customize > Customize > org-table

or use the command line

M-x set-face-font RET org-table RET -PfEd-DejaVu Sans Mono-normal-normal-normal-*-*-*-*-*-m-0-iso10646-1

Use tab to auto-complete and see other available fonts

Finaly you could also directly modify you init.el to have something like

```<code>(custom-set-faces
 '(org-table ((t (:foreground "LightSkyBlue" :family "DejaVu Sans Mono")))))
</code>```

Title: Emacs buffer-local font

Body:
Did you try to customize org-table ?

You can modify it with org-menu > Customize > Customize > org-table

or use the command line

M-x set-face-font RET org-table RET -PfEd-DejaVu Sans Mono-normal-normal-normal-*-*-*-*-*-m-0-iso10646-1

Use tab to auto-complete and see other available fonts

Finaly you could also directly modify you init.el to have something like

(custom-set-faces
 '(org-table ((t (:foreground "LightSkyBlue" :family "DejaVu Sans Mono")))))


问:
How do I call a custom function in a parent class when panResponder starts moving?
If I have an imported component called <Draggable /> in react-native,

How do I call a custom function in the parent component when onPanResponderGrant decides the gesture has started?

You'll see I'm passing an id of 'A' and 'B' into <Draggable />, and I'd like to be able to call them back out on touch, and display them in the infoBox at the bottom of the main View?

```<code>// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
        };
    }
    render(){
        return (
          <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                      <Text>Draggable Container</Text>
                      <Draggable id='A' />
                      <Draggable id='B' />
                </View>
                <View style={styles.infoBar}>{this.infoBarData()}</View>
          </View>
        );
    }
    infoBarData(){
        if (this.state.dID) {
            return(
                <Text>{this.state.dID}</Text>
            )

        }
    }
}
</code>```

and

```<code>// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated, } from 'react-native';
import styles from './styles';

class Draggable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan : new Animated.ValueXY(),
        };
        this.panResponder = PanResponder.create({
            onStartShouldSetPanResponder    : () => true,
            onPanResponderMove              : Animated.event([null,{
                dx  : this.state.pan.x,
                dy  : this.state.pan.y,
            }]),
            onPanResponderRelease           : () => {
              Animated.spring(this.state.pan,{toValue:{x:0, y:0}}).start();
            }
        });
    }
    render() {
        return (
            <Animated.View
                {...this.panResponder.panHandlers}
                style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
                <Text style={styles.textAlt}>Drag me!</Text>
                <Text style={styles.textNum}>{this.props.id}</Text>
            </Animated.View>
        )
    }
}
export default Draggable;
</code>```

EDIT

I've added the following to the parent class

```<code>// Object
<Draggable
  onPanResponderMove={this.onStopMove}
  onPanResponderRelease={this.onMove}
  id='A' />

// Methods
onMove = (dID) => {
  this.setState({ dID });
}

onStopMove = () => {
  this.setState({ dID: null });
}
</code>```

And I added the following to the Draggable class.

```<code>// Methods
_handleOnPanResponderMove(evt, gestureState) {
    Animated.event([null,{
        // These animate movement on the X/Y axis
        dx  : this.state.pan.x,
        dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
}
</code>```

But when I move the animated event out of the PanResponder.create({})

by doing the following, it loses it's ability to be dragged. I assume this is something to do with

```<code>PanResponder.create({
    ...,
    onPanResponder : this._handleOnPanResponder.bind(this),
    ...,
})
</code>```

Not being returned a value?

EDIT 2

I also tried to add the following, but again, didn't work.

```<code>PanResponder.create({
    ...,
    onPanResponder : (evt ,gesture) => {
        Animated.event([null,{
            // These animate movement on the X/Y axis
            dx  : this.state.pan.x,
            dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
    }
    ...,
})
</code>```

答:
You need to pass a callback handler with Draggable component, like

```<code><Draggable id="A" gestureHandler={(data) => {
/*
  do whatever you want to do with the data, like store it into state
*/
}}
</code>```

In your Draggable component, call this handler as per your requirement (when it is decided that gesture has started), like

```<code>if (this.props.gestureHandler instanceof Function) {
   this.props.gestureHandler.call(this, this.props.id);
}
</code>```

Body:
If I have an imported component called <Draggable /> in react-native,

How do I call a custom function in the parent component when onPanResponderGrant decides the gesture has started?

You'll see I'm passing an id of 'A' and 'B' into <Draggable />, and I'd like to be able to call them back out on touch, and display them in the infoBox at the bottom of the main View?

// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
        };
    }
    render(){
        return (
          <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                      <Text>Draggable Container</Text>
                      <Draggable id='A' />
                      <Draggable id='B' />
                </View>
                <View style={styles.infoBar}>{this.infoBarData()}</View>
          </View>
        );
    }
    infoBarData(){
        if (this.state.dID) {
            return(
                <Text>{this.state.dID}</Text>
            )

        }
    }
}

and

// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated, } from 'react-native';
import styles from './styles';

class Draggable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan : new Animated.ValueXY(),
        };
        this.panResponder = PanResponder.create({
            onStartShouldSetPanResponder    : () => true,
            onPanResponderMove              : Animated.event([null,{
                dx  : this.state.pan.x,
                dy  : this.state.pan.y,
            }]),
            onPanResponderRelease           : () => {
              Animated.spring(this.state.pan,{toValue:{x:0, y:0}}).start();
            }
        });
    }
    render() {
        return (
            <Animated.View
                {...this.panResponder.panHandlers}
                style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
                <Text style={styles.textAlt}>Drag me!</Text>
                <Text style={styles.textNum}>{this.props.id}</Text>
            </Animated.View>
        )
    }
}
export default Draggable;

EDIT

I've added the following to the parent class

// Object
<Draggable
  onPanResponderMove={this.onStopMove}
  onPanResponderRelease={this.onMove}
  id='A' />

// Methods
onMove = (dID) => {
  this.setState({ dID });
}

onStopMove = () => {
  this.setState({ dID: null });
}

And I added the following to the Draggable class.

// Methods
_handleOnPanResponderMove(evt, gestureState) {
    Animated.event([null,{
        // These animate movement on the X/Y axis
        dx  : this.state.pan.x,
        dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
}

But when I move the animated event out of the PanResponder.create({})

by doing the following, it loses it's ability to be dragged. I assume this is something to do with

PanResponder.create({
    ...,
    onPanResponder : this._handleOnPanResponder.bind(this),
    ...,
})

Not being returned a value?

EDIT 2

I also tried to add the following, but again, didn't work.

PanResponder.create({
    ...,
    onPanResponder : (evt ,gesture) => {
        Animated.event([null,{
            // These animate movement on the X/Y axis
            dx  : this.state.pan.x,
            dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
    }
    ...,
})

Body:
You need to pass a callback handler with Draggable component, like

<Draggable id="A" gestureHandler={(data) => {
/*
  do whatever you want to do with the data, like store it into state
*/
}}

In your Draggable component, call this handler as per your requirement (when it is decided that gesture has started), like

if (this.props.gestureHandler instanceof Function) {
   this.props.gestureHandler.call(this, this.props.id);
}


问:
How to convert Milliseconds to "X mins, x seconds" in Java?
I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.

What's the best way to do this?

答:
This is easier in Java 9:

```<code>    Duration elapsedTime = Duration.ofMillis(millisDiff );
    String humanReadableElapsedTime = String.format(
            "%d hours, %d mins, %d seconds",
            elapsedTime.toHours(),
            elapsedTime.toMinutesPart(),
            elapsedTime.toSecondsPart());
</code>```

This produces a string like 0 hours, 39 mins, 9 seconds.

If you want to round to whole seconds before formatting:

```<code>    elapsedTime = elapsedTime.plusMillis(500).truncatedTo(ChronoUnit.SECONDS);
</code>```

To leave out the hours if they are 0:

```<code>    long hours = elapsedTime.toHours();
    String humanReadableElapsedTime;
    if (hours == 0) {
        humanReadableElapsedTime = String.format(
                "%d mins, %d seconds",
                elapsedTime.toMinutesPart(),
                elapsedTime.toSecondsPart());

    } else {
        humanReadableElapsedTime = String.format(
                "%d hours, %d mins, %d seconds",
                hours,
                elapsedTime.toMinutesPart(),
                elapsedTime.toSecondsPart());
    }
</code>```

Now we can have for example 39 mins, 9 seconds.

To print minutes and seconds with leading zero to make them always two digits, just insert 02 into the relevant format specifiers, thus:

```<code>    String humanReadableElapsedTime = String.format(
            "%d hours, %02d mins, %02d seconds",
            elapsedTime.toHours(),
            elapsedTime.toMinutesPart(),
            elapsedTime.toSecondsPart());
</code>```

Now we can have for example 0 hours, 39 mins, 09 seconds.

OwnerDisplayName: Click Upvote

Body:
This is easier in Java 9:

    Duration elapsedTime = Duration.ofMillis(millisDiff );
    String humanReadableElapsedTime = String.format(
            "%d hours, %d mins, %d seconds",
            elapsedTime.toHours(),
            elapsedTime.toMinutesPart(),
            elapsedTime.toSecondsPart());

This produces a string like 0 hours, 39 mins, 9 seconds.

If you want to round to whole seconds before formatting:

    elapsedTime = elapsedTime.plusMillis(500).truncatedTo(ChronoUnit.SECONDS);

To leave out the hours if they are 0:

    long hours = elapsedTime.toHours();
    String humanReadableElapsedTime;
    if (hours == 0) {
        humanReadableElapsedTime = String.format(
                "%d mins, %d seconds",
                elapsedTime.toMinutesPart(),
                elapsedTime.toSecondsPart());

    } else {
        humanReadableElapsedTime = String.format(
                "%d hours, %d mins, %d seconds",
                hours,
                elapsedTime.toMinutesPart(),
                elapsedTime.toSecondsPart());
    }

Now we can have for example 39 mins, 9 seconds.

To print minutes and seconds with leading zero to make them always two digits, just insert 02 into the relevant format specifiers, thus:

    String humanReadableElapsedTime = String.format(
            "%d hours, %02d mins, %02d seconds",
            elapsedTime.toHours(),
            elapsedTime.toMinutesPart(),
            elapsedTime.toSecondsPart());

Now we can have for example 0 hours, 39 mins, 09 seconds.


问:
Json.Net deserialize JSON objects
I've popped consuming a WebServer returning the Json bellow, and I'm not able to convert it to an object.

Json

```<code>{
    "success":true,
    "data":{
        "24486146360":{
            "rfid":"123465789456",
            "products":[
            {
                "sale_id":35,
                "quantity":2,
                "price":"1",
                "total":"2",
                "unit":"uni",
                "sku":14
            },
            {
                "sale_id":36,
                "quantity":2,
                "price":"2.5",
                "total":"5",
                "unit":"uni",
                "sku":17
            }
            ]
        },
        "24758345953":{
            "rfid":"2129",
            "products":[
            {
                "sale_id":39,
                "quantity":1,
                "price":"10",
                "total":"10",
                "unit":"ml",
                "sku":19998
            }
            ]
        },
        "64577015900":{
            "rfid":"1934",
            "products":[
            {
                "sale_id":40,
                "quantity":1,
                "price":"10",
                "total":"10",
                "unit":"ml",
                "sku":19998
            }
            ]
        },
        "56768990934":{
            "rfid":"1746",
            "products":[
            {
                "sale_id":46,
                "quantity":1,
                "price":"8.00",
                "total":"8",
                "unit":"UN",
                "sku":20
            }
            ]
        }
    }
}
</code>```

I used json2sharp to generate a class from the JSON, I then cleaned up the class and was left with the following:

My Class create help for json2sharp

```<code>public class Consumo
{
    public string rfid { get; set; }
    public List<ConsumoProduto> products { get; set; }
}

public class ConsumoProduto
{
    public int sale_id { get; set; }
    public double quantity { get; set; }
    public string price { get; set; }
    public string total { get; set; }
    public string unit { get; set; }
    public int sku { get; set; }
}

public class RetornoConsumo
{
    [JsonProperty("success")]
    public bool Processado { get; set; }
    [JsonProperty("data")]
    public List<Consumo> Registro { get; set; }
}
</code>```

My Problem

how do I convert Json to a valid object using Json.Net?

Test

I tried to do this and I could not

```<code>Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);
</code>```

答:
In your RetornoConsumo class, the Registro property needs to be a Dictionary<string, Consumo> not a List<Consumo>.

```<code>public class RetornoConsumo
{
    [JsonProperty("success")]
    public bool Processado { get; set; }
    [JsonProperty("data")]
    public Dictionary<string, Consumo> Registro { get; set; }
}
</code>```

Then, you need to deserialize the JSON into the RetornoConsumo class:

```<code>var data = JsonConvert.DeserializeObject<RetornoConsumo>(json);
</code>```

Fiddle: https://dotnetfiddle.net/vfhdXp

Title: Json.Net deserialize JSON objects

Body:
I've popped consuming a WebServer returning the Json bellow, and I'm not able to convert it to an object.

Json

{
    "success":true,
    "data":{
        "24486146360":{
            "rfid":"123465789456",
            "products":[
            {
                "sale_id":35,
                "quantity":2,
                "price":"1",
                "total":"2",
                "unit":"uni",
                "sku":14
            },
            {
                "sale_id":36,
                "quantity":2,
                "price":"2.5",
                "total":"5",
                "unit":"uni",
                "sku":17
            }
            ]
        },
        "24758345953":{
            "rfid":"2129",
            "products":[
            {
                "sale_id":39,
                "quantity":1,
                "price":"10",
                "total":"10",
                "unit":"ml",
                "sku":19998
            }
            ]
        },
        "64577015900":{
            "rfid":"1934",
            "products":[
            {
                "sale_id":40,
                "quantity":1,
                "price":"10",
                "total":"10",
                "unit":"ml",
                "sku":19998
            }
            ]
        },
        "56768990934":{
            "rfid":"1746",
            "products":[
            {
                "sale_id":46,
                "quantity":1,
                "price":"8.00",
                "total":"8",
                "unit":"UN",
                "sku":20
            }
            ]
        }
    }
}

I used json2sharp to generate a class from the JSON, I then cleaned up the class and was left with the following:

My Class create help for json2sharp

public class Consumo
{
    public string rfid { get; set; }
    public List<ConsumoProduto> products { get; set; }
}

public class ConsumoProduto
{
    public int sale_id { get; set; }
    public double quantity { get; set; }
    public string price { get; set; }
    public string total { get; set; }
    public string unit { get; set; }
    public int sku { get; set; }
}

public class RetornoConsumo
{
    [JsonProperty("success")]
    public bool Processado { get; set; }
    [JsonProperty("data")]
    public List<Consumo> Registro { get; set; }
}

My Problem

how do I convert Json to a valid object using Json.Net?

Test

I tried to do this and I could not

Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);

Body:
In your RetornoConsumo class, the Registro property needs to be a Dictionary<string, Consumo> not a List<Consumo>.

public class RetornoConsumo
{
    [JsonProperty("success")]
    public bool Processado { get; set; }
    [JsonProperty("data")]
    public Dictionary<string, Consumo> Registro { get; set; }
}

Then, you need to deserialize the JSON into the RetornoConsumo class:

var data = JsonConvert.DeserializeObject<RetornoConsumo>(json);

Fiddle: https://dotnetfiddle.net/vfhdXp


问:
Join two datatables different columnName into one datatable
I need help: how to join two datatables in C# with column names different not merge, just join right or left, just get dtResult from dtA join with dtB like this below:

答:
If you mean join by index, it's more a zip of two DataTables. You could use this method:

```<code>public static DataTable MergeTablesByIndex(DataTable t1, DataTable t2)
{
    if (t1 == null || t2 == null) throw new ArgumentNullException("t1 or t2", "Both tables must not be null");

    DataTable t3 = t1.Clone();  // first add columns from table1
    foreach (DataColumn col in t2.Columns)
    {
        string newColumnName = col.ColumnName;
        int colNum = 1;
        while (t3.Columns.Contains(newColumnName))
        {
            newColumnName = string.Format("{0}_{1}", col.ColumnName, ++colNum);
        }
        t3.Columns.Add(newColumnName, col.DataType);
    }
    var mergedRows = t1.AsEnumerable().Zip(t2.AsEnumerable(),
        (r1, r2) => r1.ItemArray.Concat(r2.ItemArray).ToArray());
    foreach (object[] rowFields in mergedRows)
        t3.Rows.Add(rowFields);

    return t3;
}
</code>```

I haven't written this from scratch, it's second part of an older answer of me.

Body:
If you mean join by index, it's more a zip of two DataTables. You could use this method:

public static DataTable MergeTablesByIndex(DataTable t1, DataTable t2)
{
    if (t1 == null || t2 == null) throw new ArgumentNullException("t1 or t2", "Both tables must not be null");

    DataTable t3 = t1.Clone();  // first add columns from table1
    foreach (DataColumn col in t2.Columns)
    {
        string newColumnName = col.ColumnName;
        int colNum = 1;
        while (t3.Columns.Contains(newColumnName))
        {
            newColumnName = string.Format("{0}_{1}", col.ColumnName, ++colNum);
        }
        t3.Columns.Add(newColumnName, col.DataType);
    }
    var mergedRows = t1.AsEnumerable().Zip(t2.AsEnumerable(),
        (r1, r2) => r1.ItemArray.Concat(r2.ItemArray).ToArray());
    foreach (object[] rowFields in mergedRows)
        t3.Rows.Add(rowFields);

    return t3;
}

I haven't written this from scratch, it's second part of an older answer of me.


问:
how execute linux command using java on windows?
I need execute bash commands on a separate Linux machine using java on Windows.

I need run executable file from specified directory, like

```<code>cd /home/bin
</code>```

How can I do this?

答:
After long hours, I finally found useful information. please follow link "How do I run SSH commands on remote system using Java?"

Also use jar from "http://www.ganymed.ethz.ch/ssh2/" the link. It is the jar required for any person to execute ssh commands from java code in windows environment. There are other ways too. And most jars I didn't find them useful, especially when you want to automate user authentication to access linux environment.

Note, passing directly the password (ssh password) is not appropriate way of doing things.And many experts suggested in few other threads.But this simple solution works for someone who is not concerned about security.

Body:
I need execute bash commands on a separate Linux machine using java on Windows.

I need run executable file from specified directory, like

cd /home/bin

How can I do this?


问:
Error in <servlet-mapping> <url-pattern> in web.xml in Eclipse Helios for Java EE developers
I am providing an attribute() in  in web.xml which is

```<code><servlet-mapping>
    <servlet-name>SpringMVCTutorial</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
</code>```

but I am getting an error "The word 'htm' is not correctly spelled". Please let me know if I am making a mistake.

Thank you,
Sid

答:
Your XML file is fine. You can just ignore the warning and run it.

Since this Eclipse's builtin XML spellchecker can lead to big annoyments, I'd suggest to just disable it. Go to Window > Preferences > General > Editors > Text Editors > Spelling and untick the checkbox.

Body:
I am providing an attribute() in  in web.xml which is

<servlet-mapping>
    <servlet-name>SpringMVCTutorial</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

but I am getting an error "The word 'htm' is not correctly spelled". Please let me know if I am making a mistake.

Thank you,
Sid


问:
Significance of finally block
What is the significance of the Finally block in a Try...[Catch]...Finally block?

Isn't this code

```<code>Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
} finally {
  r.close()
}
</code>```

equivalent to

```<code>Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
}
r.close()
</code>```

? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.

Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?

答:
The two code snippets are different: the second one will not close if exception handling block ends in another exception.

Here is an illustration:

```<code>public static void one() throws Exception {
    try {
        System.out.println("One");
        throw new Exception();
    } catch (Exception e) {
        System.out.println("Catch one");
        if (2 != 3) throw new Exception(); // "if" silences compiler's check
    } finally {
        System.out.println("Finally one");
    }
}
public static void two() throws Exception {
    try {
        System.out.println("Two");
        throw new Exception();
    } catch (Exception e) {
        System.out.println("Catch two");
        if (2 != 3) throw new Exception(); // "if" silences compiler's check
    }
    System.out.println("After two");
}
</code>```

The call to one() prints Finally one, while After two never gets printed (demo 1).

The finally block becomes even more important when you catch specific exceptions (blindly catching Exception is nearly always a bad idea), because the try block may bypass your cleanup code by throwing an exception that you do not catch. Here is another illustration:

```<code>public static void error() throws Exception {
    try {
        System.out.println("Try");
        throw new Error();
    } catch (Exception e) {
        System.out.println("Catch");
        throw new Exception();
    } finally {
        System.out.println("Finally");
    }
}
</code>```

This code prints Try and Finally, without Catch in the middle, because Error is not caught in the catch block (demo 2).

It goes without saying that human readers of your program will have easier time locating you clean-up code if you place it in the finally block.

Title: Significance of finally block

Body:
What is the significance of the Finally block in a Try...[Catch]...Finally block?

Isn't this code

Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
} finally {
  r.close()
}

equivalent to

Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
}
r.close()

? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.

Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?

Body:
The two code snippets are different: the second one will not close if exception handling block ends in another exception.

Here is an illustration:

public static void one() throws Exception {
    try {
        System.out.println("One");
        throw new Exception();
    } catch (Exception e) {
        System.out.println("Catch one");
        if (2 != 3) throw new Exception(); // "if" silences compiler's check
    } finally {
        System.out.println("Finally one");
    }
}
public static void two() throws Exception {
    try {
        System.out.println("Two");
        throw new Exception();
    } catch (Exception e) {
        System.out.println("Catch two");
        if (2 != 3) throw new Exception(); // "if" silences compiler's check
    }
    System.out.println("After two");
}

The call to one() prints Finally one, while After two never gets printed (demo 1).

The finally block becomes even more important when you catch specific exceptions (blindly catching Exception is nearly always a bad idea), because the try block may bypass your cleanup code by throwing an exception that you do not catch. Here is another illustration:

public static void error() throws Exception {
    try {
        System.out.println("Try");
        throw new Error();
    } catch (Exception e) {
        System.out.println("Catch");
        throw new Exception();
    } finally {
        System.out.println("Finally");
    }
}

This code prints Try and Finally, without Catch in the middle, because Error is not caught in the catch block (demo 2).

It goes without saying that human readers of your program will have easier time locating you clean-up code if you place it in the finally block.


问:
Multi-threading to display game score while game loop is running in Python?
I want score to based on time passed in the game. To do this I want to have two loops running simultaneously. The game loop, and the score loop, which adds 1 to the score every 1.5 seconds. When I run the program, the score does not appear. Am I using multi-threading properly? Is that the best way to do this? For simplicity I have posted only the relevant code. Thanks!

```<code>def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def displayScore(text):
    while(True):
        textStyle = pygame.font.Font('freesansbold.ttf', 25)
        # pop up window defining window and textRect to align text properly
        textWindow, textRect = text_objects(text, textStyle)
        textRect.center = ((display_width/2)), ((display_height/2))
        gameDisplay.blit(textWindow, textRect)
        pygame.display.update()
        time.sleep(1.5)
        text = int(text)
        text +=1
        text = str(text)

def gameStart():

    x_change = 0
    y_change = 0
    x = (display_width * 0.39)
    y = (display_height * 0.7)
    car_width = 200
    x_brick = (display_width * random.uniform(.05, .95))
    y_brick = display_height - 925

    # exception for the game crashing and the game loop
    gameExit = False

    while not gameExit:

    # capturing user actions
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        # key-down events for car movements
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5
            elif event.key == pygame.K_UP:
                y_change = -5
            elif event.key == pygame.K_DOWN:
                y_change = 5

        # cancelling out key-up events
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                y_change = 0

    # crash conditions
    if x > display_width - car_width or x < 0:
        crash()
    if y > display_height - 175 or y < 0 - 10:
        crash()

    # updating car movements
    x += x_change
    y += y_change

    # generating display
    gameDisplay.fill(white)
    car(x, y)
    brick(x_brick, y_brick)

    # moving the brick
    y_brick += brick_speed

    # updates for parameter given or entire surface
    pygame.display.update()

    # frames per second, the more frames per second the faster and smoother things move, taxing on processing speed
    clock.tick(60)

t1 = Thread(target=gameStart())
t2 = Thread(target=displayScore('0'))
t1.start()
t2.start()
</code>```

Edit: Ended up with this..

```<code>import time

score = 0

def timer(oldsec):
    currentsec = time.time()
    if abs(currentsec - oldsec > 3):
        return True
    else:
        False

oldsec = time.time() # what time is it now

while True:
    if timer(oldsec) == True:
        score += 1
        oldsec = time.time()
        print (score)
</code>```

答:
You could use _thread. </p>

```<code>from _thread import *

count = 0

def Your_other_loop():
    global count
    while True:
        #Do loop stuff

def loop():
    global count
    while True:
        print(count)

start_new_thread(Your_other_loop,())
loop()
</code>```

Body:
I want score to based on time passed in the game. To do this I want to have two loops running simultaneously. The game loop, and the score loop, which adds 1 to the score every 1.5 seconds. When I run the program, the score does not appear. Am I using multi-threading properly? Is that the best way to do this? For simplicity I have posted only the relevant code. Thanks!

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def displayScore(text):
    while(True):
        textStyle = pygame.font.Font('freesansbold.ttf', 25)
        # pop up window defining window and textRect to align text properly
        textWindow, textRect = text_objects(text, textStyle)
        textRect.center = ((display_width/2)), ((display_height/2))
        gameDisplay.blit(textWindow, textRect)
        pygame.display.update()
        time.sleep(1.5)
        text = int(text)
        text +=1
        text = str(text)

def gameStart():

    x_change = 0
    y_change = 0
    x = (display_width * 0.39)
    y = (display_height * 0.7)
    car_width = 200
    x_brick = (display_width * random.uniform(.05, .95))
    y_brick = display_height - 925

    # exception for the game crashing and the game loop
    gameExit = False

    while not gameExit:

    # capturing user actions
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        # key-down events for car movements
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5
            elif event.key == pygame.K_UP:
                y_change = -5
            elif event.key == pygame.K_DOWN:
                y_change = 5

        # cancelling out key-up events
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                y_change = 0

    # crash conditions
    if x > display_width - car_width or x < 0:
        crash()
    if y > display_height - 175 or y < 0 - 10:
        crash()

    # updating car movements
    x += x_change
    y += y_change

    # generating display
    gameDisplay.fill(white)
    car(x, y)
    brick(x_brick, y_brick)

    # moving the brick
    y_brick += brick_speed

    # updates for parameter given or entire surface
    pygame.display.update()

    # frames per second, the more frames per second the faster and smoother things move, taxing on processing speed
    clock.tick(60)

t1 = Thread(target=gameStart())
t2 = Thread(target=displayScore('0'))
t1.start()
t2.start()

Edit: Ended up with this..

import time

score = 0

def timer(oldsec):
    currentsec = time.time()
    if abs(currentsec - oldsec > 3):
        return True
    else:
        False

oldsec = time.time() # what time is it now

while True:
    if timer(oldsec) == True:
        score += 1
        oldsec = time.time()
        print (score)

Body:
You could use _thread.

from _thread import *

count = 0

def Your_other_loop():
    global count
    while True:
        #Do loop stuff

def loop():
    global count
    while True:
        print(count)

start_new_thread(Your_other_loop,())
loop()


问:
unable to load dll cvextern while using emgu cv for x86 platform

Requirement: Load a C# DLL(which uses Emgu.CV.World.dll for image
  comparison) into python project and call function inside DLL with some
  parameters.

I tried to export a DLL usig Emgu.CV.World.dll for image comparison. While compiling for "Any CPU" target, the DLL export was not working. After changed to x86 platform, DLL was loaded correctly from Python:

```<code>mydll = ctypes.cdll.LoadLibrary(self.libPath)
</code>```

But while calling function inside the DLL:

```<code>ImageContentComparisonResult = mydll.CompareImageContent(self.OutputFile, self.OriginalFile)
</code>```

throws the following exception:

```<code>WindowsError: [Error -532462766] Windows Error 0xE0434352
</code>```

Output from Visual Studio:

```<code>A first chance exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module.
</code>```

After this, created a sample Emgu.CV project(GUI), got the same exception. There I got the exception details, like

```<code>{"The type initializer for 'Emgu.CV.CvInvoke' threw an exception."}
InnerException: {"Unable to load DLL 'cvextern': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"}
</code>```

After copying the x86 and x64 DLLs for Emgu.CV to "bin\x86\Debug", it worked for the sample app, but for non GUI C# project, it's not working even after copying the required DLLs.

答: C# DLL will not be loaded using ctypes. Need to use clr.AddReference method included in python package. If python 2.7 is using need to uninstall clr package which comes as a part of 2.7 installation(This is to avoid namespace conflict). Or IronPython can be used for the same.</p>

Body:
Requirement: Load a C# DLL(which uses Emgu.CV.World.dll for image
  comparison) into python project and call function inside DLL with some
  parameters.

I tried to export a DLL usig Emgu.CV.World.dll for image comparison. While compiling for "Any CPU" target, the DLL export was not working. After changed to x86 platform, DLL was loaded correctly from Python:

mydll = ctypes.cdll.LoadLibrary(self.libPath)

But while calling function inside the DLL:

ImageContentComparisonResult = mydll.CompareImageContent(self.OutputFile, self.OriginalFile)

throws the following exception:

WindowsError: [Error -532462766] Windows Error 0xE0434352

Output from Visual Studio:

A first chance exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module.

After this, created a sample Emgu.CV project(GUI), got the same exception. There I got the exception details, like

{"The type initializer for 'Emgu.CV.CvInvoke' threw an exception."}
InnerException: {"Unable to load DLL 'cvextern': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"}

After copying the x86 and x64 DLLs for Emgu.CV to "bin\x86\Debug", it worked for the sample app, but for non GUI C# project, it's not working even after copying the required DLLs.


问:
Trying to create a boolean expression for when a dot crosses the finish line
Here is the boolean expression that I tried to enter:

```<code>boolean finish = false;
if (GWINDOW_WIDTH == connectMe.getX())  {
    finish = true;
}
System.out.println(finish);
</code>```

GWINDOW_Width is the width of the window

connectMe.getX() is the x coordinate of the dot

I tried to make it so that if the dot touches the edge of the window, the dot finishes the race. However, when running the program, the console window gives the output of "false," even though the dot touched the finish line or the edge of the screen.

答:
You should change the conditional statement to the following for two reasons:

```<code>if (GWINDOW_WIDTH <= connectMe.getX()) {

}
</code>```

If the dot moves slightly passed the exact edge of the screen you current condition will not be trigger.

If connectMe.getX() is a float or double, you should test for a range because of the way they are stored. See here for more on that topic.

Body:
Here is the boolean expression that I tried to enter:

boolean finish = false;
if (GWINDOW_WIDTH == connectMe.getX())  {
    finish = true;
}
System.out.println(finish);

GWINDOW_Width is the width of the window

connectMe.getX() is the x coordinate of the dot

I tried to make it so that if the dot touches the edge of the window, the dot finishes the race. However, when running the program, the console window gives the output of "false," even though the dot touched the finish line or the edge of the screen.

Body:
You should change the conditional statement to the following for two reasons:

if (GWINDOW_WIDTH <= connectMe.getX()) {

}

If the dot moves slightly passed the exact edge of the screen you current condition will not be trigger.

If connectMe.getX() is a float or double, you should test for a range because of the way they are stored. See here for more on that topic.


问:
how to get height value before click event?
I tried to get height of div block before each click event in jquery and have to set as a global variable for some action.

Currently, I'm handling slide up/down action, I want to set height for slide up before each click event. I tried various way but its failed. Anyone suggest me how to get the value.

答:
Get the current div height this code:

```<code>var divHeight = $('#yourDiv').height(); // get div height
</code>```

Set the current div height this code:

```<code>$("#yourDiv").css("height", '100px');  // set div height
</code>```

Body:
Get the current div height this code:

var divHeight = $('#yourDiv').height(); // get div height

Set the current div height this code:

$("#yourDiv").css("height", '100px');  // set div height


问:
Angular2: How to enable save button if any model value changed on edit page
I am new for angular 2. I have a page where we can edit details of customer profile. How to enable save button if any property of has been changed. I know it is possible in angular1 by using $watch.</p>

答:
It is simple. dirty check your form if you are using  @angular/forms.

create form

```<code>export class HeroDetailComponent4 {
  heroForm: FormGroup;
  states = states;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.heroForm = this.fb.group({
      name: ['', Validators.required ],
      street: '',
      city: '',
      state: '',
      zip: '',
      power: '',
      sidekick: ''
    });
  }
}
</code>```

HTML:

```<code>    <h2>Hero Detail</h2>
    <h3><i>A FormGroup with multiple FormControls</i></h3>
    <form [formGroup]="heroForm" novalidate>
<button (click)="submit()" [disabled]="!heroForm.dirty" type="button">Submit</button>
      <div class="form-group">
        <label class="center-block">Name:
          <input class="form-control" formControlName="name">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">Street:
          <input class="form-control" formControlName="street">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">City:
          <input class="form-control" formControlName="city">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">State:
          <select class="form-control" formControlName="state">
              <option *ngFor="let state of states" [value]="state">{{state}}</option>
          </select>
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">Zip Code:
          <input class="form-control" formControlName="zip">
        </label>
      </div>
      <div class="form-group radio">
        <h4>Super power:</h4>
        <label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
        <label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
        <label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
      </div>
      <div class="checkbox">
        <label class="center-block">
          <input type="checkbox" formControlName="sidekick">I have a sidekick.
        </label>
      </div>
    </form>
</code>```

use heroForm.dirty to check whether form data is changed. it will set to true if any control inside heroForm has been changed.

```<code><button (click)="submit()" [disabled]="!heroForm.dirty" type="button">Submit</button>
</code>```

Refer angular docs for more info

Body:
It is simple. dirty check your form if you are using  @angular/forms.

create form

export class HeroDetailComponent4 {
  heroForm: FormGroup;
  states = states;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.heroForm = this.fb.group({
      name: ['', Validators.required ],
      street: '',
      city: '',
      state: '',
      zip: '',
      power: '',
      sidekick: ''
    });
  }
}

HTML:

    <h2>Hero Detail</h2>
    <h3><i>A FormGroup with multiple FormControls</i></h3>
    <form [formGroup]="heroForm" novalidate>
<button (click)="submit()" [disabled]="!heroForm.dirty" type="button">Submit</button>
      <div class="form-group">
        <label class="center-block">Name:
          <input class="form-control" formControlName="name">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">Street:
          <input class="form-control" formControlName="street">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">City:
          <input class="form-control" formControlName="city">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">State:
          <select class="form-control" formControlName="state">
              <option *ngFor="let state of states" [value]="state">{{state}}</option>
          </select>
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">Zip Code:
          <input class="form-control" formControlName="zip">
        </label>
      </div>
      <div class="form-group radio">
        <h4>Super power:</h4>
        <label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
        <label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
        <label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
      </div>
      <div class="checkbox">
        <label class="center-block">
          <input type="checkbox" formControlName="sidekick">I have a sidekick.
        </label>
      </div>
    </form>

use heroForm.dirty to check whether form data is changed. it will set to true if any control inside heroForm has been changed.

<button (click)="submit()" [disabled]="!heroForm.dirty" type="button">Submit</button>

Refer angular docs for more info


问:
How to remove duplicated scrollbar in Angular Covalent templates?
I am super new to Angular 4. I've onlçy created few projects with AngularJS.

I started using Teradata Covalent Framework to build front-end structure and focus on building the menu content and card lists for a Catalog Web App.

I downloaded this full template in https://stackblitz.com/edit/covalent-dashboard-ynyp1w?file=main.ts which you can see in the image below:

As you can see, the problem is those two scrollbars in the right side of the page. I think that only the inner scroll should exist there because it is not interfering with the gray toolbar.

```<code><td-layout>
  <td-navigation-drawer flex [sidenavTitle]="name" logo="assets:covalent">
    Top level navigation drawer
  </td-navigation-drawer>
  <td-layout-nav [toolbarTitle]="(media.registerQuery('gt-xs') | async) ? 'Dashboard' : ''" logo="assets:covalent" navigationRoute="/">
    <button mat-icon-button td-menu-button tdLayoutToggle>
      <mat-icon>menu</mat-icon>
    </button>
    <div td-toolbar-content>
      Top toolbar
    </div>
    <td-layout-manage-list #manageList>
      <div td-sidenav-content layout="column" layout-fill>
        Inner sidenav listing dashboards
      </div>

      <mat-sidenav-container flex>
        <mat-sidenav #sidenav align="end">
          Right Sidenav
        </mat-sidenav>
        <td-layout-nav>
          <div td-toolbar-content>
            Second toolbar
          </div>

          <div flex layout-gt-sm="row">
            <div flex-gt-sm="50">
              <mat-card>
                ...
              </mat-card>
            </div>
          </div>

        </td-layout-nav>
      </mat-sidenav-container>
    </td-layout-manage-list>
    <td-layout-footer>Footer content</td-layout-footer>
  </td-layout-nav>
</td-layout>
</code>```

Anyone who already worked with this template or is very good at CSS could tell me how to remove this creep extra scrollbar from the site? And (Bonus) How could I replace those old scrollbar style for those new skinny scrollbars from Facebook?

答:
The problem is that your page content is being wrapped in a <mat-sidenav-container flex> element. You'll want to use the  element outside of that.

I've fixed the page in this stackblitz. A simplified version of the code is below.

```<code><td-layout>
  <td-navigation-drawer flex [sidenavTitle]="name" logo="assets:covalent">
    Top level navigation drawer
  </td-navigation-drawer>
  <td-layout-nav [toolbarTitle]="(media.registerQuery('gt-xs') | async) ? 'Dashboard' : ''" logo="assets:covalent" navigationRoute="/">
    <button mat-icon-button td-menu-button tdLayoutToggle>
      <mat-icon>menu</mat-icon>
    </button>
    <div td-toolbar-content>
      Top toolbar
    </div>
    <td-layout-manage-list #manageList>
      <div td-sidenav-content layout="column" layout-fill>
        Inner sidenav listing dashboards
      </div>

      <td-layout-nav>
        <div td-toolbar-content>
          Second toolbar
        </div>

        <mat-sidenav-container flex>
          <mat-sidenav #sidenav align="end">
            Right Sidenav
          </mat-sidenav>
          <div flex layout-gt-sm="row">
            <div flex-gt-sm="50">
              <mat-card>
                ...
              </mat-card>
            </div>
          </div>

        </mat-sidenav-container>
      </td-layout-nav>
    </td-layout-manage-list>
    <td-layout-footer>Footer content</td-layout-footer>
  </td-layout-nav>
</td-layout>
</code>```

Body:
I am super new to Angular 4. I've onlçy created few projects with AngularJS.

I started using Teradata Covalent Framework to build front-end structure and focus on building the menu content and card lists for a Catalog Web App.

I downloaded this full template in https://stackblitz.com/edit/covalent-dashboard-ynyp1w?file=main.ts which you can see in the image below:

As you can see, the problem is those two scrollbars in the right side of the page. I think that only the inner scroll should exist there because it is not interfering with the gray toolbar.

    Top level navigation drawer

    <button mat-icon-button td-menu-button tdLayoutToggle>
      <mat-icon>menu</mat-icon>
    </button>

      Top toolbar

        Inner sidenav listing dashboards

      <mat-sidenav-container flex>
        <mat-sidenav #sidenav align="end">
          Right Sidenav
        </mat-sidenav>

            Second toolbar

              <mat-card>
                ...
              </mat-card>

      </mat-sidenav-container>

    Footer content

Anyone who already worked with this template or is very good at CSS could tell me how to remove this creep extra scrollbar from the site? And (Bonus) How could I replace those old scrollbar style for those new skinny scrollbars from Facebook?

Body:
The problem is that your page content is being wrapped in a <mat-sidenav-container flex> element. You'll want to use the <td-layout-nav> element outside of that.

I've fixed the page in this stackblitz. A simplified version of the code is below.

<td-layout>
  <td-navigation-drawer flex [sidenavTitle]="name" logo="assets:covalent">
    Top level navigation drawer
  </td-navigation-drawer>
  <td-layout-nav [toolbarTitle]="(media.registerQuery('gt-xs') | async) ? 'Dashboard' : ''" logo="assets:covalent" navigationRoute="/">
    <button mat-icon-button td-menu-button tdLayoutToggle>
      <mat-icon>menu</mat-icon>
    </button>
    <div td-toolbar-content>
      Top toolbar
    </div>
    <td-layout-manage-list #manageList>
      <div td-sidenav-content layout="column" layout-fill>
        Inner sidenav listing dashboards
      </div>

      <td-layout-nav>
        <div td-toolbar-content>
          Second toolbar
        </div>

        <mat-sidenav-container flex>
          <mat-sidenav #sidenav align="end">
            Right Sidenav
          </mat-sidenav>
          <div flex layout-gt-sm="row">
            <div flex-gt-sm="50">
              <mat-card>
                ...
              </mat-card>
            </div>
          </div>

        </mat-sidenav-container>
      </td-layout-nav>
    </td-layout-manage-list>
    <td-layout-footer>Footer content</td-layout-footer>
  </td-layout-nav>
</td-layout>


问:
getting the name of the form tag from an HTML element within a directive
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

```<code>.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }
</code>```

答:
You should require the formCtrl:

```<code>require: '^form',
</code>```

and use this in the link function of your directive:

```<code>link: function(scope, element, attrs, formCtrl) {
    console.log(formCtrl);
}
</code>```

For full details on passing forms into directives, see similar problem being solved at Stackoverflow here:
Pass form to directive

EDIT: With AngularJS 1.5.x you have different syntax (being able to skip the link function), just an citation of https://stackoverflow.com/users/1021943/priidu-neemre great answer, (see more with above mentioned link):

```<code>return {
  restrict : 'EA',
  require : {
    form : '^'
  },
</code>```

Body:
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }

Body:
You should require the formCtrl:

require: '^form',

and use this in the link function of your directive:

link: function(scope, element, attrs, formCtrl) {
    console.log(formCtrl);
}

For full details on passing forms into directives, see similar problem being solved at Stackoverflow here:
Pass form to directive

EDIT: With AngularJS 1.5.x you have different syntax (being able to skip the link function), just an citation of https://stackoverflow.com/users/1021943/priidu-neemre great answer, (see more with above mentioned link):

return {
  restrict : 'EA',
  require : {
    form : '^'
  },


问:
Having an issue with Multiple middleware in laravel
I am trying to process 2 middleware before routing it to controller. Laravel won't give me an error on the following code but it only processes the 1st middleware 'CheckReferer' and won't process the 2nd middleware 'CheckCart'. It process the 1st middleware even if you change the sequence (e.g 'CheckCart', 'CheckReferer').

web.php

```<code>Route::prefix($language)->middleware('CheckReferer', 'CheckCart')->group(function() {

     Route::get('/', 'HomeController@getIndex')->name('home');

});
</code>```

CheckReferer.php (Middleware)

```<code>class CheckReferer
{

    public function handle($request, Closure $next)
    {
        $Referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;

        if($Referer != null) {
            $url_parsed = parse_url($Referer);

            if ($url_parsed['host'] == 'www.example.com') {

                $Referer = true;
                Session::put('Referer', $Referer);

            }
        }

        return $next($request);
    }

}
</code>```

CheckCart.php (Middleware)

```<code>class CheckCart
{
    public function handle(Request $request, Closure $next)
    {

        $oldCart = Session::has('Cart') ? Session::get('Cart') : null;

        return $next($request);
    }
}
</code>```

答:
Pass them as array... </p>

```<code>Route::prefix($language)->middleware(['CheckReferer', 'CheckCart'])->group(function() {

     Route::get('/', 'HomeController@getIndex')->name('home');

});
</code>```

Body:
I am trying to process 2 middleware before routing it to controller. Laravel won't give me an error on the following code but it only processes the 1st middleware 'CheckReferer' and won't process the 2nd middleware 'CheckCart'. It process the 1st middleware even if you change the sequence (e.g 'CheckCart', 'CheckReferer').

web.php

Route::prefix($language)->middleware('CheckReferer', 'CheckCart')->group(function() {

     Route::get('/', 'HomeController@getIndex')->name('home');

});

CheckReferer.php (Middleware)

class CheckReferer
{

    public function handle($request, Closure $next)
    {
        $Referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;

        if($Referer != null) {
            $url_parsed = parse_url($Referer);

            if ($url_parsed['host'] == 'www.example.com') {

                $Referer = true;
                Session::put('Referer', $Referer);

            }
        }

        return $next($request);
    }

}

CheckCart.php (Middleware)

class CheckCart
{
    public function handle(Request $request, Closure $next)
    {

        $oldCart = Session::has('Cart') ? Session::get('Cart') : null;

        return $next($request);
    }
}

Body:
Pass them as array...

Route::prefix($language)->middleware(['CheckReferer', 'CheckCart'])->group(function() {

     Route::get('/', 'HomeController@getIndex')->name('home');

});


问:
How to calculate gammaln in Spark MLLib?
I am trying to implement Log likelihood function of Buytillyoudie model in Spark MLLib.

L(r, α, a, b |X = x, tx, T) = A1 · A2 · (A3 + δx>0 A4)

where

```<code>  A1 = Γ(r + x)αr/Γ(r)
  A2 = Γ(a + b)Γ(b + x)/(Γ(b)Γ(a + b + x))
  A3 = ( 1/(α + T))^(r+x)
  A4 = (a/(b+x-1))(1/(α + tx))^(r+x)
</code>```

For this, I am using L-BFGS algorithm as given here https://spark.apache.org/docs/2.2.0/mllib-optimization.html

I am implementing a custom Gradient class to be passed on to L-BFGS method LBFGS.runLBFGS.

I don't know how to calculate Γ(x) in Spark. Is there any method or another optimization library which I can use to calculate gamma or gamma log? Please suggest.

PS: I got a cue from comment section to use Breeze library of Scala. But since I am using Java, it is not possible. Can I use ND4J or Apache-commons math library in Java?

答:
Reads in a command line input x and prints Gamma(x) and
log Gamma(x). The Gamma function is defined by :
 Gamma(x) = integral( t^(x-1) e^(-t), t = 0 .. infinity)</p>

```<code> public class Gamma {

       static double logGamma(double x) {
          double tmp = (x - 0.5) * Math.log(x + 4.5) - (x + 4.5);
          double ser = 1.0 + 76.18009173    / (x + 0)   - 86.50532033    / (x + 1)
                           + 24.01409822    / (x + 2)   -  1.231739516   / (x + 3)
                           +  0.00120858003 / (x + 4)   -  0.00000536382 / (x + 5);
          return tmp + Math.log(ser * Math.sqrt(2 * Math.PI));
       }
       static double gamma(double x) { return Math.exp(logGamma(x)); }

       public static void main(String[] args) {
          double x = Double.parseDouble(args[0]);
          StdOut.println("Gamma(" + x + ") = " + gamma(x));
          StdOut.println("log Gamma(" + x + ") = " + logGamma(x));
       }

    }
</code>```

Body:
I am trying to implement Log likelihood function of Buytillyoudie model in Spark MLLib.

L(r, α, a, b |X = x, tx, T) = A1 · A2 · (A3 + δx>0 A4)

where

  A1 = Γ(r + x)αr/Γ(r)
  A2 = Γ(a + b)Γ(b + x)/(Γ(b)Γ(a + b + x))
  A3 = ( 1/(α + T))^(r+x)
  A4 = (a/(b+x-1))(1/(α + tx))^(r+x)

For this, I am using L-BFGS algorithm as given here https://spark.apache.org/docs/2.2.0/mllib-optimization.html

I am implementing a custom Gradient class to be passed on to L-BFGS method LBFGS.runLBFGS.

I don't know how to calculate Γ(x) in Spark. Is there any method or another optimization library which I can use to calculate gamma or gamma log? Please suggest.

PS: I got a cue from comment section to use Breeze library of Scala. But since I am using Java, it is not possible. Can I use ND4J or Apache-commons math library in Java?

Body:
Reads in a command line input x and prints Gamma(x) and
log Gamma(x). The Gamma function is defined by :
 Gamma(x) = integral( t^(x-1) e^(-t), t = 0 .. infinity)

 public class Gamma {

       static double logGamma(double x) {
          double tmp = (x - 0.5) * Math.log(x + 4.5) - (x + 4.5);
          double ser = 1.0 + 76.18009173    / (x + 0)   - 86.50532033    / (x + 1)
                           + 24.01409822    / (x + 2)   -  1.231739516   / (x + 3)
                           +  0.00120858003 / (x + 4)   -  0.00000536382 / (x + 5);
          return tmp + Math.log(ser * Math.sqrt(2 * Math.PI));
       }
       static double gamma(double x) { return Math.exp(logGamma(x)); }

       public static void main(String[] args) {
          double x = Double.parseDouble(args[0]);
          StdOut.println("Gamma(" + x + ") = " + gamma(x));
          StdOut.println("log Gamma(" + x + ") = " + logGamma(x));
       }

    }


问:
python random does not behave as expected in loop
I have 2 examples of python random giving different results although logically they should be the same

```<code>    In [8]: random.seed(100)

In [9]: for i in range(2):
   ...:
   ...:
   ...:     a = [1,2,3,45]
   ...:     random.shuffle(a)
   ...:     random.randint(10,20)
   ...:     print a
   ...:     random.seed(100)
   ...:
[1, 45, 3, 2]
[45, 3, 2, 1]

In [6]: for i in range(2):
   ...:     random.seed(100)
   ...:
   ...:     a = [1,2,3,45]
   ...:     random.shuffle(a)
   ...:     random.randint(10,20)
   ...:     print a
   ...:     random.seed(100)
   ...:
   ...:
[45, 3, 2, 1]
[45, 3, 2, 1]
</code>```

Can anyone explain this behaviour?

答:
You are not seeding the random number generator in your first example before calling shuffle() for the first time, so you will get a (pseudo) random result.

In the lower example, you always seed the random number generator before calling shuffle(), so you will always get the same result.

Body:
I have 2 examples of python random giving different results although logically they should be the same

    In [8]: random.seed(100)

In [9]: for i in range(2):
   ...:
   ...:
   ...:     a = [1,2,3,45]
   ...:     random.shuffle(a)
   ...:     random.randint(10,20)
   ...:     print a
   ...:     random.seed(100)
   ...:
[1, 45, 3, 2]
[45, 3, 2, 1]

In [6]: for i in range(2):
   ...:     random.seed(100)
   ...:
   ...:     a = [1,2,3,45]
   ...:     random.shuffle(a)
   ...:     random.randint(10,20)
   ...:     print a
   ...:     random.seed(100)
   ...:
   ...:
[45, 3, 2, 1]
[45, 3, 2, 1]

Can anyone explain this behaviour?


问:
How do I get the n-th level parent of an element in jQuery?
When I want to get, for example, the 3rd level parent of the element I must write $('#element').parent().parent().parent() Is there a more optimal method for this?

答:
Didn't find any answer using closest()
and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:

You can use the closest() function combined with selectors to get the first element that matches when traversing upwards from the element:

```<code>('#element').closest('div')    // returns the innermost 'div' in its parents
('#element').closest('.container')    // returns innermost element with 'container' class among parents
('#element').closest('#foo')    // returns the closest parent with id 'foo'
</code>```

Body:
Didn't find any answer using closest()
and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:

You can use the closest() function combined with selectors to get the first element that matches when traversing upwards from the element:

('#element').closest('div')    // returns the innermost 'div' in its parents
('#element').closest('.container')    // returns innermost element with 'container' class among parents
('#element').closest('#foo')    // returns the closest parent with id 'foo'


问:
Is my understanding of async/await correct?
from what I understand the code below should eventually retrieve the string classification while running other code.

```<code>[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    string classification = GetClassification(property);
    // GetClassification() runs a complex calculation but we don't need
    // the result right away so the code can do other things here related to property

    // ... code removed for brevity

    property.ClassificationCode = await classification;
    // all other code has been completed and we now need the classification

    db.Properties.Add(property);
    db.SaveChanges();
    return RedirectToAction("Details", new { id = property.UPRN });
}

public string GetClassification(Property property)
{
    // do complex calculation
    return classification;
}
</code>```

This should work the same way as in the below code from Matthew Jones' article

```<code>public async Task<string> GetNameAndContent()
{
    var nameTask = GetLongRunningName(); //This method is asynchronous
    var content = GetContent(); //This method is synchronous
    var name = await nameTask;
    return name + ": " + content;
}
</code>```

However I get an error on await classification: 'string' does not contain a definition for 'GetAwaiter'

I'm unsure why this is happening.

Additionally, according to MSDN docs for expensive calculations I should instead be using:

```<code>property.ClassificationCode = await Task.Run(() => GetClassification(property));
</code>```

Is this actually achieving what I want or is this just running synchronously anyway?

Thanks in advance for help.

答:
```<code>string classification = GetClassification(property);
</code>```

this is regular synchronous code; it will do nothing until classification is assigned. It sounds like what you want is:

```<code>Task<string> classification = GetClassificationAsync(property);
</code>```

where GetClassificationAsync does something genuinely async in the middle and eventually populates a Task<string>. Note that if GetClassificationAsync still works synchronously, the code will all continue to be synchronous. In particular, if you find yourself using Task.FromResult : you probably aren't doing anything async.

Body:
from what I understand the code below should eventually retrieve the string classification while running other code.

[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    string classification = GetClassification(property);
    // GetClassification() runs a complex calculation but we don't need
    // the result right away so the code can do other things here related to property

    // ... code removed for brevity

    property.ClassificationCode = await classification;
    // all other code has been completed and we now need the classification

    db.Properties.Add(property);
    db.SaveChanges();
    return RedirectToAction("Details", new { id = property.UPRN });
}

public string GetClassification(Property property)
{
    // do complex calculation
    return classification;
}

This should work the same way as in the below code from Matthew Jones' article

public async Task<string> GetNameAndContent()
{
    var nameTask = GetLongRunningName(); //This method is asynchronous
    var content = GetContent(); //This method is synchronous
    var name = await nameTask;
    return name + ": " + content;
}

However I get an error on await classification: 'string' does not contain a definition for 'GetAwaiter'

I'm unsure why this is happening.

Additionally, according to MSDN docs for expensive calculations I should instead be using:

property.ClassificationCode = await Task.Run(() => GetClassification(property));

Is this actually achieving what I want or is this just running synchronously anyway?

Thanks in advance for help.

Body:
string classification = GetClassification(property);

this is regular synchronous code; it will do nothing until classification is assigned. It sounds like what you want is:

Task<string> classification = GetClassificationAsync(property);

where GetClassificationAsync does something genuinely async in the middle and eventually populates a Task<string>. Note that if GetClassificationAsync still works synchronously, the code will all continue to be synchronous. In particular, if you find yourself using Task.FromResult : you probably aren't doing anything async.


问:
Blender fbx import from ascii format
I have a FBX model which I would like to open in Blender but when I try to import the model it says: ASCII FBX files are not supported. Is there a way to import the model to Blender somehow? I don't have access to any Autodesk software.

答: If you have Visual Studio installed try to open the original file then save it and import in Blender. This should work.</p>

Title: Blender fbx import from ascii format


问:
Gradle Project Sync Failed Android Studio 3.0 (JDK 9.0.1)
I tried all solutions to fix it, but nothing has succeeded. (Turned gradle to "offline work", deleted .gradle files, invalidated and restarted. I also removed the jdk-android studio completely and installed again.)

Here is the problem's screenshot:
Android Studio 3.0 Gradle Sync Problem

Here is my java version

and here is the system/log file:

答:
```<code>Take these easy steps as per developer.android.com
first add these lines on build.gradle file

buildscript {
    repositories {
            jcenter()
        // You need to add the following repository to download the
        // new plugin.
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
}

after that
update Gradle manually, edit the URL in gradle-wrapper.properties to the following:
distributionUrl=\
  https\://services.gradle.org/distributions/gradle-4.1-all.zip

For your reference you can check the below link
https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html
</code>```


问:
Redshift: Does key-based distribution optimize equality filters?
This documentation describes key-distribution in redshift as follows:

The rows are distributed according to the values in one column. The
  leader node will attempt to place matching values on the same node
  slice. If you distribute a pair of tables on the joining keys, the
  leader node collocates the rows on the slices according to the values
  in the joining columns so that matching values from the common columns
  are physically stored together.

I was wondering if key-distribution additionally helps in optimizing equality filters. My intuition says it should but it isn't mentioned anywhere.

Also, I saw a documentation regarding sort-keys which says that to select a sort-key:

Look for columns that are used in range filters and equality filters.

This got me confused since sort-keys are explicitly mentioned as a way to optimize equality filters.

I am asking this because I already have a candidate sort-key on which I will be doing range queries. But I also want to have quick equality filters on another column which is a good distribution key in my case.

答:
It is a very bad idea to be filtering on a distribution key, especially if your table / cluster is large.

The reason is that the filter may be running on just one slice, in effect running without the benefit of MPP.

For example, if you have a dist key of "added_date", you may find that all of the added date for the previous week are all together on one slice.

You will then have the majority of queries filtering for recent ranges of added_date, and these queries will be concentrated and will saturate that one slice.


问:
Code Golf: Gray Code

The Challenge

The shortest program by character count that outputs the n-bit Gray Code. n will be an arbitrary number smaller than <s>1000</s>100000 (due to user suggestions) that is taken from standard input. The gray code will be printed in standard output, like in the example.

Note: I don't expect the program to print the gray code in a reasonable time (n=100000 is overkill); I do expect it to start printing though.

Example

Input:

```<code>4
</code>```

Expected Output:

```<code>0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
</code>```

Title: Code Golf: Gray Code

Body:
The Challenge

The shortest program by character count that outputs the n-bit Gray Code. n will be an arbitrary number smaller than <s>1000</s>100000 (due to user suggestions) that is taken from standard input. The gray code will be printed in standard output, like in the example.

Note: I don't expect the program to print the gray code in a reasonable time (n=100000 is overkill); I do expect it to start printing though.

Example

Input:

4

Expected Output:

0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000

Body:
Ruby, 50 Chars

(2**n=gets.to_i).times{|i|puts"%0#{n}d"%i.to_s(2)}