问:
ExecuteNonQuery() ERROR -> The conversion of the nvarchar value '3955811801' overflowed an int column.
My code is as shown below :

```<code>using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
    using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add(new SqlParameter("@Co_ID", int.Parse(Session["Co_ID"].ToString())));

        _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.NVarChar));
        _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

        _conn.Open();
        _cmd.ExecuteNonQuery();

        Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value.ToString());
        lblSumTotalPayShow.Text = result.ToString();

            _conn.Close();
        }
    }
</code>```

my SP is like this :

```<code>create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
As
    -----------------
    Declare @Sum nvarchar(50)
    -----------------
BEGIN
    Select @Sum = convert(nvarchar(50), SUM(TotalPay))
    From Noskheh
    Where (Co_ID = @Co_ID)

    Return @Sum
END
</code>```

and the error is in line (_cmd.ExecuteNonQuery();):

Error:

Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
  the nvarchar value '3955811801' overflowed an int column. The
  'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
  NULL, which is not allowed. A status of 0 will be returned instead.

Would you please help me to figure out this problem?

答:
Change @Co_ID to bigint. 3955811801 is higher then 2^31-1

The SUM is greater than 2^31-1. The RETURN tries to convert it to int and fails.
Use an OUTPUT parameters or just return a recordset.

Like this

```<code>create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
 @Co_ID int,
 @Sum nvarchar(50) OUTPUT --or bigint?
As

BEGIN
 Select
  @Sum = convert(nvarchar(50), SUM(TotalPay))
 From Noskheh
  Where
  (Co_ID = @Co_ID)
END
</code>```

or

```<code>create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
 @Co_ID int
As

BEGIN
 Select
  SUM(TotalPay) AS SumTotalPay
 From Noskheh
  Where
  (Co_ID = @Co_ID)
END
</code>```

Body:
My code is as shown below :

using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
    using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add(new SqlParameter("@Co_ID", int.Parse(Session["Co_ID"].ToString())));

        _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.NVarChar));
        _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

        _conn.Open();
        _cmd.ExecuteNonQuery();

        Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value.ToString());
        lblSumTotalPayShow.Text = result.ToString();

            _conn.Close();
        }
    }

my SP is like this :

create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
As
    -----------------
    Declare @Sum nvarchar(50)
    -----------------
BEGIN
    Select @Sum = convert(nvarchar(50), SUM(TotalPay))
    From Noskheh
    Where (Co_ID = @Co_ID)

    Return @Sum
END

and the error is in line (_cmd.ExecuteNonQuery();):

Error:

Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
  the nvarchar value '3955811801' overflowed an int column. The
  'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
  NULL, which is not allowed. A status of 0 will be returned instead.

Would you please help me to figure out this problem?

Body:
Change @Co_ID to bigint. 3955811801 is higher then 2^31-1

The SUM is greater than 2^31-1. The RETURN tries to convert it to int and fails.
Use an OUTPUT parameters or just return a recordset.

Like this

create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
 @Co_ID int,
 @Sum nvarchar(50) OUTPUT --or bigint?
As

BEGIN
 Select
  @Sum = convert(nvarchar(50), SUM(TotalPay))
 From Noskheh
  Where
  (Co_ID = @Co_ID)
END

or

create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
 @Co_ID int
As

BEGIN
 Select
  SUM(TotalPay) AS SumTotalPay
 From Noskheh
  Where
  (Co_ID = @Co_ID)
END


来源: stackexchange

问:
Fuzzy string matching for finding Synsets in German WordNet (GermaNet)
For my bachelor thesis project, I am developing the Natural Language Understanding Unit for a Chatbot. Right now I am facing the following problem:

I have a word, let's say 'Auto', which is the German equivalent of car. Now the user might give 'autto' as an input, because he simply made a little typo (adding an extra 't') and usually in a chat interface, users don't follow upper-/lower-case rules, but type everything in lower-case.

For my NLU-algorithm, I need to find for every word the correct Synset in GermaNet (which is roughly equivalent to the WordNet for English). A Synset is a node in the wordnet, which abstracts all synonyms of a word sense into one node. Like, for example, in German 'Auto' (car) and 'Automobil' have the same meaning and are therefore representations of the same Synset.

The question now is, how can I find the correct Synset, if I don't have an orthographically correct version of the word? I mean, searching the whole wordnet is computationally to complex for every word.

I think N-Grams might offer a solution to the problem, but I am not aware of any algorithm.

As to what I use for implementation: Python3 with NLTK, Stanford CoreNLP, and pygermanet.

答: If the input word is not in GermaNet, you could apply spelling correction first, eg with PyEnchant, and look up the corrected term.</p>

ContentLicense: CC BY-SA 3.0


问:
How to rename files in subfolder into a specific format
I have files named as RabcdYYMMKKACCOUNT.TXT in the Subfolders of a folder where YYMM is year, month this will change. KK is another identifier, I want all the files to be renamed to MSFKKDNB.ABC, the KK is the identifier in the input file.

Below is the one i tried and the result of it:

```<code>FOR /R %%f IN (*account.txt) DO REN "%%f" *dnb.abc
</code>```

R00531706AUAccount.txt is renamed to R00531706AUAccount.txtdnb.abc

but the output should be MSFAUDNB.abc

答:
I would probably do it the following way, provided that the files to rename are located in immediate sub-directories (YYMM) of the given root directory and nowhere else:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "_ROOT=." & rem // (specify path to the root directory)

for /D %%D in ("%_ROOT%\????") do (
    for %%F in ("%_ROOT%\%%~nxD\R??????????Account.txt") do (
        set "FDIR=%%~nxD" & set "FILE=%%~nxF"
        setlocal EnableDelayedExpansion
        ECHO ren "!_ROOT!\!FDIR!\!FILE!" "MSF!FILE:~9,2!DNB.abc"
        endlocal
    )
)

endlocal
exit /B
```

<p>If you want to check whether both the sub-directory name and the year/month portion of the file names are purely numeric, you could use the following script:</p>

<pre class="lang-cmd prettyprint-override"><code>@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "_ROOT=." & rem // (specify path to the root directory)

for /F "delims= eol=|" %%D in ('
    dir /B /A:D "%_ROOT%\????" ^| ^
        findstr "^[0123456789][0123456789][0123456789][0123456789]$"
') do (
    for /F "delims= eol=|" %%F in ('
        dir /B /A:-D "%_ROOT%\%%~nxD\R??????????Account.txt" ^| ^
            findstr "^R....[0123456789][0123456789][0123456789][0123456789].."
    ') do (
        set "FDIR=%%~nxD" & set "FILE=%%~nxF"
        setlocal EnableDelayedExpansion
        ECHO ren "!_ROOT!\!FDIR!\!FILE!" "MSF!FILE:~9,2!DNB.abc"
        endlocal
    )
)

endlocal
exit /B
</code>```

If you want to check whether the sub-directory name matches the year/month (YYMM) portion of the file names, replace the pattern R??????????Account.txt by R????%%~nxD??Account.txt (for both scripts).

After having verified the correct output of either script, remove the upper-case ECHO commands to actually rename any files!

Basically, both scripts use sub-string expansion to extract the identifier part (KK) from the file names. Since there are variables set and read in the same block of code, delayed expansion is required for that. The second approach does not list the sub-directories and files by standard for loops, it uses the dir command, findstr to filter their names and a for /F loop to capture the resulting output for both sub-directories and files.

Body:
I have files named as RabcdYYMMKKACCOUNT.TXT in the Subfolders of a folder where YYMM is year, month this will change. KK is another identifier, I want all the files to be renamed to MSFKKDNB.ABC, the KK is the identifier in the input file.

Below is the one i tried and the result of it:

FOR /R %%f IN (*account.txt) DO REN "%%f" *dnb.abc

R00531706AUAccount.txt is renamed to R00531706AUAccount.txtdnb.abc

but the output should be MSFAUDNB.abc

Body:
I would probably do it the following way, provided that the files to rename are located in immediate sub-directories (YYMM) of the given root directory and nowhere else:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "_ROOT=." & rem // (specify path to the root directory)

for /D %%D in ("%_ROOT%\????") do (
    for %%F in ("%_ROOT%\%%~nxD\R??????????Account.txt") do (
        set "FDIR=%%~nxD" & set "FILE=%%~nxF"
        setlocal EnableDelayedExpansion
        ECHO ren "!_ROOT!\!FDIR!\!FILE!" "MSF!FILE:~9,2!DNB.abc"
        endlocal
    )
)

endlocal
exit /B

If you want to check whether both the sub-directory name and the year/month portion of the file names are purely numeric, you could use the following script:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "_ROOT=." & rem // (specify path to the root directory)

for /F "delims= eol=|" %%D in ('
    dir /B /A:D "%_ROOT%\????" ^| ^
        findstr "^[0123456789][0123456789][0123456789][0123456789]$"
') do (
    for /F "delims= eol=|" %%F in ('
        dir /B /A:-D "%_ROOT%\%%~nxD\R??????????Account.txt" ^| ^
            findstr "^R....[0123456789][0123456789][0123456789][0123456789].."
    ') do (
        set "FDIR=%%~nxD" & set "FILE=%%~nxF"
        setlocal EnableDelayedExpansion
        ECHO ren "!_ROOT!\!FDIR!\!FILE!" "MSF!FILE:~9,2!DNB.abc"
        endlocal
    )
)

endlocal
exit /B

If you want to check whether the sub-directory name matches the year/month (YYMM) portion of the file names, replace the pattern R??????????Account.txt by R????%%~nxD??Account.txt (for both scripts).

After having verified the correct output of either script, remove the upper-case ECHO commands to actually rename any files!

Basically, both scripts use sub-string expansion to extract the identifier part (KK) from the file names. Since there are variables set and read in the same block of code, delayed expansion is required for that. The second approach does not list the sub-directories and files by standard for loops, it uses the dir command, findstr to filter their names and a for /F loop to capture the resulting output for both sub-directories and files.


问:
Django's ModelForm with an HiddenInput returns invalid
I'm making a small project to learn Django, and i'm having some problems trying to use hidden fields inside a ModelForm.

Theres the class:

```<code>class Post(models.Model):
    title       = models.CharField(max_length = 140)
    message     = models.CharField(max_length = 10000)
    pub_date    = models.DateTimeField()
</code>```

And my ModelForm:

```<code>class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'message', 'pub_date',)
        widgets = {
            'message' : Textarea(attrs={'cols':80, 'rows':20}),
            'pub_date' : HiddenInput(),
        }
</code>```

This is the view:

```<code>def edit(request, post_id):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            print 'VALID'
            dados = form.cleaned_data
            post = Post.objects.get(pk=post_id)
            post.title = dados['title']
            post.message = dados['message']
            post.save()
            return HttpResponseRedirect(reverse('blog.views.detail', args=(post.id,)))
        else:
            print 'INVALID'
    form = PostForm(instance=Post.objects.get(pk=post_id))
    return render_to_response('blog/add_post.html', {'form' : form,}, context_instance = RequestContext(request))
</code>```

This is the HTML generated for the form:

```<code><div style='display:none'>
<input type='hidden' name='csrfmiddlewaretoken'
value='3b7c0735bf464fb4fd7dcd3011050e1c' />

</div>
<tr>
    <th><label for="id_title">title:</label></th>
    <td><input id="id_title" type="text" name="title" value="asd1111111111" maxlength="140" /></td>
</tr>
<tr>
    <th><label for="id_message">message:</label></th>
    <td><textarea id="id_message" rows="20" cols="80" name="message">asd11111111111</textarea>
    <input type="hidden" name="pub_date" value="2010-12-19 17:08:22.498000" id="id_pub_date" /></td>
</tr>
</code>```

I use the same template to both create and edit posts. When i'm creating, pub_date is set in another view, and when i'm editing, I can't change pub_date on my template (thus the hidden field).
On this example, form.is_valid() always return False.
If I remove the 'pub_date' : HiddenInput(), line from my form, it returns True.
What am I doing wrong?

答:
The problem is in the conversion from string to datetime object.

The datetime field, if no input_formats argument is specified, takes these formats for string->datetime conversion.

(from the docs: http://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield)

```<code>'%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
'%Y-%m-%d',              # '2006-10-25'
'%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
'%m/%d/%Y',              # '10/25/2006'
'%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
'%m/%d/%y %H:%M',        # '10/25/06 14:30'
'%m/%d/%y',              # '10/25/06'
</code>```

So your value of 2010-12-19 17:08:22.498000 won't work.

The default widget for DateTimeField is DateTimeInput widget which formats the datetime to a string correctly, but HiddenInput just takes the datetime object w/ no formatting as you've shown.

If you want to use HiddenInput you need to strftime the datetime object to be in the correct format.

An alternative option if you just want to hide it is to not set the widget as HiddenInput but simply keep the DateTimeInput widget as is and hide that element with the attrs argument.

```<code>class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'message', 'pub_date',)
        widgets = {
            'message' : Textarea(attrs={'cols':80, 'rows':20}),
            'pub_date' : DateTimeInput(attrs={'style': 'display:none;'}),
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm making a small project to learn Django, and i'm having some problems trying to use hidden fields inside a ModelForm.

Theres the class:

class Post(models.Model):
    title       = models.CharField(max_length = 140)
    message     = models.CharField(max_length = 10000)
    pub_date    = models.DateTimeField()

And my ModelForm:

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'message', 'pub_date',)
        widgets = {
            'message' : Textarea(attrs={'cols':80, 'rows':20}),
            'pub_date' : HiddenInput(),
        }

This is the view:

def edit(request, post_id):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            print 'VALID'
            dados = form.cleaned_data
            post = Post.objects.get(pk=post_id)
            post.title = dados['title']
            post.message = dados['message']
            post.save()
            return HttpResponseRedirect(reverse('blog.views.detail', args=(post.id,)))
        else:
            print 'INVALID'
    form = PostForm(instance=Post.objects.get(pk=post_id))
    return render_to_response('blog/add_post.html', {'form' : form,}, context_instance = RequestContext(request))

This is the HTML generated for the form:

<input type='hidden' name='csrfmiddlewaretoken'
value='3b7c0735bf464fb4fd7dcd3011050e1c' />

    title:
    <input id="id_title" type="text" name="title" value="asd1111111111" maxlength="140" />

    message:
    <textarea id="id_message" rows="20" cols="80" name="message">asd11111111111</textarea>
    <input type="hidden" name="pub_date" value="2010-12-19 17:08:22.498000" id="id_pub_date" />

I use the same template to both create and edit posts. When i'm creating, pub_date is set in another view, and when i'm editing, I can't change pub_date on my template (thus the hidden field).
On this example, form.is_valid() always return False.
If I remove the 'pub_date' : HiddenInput(), line from my form, it returns True.
What am I doing wrong?

Body:
The problem is in the conversion from string to datetime object.

The datetime field, if no input_formats argument is specified, takes these formats for string->datetime conversion.

(from the docs: http://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield)

'%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
'%Y-%m-%d',              # '2006-10-25'
'%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
'%m/%d/%Y',              # '10/25/2006'
'%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
'%m/%d/%y %H:%M',        # '10/25/06 14:30'
'%m/%d/%y',              # '10/25/06'

So your value of 2010-12-19 17:08:22.498000 won't work.

The default widget for DateTimeField is DateTimeInput widget which formats the datetime to a string correctly, but HiddenInput just takes the datetime object w/ no formatting as you've shown.

If you want to use HiddenInput you need to strftime the datetime object to be in the correct format.

An alternative option if you just want to hide it is to not set the widget as HiddenInput but simply keep the DateTimeInput widget as is and hide that element with the attrs argument.

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'message', 'pub_date',)
        widgets = {
            'message' : Textarea(attrs={'cols':80, 'rows':20}),
            'pub_date' : DateTimeInput(attrs={'style': 'display:none;'}),
        }


问:
How to run certain Selenium commands based on the URL
I am using the Java Language Binding with ChromeDriver as my browser.

I am creating a Selenium script that relies on very similar URL's. However, the elements on the pages are different depending on the URLs. I would like to run one set of commands if the URL is 'www.genericwebsiteA.com'. If the URL is 'www.genericwebsiteB.com' I would like a different set of instructions to run.

I have managed to get both scripts working individually as their own Selenium scripts does anyone have any possible solutions to this. I can't seem to find out how to implement an if statement to see which set of instructions my webdriver should follow.

答:
This is possible using driver.getCurrentUrl():

```<code>String currentURL = driver.getCurrentUrl();
if (currentURL.contains("www.genericwebsiteA.com")) {
    // run tests for A
} else if (currentURL.contains("www.genericwebsiteB.com")) {
    // run tests for B
}
</code>```

Body:
This is possible using driver.getCurrentUrl():

String currentURL = driver.getCurrentUrl();
if (currentURL.contains("www.genericwebsiteA.com")) {
    // run tests for A
} else if (currentURL.contains("www.genericwebsiteB.com")) {
    // run tests for B
}


问:
How to resolve moodle fresh installation issue mysql_full_unicode_support#File_format and mysql_full_unicode_support#Large_prefix
I am very new to Moodle. When i am trying to install this i got this issue(Please ref screenshot).

Can any one help me regarding this?

Thank you in advance.
Omkar

答:
Please install (or access) phpmyadmin and execute SQL</p>

```<code>set Global innodb_file_format = Barracuda
set Global innodb_file_per_table = 1
set Global innodb_large_prefix = "ON"
</code>```

Body:
Please install (or access) phpmyadmin and execute SQL

set Global innodb_file_format = Barracuda
set Global innodb_file_per_table = 1
set Global innodb_large_prefix = "ON"


问:
Resolution of implicit within class body
At a high-level, I'm curious to know how implicits defined inside a class body are resolved? I assumed they would be considered part of the current scope (as per the awesome answer here), but I am wrong.

For a specific example, why doesn't the following work:

```<code>trait Convert[T, U] {
  final def value(record: T)(implicit f: T => U): U = f(record)
}

case class ConvertMap(key: String)
  extends Convert[Map[String, String], Boolean] {
  implicit def a2b(m: Map[String, String]): Boolean = m.contains(key)
}
</code>```

I can instantiate the class ConvertMap, but when I call the value method I get an error stating that the view from Map[String, String] => Boolean can't be found.

```<code>scala> val c = ConvertMap("key")
c: ConvertMap = ConvertMap(key)

scala> c.value(Map("key" -> "value"))
<console>:13: error: No implicit view available from Map[String,String] => Boolean.
</code>```

答:
It needs to be resolvable at the call site (where c.value is called).
At that time, the only thing you have in scope c. I am not sure why you would think it makes sense for something defined inside a class to be considered in scope at that point.

BTW, your example doesn't really seem like a good use for implicits to begin with. Why not just make f a member method in the trait?

Body:
At a high-level, I'm curious to know how implicits defined inside a class body are resolved? I assumed they would be considered part of the current scope (as per the awesome answer here), but I am wrong.

For a specific example, why doesn't the following work:

trait Convert[T, U] {
  final def value(record: T)(implicit f: T => U): U = f(record)
}

case class ConvertMap(key: String)
  extends Convert[Map[String, String], Boolean] {
  implicit def a2b(m: Map[String, String]): Boolean = m.contains(key)
}

I can instantiate the class ConvertMap, but when I call the value method I get an error stating that the view from Map[String, String] => Boolean can't be found.

scala> val c = ConvertMap("key")
c: ConvertMap = ConvertMap(key)

scala> c.value(Map("key" -> "value"))
<console>:13: error: No implicit view available from Map[String,String] => Boolean.


问:
Not able to dump data.Json serializable issue
```<code>import json

newdic={"name":"John","age":30,"cars": [{ "name":"Ford", "models":["Fiesta", "Focus", "Mustang" ] },{ "name":"BMW", "models":[ "320", "X3", "X5"] },{ "name":"Fiat", "models":[ "500", "Panda" ] }]}

 with open('newjson','w') as pointer:
 json.dumps(pointer,newdic)
</code>```

I am new to json  and getting error while doing json dump.

```<code>json.dump(pointer,newdic)   File "/usr/lib/python3.5/json/__init__.py", line 178, in dump
for chunk in iterable:   File "/usr/lib/python3.5/json/encoder.py", line 436, in _iterencode
o = _default(o)   File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable") TypeError: <_io.TextIOWrapper name='newjson' mode='w' encoding='UTF-8'> is not JSON serializable
</code>```

can you please tell me which  all object do json support?

答:
There are two problems with your code:

You need to call json.dump, not json.dumps.

You got the order of arguments wrong.  It's json.dump(obj, fp), not json.dump(fp, obj)

Body:
import json

newdic={"name":"John","age":30,"cars": [{ "name":"Ford", "models":["Fiesta", "Focus", "Mustang" ] },{ "name":"BMW", "models":[ "320", "X3", "X5"] },{ "name":"Fiat", "models":[ "500", "Panda" ] }]}

 with open('newjson','w') as pointer:
 json.dumps(pointer,newdic)

I am new to json  and getting error while doing json dump.

json.dump(pointer,newdic)   File "/usr/lib/python3.5/json/__init__.py", line 178, in dump
for chunk in iterable:   File "/usr/lib/python3.5/json/encoder.py", line 436, in _iterencode
o = _default(o)   File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable") TypeError: <_io.TextIOWrapper name='newjson' mode='w' encoding='UTF-8'> is not JSON serializable

can you please tell me which  all object do json support?


问:
How can I allow a polymer component to contain dynamic elements?
In polymer, let's say I have a container element <x-container>, and two child elements , . In an  element, I want to be able to specify that it contains either  or  (it will never have both).

For example, it could look like:

1. <x-container></x-container>

or,

2. <x-container></x-container>.

Since <x-container> has a lot of code, I don't want to duplicate it, but want to be able to use an <x-container> like this:

<x-container type = 'a-child'></x-container> which would then have the same behavior as the first item mentioned. How could I achieve this functionality?

答:
Just instanciate it when you have the information which one its going to be!

```<code>//in your x-container component
observers: ['_typeChanged(type)'],
_typeChanged: function(type) {
    var child = this.create(type);
    Polymer.dom(this.root).appendChild(child);
}
</code>```

Or you use a slot then you could do smth like this

parent component

```<code><x-container>
   <template is="dom-if" if="[[_isA()]]"><a-child></a-child></template>
   <template is="dom-if" if="[[_isB()]]"><b-child></b-child></template>
</x-container>
</code>```

and in your x-container´s template just simply put a slot the child will be rendered within the slot

```<code><slot></slot>
</code>```

Body:
Just instanciate it when you have the information which one its going to be!

//in your x-container component
observers: ['_typeChanged(type)'],
_typeChanged: function(type) {
    var child = this.create(type);
    Polymer.dom(this.root).appendChild(child);
}

Or you use a slot then you could do smth like this

parent component

<x-container>
   <template is="dom-if" if="[[_isA()]]"><a-child></a-child></template>
   <template is="dom-if" if="[[_isB()]]"><b-child></b-child></template>
</x-container>

and in your x-container´s template just simply put a slot the child will be rendered within the slot

<slot></slot>


问:
Redirect Subdomain URL to another SubDomain with a folder in IIS
i want redirect a subdomain to another subdomain, but additionally i want it to redirect to a folder.

I tried this:

```<code><rewrite>
    <rules>
        <rule name="report" stopProcessing="true">
          <conditions logicalGrouping="MatchAll">
            <add input="{HTTP_HOST}" pattern="old.domain.com" negate="false" />
          </conditions>
          <action type="Redirect" url="http://new.domain.com/admin-dashboard/" appendQueryString="true" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>
</code>```

With my code i only redirect to the new subdomain. But my folder is ignored.
What i'm doing wrong?

Thanks for reading

答:
Your rule is absolutely correct.

Problem is that all browsers will cache 301 redirects, because this redirect is permanent. To get around this, you'll just need to clear your browser cache.

If you put a permanent(301) redirect, that redirect will be cached in the browser for any visitors. You can’t clear the browser cache for your users, so if you need to change or undo a 301 redirect, the old redirect is still going to work until their cache expires.

P.S. Do not put a 301 (permanent) redirect in place unless it is truly permanent! You can use 302 redirect for that

Body:
i want redirect a subdomain to another subdomain, but additionally i want it to redirect to a folder.

I tried this:

<rewrite>
    <rules>
        <rule name="report" stopProcessing="true">
          <conditions logicalGrouping="MatchAll">
            <add input="{HTTP_HOST}" pattern="old.domain.com" negate="false" />
          </conditions>
          <action type="Redirect" url="http://new.domain.com/admin-dashboard/" appendQueryString="true" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>

With my code i only redirect to the new subdomain. But my folder is ignored.
What i'm doing wrong?

Thanks for reading


问:
React/Redux dispatch action from root component?
I'm trying to use firebase with React-Native / Redux I need to dispatch an action every time a user signs in or signs out. How can I dispatch an action from the root component?</p>

```<code>class App extends Component {
    componentWillMount() {
        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
            // Dispatch Action here
            } else {
            // Disptach Action here
            }
        });
    }

    render() {
        const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

        return (
            <Provider store={store}>
                <Router />
            </Provider>
        );
    }
}

export default App;
</code>```

答:
I found a solution for this problem. Shouldn't be the best way, but it works.

Make your request for authentication on the Root Component (App.js) setting loggedIn to true or false. (Im using firebase authentication on the example below)

With that done, you pass the state as a prop to a Component (InitialSetUp.js) and there you can set the state using Redux.

On the InitialSetUp, you act like the root, rendering the app itself.

Following you can find the example.

App.js

```<code>...

const store = createStore(reducers,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__());

export default class App extends Component {
state = { loggedIn: null};

componentWillMount() {
firebase.initializeApp({
...YOUR SETUP
});

firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ loggedIn: true});
} else {
this.setState({ loggedIn: false});
}
});
}

renderInitialView() {
return  <InitialSetUp loggedIn={this.state.loggedIn}/>
}

render() {
return (
<Provider store={store}>
<View style={styles.container}>
{this.renderInitialView()}
</View>
</Provider>
);
}
}
</code>```

InitialSetup.js

```<code>...

class initialSetUp extends Component {

renderInitialView() {
this.props.setLogged(this.props.loggedIn);
return  <Navigation />
}

render() {
return (
<View style={styles.container}>
{this.renderInitialView()}
</View>
);
}
}

export default connect(null, actions)(initialSetUp);
</code>```

Good Luck o/

Body:
I'm trying to use firebase with React-Native / Redux I need to dispatch an action every time a user signs in or signs out. How can I dispatch an action from the root component?

class App extends Component {
    componentWillMount() {
        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
            // Dispatch Action here
            } else {
            // Disptach Action here
            }
        });
    }

    render() {
        const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

        return (
            <Provider store={store}>
                <Router />
            </Provider>
        );
    }
}

export default App;

Body:
I found a solution for this problem. Shouldn't be the best way, but it works.

Make your request for authentication on the Root Component (App.js) setting loggedIn to true or false. (Im using firebase authentication on the example below)

With that done, you pass the state as a prop to a Component (InitialSetUp.js) and there you can set the state using Redux.

On the InitialSetUp, you act like the root, rendering the app itself.

Following you can find the example.

App.js

...

const store = createStore(reducers,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__());

export default class App extends Component {
state = { loggedIn: null};

componentWillMount() {
firebase.initializeApp({
...YOUR SETUP
});

firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ loggedIn: true});
} else {
this.setState({ loggedIn: false});
}
});
}

renderInitialView() {
return  <InitialSetUp loggedIn={this.state.loggedIn}/>
}

render() {
return (
<Provider store={store}>
<View style={styles.container}>
{this.renderInitialView()}
</View>
</Provider>
);
}
}

InitialSetup.js

...

class initialSetUp extends Component {

renderInitialView() {
this.props.setLogged(this.props.loggedIn);
return  <Navigation />
}

render() {
return (
<View style={styles.container}>
{this.renderInitialView()}
</View>
);
}
}

export default connect(null, actions)(initialSetUp);

Good Luck o/


问:
Partially fill object when hovering
I have code below for a content cycle I have created with the help from some other Stack Overflow users. Is it possible to have the circular arrow fill up partially depending on what box your hovered on. Example: If the user hovers on box four (the bottom box) the circular arrow would fill up with a different color only up until that box. Is this possible to do with pure CSS only? If not would this be possible with vanilla JavaScript (no Jquery)? Anything helps, cheers.

.container .row {
  text-align: center;
  position: relative;
}

.row {
  position: relative;
}

.one {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.one:hover {
  cursor:pointer;
  transform:scale(1.019);
  border-color:f4f4f4;
  background-color:#214d84;
  box-shadow: 0px 2px 9px #888888;
}

.two {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.two:hover {
  cursor:pointer;
  transform:scale(1.019);
  border-color:f4f4f4;
  background-color:#214d84;
  box-shadow: 0px 2px 9px #888888;
}

.three {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.three:hover {
  cursor:pointer;
  transform:scale(1.019);
  border-color:f4f4f4;
  background-color:#214d84;
  box-shadow: 0px 2px 9px #888888;
}

.four {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.four:hover {
  cursor:pointer;
  transform:scale(1.019);
  border-color:f4f4f4;
  background-color:#214d84;
  box-shadow: 0px 2px 9px #888888;
}

.five {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.five:hover {
  cursor:pointer;
  transform:scale(1.019);
  border-color:f4f4f4;
  background-color:#214d84;
  box-shadow: 0px 2px 9px #888888;
}

.six {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.six:hover {
  cursor:pointer;
  transform:scale(1.019);
  border-color:f4f4f4;
  background-color:#214d84;
  box-shadow: 0px 2px 9px #888888;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 250px;
  height: 250px;
  border: 17px solid;
  border-radius: 50%;
  position: absolute;
  top: 15px;
  left: 50%;
  transform: translate(-50%, 0);
  z-index: -1;
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 30px;
  position: absolute;
  bottom: 0;
  top: -10px;
  left: 55px;
  background: #fff;
  transform: rotate(-120deg);
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  top: 0px;
  left: 40px;
  transform: rotate(-120deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="one"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="six"></div>
    <div class="invisible"></div>
    <div class="two"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="five"></div>
    <div class="invisible"></div>
    <div class="three"></div>
  </div>
  <div class="row">
    <div class="four"></div>
  </div>
  <div class="arrow"></div>
</div></code>```

答:
If you don't mind using images for your arrow, you could have a different image for the arrow depending on which box is hovered and then you can change the image out via css:

```<code>.one:hover {
  background: url("box1arrow.jpg"); // obviously, set this to whichever image you need
}
</code>```

Title: Partially fill object when hovering

Body:
If you don't mind using images for your arrow, you could have a different image for the arrow depending on which box is hovered and then you can change the image out via css:

.one:hover {
  background: url("box1arrow.jpg"); // obviously, set this to whichever image you need
}


问:
Python regex split multiple matches
I'm trying to split strings containing sequences of 2 different characters into groups. If we assume the characters are a and b, the plain text rules for grouping are:

groups consist of 0+ a's followed by 1+ b's

all following a's are included in the next group, unless we're at the end of the word.

For example: after processing tests the goal is to break into groups like expected.

```<code>tests = ['abab',
    'ababab',
    'aabab',
    'aababa',
    'aba',
    'baba']

expected = [['ab','ab'],
    ['ab','ab','ab'],
    ['aab','ab'],
    ['aab','aba'],
    ['aba'],
    ['b','aba']]
</code>```

The closest I've gotten is the below:

```<code>import re

# filter() returns iterator not list in Python 3
def testing(s):
    return list(filter(None, re.compile('(a*b+a*(?=$))').split(s)))

output = [testing(s) for s in tests]

output

[['ab', 'ab'], ['abab', 'ab'], ['aab', 'ab'], ['aab', 'aba'], ['aba']]
</code>```

Which does well on groups of 1-2 but not for groups larger than that, which means my regex needs improvement. Should I rethink the approach? I could probably do something brute force with for loops but was hoping for something more elegant.

N.B.: This post leads me to believe that .split() may not be the way to go here, but I've gotten the best results with it so far.

答:
This gives me correct results for the test data:

```<code>tests = ['abab',
'ababab',
'aabab',
'aababa',
'aba',
'baba',
'abba']

for s in tests:
    r = re.findall("(?:a*b+a*$)|(?:a*b+)",s)
    print(r)
</code>```

Results:

```<code>['ab', 'ab']
['ab', 'ab', 'ab']
['aab', 'ab']
['aab', 'aba']
['aba']
['b', 'aba']
['abba']
</code>```

Title: Python regex split multiple matches

Body:
I'm trying to split strings containing sequences of 2 different characters into groups. If we assume the characters are a and b, the plain text rules for grouping are:

groups consist of 0+ a's followed by 1+ b's

all following a's are included in the next group, unless we're at the end of the word.

For example: after processing tests the goal is to break into groups like expected.

tests = ['abab',
    'ababab',
    'aabab',
    'aababa',
    'aba',
    'baba']

expected = [['ab','ab'],
    ['ab','ab','ab'],
    ['aab','ab'],
    ['aab','aba'],
    ['aba'],
    ['b','aba']]

The closest I've gotten is the below:

import re

# filter() returns iterator not list in Python 3
def testing(s):
    return list(filter(None, re.compile('(a*b+a*(?=$))').split(s)))

output = [testing(s) for s in tests]

output

[['ab', 'ab'], ['abab', 'ab'], ['aab', 'ab'], ['aab', 'aba'], ['aba']]

Which does well on groups of 1-2 but not for groups larger than that, which means my regex needs improvement. Should I rethink the approach? I could probably do something brute force with for loops but was hoping for something more elegant.

N.B.: This post leads me to believe that .split() may not be the way to go here, but I've gotten the best results with it so far.

Body:
This gives me correct results for the test data:

tests = ['abab',
'ababab',
'aabab',
'aababa',
'aba',
'baba',
'abba']

for s in tests:
    r = re.findall("(?:a*b+a*$)|(?:a*b+)",s)
    print(r)

Results:

['ab', 'ab']
['ab', 'ab', 'ab']
['aab', 'ab']
['aab', 'aba']
['aba']
['b', 'aba']
['abba']


问:
Can't access nested object in blade template
I'm using Laravel, Eloquent for queries, and Blade for templating.

Here are the models I'm working with:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class DistrictCharge extends Model
{
    protected $fillable = [ 'plan_year', 'location_id', 'meal_id', 'charge_id', 'price' ];

    public function plan_year() {
        return $this->belongsTo('App\PlanYear', 'plan_year');
    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlanYear extends Model
{
    protected $fillable = [ 'year', 'start_date', 'end_date' ];

    public $primaryKey = 'year';
}
</code>```

Relevant controller code:

```<code>public function index()
{
    $district_charges = DistrictCharge::with('plan_year')->get();

    return view('district-charges/index', compact(
        'district_charges',
    ));
}
</code>```

In my template, when I do this:

```<code>{{ $district_charges[0] }}
</code>```

I get this (indented for readability):

```<code>{
    "id":1,
    "created_at":"2017-01-23 21:33:53",
    "updated_at":"2017-01-23 21:33:53",
    "plan_year": {
        "year":2016,
        "start_date":"2015-07-01",
        "end_date":"2016-06-30",
        "created_at":"2017-01-23 21:03:08",
        "updated_at":"2017-01-23 21:03:08"
    },
    "location_id":"2",
    "meal_id":"1",
    "charge_id":"4",
    "price":"175"
}
</code>```

This makes sense; the plan_year field is populated with the contents of the database entry it refers to, exactly as I want. But when I do this:

```<code>{{ $district_charges[0]->plan_year }}
</code>```

I just get 2016, a non-object. This is a problem because I queried in order to populate the plan_year field because I need the start_date and end_date fields that it comes with for my view. When I try to access these properties in my view I just get a 'trying to get properties of a non-object' error. I'm not that familiar with Laravel, Eloquent, or Blade, so any help would be great.

Edit:

Table structure as requested:

```<code>district_charges
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| created_at  | timestamp        | YES  |     | NULL    |                |
| updated_at  | timestamp        | YES  |     | NULL    |                |
| plan_year   | int(11)          | NO   |     | NULL    |                |
| location_id | int(11)          | NO   |     | NULL    |                |
| meal_id     | int(11)          | NO   |     | NULL    |                |
| charge_id   | int(11)          | NO   |     | NULL    |                |
| price       | int(11)          | NO   |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

plan_years
+------------+-----------+------+-----+---------+-------+
| Field      | Type      | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+-------+
| year       | int(11)   | NO   |     | NULL    |       |
| start_date | date      | NO   |     | NULL    |       |
| end_date   | date      | NO   |     | NULL    |       |
| created_at | timestamp | YES  |     | NULL    |       |
| updated_at | timestamp | YES  |     | NULL    |       |
+------------+-----------+------+-----+---------+-------+
</code>```

What I'm not getting is why I can see the contents of the variable I want when I output the whole thing in a template, but when I selectively output just parts of it, it says it doesn't exist.

答:
```<code> public function plan_year() {
    return $this->belongsTo('App\PlanYear', 'plan_year','year');
}
</code>```

I believe year is a primary key in your table

I believe you have a data in your tables otherwise you will get fatal error

```<code>$district_charges[0]->plan_year->start_date
</code>```

for showing end Date you need to do the same

```<code>$district_charges[0]->plan_year-> end_date
</code>```

Body:
I'm using Laravel, Eloquent for queries, and Blade for templating.

Here are the models I'm working with:

namespace App;

use Illuminate\Database\Eloquent\Model;

class DistrictCharge extends Model
{
    protected $fillable = [ 'plan_year', 'location_id', 'meal_id', 'charge_id', 'price' ];

    public function plan_year() {
        return $this->belongsTo('App\PlanYear', 'plan_year');
    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlanYear extends Model
{
    protected $fillable = [ 'year', 'start_date', 'end_date' ];

    public $primaryKey = 'year';
}

Relevant controller code:

public function index()
{
    $district_charges = DistrictCharge::with('plan_year')->get();

    return view('district-charges/index', compact(
        'district_charges',
    ));
}

In my template, when I do this:

{{ $district_charges[0] }}

I get this (indented for readability):

{
    "id":1,
    "created_at":"2017-01-23 21:33:53",
    "updated_at":"2017-01-23 21:33:53",
    "plan_year": {
        "year":2016,
        "start_date":"2015-07-01",
        "end_date":"2016-06-30",
        "created_at":"2017-01-23 21:03:08",
        "updated_at":"2017-01-23 21:03:08"
    },
    "location_id":"2",
    "meal_id":"1",
    "charge_id":"4",
    "price":"175"
}

This makes sense; the plan_year field is populated with the contents of the database entry it refers to, exactly as I want. But when I do this:

{{ $district_charges[0]->plan_year }}

I just get 2016, a non-object. This is a problem because I queried in order to populate the plan_year field because I need the start_date and end_date fields that it comes with for my view. When I try to access these properties in my view I just get a 'trying to get properties of a non-object' error. I'm not that familiar with Laravel, Eloquent, or Blade, so any help would be great.

Edit:

Table structure as requested:

district_charges
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| created_at  | timestamp        | YES  |     | NULL    |                |
| updated_at  | timestamp        | YES  |     | NULL    |                |
| plan_year   | int(11)          | NO   |     | NULL    |                |
| location_id | int(11)          | NO   |     | NULL    |                |
| meal_id     | int(11)          | NO   |     | NULL    |                |
| charge_id   | int(11)          | NO   |     | NULL    |                |
| price       | int(11)          | NO   |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

plan_years
+------------+-----------+------+-----+---------+-------+
| Field      | Type      | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+-------+
| year       | int(11)   | NO   |     | NULL    |       |
| start_date | date      | NO   |     | NULL    |       |
| end_date   | date      | NO   |     | NULL    |       |
| created_at | timestamp | YES  |     | NULL    |       |
| updated_at | timestamp | YES  |     | NULL    |       |
+------------+-----------+------+-----+---------+-------+

What I'm not getting is why I can see the contents of the variable I want when I output the whole thing in a template, but when I selectively output just parts of it, it says it doesn't exist.

Body:
 public function plan_year() {
    return $this->belongsTo('App\PlanYear', 'plan_year','year');
}

I believe year is a primary key in your table

I believe you have a data in your tables otherwise you will get fatal error

$district_charges[0]->plan_year->start_date

for showing end Date you need to do the same

$district_charges[0]->plan_year-> end_date


问:
Most Efficient way to access schema with ODBC and OleDB
I am making a DAL template with C# and I am wondering what is the most efficient way to access schema information with ODBC and OleDB. I need the columns, column types, and primary key information.

thanks

答:
Use the SQL Server Management Objects:

http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.aspx

for example:

```<code>Microsoft.SqlServer.Management.Smo.Server s = new
        Microsoft.SqlServer.Management.Smo.Server( @"DUFF\SQLEXPRESS" );

foreach ( Database db in s.Databases )
{
    if ( ! db.IsSystemObject )
    {
        listboxDatabase.Items.Add( db.Name );
    }
}
</code>```

from here, you can get the tables in the database (and other objects).

Body:
Use the SQL Server Management Objects:

http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.aspx

for example:

Microsoft.SqlServer.Management.Smo.Server s = new
        Microsoft.SqlServer.Management.Smo.Server( @"DUFF\SQLEXPRESS" );

foreach ( Database db in s.Databases )
{
    if ( ! db.IsSystemObject )
    {
        listboxDatabase.Items.Add( db.Name );
    }
}

from here, you can get the tables in the database (and other objects).

OwnerDisplayName: rp


问:
Tunneling events and ContextMenu
I have the following WPF Control, that should behave like, by e.g. GoogleMaps does(zoom on left double click, unzoom on right double click):

```<code><Grid>
    <ScrollViewer x:Name="scrollViewer">
        <Canvas x:Name="myCanvas"/>
    </ScrollViewer>
</Grid>
</code>```

And some code:

```<code>void OnScrollViewerPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    //this.myCanvas.ContextMenu = null;
    if (e.OriginalSource is Canvas)
    {
        // zoom on left doubleClick
        if (e.ChangedButton == MouseButton.Left)
        {
            ZoomOnMouseOnce();
        } // UNzoom on right doubleClick
        else if (e.ChangedButton == MouseButton.Right)
        {
            UnzoomOnMouseOnce();
        }
        e.Handled = true;
    }
}
</code>```

The problem is that When myCanvas have a ContextMenu the UnZoom method does not work, because DoubleClick event is not catched anymore on ScrollViewer...

Setting this.myCanvas.ContextMenu = null; solves the problem, but Is there a way to bypass this?...

答:
Update

Uploaded small sample project demonstrating the effect.

http://www.mediafire.com/?du2jr18khx8ooy9

I tried a bunch of different approaches for this and the closest thing I found was to offset the HorizontalOffset by 1 for the ContextMenu. This allowed for right-double-click when the ContextMenu was open. It still didn't work when the ContextMenu wasn't open since the ScrollViewer only recieved the first click.

You could work around this by using your timing code for the first right-mouse-click and if another right-mouse-click occurs before the Thread runs out, you simulate another right-mouse-click using SendInput. Although it may not be so pretty, I gets the job done.

```<code><Canvas ...>
    <Canvas.ContextMenu>
        <ContextMenu Placement="RelativePoint" HorizontalOffset="1">
            <MenuItem Header="MenuItem 1"/>
        </ContextMenu>
    </Canvas.ContextMenu>
</code>```

Code behind

```<code>private bool m_waitingForRightMouseDoubleClick = false;
private void scrollViewer_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Right)
    {
        if (m_waitingForRightMouseDoubleClick == false)
        {
            m_waitingForRightMouseDoubleClick = true;
            Thread thread = new Thread(new System.Threading.ThreadStart(delegate()
                {
                    Thread.Sleep(System.Windows.Forms.SystemInformation.DoubleClickTime);
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,
                        new Action(delegate()
                            {
                                m_waitingForRightMouseDoubleClick = false;
                            }
                            ));
                }));
            thread.Start();
        }
        else
        {
            MouseSimulator.ClickRightMouseButton();
        }
    }
}
</code>```

MouseSimulator.cs

```<code>public class MouseSimulator
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

    [StructLayout(LayoutKind.Sequential)]
    struct INPUT
    {
        public SendInputEventType type;
        public MouseKeybdhardwareInputUnion mkhi;
    }
    [StructLayout(LayoutKind.Explicit)]
    struct MouseKeybdhardwareInputUnion
    {
        [FieldOffset(0)]
        public MouseInputData mi;

        [FieldOffset(0)]
        public KEYBDINPUT ki;

        [FieldOffset(0)]
        public HARDWAREINPUT hi;
    }
    [StructLayout(LayoutKind.Sequential)]
    struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }
    [StructLayout(LayoutKind.Sequential)]
    struct HARDWAREINPUT
    {
        public int uMsg;
        public short wParamL;
        public short wParamH;
    }
    struct MouseInputData
    {
        public int dx;
        public int dy;
        public uint mouseData;
        public MouseEventFlags dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }
    [Flags]
    enum MouseEventFlags : uint
    {
        MOUSEEVENTF_MOVE = 0x0001,
        MOUSEEVENTF_LEFTDOWN = 0x0002,
        MOUSEEVENTF_LEFTUP = 0x0004,
        MOUSEEVENTF_RIGHTDOWN = 0x0008,
        MOUSEEVENTF_RIGHTUP = 0x0010,
        MOUSEEVENTF_MIDDLEDOWN = 0x0020,
        MOUSEEVENTF_MIDDLEUP = 0x0040,
        MOUSEEVENTF_XDOWN = 0x0080,
        MOUSEEVENTF_XUP = 0x0100,
        MOUSEEVENTF_WHEEL = 0x0800,
        MOUSEEVENTF_VIRTUALDESK = 0x4000,
        MOUSEEVENTF_ABSOLUTE = 0x8000
    }
    enum SendInputEventType : int
    {
        InputMouse,
        InputKeyboard,
        InputHardware
    }

    public static void ClickRightMouseButton()
    {
        INPUT mouseDownInput = new INPUT();
        mouseDownInput.type = SendInputEventType.InputMouse;
        mouseDownInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_RIGHTDOWN;
        SendInput(1, ref mouseDownInput, Marshal.SizeOf(new INPUT()));

        INPUT mouseUpInput = new INPUT();
        mouseUpInput.type = SendInputEventType.InputMouse;
        mouseUpInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_RIGHTUP;
        SendInput(1, ref mouseUpInput, Marshal.SizeOf(new INPUT()));
    }
}
</code>```

Title: Tunneling events and ContextMenu

Body:
I have the following WPF Control, that should behave like, by e.g. GoogleMaps does(zoom on left double click, unzoom on right double click):

<Grid>
    <ScrollViewer x:Name="scrollViewer">
        <Canvas x:Name="myCanvas"/>
    </ScrollViewer>
</Grid>

And some code:

void OnScrollViewerPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    //this.myCanvas.ContextMenu = null;
    if (e.OriginalSource is Canvas)
    {
        // zoom on left doubleClick
        if (e.ChangedButton == MouseButton.Left)
        {
            ZoomOnMouseOnce();
        } // UNzoom on right doubleClick
        else if (e.ChangedButton == MouseButton.Right)
        {
            UnzoomOnMouseOnce();
        }
        e.Handled = true;
    }
}

The problem is that When myCanvas have a ContextMenu the UnZoom method does not work, because DoubleClick event is not catched anymore on ScrollViewer...

Setting this.myCanvas.ContextMenu = null; solves the problem, but Is there a way to bypass this?...

Body:
Update

Uploaded small sample project demonstrating the effect.

http://www.mediafire.com/?du2jr18khx8ooy9

I tried a bunch of different approaches for this and the closest thing I found was to offset the HorizontalOffset by 1 for the ContextMenu. This allowed for right-double-click when the ContextMenu was open. It still didn't work when the ContextMenu wasn't open since the ScrollViewer only recieved the first click.

You could work around this by using your timing code for the first right-mouse-click and if another right-mouse-click occurs before the Thread runs out, you simulate another right-mouse-click using SendInput. Although it may not be so pretty, I gets the job done.

<Canvas ...>
    <Canvas.ContextMenu>
        <ContextMenu Placement="RelativePoint" HorizontalOffset="1">
            <MenuItem Header="MenuItem 1"/>
        </ContextMenu>
    </Canvas.ContextMenu>

Code behind

private bool m_waitingForRightMouseDoubleClick = false;
private void scrollViewer_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Right)
    {
        if (m_waitingForRightMouseDoubleClick == false)
        {
            m_waitingForRightMouseDoubleClick = true;
            Thread thread = new Thread(new System.Threading.ThreadStart(delegate()
                {
                    Thread.Sleep(System.Windows.Forms.SystemInformation.DoubleClickTime);
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,
                        new Action(delegate()
                            {
                                m_waitingForRightMouseDoubleClick = false;
                            }
                            ));
                }));
            thread.Start();
        }
        else
        {
            MouseSimulator.ClickRightMouseButton();
        }
    }
}

MouseSimulator.cs

public class MouseSimulator
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

    [StructLayout(LayoutKind.Sequential)]
    struct INPUT
    {
        public SendInputEventType type;
        public MouseKeybdhardwareInputUnion mkhi;
    }
    [StructLayout(LayoutKind.Explicit)]
    struct MouseKeybdhardwareInputUnion
    {
        [FieldOffset(0)]
        public MouseInputData mi;

        [FieldOffset(0)]
        public KEYBDINPUT ki;

        [FieldOffset(0)]
        public HARDWAREINPUT hi;
    }
    [StructLayout(LayoutKind.Sequential)]
    struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }
    [StructLayout(LayoutKind.Sequential)]
    struct HARDWAREINPUT
    {
        public int uMsg;
        public short wParamL;
        public short wParamH;
    }
    struct MouseInputData
    {
        public int dx;
        public int dy;
        public uint mouseData;
        public MouseEventFlags dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }
    [Flags]
    enum MouseEventFlags : uint
    {
        MOUSEEVENTF_MOVE = 0x0001,
        MOUSEEVENTF_LEFTDOWN = 0x0002,
        MOUSEEVENTF_LEFTUP = 0x0004,
        MOUSEEVENTF_RIGHTDOWN = 0x0008,
        MOUSEEVENTF_RIGHTUP = 0x0010,
        MOUSEEVENTF_MIDDLEDOWN = 0x0020,
        MOUSEEVENTF_MIDDLEUP = 0x0040,
        MOUSEEVENTF_XDOWN = 0x0080,
        MOUSEEVENTF_XUP = 0x0100,
        MOUSEEVENTF_WHEEL = 0x0800,
        MOUSEEVENTF_VIRTUALDESK = 0x4000,
        MOUSEEVENTF_ABSOLUTE = 0x8000
    }
    enum SendInputEventType : int
    {
        InputMouse,
        InputKeyboard,
        InputHardware
    }

    public static void ClickRightMouseButton()
    {
        INPUT mouseDownInput = new INPUT();
        mouseDownInput.type = SendInputEventType.InputMouse;
        mouseDownInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_RIGHTDOWN;
        SendInput(1, ref mouseDownInput, Marshal.SizeOf(new INPUT()));

        INPUT mouseUpInput = new INPUT();
        mouseUpInput.type = SendInputEventType.InputMouse;
        mouseUpInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_RIGHTUP;
        SendInput(1, ref mouseUpInput, Marshal.SizeOf(new INPUT()));
    }
}


问:
Fastest way to read a binary file with a defined format?
I have large binary data files that have a predefined format, originally written by a Fortran program as little endians. I would like to read these files in the fastest, most efficient manner, so using the array package seemed right up my alley as suggested in Improve speed of reading and converting from binary file?.

The problem is the pre-defined format is non-homogeneous. It looks something like this:
['<2i','<5d','<2i','<d','<i','<3d','<2i','<3d','<i','<d','<i','<3d']

with each integer i taking up 4 bytes, and each double d taking 8 bytes.

Is there a way I can still use the super efficient array package (or another suggestion) but with the right format?

答:
It's not clear from your question whether you're concerned about the actual file reading speed (and building data structure in memory), or about later data processing speed.

If you are reading only once, and doing heavy processing later, you can read the file record by record (if your binary data is a recordset of repeated records with identical format), parse it with struct.unpack and append it to a [double] array:

```<code>from functools import partial

data = array.array('d')
record_size_in_bytes = 9*4 + 16*8   # 9 ints + 16 doubles

with open('input', 'rb') as fin:
    for record in iter(partial(fin.read, record_size_in_bytes), b''):
        values = struct.unpack("<2i5d...", record)
        data.extend(values)
</code>```

Under assumption you are allowed to cast all your ints to doubles and willing to accept increase in allocated memory size (22% increase for your record from the question).

If you are reading the data from file many times, it could be worthwhile to convert everything to one large array of doubles (like above) and write it back to another file from which you can later read with array.fromfile():

```<code>data = array.array('d')
with open('preprocessed', 'rb') as fin:
    n = os.fstat(fin.fileno()).st_size // 8
    data.fromfile(fin, n)
</code>```

Update. Thanks to a nice benchmark by @martineau, now we know for a fact that preprocessing the data and turning it into an homogeneous array of doubles ensures that loading such data from file (with array.fromfile()) is ~20x to ~40x faster than reading it record-per-record, unpacking and appending to array (as shown in the first code listing above).

A faster (and a more standard) variation of record-by-record reading in @martineau's answer which appends to list and doesn't upcast to double is only ~6x to ~10x slower than array.fromfile() method and seems like a better reference benchmark.

ContentLicense: CC BY-SA 4.0

Body:
It's not clear from your question whether you're concerned about the actual file reading speed (and building data structure in memory), or about later data processing speed.

If you are reading only once, and doing heavy processing later, you can read the file record by record (if your binary data is a recordset of repeated records with identical format), parse it with struct.unpack and append it to a [double] array:

from functools import partial

data = array.array('d')
record_size_in_bytes = 9*4 + 16*8   # 9 ints + 16 doubles

with open('input', 'rb') as fin:
    for record in iter(partial(fin.read, record_size_in_bytes), b''):
        values = struct.unpack("<2i5d...", record)
        data.extend(values)

Under assumption you are allowed to cast all your ints to doubles and willing to accept increase in allocated memory size (22% increase for your record from the question).

If you are reading the data from file many times, it could be worthwhile to convert everything to one large array of doubles (like above) and write it back to another file from which you can later read with array.fromfile():

data = array.array('d')
with open('preprocessed', 'rb') as fin:
    n = os.fstat(fin.fileno()).st_size // 8
    data.fromfile(fin, n)

Update. Thanks to a nice benchmark by @martineau, now we know for a fact that preprocessing the data and turning it into an homogeneous array of doubles ensures that loading such data from file (with array.fromfile()) is ~20x to ~40x faster than reading it record-per-record, unpacking and appending to array (as shown in the first code listing above).

A faster (and a more standard) variation of record-by-record reading in @martineau's answer which appends to list and doesn't upcast to double is only ~6x to ~10x slower than array.fromfile() method and seems like a better reference benchmark.


问:
Lua: how are tables used as hash key?
When a table is being used as a hash key, does it have anything to do with the hex id you get when you print out the table?

For example,

```<code>obj = {}
print(obj)
</code>```

You might get something like table: 153CF5A0. Is this value used in the hashing process of this table?

I noticed that if you create two identical tables that aren't references of each other, they hash to different things:

```<code>obj1 = {}
obj2 = {}
map = {}

map[obj1] = 'obj1'
map[obj2] = 'obj2'
print(map[obj1]) -- obj1
print(map[obj2]) -- obj2
</code>```

答: Yes, the memory address of a table is used as a key for hashing when the table is used to index another table. See the source code (tables are handled in the default case).</p>

Title: Lua: how are tables used as hash key?

Body:
When a table is being used as a hash key, does it have anything to do with the hex id you get when you print out the table?

For example,

obj = {}
print(obj)

You might get something like table: 153CF5A0. Is this value used in the hashing process of this table?

I noticed that if you create two identical tables that aren't references of each other, they hash to different things:

obj1 = {}
obj2 = {}
map = {}

map[obj1] = 'obj1'
map[obj2] = 'obj2'
print(map[obj1]) -- obj1
print(map[obj2]) -- obj2


问:
Updating react state after data is sent to api
So it seems I broke the React way of things. I currently have things setup that the main App container (which contains all the router logic) will fetch all data from the API on it's initial state.

I pass down the function:

```<code>  createPage(page) {
    console.log('submitted')
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

The API accepts the data and I see it update the database.

My issue is: after I submit the data, the container component doesn't update it's state which holds all the data.

For example, this is the App container:

```<code>import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    console.log('submitted')
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>
        <div className="Router">
          <div className="Navbar">
            <Header />
          </div>
          <div className="Wrapper">
            <Route exact path="/" render={ () => (
              <Dashboard pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ () => (
              <AddEditPage createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ () => (
              <AddEditPage />
            )} />
          </div>
        </div>
      </Router>

    );
  }
}

export default App;
</code>```

Currently, I get around this issue by setting the window.href after submit. This reloads the whole page (not ideal).

```<code>  handleSubmit(e) {
    e.preventDefault();
    this.props.createPage(this.state)
    //TODO: update main container state of page titles, then redirect
    window.location = "/"

  }
</code>```

答:
this.getPages is only being called on componentDidMount - so after the component initially mounts, your state is never updated. You need to call this.getPages again after creating the new page:

```<code>createPage(page) {
  console.log('submitted')
  instance.post('/admin/createPage',page).then((response) => {
    console.log(response);

    // after page is created, refetch pages
    // this.getPages calls setState and your component will re-render
    this.getPages();
  }).catch((error) => {
    console.log(error);
  })
}
</code>```

or if you prefer you can chain it in your handleSubmit:

```<code>handleSubmit(e) {
  e.preventDefault();
  this.props.createPage(this.state).then(this.getPages);
}
</code>```

Body:
So it seems I broke the React way of things. I currently have things setup that the main App container (which contains all the router logic) will fetch all data from the API on it's initial state.

I pass down the function:

  createPage(page) {
    console.log('submitted')
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }

The API accepts the data and I see it update the database.

My issue is: after I submit the data, the container component doesn't update it's state which holds all the data.

For example, this is the App container:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    console.log('submitted')
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>

            <Route exact path="/" render={ () => (
              <Dashboard pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ () => (
              <AddEditPage createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ () => (
              <AddEditPage />
            )} />

      </Router>

    );
  }
}

export default App;

Currently, I get around this issue by setting the window.href after submit. This reloads the whole page (not ideal).

  handleSubmit(e) {
    e.preventDefault();
    this.props.createPage(this.state)
    //TODO: update main container state of page titles, then redirect
    window.location = "/"

  }

Body:
this.getPages is only being called on componentDidMount - so after the component initially mounts, your state is never updated. You need to call this.getPages again after creating the new page:

createPage(page) {
  console.log('submitted')
  instance.post('/admin/createPage',page).then((response) => {
    console.log(response);

    // after page is created, refetch pages
    // this.getPages calls setState and your component will re-render
    this.getPages();
  }).catch((error) => {
    console.log(error);
  })
}

or if you prefer you can chain it in your handleSubmit:

handleSubmit(e) {
  e.preventDefault();
  this.props.createPage(this.state).then(this.getPages);
}


问:
Change styles & size of Google's "I'm not a robot" ReCaptcha V2
So many threads about not being able to change the styles (background-color, text color...) of Googles ReCaptcha. However, less than 2 weeks ago I visited the website of Spotify.com and at the Sign Up page, I saw the official ReCaptcha with a dark background, white text and same blue and gray logo.

A day after, I wanted to change the styles of the ReCaptcha on my website, so I went to Spotify.com to check how they did it. Unfortunately, they changed the Sign Up page or they moved it or whatever. I am sure it is possible in some way, but I'm too inexperienced to find out how myself. I found something on Google Developers mentioning "theme": https://developers.google.com/recaptcha/docs/display#render_param. Furthermore, it says something about size.

How do I change the styles and size of Google's official "I'm not a robot" ReCaptcha?

答:
reCAPTCHA V2 allows you to change the theme of the rendered captcha, perhaps they were using the "dark" theme. Here is the documentation: https://developers.google.com/recaptcha/docs/display#render_param

So for example:

```<code><script type="text/javascript">
   var onloadCallback = function() {
   grecaptcha.render('html_element', {
     'data-theme' : 'dark'
   });
 };
</script>
</code>```

Body:
reCAPTCHA V2 allows you to change the theme of the rendered captcha, perhaps they were using the "dark" theme. Here is the documentation: https://developers.google.com/recaptcha/docs/display#render_param

So for example:

<script type="text/javascript">
   var onloadCallback = function() {
   grecaptcha.render('html_element', {
     'data-theme' : 'dark'
   });
 };
</script>


问:
Find max time delta after sorting data and applying groupby
I have a data frame (df) that contains two rows with multiple entries per 'name':

```<code>                     name                           date
       Official Press FRC        2015-02-19 20:30:00.000
   Other Publications BOJ        2015-04-16 07:00:00.000
           Bank of Russia        2015-06-11 09:44:37.000
</code>```

I would like to find the maximum difference in 'dates' for each 'name'. My approach to this was to try and sort the dates while simultaneously grouping by name and then take the difference using .diff(). Below is the code I tried:

```<code>grouped = df.sort_values('date').groupby('name')
differences = grouped.diff()
</code>```

I also tried to approach the problem by constructing a pivot table:

```<code>grouped = df.pivot(columns='name', values='date')
</code>```

答:
I think you need custom function with diff and max for max timedelta:

```<code>#if necessary convert to datetime
df['date'] = pd.to_datetime(df['date'])
df1 = df.sort_values('date')
        .groupby('name')['date'].apply(lambda x: x.diff().max())
        .reset_index(name='max_diff')
</code>```

Body:
I have a data frame (df) that contains two rows with multiple entries per 'name':

                     name                           date
       Official Press FRC        2015-02-19 20:30:00.000
   Other Publications BOJ        2015-04-16 07:00:00.000
           Bank of Russia        2015-06-11 09:44:37.000

I would like to find the maximum difference in 'dates' for each 'name'. My approach to this was to try and sort the dates while simultaneously grouping by name and then take the difference using .diff(). Below is the code I tried:

grouped = df.sort_values('date').groupby('name')
differences = grouped.diff()

I also tried to approach the problem by constructing a pivot table:

grouped = df.pivot(columns='name', values='date')

Body:
I think you need custom function with diff and max for max timedelta:

#if necessary convert to datetime
df['date'] = pd.to_datetime(df['date'])
df1 = df.sort_values('date')
        .groupby('name')['date'].apply(lambda x: x.diff().max())
        .reset_index(name='max_diff')


问:
How to parse the contents of a .csv file into a dict while always skipping the header?
I apologize if this a really basic question, but I have designed a program that requires the user to input a .csv file. I have set up my code to parse this .csv file, remove any characters that could potentially interfere with the rest of the code, and also remove any entry into the dict with the key 'Sequence number' (which is the header in the .csv). However, I know this removal of the header isn't very pythonic, and furthermore, it also assumes that the user will always be uploading a .csv file whose header follows the format 'Sequence number', 'sequence1', 'sequence2'. What should I do so that, no matter how the header is set up in the .csv file, the header is always skipped when it is being parsed into a dict?</p>

```<code>import csv

def check_sequences_csv_file(csv_file):
    sequence_dict= {}
    while True:
        try:
            with open(csv_file, "rU") as csvfile:
                sequences = csv.reader(csvfile, dialect= 'excel')
                for line in sequences:
                    candidate_number= line[0]
                    switch= line[1].replace(' ','').replace('\r','').replace('\n','')
                    trigger= line[2].replace(' ','').replace('\r','').replace('\n','')
                    sequence_csv_dict[candidate_number]= [switch, trigger]
                sequence_csv_dict.pop('Sequence number', None)
        except IOError:
            print("Please make sure the file is present in the working directory.")
            continue
        else:
            break
    return sequence_dict
</code>```

答:
Using only built-in csv module, the naive approach would be:

```<code>with open(csv_file, "rU") as csvfile:
     csv_file.readline()
     sequences = csv.reader(csvfile, dialect= 'excel')
</code>```

that would work most of the time, BUT if the title line is multi-line you'll get a parsing error. So the best way is to consume the first iteration of the csv.reader object:

```<code>with open(csv_file, "rU") as csvfile:
     sequences = csv.reader(csvfile, dialect= 'excel')
     next(sequences)
</code>```

(you can save the title line for later: title_row = next(sequences)

then go on with your for loop to read the rest of the rows.

Body:
I apologize if this a really basic question, but I have designed a program that requires the user to input a .csv file. I have set up my code to parse this .csv file, remove any characters that could potentially interfere with the rest of the code, and also remove any entry into the dict with the key 'Sequence number' (which is the header in the .csv). However, I know this removal of the header isn't very pythonic, and furthermore, it also assumes that the user will always be uploading a .csv file whose header follows the format 'Sequence number', 'sequence1', 'sequence2'. What should I do so that, no matter how the header is set up in the .csv file, the header is always skipped when it is being parsed into a dict?

import csv

def check_sequences_csv_file(csv_file):
    sequence_dict= {}
    while True:
        try:
            with open(csv_file, "rU") as csvfile:
                sequences = csv.reader(csvfile, dialect= 'excel')
                for line in sequences:
                    candidate_number= line[0]
                    switch= line[1].replace(' ','').replace('\r','').replace('\n','')
                    trigger= line[2].replace(' ','').replace('\r','').replace('\n','')
                    sequence_csv_dict[candidate_number]= [switch, trigger]
                sequence_csv_dict.pop('Sequence number', None)
        except IOError:
            print("Please make sure the file is present in the working directory.")
            continue
        else:
            break
    return sequence_dict

Body:
Using only built-in csv module, the naive approach would be:

with open(csv_file, "rU") as csvfile:
     csv_file.readline()
     sequences = csv.reader(csvfile, dialect= 'excel')

that would work most of the time, BUT if the title line is multi-line you'll get a parsing error. So the best way is to consume the first iteration of the csv.reader object:

with open(csv_file, "rU") as csvfile:
     sequences = csv.reader(csvfile, dialect= 'excel')
     next(sequences)

(you can save the title line for later: title_row = next(sequences)

then go on with your for loop to read the rest of the rows.


问:
Replacing ViewPager with new fragment
I have an app where my MainActivity has a viewpager and TabLayout with three fragments (fragments a,b, and c). I have a menu item when selected I want to open a new separate fragment (fragment d) to overlap my viewpager an tablayout. When I click on my menu option fragment d appears but fragment a, b, or c is still in the background.

What is happening

What I want to do

MainActivity.Java

```<code> public class MainActivity extends AppCompatActivity  {

    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private ActionBarDrawerToggle drawerToggle;
    private static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        BookShelfPagerAdapter bookShelfPagerAdapter = new BookShelfPagerAdapter(getApplicationContext(), getSupportFragmentManager());
        viewPager.setAdapter(bookShelfPagerAdapter);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_book_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
            case R.id.action_discover:
                Fragment discoverFragment = new DiscoverFragment();
                this.getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.flContent, discoverFragment)
                        .addToBackStack(null)
                        .commit();

            return true;
        return super.onOptionsItemSelected(item);
    }
}
</code>```

XML Layout: MainAcitvity

```<code><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- This LinearLayout represents the contents of the screen  -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <!-- The ActionBar displayed at the top -->
            <include
                layout="@layout/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <!-- The main content view where fragments are loaded  -->

            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>
    </FrameLayout>

    <!-- The navigation drawer that comes from the left --><!-- Note that `android:layout_gravity` needs to be set to 'start' -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
</code>```

答: So it turns out I can use an activity and I did that instead of a fragment!</p>

Title: Replacing ViewPager with new fragment

Body:
I have an app where my MainActivity has a viewpager and TabLayout with three fragments (fragments a,b, and c). I have a menu item when selected I want to open a new separate fragment (fragment d) to overlap my viewpager an tablayout. When I click on my menu option fragment d appears but fragment a, b, or c is still in the background.

What is happening

What I want to do

MainActivity.Java

 public class MainActivity extends AppCompatActivity  {

    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private ActionBarDrawerToggle drawerToggle;
    private static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        BookShelfPagerAdapter bookShelfPagerAdapter = new BookShelfPagerAdapter(getApplicationContext(), getSupportFragmentManager());
        viewPager.setAdapter(bookShelfPagerAdapter);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_book_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
            case R.id.action_discover:
                Fragment discoverFragment = new DiscoverFragment();
                this.getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.flContent, discoverFragment)
                        .addToBackStack(null)
                        .commit();

            return true;
        return super.onOptionsItemSelected(item);
    }
}

XML Layout: MainAcitvity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include
                layout="@layout/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>
    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>


问:
Rails.logger statements don't have fluent tags
I'm trying to setup sending Rails logs to a collector via fluentd. I'm using the act-fluent-logger-rails, lograge and fluent-plugin-parser gems. When I navigate my site, GET and POST requests get matched, parsed, tagged and sent along to the collector correctly, but I can't get anything I log during a request via Rails.logger to be passed along by fluentd because the statements don't have a tag.

For example, in the rails console of the app:

irb(main):003:0> logger.info("Test")

results in the following in my td-agent.log:

2016-05-23 20:01:45 +0000 [warn]: pattern not match with data 'Test'
 2016-05-23 20:01:45 +0000 fluent.warn: {"message":"pattern not match with data 'Test'"}

The relevant configuration:

/etc/td-agent/td-agent.conf

```<code>    <match tv.app>
      @type forward

      # primary host
      <server>
        host 10.0.0.0
        port 24224
      </server>

      flush_interval 60s
    </match>

    <match rails.app>
      @type parser
      key_name messages
      format json
      tag tv.app
    </match>
</code>```

config/application.rb

```<code>config.logger = ActFluentLoggerRails::Logger.
            new(settings: {
               host: '127.0.0.1',
               port: 24224,
               tag: 'rails.app',
               messages_type: 'string'
            })
config.lograge.enabled = true
config.lograge.formatter = Lograge::Formatters::Json.new
</code>```

Anyone have any ideas what I'm doing wrong?

答:
You have lograge formatter set to JSON, and your fluentd.conf also specifies JSON.
However, your code from the console is a string.

Have you tried

```<code>logger.info({:test => true}.to_json)
</code>```

Body:
I'm trying to setup sending Rails logs to a collector via fluentd. I'm using the act-fluent-logger-rails, lograge and fluent-plugin-parser gems. When I navigate my site, GET and POST requests get matched, parsed, tagged and sent along to the collector correctly, but I can't get anything I log during a request via Rails.logger to be passed along by fluentd because the statements don't have a tag.

For example, in the rails console of the app:

irb(main):003:0> logger.info("Test")

results in the following in my td-agent.log:

2016-05-23 20:01:45 +0000 [warn]: pattern not match with data 'Test'
 2016-05-23 20:01:45 +0000 fluent.warn: {"message":"pattern not match with data 'Test'"}

The relevant configuration:

/etc/td-agent/td-agent.conf

    <match tv.app>
      @type forward

      # primary host
      <server>
        host 10.0.0.0
        port 24224
      </server>

      flush_interval 60s
    </match>

    <match rails.app>
      @type parser
      key_name messages
      format json
      tag tv.app
    </match>

config/application.rb

config.logger = ActFluentLoggerRails::Logger.
            new(settings: {
               host: '127.0.0.1',
               port: 24224,
               tag: 'rails.app',
               messages_type: 'string'
            })
config.lograge.enabled = true
config.lograge.formatter = Lograge::Formatters::Json.new

Anyone have any ideas what I'm doing wrong?

Body:
You have lograge formatter set to JSON, and your fluentd.conf also specifies JSON.
However, your code from the console is a string.

Have you tried

logger.info({:test => true}.to_json)


问:
Different Truncation Results When Casting
I'm having some some difficulty predicting how my C code will truncate results. Refer to the following:

```<code>float fa,fb,fc;
short ia,ib;

fa=160
fb=0.9;
fc=fa*fb;
ia=(short)fc;
ib=(short)(fa*fb);
</code>```

The results are ia=144, ib=143.

I can understand the reasoning for either result, but I don't understand why the two calculations are treated differently. Can anyone refer me to where this behaviour is defined or explain the difference?

Edit: the results are compiled with MS Visual C++ Express 2010 on Intel core i3-330m. I get the same results on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) under Virtual Box on the same machine.

答:
This is compiler dependent. On mine (gcc 4.4.3) it produces the same result for both expressions, namely -144, probably because the identical expression is optimized away.

Others explained well what happened. In other words I would say that the differences probably happens because your compiler internally promotes floats to 80 bits fpu registers before performing the multiplication, then convert back either to float or to short.

If my hypothesis is true if you write ib = (short)(float)(fa * fb); you should get the same result than when casting fc to short.

Body:
I'm having some some difficulty predicting how my C code will truncate results. Refer to the following:

float fa,fb,fc;
short ia,ib;

fa=160
fb=0.9;
fc=fa*fb;
ia=(short)fc;
ib=(short)(fa*fb);

The results are ia=144, ib=143.

I can understand the reasoning for either result, but I don't understand why the two calculations are treated differently. Can anyone refer me to where this behaviour is defined or explain the difference?

Edit: the results are compiled with MS Visual C++ Express 2010 on Intel core i3-330m. I get the same results on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) under Virtual Box on the same machine.


问:
Coldfusion Looping
I need to use cfloop to insert records.

There's a form a customer fills out. They add an item from a dropdown list, and then enter in a quantity in a text box. Normally, the quantity is only between 1 and 5.

I need to run a loop to insert the records one at a time with a unique Item ID for each with a quantity of 1.

For example, if they add Specific Item 5 with a quantity of 4, I need 4 records inserted into the table  with a qty of 1 each. What I really want more than the answer here is the thought process of how I'd come to that going forward without having to ask.

答:
Really minor changes to Shawn's excellent answer

```<code><cfquery name="insertRecords" datasource="#APPLICATION.DSN#">
DECLARE @OtherDetails varchar(80) = <cfqueryparam cfsqltype="cf_sql_varchar" value="#sanitizedOtherDetails#">

INSERT INTO <TheTable> ( ItemID, Qty, <OtherDetails> )
VALUES
    <cfloop from="1" to="#sanitizedFORMQuantity# index="i">
        (
            <cfqueryparam cfsqltype="cf_sql_smallint" value="#sanitizedItemID#">
            , 1
            , @otherDetails
        )
        <cfif index NEQ sanitizedFORMQuantity>,</cfif>
    </cfloop>
</cfquery>
</code>```

This will create fewer temp variables

If you are really creating more than a small int number of variables, you have a real problem in the approach.

Title: Coldfusion Looping

Body:
Really minor changes to Shawn's excellent answer

<cfquery name="insertRecords" datasource="#APPLICATION.DSN#">
DECLARE @OtherDetails varchar(80) = <cfqueryparam cfsqltype="cf_sql_varchar" value="#sanitizedOtherDetails#">

INSERT INTO <TheTable> ( ItemID, Qty, <OtherDetails> )
VALUES
    <cfloop from="1" to="#sanitizedFORMQuantity# index="i">
        (
            <cfqueryparam cfsqltype="cf_sql_smallint" value="#sanitizedItemID#">
            , 1
            , @otherDetails
        )
        <cfif index NEQ sanitizedFORMQuantity>,</cfif>
    </cfloop>
</cfquery>

This will create fewer temp variables

If you are really creating more than a small int number of variables, you have a real problem in the approach.