问:
Python Riemann Sum does not yield zero for equal positive and negative areas
I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead.

The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15.

What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this.

I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number.

The Python code:

```<code>import matplotlib.pyplot as plt
import numpy as np

# Approximates and graphs integral using Riemann Sum

# example function: f(x) = x^3
def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a) / n

x = np.arange(a, b+delta_x, delta_x)

y = [f_x(i) for i in x]

area = sum(y) * delta_x

# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()
</code>```

答:
You need to be aware that what you are computing is not a Riemann integral in the original sense. You are dividing the interval into n bins, but then sum over n+1 bins (here n = 1000 but len(x) == 1001). So the result may be close to what you expect, but it is certainly not a good way to get there.

Using the Riemann sum you would divide your interval into n bins, and then sum over the values of those n bins. You have the choice whether to compute the left Riemann sum, the right Riemann sum, or possibly taking the midpoints.

```<code>import numpy as np

def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

delta_x = (b - a) / float(n)

x_left = np.arange(a, b, delta_x)
x_right = np.arange(a+delta_x, b+delta_x, delta_x)
x_mid = np.arange(a+delta_x/2., b+delta_x/2., delta_x)

print len(x_left),  len(x_right), len(x_mid)          ### 1000 1000 1000

area_left = f_x(x_left).sum() * delta_x
area_right = f_x(x_right).sum() * delta_x
area_mid = f_x(x_mid).sum() * delta_x

print area_left     # -0.002
print area_right    #  0.002
print area_mid      # 1.81898940355e-15
</code>```

While the midpoint sum already gives a good result, for symmetric functions it would be a good idea to choose n even, and take the average of the left and right sum,

```<code>print 0.5*(area_right+area_left)   # 1.76204537072e-15
</code>```

This is equally close to 0.

Now it is worthwhile noting that numpy.arange produces some errors by itself. A better choice would be using numpy.linspace

```<code>x_left = np.linspace(a, b-delta_x, n)
x_right = np.linspace(a+delta_x, b, n)
x_mid = np.linspace(a+delta_x/2., b-delta_x/2., n)
</code>```

yielding

```<code>print area_left     # -0.002
print area_right    #  0.002
print area_mid      # 8.52651282912e-17
print 0.5*(area_right+area_left)   # 5.68121938382e-17
</code>```

5.68121938382e-17 is pretty close to 0. The reason why it is not entirely 0 is indeed floating point inaccuracies.

The famous example of that would be
0.1 + 0.2 - 0.3
which results in 5.5e-17 instead of 0. This is to show that this simply operation introduces the same error of the order of 1e-17 as the Riemann integration.

Body:
I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead.

The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15.

What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this.

I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number.

The Python code:

import matplotlib.pyplot as plt
import numpy as np

# Approximates and graphs integral using Riemann Sum

# example function: f(x) = x^3
def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a) / n

x = np.arange(a, b+delta_x, delta_x)

y = [f_x(i) for i in x]

area = sum(y) * delta_x

# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()

Body:
You need to be aware that what you are computing is not a Riemann integral in the original sense. You are dividing the interval into n bins, but then sum over n+1 bins (here n = 1000 but len(x) == 1001). So the result may be close to what you expect, but it is certainly not a good way to get there.

Using the Riemann sum you would divide your interval into n bins, and then sum over the values of those n bins. You have the choice whether to compute the left Riemann sum, the right Riemann sum, or possibly taking the midpoints.

import numpy as np

def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

delta_x = (b - a) / float(n)

x_left = np.arange(a, b, delta_x)
x_right = np.arange(a+delta_x, b+delta_x, delta_x)
x_mid = np.arange(a+delta_x/2., b+delta_x/2., delta_x)

print len(x_left),  len(x_right), len(x_mid)          ### 1000 1000 1000

area_left = f_x(x_left).sum() * delta_x
area_right = f_x(x_right).sum() * delta_x
area_mid = f_x(x_mid).sum() * delta_x

print area_left     # -0.002
print area_right    #  0.002
print area_mid      # 1.81898940355e-15

While the midpoint sum already gives a good result, for symmetric functions it would be a good idea to choose n even, and take the average of the left and right sum,

print 0.5*(area_right+area_left)   # 1.76204537072e-15

This is equally close to 0.

Now it is worthwhile noting that numpy.arange produces some errors by itself. A better choice would be using numpy.linspace

x_left = np.linspace(a, b-delta_x, n)
x_right = np.linspace(a+delta_x, b, n)
x_mid = np.linspace(a+delta_x/2., b-delta_x/2., n)

yielding

print area_left     # -0.002
print area_right    #  0.002
print area_mid      # 8.52651282912e-17
print 0.5*(area_right+area_left)   # 5.68121938382e-17

5.68121938382e-17 is pretty close to 0. The reason why it is not entirely 0 is indeed floating point inaccuracies.

The famous example of that would be
0.1 + 0.2 - 0.3
which results in 5.5e-17 instead of 0. This is to show that this simply operation introduces the same error of the order of 1e-17 as the Riemann integration.


来源: stackexchange

答:
You can use boolean indexing for max volume and tail(1) for last value of open inside apply since you have duplicate index i.e

```<code>ohlc_dict = {
   'high': 'max',
   'low': 'min',
   'close': 'last',
   'volume': 'max',
}
grp = df.groupby(pd.Grouper(freq='1Min',level=0,label='left'))
ndf = grp.agg(ohlc_dict)

ndf['open'] = grp['open','volume'].apply(lambda x : x[x['volume'] == x['volume'].max()].tail(1)['open'])
</code>```

Output :

```
                        low  volume    close     high     open
datetime
2017-11-17 12:35:00  0.96213      29  0.96222  0.96223  0.96213
```

ContentLicense: CC BY-SA 3.0

Title: Grouping By Using a Conditional Statement from a Different Column

Body:
I need to group a pandas Dataframe according to the following criteria, it is like-ish a ohlc aggregation:

open = last where volume > 0, in case there is no entry with volume > 0 use overall last
high = max
low = min
last = last
volume = max

My current implementation for these kinds of operations (ohlc aggregation) is:

ohlc_dict = {
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
}

df = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')).agg(ohlc_dict)

How can I solve this? Thank you.

Sample:

                     fi  ts     open     high      low    close  volume
datetime
2017-11-17 12:35:00   0   0  0.96214  0.96214  0.96214  0.96214       0
2017-11-17 12:35:00   0   0  0.96214  0.96214  0.96214  0.96214       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96213  0.96220  0.96213  0.96219      19
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96219       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96222       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96223       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96220      29
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96220      29
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96222       0

Desired Output:

                     fi  ts     open     high      low    close  volume
datetime
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96222       29

Additional Information:

There are two data sources which can be identified by their 'Volume' values:

a. Volume = 0 (more frequent, less reliable)
b. Volume > 0 (less frequent, more reliable)

As type 'b.' is more reliable, it is preferrable to use its open value to type 'a' open value.

As to whether last aggregation, it doesn't really matter to be honest, other aggregations (first,max,min) would work, as the open value is the first quoted value in a minute (on this example) and never changes.

The issues of incorrect values arise when there is an interruption on the connection to the server. Type 'a' data cannot deal with this and will give me possibly wrong values, type 'b' data can deal with this just fine and will give me correct values.

Body:
You can use boolean indexing for max volume and tail(1) for last value of open inside apply since you have duplicate index i.e

ohlc_dict = {
   'high': 'max',
   'low': 'min',
   'close': 'last',
   'volume': 'max',
}
grp = df.groupby(pd.Grouper(freq='1Min',level=0,label='left'))
ndf = grp.agg(ohlc_dict)

ndf['open'] = grp['open','volume'].apply(lambda x : x[x['volume'] == x['volume'].max()].tail(1)['open'])

Output :

                        low  volume    close     high     open
datetime
2017-11-17 12:35:00  0.96213      29  0.96222  0.96223  0.96213


问:
Xcode crashes on opening xib files
I have problems with xcode and can't open xib files. Everytime I click on the xib file, xcode crashes. This happens on the xcode3.2 as well as the xcode4.

Is there anything I can do to it? I have un-installed and re-installed but still not working.

Any help would really be appreciable.

If it helps, I am using xcode4 and bought it from the app store.

答:
Its an XCode bug.

Creating a new .storyboard and opening it before opening .xib will fix the crash, at least temporarily.

ContentLicense: CC BY-SA 4.0

Title: Xcode crashes on opening xib files


问:
Multiple line execution in Neo4j
I am trying to execute the following cypher code:

```<code>// Nodes created for Lessons, Submitter, Center and Topic
// Relations created
// Uniqueness constraints.
CREATE CONSTRAINT ON (l:Lesson) ASSERT l.name IS UNIQUE;
// Load.
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM
'file:///llis.csv' AS line
WITH line, SPLIT(line.LessonDate, '-') AS date
CREATE (lesson:Lesson { name: TOINT(line.`LessonId`) } )
SET lesson.year = TOINT(date[0]),
    lesson.month = TOINT(date[1]),
    lesson.day = TOINT(date[2]),
    lesson.title = (line.Title),
    lesson.abstract = (line.Abstract),
    lesson.lesson = (line.Lesson),
    lesson.org = (line.MissionDirectorate),
    lesson.safety = (line.SafetyIssue),
    lesson.url = (line.url)
</code>```

However, I cannot do this in the browser because it's two separate lines. See error:

Node(562) already exists with label Lesson and property name = 0

I know I am meant to do this in the Neo4j-shell. I have managed to get in to the Neo4j-shell but how do I run this bit of code there?

答:
Put your syntax in a file and then run it as follows :

on Windows

```<code>type yourfile.cypher | bin\cypher-shell.bat -u <user> -p <password>
</code>```

on Linux

```<code>cat yourfile.cypher | bin/cypher-shell -u <user> -p <password>
</code>```

Hope this helps,
Tom

Title: Multiple line execution in Neo4j

Body:
I am trying to execute the following cypher code:

// Nodes created for Lessons, Submitter, Center and Topic
// Relations created
// Uniqueness constraints.
CREATE CONSTRAINT ON (l:Lesson) ASSERT l.name IS UNIQUE;
// Load.
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM
'file:///llis.csv' AS line
WITH line, SPLIT(line.LessonDate, '-') AS date
CREATE (lesson:Lesson { name: TOINT(line.`LessonId`) } )
SET lesson.year = TOINT(date[0]),
    lesson.month = TOINT(date[1]),
    lesson.day = TOINT(date[2]),
    lesson.title = (line.Title),
    lesson.abstract = (line.Abstract),
    lesson.lesson = (line.Lesson),
    lesson.org = (line.MissionDirectorate),
    lesson.safety = (line.SafetyIssue),
    lesson.url = (line.url)

However, I cannot do this in the browser because it's two separate lines. See error:

Node(562) already exists with label Lesson and property name = 0

I know I am meant to do this in the Neo4j-shell. I have managed to get in to the Neo4j-shell but how do I run this bit of code there?

Body:
Put your syntax in a file and then run it as follows :

on Windows

type yourfile.cypher | bin\cypher-shell.bat -u <user> -p <password>

on Linux

cat yourfile.cypher | bin/cypher-shell -u <user> -p <password>

Hope this helps,
Tom


问:
How to start IMA HTML5 SDK ads muted?
What I'm trying to do is to make the autoplay video on ios 10 using HTML5 and I did that using:

```<code><video autoplay loop muted playsinline controls>
    <source src="http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4">
</video>
</code>```

But when using IMA SDK for HTML5 the ad start unmuted and therefore the autoplay will not work.

Is there a way to mute the ads on start (initialize the ads muted)?

答:
You have to mute AdsManager it after google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED event.

```<code>loader = new google.ima.AdsLoader(...);
loader.addEventListener(
    google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
    (event) => {
       event.getAdsManager(videoTag).setVolume(0);
    }
</code>```

Title: How to start IMA HTML5 SDK ads muted?

Body:
What I'm trying to do is to make the autoplay video on ios 10 using HTML5 and I did that using:

<video autoplay loop muted playsinline controls>
    <source src="http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4">
</video>

But when using IMA SDK for HTML5 the ad start unmuted and therefore the autoplay will not work.

Is there a way to mute the ads on start (initialize the ads muted)?

Body:
You have to mute AdsManager it after google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED event.

loader = new google.ima.AdsLoader(...);
loader.addEventListener(
    google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
    (event) => {
       event.getAdsManager(videoTag).setVolume(0);
    }


问:
HTML data is hidden from urllib
How do I get the real content from this page:
http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv

All I get from the code below is some links to javascript and CSS files. Is there a way out of this?

```<code>from urllib.request import urlopen
html = urlopen("http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv")
print(html.read())
</code>```

Best regards, Kresten

答:
What is  printed is the 'real' content. If you wanted to see the output of that JavaScript code you would need to fetch all the JavaScript through the  tags and external script and then use a JavaScript Parser to read it.  You would not need the CSS scripts for just reading the content as they are just used to style the page.

Unfortunately I can think of no alternative.

I hope I was helpful.

Title: HTML data is hidden from urllib

Body:
How do I get the real content from this page:
http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv

All I get from the code below is some links to javascript and CSS files. Is there a way out of this?

from urllib.request import urlopen
html = urlopen("http://kursuskatalog.au.dk/da/course/74960/105E17-Demokrati-og-diktatur-i-komparativt-perspektiv")
print(html.read())

Best regards, Kresten

Body:
What is  printed is the 'real' content. If you wanted to see the output of that JavaScript code you would need to fetch all the JavaScript through the <script></script> tags and external script and then use a JavaScript Parser to read it.  You would not need the CSS scripts for just reading the content as they are just used to style the page.

Unfortunately I can think of no alternative.

I hope I was helpful.


问:
Linking Matlab shared library into Qt (Windows)
I want to use Matlab's C API within QT (http://www.mathworks.com/help/techdoc/matlab_external/f39876.html#bsfvqhp-1) under Windows for opening a .mat file. In my .pro file I have included
INCLUDEPATH += "C:\Program Files\MATLAB\R2010b\extern\include"
which works fine (the code compiles). But when trying to link the libmat.lib file (I have read the .dll files cannot be linked directly) using
LIBS += -L"C:\Program Files\MATLAB\R2010b\extern\lib\win32\microsoft" -llibmat
the application crashes on execution. The error given says [file].exe exited with code -1073741515

I'm neither a QT nor a Windows expert but for this project I am forced to use both (I guess it would be easier to fix this in GNU/Linux) so any help would be appreciated. Using Windows XP, QT version 4.7.0 with Qt Creator 2.0.1, and Matlab R2010b.

The last output from the compiler just in case it is useful:

g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -Wl,-subsystem,windows -o debug/MainUI.exe debug/main.o debug/maingui.o debug/matparser.o debug/matutils.o debug/moc_maingui.o  -L'c:/Qt/2010.05/qt/lib' -lmingw32 -lqtmaind "-LC:\Program Files\MATLAB\R2010b\extern\lib\win32\microsoft" -llibmat -lQtGuid4 -lQtCored4

答:
I suspect that the Matlab library will have been compiled with MSVC and since you say you are compiling your own code with MingW I would imagine the two are incompatible.

Have a look at the MingW page on mixing compilers for more information.

ContentLicense: CC BY-SA 2.5


问:
Postgres: use function that returns a string in another function
I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

```<code>CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;
</code>```

If I run this query I obtain the error:

```<code>ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();
</code>```

What I'm doing wrong? How can I use the return value of the first function into the second one?

答:
Note to other answers: select is implicitly added in plpgsql context. Example:

```<code>do $$
declare
  v text[];
begin
  v := array_agg(datname) from pg_database;
  raise info 'List of databases: %', v;
end $$;
</code>```

So when you call mytext := select public.get_some_string(); it is transformed to select select public.get_some_string(); internally.

Thats why parenthesesis mytext := (select public.get_some_string()); could be the solution: select (select public.get_some_string()); is the acceptable statement.

Body:
I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;

If I run this query I obtain the error:

ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();

What I'm doing wrong? How can I use the return value of the first function into the second one?

Body:
Note to other answers: select is implicitly added in plpgsql context. Example:

do $$
declare
  v text[];
begin
  v := array_agg(datname) from pg_database;
  raise info 'List of databases: %', v;
end $$;

So when you call mytext := select public.get_some_string(); it is transformed to select select public.get_some_string(); internally.

Thats why parenthesesis mytext := (select public.get_some_string()); could be the solution: select (select public.get_some_string()); is the acceptable statement.


问:
Batch script for /f loop does not show all tokens
I have weather.txt

```<code>January,Snowy,02
February,Rainy,15
March,Sunny,25
</code>```

and main.cmd

```<code>@echo off
for /f "tokens=1,3 delims=," %%M in (weather.txt) do (echo %%M %%T)
</code>```

I expect output

```<code>January 02
February 15
March 25
</code>```

But I get

```<code>January %T
February %T
March %T
</code>```

Help THX

答:
Strange that you use %%T if you did a for in %%M.

cmd cannot assume a variable, they have to be in order. so for tokens 1 and 3 if you start with %%M you need the next alphabetical letter to display that token, not just a random letter. So therefore your code should be:

```<code>@echo off
for /f "tokens=1,3 delims=," %%M in (weather.txt) do (echo %%M %%N)
</code>```

Body:
I have weather.txt

January,Snowy,02
February,Rainy,15
March,Sunny,25

and main.cmd

@echo off
for /f "tokens=1,3 delims=," %%M in (weather.txt) do (echo %%M %%T)

I expect output

January 02
February 15
March 25

But I get

January %T
February %T
March %T

Help THX

Body:
Strange that you use %%T if you did a for in %%M.

cmd cannot assume a variable, they have to be in order. so for tokens 1 and 3 if you start with %%M you need the next alphabetical letter to display that token, not just a random letter. So therefore your code should be:

@echo off
for /f "tokens=1,3 delims=," %%M in (weather.txt) do (echo %%M %%N)


问:
Debug C# method at runtime
I am working on an application that should compile and debug C# code on the fly.

A simplified version of the code is included below.

What should be changed in this code to run the generated method step by step and get the state of the variables x and y after each step?

If everything should be changed that is okay, I am happy with any constructive response.

EDIT: to clarify: what I want to do is have my code debug the code that is generated with reflection, not the debug function in Visual Studio.

```<code>string code =
@"
namespace MyNameSpace
{
    public class MyClass
    {
        public static int MyMethod()
        {
            var x = 3;
            var y = 4;
            return x * y;
        }
    }
}";

string namespaceName = "MyNameSpace";
string className = "MyClass";
string methodName = "MyMethod";
string language = "csharp";
string classFullname = namespaceName + "." + className;

CodeDomProvider provider = CodeDomProvider.CreateProvider(language);
CompilerParameters parameters = new CompilerParameters();
CompilerResults results;

parameters.OutputAssembly = "Compiler";

parameters.CompilerOptions = "/t:library";
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;

results = provider.CompileAssemblyFromSource(parameters, code);

if (results.Errors.Count != 0)
{
    throw new Exception("Code compilation errors occurred.");
}

var instance = results.CompiledAssembly.CreateInstance(classFullname, false);

// TODO run the method step by step and get the state after each step
</code>```

答: Click just left side of your code it will mark red dot that is called break point.After that when your code execute at the point it will break at the point and you can debug step by step bt pressing F10 key.

Title: Debug C# method at runtime

Body:
I am working on an application that should compile and debug C# code on the fly.

A simplified version of the code is included below.

What should be changed in this code to run the generated method step by step and get the state of the variables x and y after each step?

If everything should be changed that is okay, I am happy with any constructive response.

EDIT: to clarify: what I want to do is have my code debug the code that is generated with reflection, not the debug function in Visual Studio.

string code =
@"
namespace MyNameSpace
{
    public class MyClass
    {
        public static int MyMethod()
        {
            var x = 3;
            var y = 4;
            return x * y;
        }
    }
}";

string namespaceName = "MyNameSpace";
string className = "MyClass";
string methodName = "MyMethod";
string language = "csharp";
string classFullname = namespaceName + "." + className;

CodeDomProvider provider = CodeDomProvider.CreateProvider(language);
CompilerParameters parameters = new CompilerParameters();
CompilerResults results;

parameters.OutputAssembly = "Compiler";

parameters.CompilerOptions = "/t:library";
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;

results = provider.CompileAssemblyFromSource(parameters, code);

if (results.Errors.Count != 0)
{
    throw new Exception("Code compilation errors occurred.");
}

var instance = results.CompiledAssembly.CreateInstance(classFullname, false);

// TODO run the method step by step and get the state after each step


问:
Placing UiView as a subview programmatically
I have ViewController that looks like this. There is parent ScrollView that holds UIView (wrapperView) and this wrapper view has TextView and ImageView inside.
This simple structure is created form interface builder with all constraints needed so it works fine.

In some cases I need to programmatically add one more UIView inside my wrapperView right under ImageView (green arrow points there).

So I created xib file for my new UIView and separate class for it

```<code>class MyView : UIView {
    class func instanceFromNib() -> UIView {
        return UINib(nibName: "MyView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}
</code>```

And I code of my ViewController I added

```<code>let myView = MyView.instanceFromNib()
myView = CGRect(x: 0, y: 0, width: 300, height: 80)
wrapperView.addSubview(myView)
</code>```

now i see myView on the screen in top of wrapperView but when i try to apply constraints like

```<code>NSLayoutConstraint(item: myView, attribute: .top, relatedBy: .equal, toItem: myImageView, attribute: .bottom, multiplier: 1.0, constant: 8).isActive = true
</code>```

I got

Unable to simultaneously satisfy constraints

What am I doing wrong?

答:
First you need to set this:

```<code>myView.translatesAutoresizingMaskIntoConstraints = false
</code>```

And then you have to make sure that there are no your own constraints that are in conflict. In storyboard you have probably added a constraint that binds imageView.bottomAnchor to wrapperView.bottomAnchor. Now if you put between these two anchors another view, you need to deactivate that constraint.

Otherwise if you try to squeeze myView there, it may result in constraint conflicts - imagine there is a constraint saying that

imageView.bottomAnchor should be 10 points from wrapperView.bottomAnchor,

but there are also two more constraints saying that

imageView.bottomAnchor should be 10 points from myView.topAnchor and myView.bottomAnchor should be 10 points from wrapperView.bottomAnchor.

Obviously both these scenarios cannot be satisfied.

Body:
I have ViewController that looks like this. There is parent ScrollView that holds UIView (wrapperView) and this wrapper view has TextView and ImageView inside.
This simple structure is created form interface builder with all constraints needed so it works fine.

In some cases I need to programmatically add one more UIView inside my wrapperView right under ImageView (green arrow points there).

So I created xib file for my new UIView and separate class for it

class MyView : UIView {
    class func instanceFromNib() -> UIView {
        return UINib(nibName: "MyView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}

And I code of my ViewController I added

let myView = MyView.instanceFromNib()
myView = CGRect(x: 0, y: 0, width: 300, height: 80)
wrapperView.addSubview(myView)

now i see myView on the screen in top of wrapperView but when i try to apply constraints like

NSLayoutConstraint(item: myView, attribute: .top, relatedBy: .equal, toItem: myImageView, attribute: .bottom, multiplier: 1.0, constant: 8).isActive = true

I got

Unable to simultaneously satisfy constraints

What am I doing wrong?

Body:
First you need to set this:

myView.translatesAutoresizingMaskIntoConstraints = false

And then you have to make sure that there are no your own constraints that are in conflict. In storyboard you have probably added a constraint that binds imageView.bottomAnchor to wrapperView.bottomAnchor. Now if you put between these two anchors another view, you need to deactivate that constraint.

Otherwise if you try to squeeze myView there, it may result in constraint conflicts - imagine there is a constraint saying that

imageView.bottomAnchor should be 10 points from wrapperView.bottomAnchor,

but there are also two more constraints saying that

imageView.bottomAnchor should be 10 points from myView.topAnchor and myView.bottomAnchor should be 10 points from wrapperView.bottomAnchor.

Obviously both these scenarios cannot be satisfied.


问:
How to disable margin-collapsing?
Is there a way to disable margin-collapsing altogether?  The only solutions I've found (by the name of "uncollapsing") entail using a 1px border or 1px padding.  I find this unacceptable: the extraneous pixel complicates calculations for no good reason.  Is there a more reasonable way to disable this margin-collapsing?</p>

答:
Actually, there is one that works flawlessly:

display: flex;
flex-direction: column;

as long as you can live with supporting only IE10 and up

.container {
  display: flex;
  flex-direction: column;
    background: #ddd;
    width: 15em;
}

.square {
    margin: 15px;
    height: 3em;
    background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>
<div class="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div></code>```

Title: How to disable margin-collapsing?

Body:
Actually, there is one that works flawlessly:

display: flex;
flex-direction: column;

as long as you can live with supporting only IE10 and up

.container {
  display: flex;
  flex-direction: column;
    background: #ddd;
    width: 15em;
}

.square {
    margin: 15px;
    height: 3em;
    background: yellow;
}

<div class="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>
<div class="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>


问:
How do I convert and integer to datetime
I am using ASP.NET Visual Basic.

I have an integer field in my database which I need to read as a date e.g. 20130813. But at the moment it says I cannot convert to datetime.

Is there a way to split the integer up into DD, MM, YYYY so I could even store those in variables to then use to create a date. Or a simple way of just converting to date.

Thanks for your time.

答:
Quicker:

```<code>Dim d As Date = Date.FromOADate(41498)
</code>```

(from Robert Shutt in experts-exchange.com)

Body:
Quicker:

Dim d As Date = Date.FromOADate(41498)

(from Robert Shutt in experts-exchange.com)


问:
Why TypeScript doesn't generate code for interfaces?
I'm using TS Playground to learn TypeScript. What I found strange is that TypeScript doesn't generate a specific code for interfaces.

Example:

```<code>interface Person {
    id: number,
    fullName: string,
    sayHello: Function
}

let p: Person;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () {return "Hello from " + p.fullName;}
</code>```

Will be translated to:

```<code>var p;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () { return "Hello from " + p.fullName; };
</code>```

Is there an explanation why TypeScript doesn't generate any code for the interface ?

答:
The TypeScript compiler performs a task called type erasure, which removes all types from the output (see note below). There are two key reasons for this:

Type information cannot logically be represented in JavaScript

Type information is intended for the compiler, not for runtime, so it isn't needed in the output

There have been some projects that intended to bring TypeScript's types to the runtime in order to perform runtime-type-checking, but there honestly wasn't a great appetite for this. Given we are moving from totally dynamic types at all times to static type checking at design/compile time, the leap may be big enough for the majority of people.

Types aren't the only thing that can be removed during compilation; another example is uninitialized class members, such as the name property in the example below, which you won't find in your JavaScript file.

```<code>class Example {
    public name: string;
}

const example = new Example();

console.log(example.name);
</code>```

But most of the removals in your application will be types and ambient declarations.

The Note Below

All types are erased? There is some experimental support for emitting type information to be used with reflection, which you can try with the reflect-metadata package.

Body:
I'm using TS Playground to learn TypeScript. What I found strange is that TypeScript doesn't generate a specific code for interfaces.

Example:

interface Person {
    id: number,
    fullName: string,
    sayHello: Function
}

let p: Person;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () {return "Hello from " + p.fullName;}

Will be translated to:

var p;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () { return "Hello from " + p.fullName; };

Is there an explanation why TypeScript doesn't generate any code for the interface ?

Body:
The TypeScript compiler performs a task called type erasure, which removes all types from the output (see note below). There are two key reasons for this:

Type information cannot logically be represented in JavaScript

Type information is intended for the compiler, not for runtime, so it isn't needed in the output

There have been some projects that intended to bring TypeScript's types to the runtime in order to perform runtime-type-checking, but there honestly wasn't a great appetite for this. Given we are moving from totally dynamic types at all times to static type checking at design/compile time, the leap may be big enough for the majority of people.

Types aren't the only thing that can be removed during compilation; another example is uninitialized class members, such as the name property in the example below, which you won't find in your JavaScript file.

class Example {
    public name: string;
}

const example = new Example();

console.log(example.name);

But most of the removals in your application will be types and ambient declarations.

The Note Below

All types are erased? There is some experimental support for emitting type information to be used with reflection, which you can try with the reflect-metadata package.


问:
grouping array values like mysqli 'like' functionality
friends, i don't it's possible or not, anyway i want to group users who have same like preference names ( mysql 'like' functionality)

```<code>[0]=>
 array(5) {
  ["id"]=>"21"
  ["user_id"]=>"58"
  ["preference_id"]=>"4"
  ["sub_preference_id"]=>"7"
  ["preference_name"]=>"stephens collage"
}
[1]=>
 array(5) {
  ["id"]=>"22"
  ["user_id"]=>"52"
  ["preference_id"]=>"4"
  ["sub_preference_id"]=>"1"
  ["preference_name"]=>"st stephens"
}
[2]=>
 array(5) {
  ["id"]=>"25"
  ["user_id"]=>"61"
  ["preference_id"]=>"4"
  ["sub_preference_id"]=>"9"
  ["preference_name"]=>"joseph"
}
</code>```

means i want output as like this :

1]stephens collage, st stephens

2] joseph

i tried this code :

```<code>$school_preference ="SELECT * FROM gic_user_preference where preference_id='4'";

$result_school_preference = mysqli_query($createCon->connect(), $school_preference);

$school = array();

 while ($show_school_preference = mysqli_fetch_assoc($result_school_preference)) {

    $school_preference = $show_school_preference['sub_preference_id'];

    $get_all_school_preference =mysqli_query($createCon->connect(),"SELECT gic_user_preference.id,gic_user_preference.user_id,gic_user_preference.preference_id,gic_user_preference.sub_preference_id,gic_user_wise_school_preference.preference_name FROM gic_user_preference INNER JOIN gic_user_wise_school_preference ON gic_user_preference.sub_preference_id = gic_user_wise_school_preference.id where gic_user_preference.sub_preference_id='$school_preference'");

    while ($schools = mysqli_fetch_assoc($get_all_school_preference)) {
        $school[$schools['preference_name']][] = $schools;
    }
 }
</code>```

it's give the output

```<code> array(4) {
 ["stephens collage"]=>
 array(1) {
  [0]=>
  array(5) {
  ["id"]=>
  string(2) "21"
  ["user_id"]=>
  string(2) "58"
  ["preference_id"]=>
  string(1) "4"
  ["sub_preference_id"]=>
  string(1) "7"
  ["preference_name"]=>
  string(16) "stephens collage"
   }
 }
  ["st stephens"]=>
  array(1) {
   [0]=>
   array(5) {
  ["id"]=>
  string(2) "22"
  ["user_id"]=>
  string(2) "52"
  ["preference_id"]=>
  string(1) "4"
  ["sub_preference_id"]=>
  string(1) "1"
  ["preference_name"]=>
  string(11) "st stephens"
  }
 }
 ["joseph"]=>
 array(1) {
  [0]=>
   array(5) {
  ["id"]=>
  string(2) "25"
  ["user_id"]=>
  string(2) "61"
  ["preference_id"]=>
  string(1) "4"
  ["sub_preference_id"]=>
  string(1) "9"
  ["preference_name"]=>
  string(6) "joseph"
  }
 }
}
</code>```

any idea how to grouping this data as mysqli like function works ...

答: I think you can use regular expression match for find same names!</p>

Body:
friends, i don't it's possible or not, anyway i want to group users who have same like preference names ( mysql 'like' functionality)

[0]=>
 array(5) {
  ["id"]=>"21"
  ["user_id"]=>"58"
  ["preference_id"]=>"4"
  ["sub_preference_id"]=>"7"
  ["preference_name"]=>"stephens collage"
}
[1]=>
 array(5) {
  ["id"]=>"22"
  ["user_id"]=>"52"
  ["preference_id"]=>"4"
  ["sub_preference_id"]=>"1"
  ["preference_name"]=>"st stephens"
}
[2]=>
 array(5) {
  ["id"]=>"25"
  ["user_id"]=>"61"
  ["preference_id"]=>"4"
  ["sub_preference_id"]=>"9"
  ["preference_name"]=>"joseph"
}

means i want output as like this :

1]stephens collage, st stephens

2] joseph

i tried this code :

$school_preference ="SELECT * FROM gic_user_preference where preference_id='4'";

$result_school_preference = mysqli_query($createCon->connect(), $school_preference);

$school = array();

 while ($show_school_preference = mysqli_fetch_assoc($result_school_preference)) {

    $school_preference = $show_school_preference['sub_preference_id'];

    $get_all_school_preference =mysqli_query($createCon->connect(),"SELECT gic_user_preference.id,gic_user_preference.user_id,gic_user_preference.preference_id,gic_user_preference.sub_preference_id,gic_user_wise_school_preference.preference_name FROM gic_user_preference INNER JOIN gic_user_wise_school_preference ON gic_user_preference.sub_preference_id = gic_user_wise_school_preference.id where gic_user_preference.sub_preference_id='$school_preference'");

    while ($schools = mysqli_fetch_assoc($get_all_school_preference)) {
        $school[$schools['preference_name']][] = $schools;
    }
 }

it's give the output

 array(4) {
 ["stephens collage"]=>
 array(1) {
  [0]=>
  array(5) {
  ["id"]=>
  string(2) "21"
  ["user_id"]=>
  string(2) "58"
  ["preference_id"]=>
  string(1) "4"
  ["sub_preference_id"]=>
  string(1) "7"
  ["preference_name"]=>
  string(16) "stephens collage"
   }
 }
  ["st stephens"]=>
  array(1) {
   [0]=>
   array(5) {
  ["id"]=>
  string(2) "22"
  ["user_id"]=>
  string(2) "52"
  ["preference_id"]=>
  string(1) "4"
  ["sub_preference_id"]=>
  string(1) "1"
  ["preference_name"]=>
  string(11) "st stephens"
  }
 }
 ["joseph"]=>
 array(1) {
  [0]=>
   array(5) {
  ["id"]=>
  string(2) "25"
  ["user_id"]=>
  string(2) "61"
  ["preference_id"]=>
  string(1) "4"
  ["sub_preference_id"]=>
  string(1) "9"
  ["preference_name"]=>
  string(6) "joseph"
  }
 }
}

any idea how to grouping this data as mysqli like function works ...


问:
Multiple AND relationship in Wordpress Query
I need to make a query that has multiple AND relationship requirements. So I have courses and I need the query to look at the custom fields and find the courses (custom posts) between 2 dates, at a location at if the course is open. This is the code I have any idea why it is returning nothing when I have a course that should fulfil the requirements of the query.

```<code>      $query = array(
            'post_type' => 'courses',
                'meta_query' => array(
                    'relation' => 'AND',
                        array(
                            'key' => 'course_date',
                            'compare' => '>=',
                            'value' => '2017-01-01',
                            'type' => 'DATE'
                        ),
                        array(
                            'key' => 'course_date',
                            'compare' => '<=',
                            'value' => '2017-12-30',
                            'type' => 'DATE'
                        ),
                        array(
                            'key' => 'course_location',
                            'compare' => '=',
                            'value' => 'Leeds',
                        ),
                        array(
                            'key' => 'course_open',
                            'compare' => '=',
                            'value' => false,
                        ),
                ),
        );
</code>```

I think it is the way I have structured the query which is not correct. Basically all the criteria needs to be met.

答:
Basically your query looks pretty well done. It says:

Give me all courses, between 2017-01-01 and 2017-12-30 where the course location is Leeds and the course is not open.

Are you sure you have courses like this in your database?

Why your query might fail anyway:

Have you tried without type DATE? (Though this should be correct)

course_open value: Have you tried to use the exact string value instead of false?

If it STILL does not work remove single parts of the query to find out which one may be responsible for no results to be returned.

You also can check the generated SQL manually f.e. like this:

```<code>$posts = new WP_Query($query);
echo "Last SQL-Query: {$posts->request}";
</code>```

Body:
I need to make a query that has multiple AND relationship requirements. So I have courses and I need the query to look at the custom fields and find the courses (custom posts) between 2 dates, at a location at if the course is open. This is the code I have any idea why it is returning nothing when I have a course that should fulfil the requirements of the query.

      $query = array(
            'post_type' => 'courses',
                'meta_query' => array(
                    'relation' => 'AND',
                        array(
                            'key' => 'course_date',
                            'compare' => '>=',
                            'value' => '2017-01-01',
                            'type' => 'DATE'
                        ),
                        array(
                            'key' => 'course_date',
                            'compare' => '<=',
                            'value' => '2017-12-30',
                            'type' => 'DATE'
                        ),
                        array(
                            'key' => 'course_location',
                            'compare' => '=',
                            'value' => 'Leeds',
                        ),
                        array(
                            'key' => 'course_open',
                            'compare' => '=',
                            'value' => false,
                        ),
                ),
        );

I think it is the way I have structured the query which is not correct. Basically all the criteria needs to be met.

Body:
Basically your query looks pretty well done. It says:

Give me all courses, between 2017-01-01 and 2017-12-30 where the course location is Leeds and the course is not open.

Are you sure you have courses like this in your database?

Why your query might fail anyway:

Have you tried without type DATE? (Though this should be correct)

course_open value: Have you tried to use the exact string value instead of false?

If it STILL does not work remove single parts of the query to find out which one may be responsible for no results to be returned.

You also can check the generated SQL manually f.e. like this:

$posts = new WP_Query($query);
echo "Last SQL-Query: {$posts->request}";


问:
Chai deep equal not working
I'm trying to use Chai, but I cannot get the deep equal comparison to work for some reason.

This is a minimum example

```<code>var chai = require('chai');
var expect = chai.expect;
...

expect({
    test: {a:2}
    }).to.have.deep.property('test', {a:2});
</code>```

That generates this output

```<code>AssertionError: expected { test: { a: 2 } } to have a deep property 'test' of { a: 2 }, but got { a: 2 }
</code>```

I'm using Chai 3.5.0 and would expect this assertion to be true.

答: You have to upgrade to a newer version of Chai. This feature was introduced in Chai 4, see 4.x.x Complete Migration Guide.</p>

Title: Chai deep equal not working

Body:
I'm trying to use Chai, but I cannot get the deep equal comparison to work for some reason.

This is a minimum example

var chai = require('chai');
var expect = chai.expect;
...

expect({
    test: {a:2}
    }).to.have.deep.property('test', {a:2});

That generates this output

AssertionError: expected { test: { a: 2 } } to have a deep property 'test' of { a: 2 }, but got { a: 2 }

I'm using Chai 3.5.0 and would expect this assertion to be true.


问:
Help structure query to list concerts/venues by distance
SQL noob here needing some help. I've got an idea of how to do this in PHP/SQL, but I would really like to condense this into one SELECT statement. OK:

The site I am working on is a list of concerts and venues. Venues have a latitude and longitude, and so do accounts corresponding to that users location.

I have three tables, accounts (users), concerts, I would like to SELECT a list of concerts (and join on venues for that info) that are happening at venues within x miles of the account, using this cheap formula for distance calculation (the site only lists venues in the UK so the error is acceptable):

x = 69.1 * (accountLatitude - venueLatitude);

y = 69.1 * (accountLongitude - venueLongitude) * cos(venueLatitude / 57.3);

distance = sqrt(x * x + y * y);

How can I achieve this in a single query?

Thanks in advance xD

答:
For everyone elses benefit heres now I did it in the end:

```<code>$q = 'SELECT gigs.date, bands.idbands, venues.latitude, venues.longitude, venues.idvenues, bands.name AS band, venues.name AS venue,
        SQRT(POW(69.1 * (' . $lat . ' - venues.latitude), 2) + POW(69.1 * (' . $lon . ' - venues.longitude) * cos(venues.latitude / 57.3), 2)) AS distance
        FROM gigs
        LEFT JOIN bands ON bands.idbands=gigs.bands_idbands
        LEFT JOIN venues ON venues.idvenues=gigs.venues_idvenues
        WHERE 1
        ORDER BY distance';
</code>```

where $lat and $lon are the latitude and longitude of the user currently logged in!
this selects every single gig thats happening at every venue, and arranges them in order of distance

Body:
For everyone elses benefit heres now I did it in the end:

$q = 'SELECT gigs.date, bands.idbands, venues.latitude, venues.longitude, venues.idvenues, bands.name AS band, venues.name AS venue,
        SQRT(POW(69.1 * (' . $lat . ' - venues.latitude), 2) + POW(69.1 * (' . $lon . ' - venues.longitude) * cos(venues.latitude / 57.3), 2)) AS distance
        FROM gigs
        LEFT JOIN bands ON bands.idbands=gigs.bands_idbands
        LEFT JOIN venues ON venues.idvenues=gigs.venues_idvenues
        WHERE 1
        ORDER BY distance';

where $lat and $lon are the latitude and longitude of the user currently logged in!
this selects every single gig thats happening at every venue, and arranges them in order of distance


问:
Responsive column for CSS not working
Why does the image not automatically go down if I reduce the width(mobile device)? Is there something wrong with my , @media or something else?

*I tried to make it responsive like bootstrap column. I divide it : twothird and third part, but the third part doesn't go down responsively, stuck on the right side even if I already adjust twothird and third only implemented in device with min-width:601px. Please help.

Thank you in advance.*

html {
   box-sizing : border-box;
}*,
*:before,
*:after {
   box-sizing : inherit;
}

html {
   -ms-text-size-adjust : 100%;
   -webkit-text-size-adjust : 100%;
   overflow-x : hidden;
   min-height: 100%;
   min-width: 100%;
}

html, body {
   font-family : Verdana, sans-serif;
   font-size : 15px;
   line-height : 1.5;
}

body {
   margin : 0;
}

a {
   background-color : transparent;
   -webkit-text-decoration-skip : objects;
   color : inherit;
}

a : active, a : hover {
   outline-width : 0;
}

h1 {
   font-size : 36px;
}

h2 {
   font-size : 30px;
}

h3 {
   font-size : 24px;
}

h4 {
   font-size : 20px;
}

h5 {
   font-size : 18px;
}

h5.italic {
   font-style : italic;
}

h6 {
   font-size : 16px;
}

p {
   color : #757575!important;
}

p.italic {
    font-style : italic;
}

@media (min-width : 993px) {
   .hide-large {
      display : none!important;
   }
}

@media (max-width : 992px) and (min-width : 601px) {
   .hide-medium {
      display : none!important;
   }
}

@media (max-width:600px){
   .hide-small {
      display:none!important;
   } .content-main {
      flex-direction: row;
   }
}

@media (min-width:601px){
   .quarter {
      width : 24.99999%;
   } .third {
      width : 33.33333%;
   } .twothird {
      width : 66.66666%;
   }
}

@media (max-width:992px){
   .content-main {
      margin-left : 0!important;
      margin-right : 0!important;
   }
}

img {
   border-style : none;
}

.theme {
   color : #fff!important;
   background-color : #000000!important;
}

.theme-l1 {
   color : #fff!important;
   background-color : #333333!important;
}

.top,.bottom {
   position : fixed;
   width : 100%;
   z-index : 1;
}

.top {
   top : 0;
}

.bottom {
   bottom : 0;
}

.bar {
   width : 100%;
   overflow : hidden;
}

.container, .panel {
   padding : 0.01em 16px;
   min-height: 50px;
   overflow: hidden;
}

.panel {
   margin-top : 16px;
   margin-bottom : 16px;
}

.bar .bar-item {
   padding : 8px 16px;
   float : left;
   width : auto;
   border : none;
   outline : none;
   display : block;
}

.bar .button {
   white-space : normal;
}

.bar-block .bar-item{
   width : 100%;
   display : block;
   padding : 8px 16px;
   text-align : left;
   border : none;
   outline : none;
   white-space : normal;
   float : none;
}

.button {
   -webkit-touch-callout : none;
   -webkit-user-select : none;
   -khtml-user-select : none;
   -moz-user-select : none;
   -ms-user-select : none;
   user-select : none;
   border : none;
   display : inline-block;
   outline : 0;
   padding : 8px 16px;
   vertical-align : middle;
   overflow : hidden;
   text-decoration : none;
   color : inherit;
   background-color : inherit;
   text-align : center;
   cursor : pointer;
   white-space : nowrap;
}

.button : hover {
   color : #000!important;
   background-color : #ccc!important;
}

.button : disabled{
   cursor : not-allowed;
   opacity : 0.3;
}

.teal {
   color : #fff!important;
   background-color : #009688!important;
}

.teal, .hover-teal : hover {
   color : #fff!important;
   background-color : #009688!important;
}

.white, .hover-white : hover {
   color : #000!important;
   background-color : #fff!important;
}

.margin-top {
   margin-top : 16px!important;
}

.margin-bottom {
   margin-bottom : 16px!important;
}

.margin-left {
   margin-left : 16px!important;
}

.margin-right {
   margin-right : 16px!important;
}

.right {
   float : right!important;
}

.display-container {
   position : relative;
}

.animate-opacity {
   animation : opac 0.8s;
} @keyframes opac {
   from {
      opacity : 0;
   } to {
      opacity : 1;
   }
}

.xlarge {
   font-size : 24px!important;
}

.xxlarge{
   font-size : 36px!important;
}

.left-align {
   text-align : left!important;
}

.center {
   text-align : center!important;
}

.padding-65 {
   padding-top : 65px!important;
   padding-bottom : 65px!important;
}

.padding-64 {
   padding-top : 64px!important;
   padding-bottom : 64px!important;
}

.light-grey, .hover-light-grey : hover {
   color : #000!important;
   background-color : #f1f1f1!important;
}

.bottombar {
   border-bottom : 6px solid #ccc!important;
}

.topbar {
   border-top : 6px solid #ccc!important;
}

.padding-16 {
   padding-top : 16px!important;
   padding-bottom : 16px!important;
}

.padding {
   padding : 8px 16px!important;
}
.quarter, .third,
.twothird {
   float : left;
   width : 100%;
}

.quarter {
   width : 24.99999%;
}

.third {
   width : 33.33333%;
}

.twothird {
   width : 66.66666%;
}

.row-padding,
.row-padding > .quarter,
.row-padding > .third,
.row-padding > .twothird {
   padding : 0 8px;
}

.content{
   max-width : 980px;
   margin : auto;
}

.hide{
   display : none!important;
}

.show {
   display : block!important;
}

.container : after, .container : before,
.panel : after, .panel : before,
.row-padding : after, .row-padding : before,
.bar : before, .bar : after {
   content : "";
   display : table;
   clear : both;
}

.circle {
   border-radius : 50%;
}

.content-main {
   max-width : 1020px;
   margin : auto;
   min-height: 50px;
   overflow: hidden;
}

.leftbar {
   border-left : 6px solid #ccc!important;
}

.serif {
   font-family : serif;
}

.karma {
   font-family :"Karma", sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container row-padding padding-64" id="about">
  <div class="content">
   <div class="twothird">
   <h1 class="xlarge bottombar padding-16">About</h1>
   <h5 class="padding-32">Between art and craft, lies The Chino A Serie.</h5>

      <p class="padding-32">Discover brand new wave of chinoserie inside us, whether you just want an instagenic background for your dayout or appreciate a new beauty, history and art while you sip your Macadamia Coffee or chop the Feast Roasta Lamb. We present you "turn-back time" experience through walking corridor gallery with theme from contemporer to ancient baroque style. Oh, once more! Check out the fusion tile work in the floor of the cafe.</p>

      <h5 class="padding-32 italic">Entre art et artisanat, se trouve La  Chino A Série.</h5>

      <p class="padding-32 italic">Découvrez la toute nouvelle vague de chinoserie en nous, que vous souhaitiez simplement un arrière-plan instagène pour votre journée ou apprécier une nouvelle beauté, histoire et art pendant que vous sirotez votre Macadamia Coffee ou que vous coupez l'agneau Roasta Feast. Nous vous présentons l'expérience du temps de retour à travers la galerie de couloir à pied avec le thème du style contemporain à l'ancien style baroque. Oh, encore une fois! Découvrez le travail de carreaux de fusion dans le plancher du café.</p><br>
   </div><br><br>
   <div class="third center content padding-64">
    <img src="images/TealBird.jpg" alt="chinoiserie" style="width : 90%">
    <div class="panel">
     <p><i class="fa fa-quote-left xxlarge"></i><br>
      <i class="xlarge serif">White becomes teal, Birds free from the tale.
      </i><br>
      <i class="fa fa-quote-right xxlarge"></i>
     </p>
    </div>
   </div>
     </div>
 </div></code>```

答:
Your media queries seems good, in max-width:600px I add a clear:both for third class:</p>

```<code>@media (max-width:600px){
   .hide-small {
      display:none!important;
   } .content-main {
      flex-direction: row;
   }
  .third {
    clear: both
  }
}
</code>```

Title: Responsive column for CSS not working

Body:
Why does the image not automatically go down if I reduce the width(mobile device)? Is there something wrong with my , @media or something else?

*I tried to make it responsive like bootstrap column. I divide it : twothird and third part, but the third part doesn't go down responsively, stuck on the right side even if I already adjust twothird and third only implemented in device with min-width:601px. Please help.

Thank you in advance.*

html {
   box-sizing : border-box;
}*,
*:before,
*:after {
   box-sizing : inherit;
}

html {
   -ms-text-size-adjust : 100%;
   -webkit-text-size-adjust : 100%;
   overflow-x : hidden;
   min-height: 100%;
   min-width: 100%;
}

html, body {
   font-family : Verdana, sans-serif;
   font-size : 15px;
   line-height : 1.5;
}

body {
   margin : 0;
}

a {
   background-color : transparent;
   -webkit-text-decoration-skip : objects;
   color : inherit;
}

a : active, a : hover {
   outline-width : 0;
}

h1 {
   font-size : 36px;
}

h2 {
   font-size : 30px;
}

h3 {
   font-size : 24px;
}

h4 {
   font-size : 20px;
}

h5 {
   font-size : 18px;
}

h5.italic {
   font-style : italic;
}

h6 {
   font-size : 16px;
}

p {
   color : #757575!important;
}

p.italic {
    font-style : italic;
}

@media (min-width : 993px) {
   .hide-large {
      display : none!important;
   }
}

@media (max-width : 992px) and (min-width : 601px) {
   .hide-medium {
      display : none!important;
   }
}

@media (max-width:600px){
   .hide-small {
      display:none!important;
   } .content-main {
      flex-direction: row;
   }
}

@media (min-width:601px){
   .quarter {
      width : 24.99999%;
   } .third {
      width : 33.33333%;
   } .twothird {
      width : 66.66666%;
   }
}

@media (max-width:992px){
   .content-main {
      margin-left : 0!important;
      margin-right : 0!important;
   }
}

img {
   border-style : none;
}

.theme {
   color : #fff!important;
   background-color : #000000!important;
}

.theme-l1 {
   color : #fff!important;
   background-color : #333333!important;
}

.top,.bottom {
   position : fixed;
   width : 100%;
   z-index : 1;
}

.top {
   top : 0;
}

.bottom {
   bottom : 0;
}

.bar {
   width : 100%;
   overflow : hidden;
}

.container, .panel {
   padding : 0.01em 16px;
   min-height: 50px;
   overflow: hidden;
}

.panel {
   margin-top : 16px;
   margin-bottom : 16px;
}

.bar .bar-item {
   padding : 8px 16px;
   float : left;
   width : auto;
   border : none;
   outline : none;
   display : block;
}

.bar .button {
   white-space : normal;
}

.bar-block .bar-item{
   width : 100%;
   display : block;
   padding : 8px 16px;
   text-align : left;
   border : none;
   outline : none;
   white-space : normal;
   float : none;
}

.button {
   -webkit-touch-callout : none;
   -webkit-user-select : none;
   -khtml-user-select : none;
   -moz-user-select : none;
   -ms-user-select : none;
   user-select : none;
   border : none;
   display : inline-block;
   outline : 0;
   padding : 8px 16px;
   vertical-align : middle;
   overflow : hidden;
   text-decoration : none;
   color : inherit;
   background-color : inherit;
   text-align : center;
   cursor : pointer;
   white-space : nowrap;
}

.button : hover {
   color : #000!important;
   background-color : #ccc!important;
}

.button : disabled{
   cursor : not-allowed;
   opacity : 0.3;
}

.teal {
   color : #fff!important;
   background-color : #009688!important;
}

.teal, .hover-teal : hover {
   color : #fff!important;
   background-color : #009688!important;
}

.white, .hover-white : hover {
   color : #000!important;
   background-color : #fff!important;
}

.margin-top {
   margin-top : 16px!important;
}

.margin-bottom {
   margin-bottom : 16px!important;
}

.margin-left {
   margin-left : 16px!important;
}

.margin-right {
   margin-right : 16px!important;
}

.right {
   float : right!important;
}

.display-container {
   position : relative;
}

.animate-opacity {
   animation : opac 0.8s;
} @keyframes opac {
   from {
      opacity : 0;
   } to {
      opacity : 1;
   }
}

.xlarge {
   font-size : 24px!important;
}

.xxlarge{
   font-size : 36px!important;
}

.left-align {
   text-align : left!important;
}

.center {
   text-align : center!important;
}

.padding-65 {
   padding-top : 65px!important;
   padding-bottom : 65px!important;
}

.padding-64 {
   padding-top : 64px!important;
   padding-bottom : 64px!important;
}

.light-grey, .hover-light-grey : hover {
   color : #000!important;
   background-color : #f1f1f1!important;
}

.bottombar {
   border-bottom : 6px solid #ccc!important;
}

.topbar {
   border-top : 6px solid #ccc!important;
}

.padding-16 {
   padding-top : 16px!important;
   padding-bottom : 16px!important;
}

.padding {
   padding : 8px 16px!important;
}
.quarter, .third,
.twothird {
   float : left;
   width : 100%;
}

.quarter {
   width : 24.99999%;
}

.third {
   width : 33.33333%;
}

.twothird {
   width : 66.66666%;
}

.row-padding,
.row-padding > .quarter,
.row-padding > .third,
.row-padding > .twothird {
   padding : 0 8px;
}

.content{
   max-width : 980px;
   margin : auto;
}

.hide{
   display : none!important;
}

.show {
   display : block!important;
}

.container : after, .container : before,
.panel : after, .panel : before,
.row-padding : after, .row-padding : before,
.bar : before, .bar : after {
   content : "";
   display : table;
   clear : both;
}

.circle {
   border-radius : 50%;
}

.content-main {
   max-width : 1020px;
   margin : auto;
   min-height: 50px;
   overflow: hidden;
}

.leftbar {
   border-left : 6px solid #ccc!important;
}

.serif {
   font-family : serif;
}

.karma {
   font-family :"Karma", sans-serif;
}

About

Between art and craft, lies The Chino A Serie.

Discover brand new wave of chinoserie inside us, whether you just want an instagenic background for your dayout or appreciate a new beauty, history and art while you sip your Macadamia Coffee or chop the Feast Roasta Lamb. We present you "turn-back time" experience through walking corridor gallery with theme from contemporer to ancient baroque style. Oh, once more! Check out the fusion tile work in the floor of the cafe.

Entre art et artisanat, se trouve La  Chino A Série.

Découvrez la toute nouvelle vague de chinoserie en nous, que vous souhaitiez simplement un arrière-plan instagène pour votre journée ou apprécier une nouvelle beauté, histoire et art pendant que vous sirotez votre Macadamia Coffee ou que vous coupez l'agneau Roasta Feast. Nous vous présentons l'expérience du temps de retour à travers la galerie de couloir à pied avec le thème du style contemporain à l'ancien style baroque. Oh, encore une fois! Découvrez le travail de carreaux de fusion dans le plancher du café.

      White becomes teal, Birds free from the tale.

Body:
Your media queries seems good, in max-width:600px I add a clear:both for third class:

@media (max-width:600px){
   .hide-small {
      display:none!important;
   } .content-main {
      flex-direction: row;
   }
  .third {
    clear: both
  }
}


问:
How to remove animation of icon and text being bigger on bottom navigation bar?
Hi I have 4 items on bottom navigation bar and I got 'the issue'.
I have solved it with the way from this link -
How to disable BottomNavigationView shift mode?

Now I wonder how to keep size of icon and title same.
My question is that the icon and title get bigger when they are clicked.
My code is the same with the link above.

Thanks for your help so much. If more info is needed I will add it.

答:
I added some code in 'dimens.xml' file, then my icon and text size remains same as before clicked.

before

```<code><resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>
</code>```

after

```<code><resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="design_bottom_navigation_active_text_size">12sp</dimen>
    <dimen name="design_bottom_navigation_active_icon_size">25dp</dimen>
</resources>
</code>```

Body:
I added some code in 'dimens.xml' file, then my icon and text size remains same as before clicked.

before

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>

after

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="design_bottom_navigation_active_text_size">12sp</dimen>
    <dimen name="design_bottom_navigation_active_icon_size">25dp</dimen>
</resources>


问:
scala_spark _dataframe_hivecontext
I have a hive table. It contain some one column as "query" and there are 4 records in it. I will read the hive using :

```<code>val query_hive=sqlContext.sql(s"select * from hive_query limit 1")
</code>```

I need to use this query in another hive for the calculation.

I have tried this method:

```<code>val ouput=sqlContext.sql(s"$query_hive")
</code>```

But I am getting an error. Can anybody suggest the solution for the same?

答:
You can do this. You are not passing query correctly, just look it below:

```<code>scala> val query = "select * from src limit 1"
query: String = select * from src limit 1

scala> sql(s"""$query""").show
+---+-----+
|key|value|
+---+-----+
|  1|    a|
+---+-----+
</code>```

Thanks.

Title: scala_spark _dataframe_hivecontext

Body:
I have a hive table. It contain some one column as "query" and there are 4 records in it. I will read the hive using :

val query_hive=sqlContext.sql(s"select * from hive_query limit 1")

I need to use this query in another hive for the calculation.

I have tried this method:

val ouput=sqlContext.sql(s"$query_hive")

But I am getting an error. Can anybody suggest the solution for the same?

Body:
You can do this. You are not passing query correctly, just look it below:

scala> val query = "select * from src limit 1"
query: String = select * from src limit 1

scala> sql(s"""$query""").show
+---+-----+
|key|value|
+---+-----+
|  1|    a|
+---+-----+

Thanks.


问:
How to Launch specific activity when my Application is in Recent Apps List?
in my android application 3 activities are there.those are A,B&C.
Initial landing screen is A.then navigate to B.
But I want to display Activity C when this app is in recent appslist kind of App Masking.
Any one have idea please share me.
Thanks in Advance!!!</p>

答: Use ActivityLifecycleCallbacks check in on resume check weather your Activity exits in ActivityManager.


问:
Installation C# application without dot net framework
I have created a new application on C# 2010. After creating a Setup file I came to know that for installation purposes user must have a dot net framework. Is there any way I can get rid of installing dot net framework on a user computer. Each time I try to install my application on the user computer it redirects to install the dot net framework. Any suggestion?</p>

答:
When you are using managed languages to writing applications you agreed to use their vm, c# codes compiles to IL which needs dot net framework for executing.

.net framework by default exists on windows 7,8,8.1 and 10 and I don't think that this is a challenge.

but if you insist on it so there is a way by using Mono, just remove features that does not support in mono from your project.

first install mono and cygwin, then copy your exe and mono.dll file to a folder,  be sure that your file name is not long because in some cases bundling faild,now you can start bundling using mkbundle command.

after bundling finished you have a exe file that can run without .net framework

hope this help you


问:
In which file joomla checks the password equality?
I want to know the file in which the passwords, for creating new user are checked for equality.</p>

答:
The Registration process is handled in com_users, the password fields are named password1 and password2 in the form manifest registration.xml, it has password1 set to validate="password"and password2 to validate="equals".
Depending on what exactly you want to find out, you need to reverse engineer from there.


问:
Proper place to put Postgres JDBC Driver (postgresql-42.1.4.jar) on linux
```<code>import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

class Demopsql{

Demopsql()
{
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
            return;
    }
}
</code>```

where should it be paste postgresql-42.1.4.jar or extracted at where?

so that program won't throw class not found exception.

答: If you are using a build tool like maven, add this jar as a dependency. Otherwise you have to make sure that this jar is accessible in classpath. In Eclipse go to project properties -> build path -> Libraries tab , you can find a button to Add External JARs. Add this JAR as external jar.</p>

Body:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

class Demopsql{

Demopsql()
{
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
            return;
    }
}

where should it be paste postgresql-42.1.4.jar or extracted at where?

so that program won't throw class not found exception.


问:
Circular-dependency best practice
I'm currently writing a web scraper which retrieves information from the internet. Simplified it looks like this.

Data access project

Objects to retrieve raw data

Objects to parse the the raw data into objects (!!)

The entities that the parser returns.

Now, I'm creating the actual parser, and I'm going to use it like this:

```<code>using Application.DataAccess;
using Application.DataAccess.Entities;

namespace Application{
 public class TestScraper{
  public static ScrapeIt()
  {
   var source = DataAcces.Retriever.Retrieve("http://example.com");
   DataAccess.Entities.Entity entity = DataAccess.Parser.Parse(source);

   //Do stuf with source here.
  }
 }
}
</code>```

As you can see, the Parser returns a Entity. However this is in the DataAccess namespace, yet, it makes no sense... it´s a circle, and I don´t really know how to fix this. Well I could come up with a few things, like creating another layer between those layers.

But I just want to know, how would YOU solve this. And what is a good (or the best practice) for this.

答: Data Access Layer should not be in the same namespace as your domain objects. Entities should stand alone in an assembly/namespace that does not reference any other namespace, which will allow other logic based classes such as DataAccess and Parsers to reference the Entity on their own in a more clean manner.</p>

Title: Circular-dependency best practice

Body:
I'm currently writing a web scraper which retrieves information from the internet. Simplified it looks like this.

Data access project

Objects to retrieve raw data

Objects to parse the the raw data into objects (!!)

The entities that the parser returns.

Now, I'm creating the actual parser, and I'm going to use it like this:

using Application.DataAccess;
using Application.DataAccess.Entities;

namespace Application{
 public class TestScraper{
  public static ScrapeIt()
  {
   var source = DataAcces.Retriever.Retrieve("http://example.com");
   DataAccess.Entities.Entity entity = DataAccess.Parser.Parse(source);

   //Do stuf with source here.
  }
 }
}

As you can see, the Parser returns a Entity. However this is in the DataAccess namespace, yet, it makes no sense... it´s a circle, and I don´t really know how to fix this. Well I could come up with a few things, like creating another layer between those layers.

But I just want to know, how would YOU solve this. And what is a good (or the best practice) for this.


答:
You can first aggregate by last of opencolumn:

```<code>ohlc_dict = {
   'high': 'max',
   'low': 'min',
   'close': 'last',
   'open':'last',
   'volume':'sum'
}

g = df.groupby(pd.Grouper(freq='1Min',level=0,label='left'))
df2 = g.agg(ohlc_dict)
print (df2)
                         low    close     high     open  volume
datetime
2017-11-17 12:35:00  0.96213  0.96222  0.96223  0.96215      77
</code>```

Then filter out all 0 volumes and aggregate only last value of open:

```<code>g1 = df[df['volume'] > 0].groupby(pd.Grouper(freq='1Min',level=0,label='left'))
df1 = g1['open'].last().reindex(df2.index)
print (df1)
datetime
2017-11-17 12:35:00    0.96213
Freq: T, Name: open, dtype: float64
</code>```

Last combine both DataFrames to one with to_frame and combine_first:

```<code>df3 = df1.to_frame().combine_first(df2)
print (df3)
                       close     high      low     open  volume
datetime
2017-11-17 12:35:00  0.96222  0.96223  0.96213  0.96213    77.0
</code>```

Use custom function with condition (slowier):

```<code>def ohlc_func(x):
    a = x.loc[x['volume'] > 0, 'open'].tail(1)
    a = a.item() if len(a) == 1 else x['open'].tail(1)[0]
    b = x['high'].max()
    c = x['low'].min()
    d = x['close'].tail(1)[0]
    e = x['volume'].sum()
    col = ['open','high','low','close','volume']
    return pd.Series([a,b,c,d,e], index=col)

df = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')).apply(ohlc_func)
print (df)
                        open     high      low    close  volume
datetime
2017-11-17 12:35:00  0.96213  0.96223  0.96213  0.96222    77.0
</code>```

Body:
I need to group a pandas Dataframe according to the following criteria, it is like-ish a ohlc aggregation:

open = last where volume > 0, in case there is no entry with volume > 0 use overall last
high = max
low = min
last = last
volume = max

My current implementation for these kinds of operations (ohlc aggregation) is:

ohlc_dict = {
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
}

df = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')).agg(ohlc_dict)

How can I solve this? Thank you.

Sample:

                     fi  ts     open     high      low    close  volume
datetime
2017-11-17 12:35:00   0   0  0.96214  0.96214  0.96214  0.96214       0
2017-11-17 12:35:00   0   0  0.96214  0.96214  0.96214  0.96214       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96213  0.96220  0.96213  0.96219      19
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96219       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96222       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96223       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96220      29
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96220      29
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96222       0

Desired Output:

                     fi  ts     open     high      low    close  volume
datetime
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96222       29

Additional Information:

There are two data sources which can be identified by their 'Volume' values:

a. Volume = 0 (more frequent, less reliable)
b. Volume > 0 (less frequent, more reliable)

As type 'b.' is more reliable, it is preferrable to use its open value to type 'a' open value.

As to whether last aggregation, it doesn't really matter to be honest, other aggregations (first,max,min) would work, as the open value is the first quoted value in a minute (on this example) and never changes.

The issues of incorrect values arise when there is an interruption on the connection to the server. Type 'a' data cannot deal with this and will give me possibly wrong values, type 'b' data can deal with this just fine and will give me correct values.

Body:
You can first aggregate by last of opencolumn:

ohlc_dict = {
   'high': 'max',
   'low': 'min',
   'close': 'last',
   'open':'last',
   'volume':'sum'
}

g = df.groupby(pd.Grouper(freq='1Min',level=0,label='left'))
df2 = g.agg(ohlc_dict)
print (df2)
                         low    close     high     open  volume
datetime
2017-11-17 12:35:00  0.96213  0.96222  0.96223  0.96215      77

Then filter out all 0 volumes and aggregate only last value of open:

g1 = df[df['volume'] > 0].groupby(pd.Grouper(freq='1Min',level=0,label='left'))
df1 = g1['open'].last().reindex(df2.index)
print (df1)
datetime
2017-11-17 12:35:00    0.96213
Freq: T, Name: open, dtype: float64

Last combine both DataFrames to one with to_frame and combine_first:

df3 = df1.to_frame().combine_first(df2)
print (df3)
                       close     high      low     open  volume
datetime
2017-11-17 12:35:00  0.96222  0.96223  0.96213  0.96213    77.0

Use custom function with condition (slowier):

def ohlc_func(x):
    a = x.loc[x['volume'] > 0, 'open'].tail(1)
    a = a.item() if len(a) == 1 else x['open'].tail(1)[0]
    b = x['high'].max()
    c = x['low'].min()
    d = x['close'].tail(1)[0]
    e = x['volume'].sum()
    col = ['open','high','low','close','volume']
    return pd.Series([a,b,c,d,e], index=col)

df = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')).apply(ohlc_func)
print (df)
                        open     high      low    close  volume
datetime
2017-11-17 12:35:00  0.96213  0.96223  0.96213  0.96222    77.0


问:
What would be a good project to learn node.js
Everyone is talking about NodeJS so I though I'll look into it by creating a usefull project but I cant really think of something usefull to build on NodeJS tha fully demonstrates it's capabilities.

does any of you have a good idea ?

答:
Build a web framework, like everybody else. ;)

But seriously, this can expose you to network programming, file i/o, and HTTP at a level that isn't typically reached when using someone else's framework (hands-on is much better than reading somebody else's code).

With Node it may no longer be "Build a blog," but rather "Build a framework that builds a blog."


问:
How to add an API with oauth2 on the top of Kong
I'm trying to add an API on the top kong with using oauth2 authorization plugin of Kong. The steps
I have followed as per their Kong documentation :

Create an API and add oauth2 plugin

Create consumer

Create an application

I got client_id, client_secret, provision_key etc from the above steps, but I'm wondering that if I need to create oauth2 server at my end or kong itself configured it at their end and we just need to call their endpoints.
I'm building my APIs in laravel.

答:
I think we spoke really briefly on Gitter, and there I already said that it depends on your use case. I'll do a brief rundown of typical use cases, and where you need which kind of additional implementation.

Machine to Machine communication

If you need two systems to talk to each other from the backends, and these systems trust each other, you can use the OAuth2 "Client Credentials Flow". In this case, there is no "end user" identity involved, only the two systems which explicitly trust each other.

For this scenario, Kong is everything you need - you just ask Kong's API Token end point (<address of kong>:8443/your_api/oauth2/token for URI based routing, or fqdn.of.kong:8443/oauth2/token if you're using host based routing) for an access token using your client ID and Secret, and you will get one back.

Example:

```<code>curl --insecure -d 'grant_type=client_credentials&client_id=<...>&client_secret=<..>' https://<address of kong>:8443/your_api/oauth2_token
</code>```

Your backend service will get some extra headers injected, such as X-Consumer-Id and X-Custom-ConsumerId which maps to the consumer you created in Kong.

Confidential Web Application with End User context

In case you need to use your API from a confidential (=classic) web application, and you need to have an end user context with each call, you might want to use the OAuth2 "Authorization Code Grant". In this case, you will also need an Authorization Server which you need to implement yourself.

The Task of the Authorization Server is to establish an end user identity (mind you: This is not specified in OAuth2 how this is done, and is up to you; you can federate to some other IdP, you can ask for username and password,...) and then to decide on which rights (="scopes") the user gets when accessing the API. This is completely up to you, and part of your business logic how to decide this.

The flow goes like this:

You (re-)direct a user to the web page of the authorization server

The AS authenticates the user (by whatever means) and decides on the scopes (by whatever other means)

The AS talks to Kong on two different levels

Via the Kong Admin API, to retrieve the provision_key of the desired API

Via the [/your_api]/oauth2/authorize end point, which it uses to get a redirect URI which includes an authorization code, in the context of the authenticated user and his scope (scope and authenticated_userid); to call this end point, you will need response_type=code, client_id, client_secret, provision_key, authenticated_userid (whatever is suitable) and optionally scope (scopes need to be defined on the API as well if you want to use this)

If successful, the AS redirects back to the web application, using the redirect URI returned by Kong

The web app calls Kong's [/your_api]/oauth2/token end point with its client_id, client_secret and code, using the grant_type=code

Now you will have an access token (and a refresh token) which lets your web application access the API on behalf of the authenticated user.

The Authorization Server has to be implemented by you; this is not super complicated, but you still need to make sure you know how to authenticate a user, and/or how you delegate this to some other IdP.

Public Client (Single Page Application) with End User Context

In case you need access to an API from a Single Page Application (like from an Angular app or similar), you should look at the OAuth2 "Implicit Flow", which is a simpler flow than the authorization code grant, but which has other drawbacks, like not being able to use refresh tokens.

This flow works in the following way:

Just like for the Authorization Code grant, you redirect the user to the Authorization Server

The AS establishes identity and decides on scope (once again, this is up to you)

The AS calls the authorize end point, just like with the Authorization Code grant, but this time with response_type=token

Kong, if successful, will return a redirect URI which already contains a token

The AS redirects back to the SPA, using the redirect URI from Kong, which has the access token in the "fragment" of the URI (e.g. https://your.app.com/#access_token=<...>&token_type=bearer&...)

Your SPA will now be able to use the access token to access the API, just like with the Authorization Code grant, on behalf of the authenticated user.

The drawback with this approach is that you can't (that) easily refresh the token, and that it's somewhat less secure than the Authorization Code grant. But dealing with SPAs, there are not many other secure ways of delegating access to it.

Mobile Applications

The last scenario I would like to touch here is Mobile Applications, like Android or iOS apps. For these, the last OAuth2 flow, the "Resource Owner Password Grant" can be used. In short, with this grant you exchange the actual user credentials (username and password) against an access token and a refresh token, so that you don't have to store username and password on the mobile device more than temporarily.

This flow also needs an Authorization Server to be able to use with Kong, albeit a less complicated one this time, even though you must implement an additional token end point (in addition to the one Kong has), which is not ideally described in the Kong documentation.

It'd go like this:

The mobile app uses its client_id (NOT the secret, the secret should not be deployed with the application), the username and password to call the Authorization Server's token end point

The Authorization Server checks username and password (by whatever means, you know the story) and decides on the scope (...)

The AS talks to Kong over admin API again, getting the client_secret for the provided client_id and the provision_key for the desired API

The AS issues a call to Kong's token end point [/your_api]/oauth2/token, like this:

curl --insecure -d 'grant_type=password&provision_key=<...>&client_id=<...>&client_secret=<...>&authenticated_userid=<...>&scope=' https://:8443/your_api/oauth2/token

Note that this call does not contain username and password; those don't belong here, you must check username and password against your own source of identity, Kong will not help you with that.

This call should return both an access token and a refresh token which you then store (as safely as possible) on your device. These replace the username and password, which must not be stored on the device. The access token can as with the other end user context flows (Authorization Code Grant, Implicit Grant) be used to access the API on behalf of the authenticated user.

Using Kong with OAuth2 is tricky and involved, but Kong can really help getting this right and separate your concerns.

Body:
I think we spoke really briefly on Gitter, and there I already said that it depends on your use case. I'll do a brief rundown of typical use cases, and where you need which kind of additional implementation.

Machine to Machine communication

If you need two systems to talk to each other from the backends, and these systems trust each other, you can use the OAuth2 "Client Credentials Flow". In this case, there is no "end user" identity involved, only the two systems which explicitly trust each other.

For this scenario, Kong is everything you need - you just ask Kong's API Token end point (<address of kong>:8443/your_api/oauth2/token for URI based routing, or fqdn.of.kong:8443/oauth2/token if you're using host based routing) for an access token using your client ID and Secret, and you will get one back.

Example:

curl --insecure -d 'grant_type=client_credentials&client_id=<...>&client_secret=<..>' https://<address of kong>:8443/your_api/oauth2_token

Your backend service will get some extra headers injected, such as X-Consumer-Id and X-Custom-ConsumerId which maps to the consumer you created in Kong.

Confidential Web Application with End User context

In case you need to use your API from a confidential (=classic) web application, and you need to have an end user context with each call, you might want to use the OAuth2 "Authorization Code Grant". In this case, you will also need an Authorization Server which you need to implement yourself.

The Task of the Authorization Server is to establish an end user identity (mind you: This is not specified in OAuth2 how this is done, and is up to you; you can federate to some other IdP, you can ask for username and password,...) and then to decide on which rights (="scopes") the user gets when accessing the API. This is completely up to you, and part of your business logic how to decide this.

The flow goes like this:

You (re-)direct a user to the web page of the authorization server

The AS authenticates the user (by whatever means) and decides on the scopes (by whatever other means)

The AS talks to Kong on two different levels

Via the Kong Admin API, to retrieve the provision_key of the desired API

Via the [/your_api]/oauth2/authorize end point, which it uses to get a redirect URI which includes an authorization code, in the context of the authenticated user and his scope (scope and authenticated_userid); to call this end point, you will need response_type=code, client_id, client_secret, provision_key, authenticated_userid (whatever is suitable) and optionally scope (scopes need to be defined on the API as well if you want to use this)

If successful, the AS redirects back to the web application, using the redirect URI returned by Kong

The web app calls Kong's [/your_api]/oauth2/token end point with its client_id, client_secret and code, using the grant_type=code

Now you will have an access token (and a refresh token) which lets your web application access the API on behalf of the authenticated user.

The Authorization Server has to be implemented by you; this is not super complicated, but you still need to make sure you know how to authenticate a user, and/or how you delegate this to some other IdP.

Public Client (Single Page Application) with End User Context

In case you need access to an API from a Single Page Application (like from an Angular app or similar), you should look at the OAuth2 "Implicit Flow", which is a simpler flow than the authorization code grant, but which has other drawbacks, like not being able to use refresh tokens.

This flow works in the following way:

Just like for the Authorization Code grant, you redirect the user to the Authorization Server

The AS establishes identity and decides on scope (once again, this is up to you)

The AS calls the authorize end point, just like with the Authorization Code grant, but this time with response_type=token

Kong, if successful, will return a redirect URI which already contains a token

The AS redirects back to the SPA, using the redirect URI from Kong, which has the access token in the "fragment" of the URI (e.g. https://your.app.com/#access_token=<...>&token_type=bearer&...)

Your SPA will now be able to use the access token to access the API, just like with the Authorization Code grant, on behalf of the authenticated user.

The drawback with this approach is that you can't (that) easily refresh the token, and that it's somewhat less secure than the Authorization Code grant. But dealing with SPAs, there are not many other secure ways of delegating access to it.

Mobile Applications

The last scenario I would like to touch here is Mobile Applications, like Android or iOS apps. For these, the last OAuth2 flow, the "Resource Owner Password Grant" can be used. In short, with this grant you exchange the actual user credentials (username and password) against an access token and a refresh token, so that you don't have to store username and password on the mobile device more than temporarily.

This flow also needs an Authorization Server to be able to use with Kong, albeit a less complicated one this time, even though you must implement an additional token end point (in addition to the one Kong has), which is not ideally described in the Kong documentation.

It'd go like this:

The mobile app uses its client_id (NOT the secret, the secret should not be deployed with the application), the username and password to call the Authorization Server's token end point

The Authorization Server checks username and password (by whatever means, you know the story) and decides on the scope (...)

The AS talks to Kong over admin API again, getting the client_secret for the provided client_id and the provision_key for the desired API

The AS issues a call to Kong's token end point [/your_api]/oauth2/token, like this:

curl --insecure -d 'grant_type=password&provision_key=<...>&client_id=<...>&client_secret=<...>&authenticated_userid=<...>&scope=' https://:8443/your_api/oauth2/token

Note that this call does not contain username and password; those don't belong here, you must check username and password against your own source of identity, Kong will not help you with that.

This call should return both an access token and a refresh token which you then store (as safely as possible) on your device. These replace the username and password, which must not be stored on the device. The access token can as with the other end user context flows (Authorization Code Grant, Implicit Grant) be used to access the API on behalf of the authenticated user.

Using Kong with OAuth2 is tricky and involved, but Kong can really help getting this right and separate your concerns.


问:
Why are my in-war CSS-files not evaluated for webapp deployed on JBoss?
I have migrated one of my web applications from Weblogic 10.3.6 to JBoss 7.1. For some reason, none of my css-files packaged inside the war-file is working anymore. Take a look at the consol message:

This is the only message I get, and it is only a warning, not an error. Even with that warning, I would expect the CSS to work. I can also find all of the css files in the resources tab, in the Chrome debugger.

The exact same thing happens in other browsers as well.

CSS files downloaded through CDNs are evaluated however. Any ideas whatsoever how to debug this?

EDIT:

All CSS files are available in dev tools. Both in resources tab, and network tab. The full content of each file is available. They seem to all be there, but not be evaluated.

EDIT 2:

After further reading in the network tab, I can see a difference between my old deployment (weblogic) and the new (JBoss). Even though I specify type="text/css", the css files are retrieved with type="text/html" in the JBoss deployment. This question here offers a myriad of possible solutions, none of which I have been able to implement yet.

This answer states that:

"Then something else about your server is making that stylesheet come
  with the wrong content type"

Any ideas at all on what that "something else" can be?

答:
I found it.

Because of special scandinavian characters, I had implemented a CharsetFilter class, which was intended to make sure that character encoding always was the same. However, I also set content type. It did not break the application while deployed on weblogic, but JBoss handled it differently. I simply removed the top line of these two:

```<code>    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
</code>```

And now it works.

Body:
I found it.

Because of special scandinavian characters, I had implemented a CharsetFilter class, which was intended to make sure that character encoding always was the same. However, I also set content type. It did not break the application while deployed on weblogic, but JBoss handled it differently. I simply removed the top line of these two:

    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

And now it works.