问:
.NET: NullReferenceException when applying Culture Infos
this error is driving me nuts.
Im building a website with the option to change between multiple languages.

Heres the (very) basic structure of the site:

Default.aspx (with CodeBehind-File)

Shared/Default.Master (with CodeBehinde-File)

App_Code/BasePage.cs

App_LocalResources/Default.aspx.en.resx

Default.aspx uses the Masterpage.

BasePage.cs: The BasePage class derivates from System.Web.Ui.Page (public class BasePage : Page)

Default.aspx.cs: Default derivates from BasePage (public partial class Default : BasePage)

All that works well.

Then I tried to override the InitializeCulture() Method to make it possible to change the language of the site.
The culture should be in two-letter form (so "en" not "en-US" etc.).

This is how the BasePage.css File looks like:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Threading;
using System.Globalization;

namespace Web
{
public class BasePage : Page
{
    protected override void InitializeCulture()
    {
        LanguageQS = Request.QueryString["l"].ToString();

        // Language
        if( !String.IsNullOrEmpty( LanguageQS ) )
        {
            // Validate the QueryString Value
            string[] LanguagesArray = ConfigurationManager.AppSettings["Languages"].ToString().Split( ',' );
            if( LanguagesArray.Contains( LanguageQS ) )
            {
                Session["Language"] = LanguageQS;
                cultureString = LanguageQS;
            }
        }
        else if( Session.IsNewSession || String.IsNullOrEmpty( Session["Language"].ToString() ) )
        {
            // New Session, set default Language
            cultureString = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();
        }
        else
        {
            // Get language from session
            cultureString = Session["Language"].ToString();
        }

        // Set the language
        try
        {

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
            Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );
        }
        catch { throw; }

        base.InitializeCulture();
    }

    private string _culture;
    public string cultureString
    {
        set { this._culture = value; }
        get { return this._culture; }
    }

    private string _languageQS;
    public string LanguageQS
    {
        set { this._languageQS = value; }
        get { return this._languageQS; }
    }
}
</code>```

}

Now I get the following error when I open the Page:

```<code>Line 1:  <%@ Page Language="C#" MasterPageFile="~/Shared/Default.Master" Inherits="Default" meta:resourcekey="PageResource" Codebehind="Default.aspx.cs" AutoEventWireup="True" %>

System.NullReferenceException: Object reference not set to an instance of an object.
</code>```

I traced the error down to these two rows:

```<code>Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );
</code>```

If I remove them all works well again.

But even if I put

```<code>cultureString = "en";
</code>```

or

```<code>cultureString = "en-US";
</code>```

right in front of those lines I get that NullException.

Anyone got a hint?

Im pretty new to .NET-Development and cant find whats causing this error.

答:
Thanks everyone.

My biggest culpa is not checking the debugger before posting here. :(

Debugger told me that

```<code>LanguageQS = Request.QueryString["l"].ToString();
</code>```

failed, because no QuerySting was given and ToString() cant convert null to a string.

Fixed that.

Thanks for the hint on the return paths. Fixed that as well.

Body:
this error is driving me nuts.
Im building a website with the option to change between multiple languages.

Heres the (very) basic structure of the site:

Default.aspx (with CodeBehind-File)

Shared/Default.Master (with CodeBehinde-File)

App_Code/BasePage.cs

App_LocalResources/Default.aspx.en.resx

Default.aspx uses the Masterpage.

BasePage.cs: The BasePage class derivates from System.Web.Ui.Page (public class BasePage : Page)

Default.aspx.cs: Default derivates from BasePage (public partial class Default : BasePage)

All that works well.

Then I tried to override the InitializeCulture() Method to make it possible to change the language of the site.
The culture should be in two-letter form (so "en" not "en-US" etc.).

This is how the BasePage.css File looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Threading;
using System.Globalization;

namespace Web
{
public class BasePage : Page
{
    protected override void InitializeCulture()
    {
        LanguageQS = Request.QueryString["l"].ToString();

        // Language
        if( !String.IsNullOrEmpty( LanguageQS ) )
        {
            // Validate the QueryString Value
            string[] LanguagesArray = ConfigurationManager.AppSettings["Languages"].ToString().Split( ',' );
            if( LanguagesArray.Contains( LanguageQS ) )
            {
                Session["Language"] = LanguageQS;
                cultureString = LanguageQS;
            }
        }
        else if( Session.IsNewSession || String.IsNullOrEmpty( Session["Language"].ToString() ) )
        {
            // New Session, set default Language
            cultureString = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();
        }
        else
        {
            // Get language from session
            cultureString = Session["Language"].ToString();
        }

        // Set the language
        try
        {

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
            Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );
        }
        catch { throw; }

        base.InitializeCulture();
    }

    private string _culture;
    public string cultureString
    {
        set { this._culture = value; }
        get { return this._culture; }
    }

    private string _languageQS;
    public string LanguageQS
    {
        set { this._languageQS = value; }
        get { return this._languageQS; }
    }
}

}

Now I get the following error when I open the Page:

Line 1:  <%@ Page Language="C#" MasterPageFile="~/Shared/Default.Master" Inherits="Default" meta:resourcekey="PageResource" Codebehind="Default.aspx.cs" AutoEventWireup="True" %>

System.NullReferenceException: Object reference not set to an instance of an object.

I traced the error down to these two rows:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );

If I remove them all works well again.

But even if I put

cultureString = "en";

or

cultureString = "en-US";

right in front of those lines I get that NullException.

Anyone got a hint?

Im pretty new to .NET-Development and cant find whats causing this error.

Body:
Thanks everyone.

My biggest culpa is not checking the debugger before posting here. :(

Debugger told me that

LanguageQS = Request.QueryString["l"].ToString();

failed, because no QuerySting was given and ToString() cant convert null to a string.

Fixed that.

Thanks for the hint on the return paths. Fixed that as well.


来源: stackexchange

问:
How to transform an array into an object in javascript
I have an array like this:

```<code>[
{ id: “Идент”, name: “Назв”, price: “Сто”, quantity: “Коло” },
[ 1, “продукт 1”, “400”, 5 ],
[ 2, “продукт 2”, “300”, 7 ],
[ 2, “продукт 2”, “300”, 7 ]]
</code>```

How can I transform it into something like this:

```<code>{
    items: [
        { name: "Хлеб", id: 1, price: 15.9, quantity: 3 },
        { name: "Масло", id: 2, price: 60, quantity: 1 },
        { name: "Картофель", id: 3, price: 22.6, quantity: 6 },
        { name: "Сыр", id: 4, price:310, quantity: 9 }
    ]
};
</code>```

答:
I assume that index 0:id,1:name,2:price,3:quantity. here you go,</p>

```<code>var array = [
         [12,"abc",232,2],
         [12,"abc",232,2],
         [12,"abc",232,2],
         [12,"abc",232,2]
       ];
       var obj = {};
       obj.options  = (function(array){
          var e = [];
          for(i in array){
            t = {};
            t.id = array[i][0];
            t.name = array[i][1];
            t.price = array[i][2];
            t.quantity = array[i][3];
            e.push(t);
          }
          return e;
       })(array);
       console.log(obj)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array like this:

[
{ id: “Идент”, name: “Назв”, price: “Сто”, quantity: “Коло” },
[ 1, “продукт 1”, “400”, 5 ],
[ 2, “продукт 2”, “300”, 7 ],
[ 2, “продукт 2”, “300”, 7 ]]

How can I transform it into something like this:

{
    items: [
        { name: "Хлеб", id: 1, price: 15.9, quantity: 3 },
        { name: "Масло", id: 2, price: 60, quantity: 1 },
        { name: "Картофель", id: 3, price: 22.6, quantity: 6 },
        { name: "Сыр", id: 4, price:310, quantity: 9 }
    ]
};

Body:
I assume that index 0:id,1:name,2:price,3:quantity. here you go,

var array = [
         [12,"abc",232,2],
         [12,"abc",232,2],
         [12,"abc",232,2],
         [12,"abc",232,2]
       ];
       var obj = {};
       obj.options  = (function(array){
          var e = [];
          for(i in array){
            t = {};
            t.id = array[i][0];
            t.name = array[i][1];
            t.price = array[i][2];
            t.quantity = array[i][3];
            e.push(t);
          }
          return e;
       })(array);
       console.log(obj)

ContentLicense: CC BY-SA 3.0


问:
Uploading a file from window.onbeforeunload()
In my application I need to make sure that if a user moves away from the application (by closing the tab, closing the browser, or navigation to another page) that if they try to come back to the application (using the back button, history, or typing the link) they are directed to a screen that makes them log back in.

I think I have this all worked out:

On every page, check to see if my session is available.

If it is, move on.  If not, redirect to "You must log in again." page.

On the window.onbeforeunload() event, run a destroy.php script.

The destroy script kills the session.

But I can NOT get my destroy script loaded from the onbeforeunload() event.

Here is the index file, that starts things off:

```<code><?php

/***********************
INDEX for CloseTab test
************************/

// Start the session
echo "```";
echo "Starting session now...";
session_start();

// Put something in the variable that we can get on another page
$_SESSION["name"] = "Joe";
echo "\nJust set session var 'name' to 'Joe'.";

?>

<a href= <?php echo "home.php"; ?> > Click here to open Home page
```

<p>Here is the HOME page, just to have somewhere to go and test for the session:</p>

<p>
    </p>

```

    <?php

    // Start the session
    session_start();

    // See if there is any indication that a session is not available.
    // Test with closing tab, closing browser, navigating away from page.
    // We want to see this message if the user is coming here from anywhere except the index page.
    // Test back button, typing the URL, browser history.
    if ( (!isset($_SESSION)) || (session_status() == PHP_SESSION_NONE) || (count($_SESSION) < 1) ) {
        echo "```";
        echo "Your session is not longer active.  Log in again.";
        echo "\n\nPretending to go to a login page...";
        exit;
    }

    ?>

    <!-- If the session is good, we MUST have come from index page, and can access the session var. -->
    <div class="container">
        <h1>Home Page</h1>
        <h2>Here is the name from the session var: <?php echo $_SESSION["name"]; ?> </h2>
    </div>

<div>
    <h3><a href= <?php echo "destroy.php"; ?> > Click here to log out</a></h3>
</div>

</html>
</code>```

Here is my javascript code:

```<code>/***********************
my_scripts.js
************************/

console.log("in js file");

// Before a page unloads, run the destroy code
window.onbeforeunload = function() {
    console.log("inside onbeforeunload");             // I get this to print

    // Try to execute with AJAX call                  // Nothing in the middle seems to be running
    $.ajax({
        type: "GET",
        url: "destroy.php",
        async: false
     });

    // Try with jQuery syntax
    $("container").load("destroy.php");

   console.log("Got this far");                       // I get this to print
}
</code>```

Here is the destroy code I am trying to load:

```<code><?php

/******************************************************************
Destroy
- Clears the session var and destroys the session if user leaves app.
******************************************************************/

// Unset all of the session variables and destroy the session.
session_start();
$_SESSION = array();
session_destroy();

?>

<script type="text/javascript">
    // Place message in the console that we can see even if the window closes.
    console.log("DONE!  Session destroyed.")
</script>
</code>```

答:
You need to be careful with onbeforeunload.  Browsers don't let you do too much in this event.

If you want to make an AJAX call, you need to add async: false.  That's something that's usually discouraged, but here, if the call is asynchronous, then the browser will probably finish the event and close the page before the call is done.

```<code>$.ajax({
    type: "GET",
    url: "destroy.php",
    async: false
 });
</code>```

Body:
In my application I need to make sure that if a user moves away from the application (by closing the tab, closing the browser, or navigation to another page) that if they try to come back to the application (using the back button, history, or typing the link) they are directed to a screen that makes them log back in.

I think I have this all worked out:

On every page, check to see if my session is available.

If it is, move on.  If not, redirect to "You must log in again." page.

On the window.onbeforeunload() event, run a destroy.php script.

The destroy script kills the session.

But I can NOT get my destroy script loaded from the onbeforeunload() event.

Here is the index file, that starts things off:

<?php

/***********************
INDEX for CloseTab test
************************/

// Start the session
echo "
";
echo "Starting session now...";
session_start();

// Put something in the variable that we can get on another page
$_SESSION["name"] = "Joe";
echo "\nJust set session var 'name' to 'Joe'.";

?>

<a href= <?php echo "home.php"; ?> > Click here to open Home page

Here is the HOME page, just to have somewhere to go and test for the session:

    <?php

    // Start the session
    session_start();

    // See if there is any indication that a session is not available.
    // Test with closing tab, closing browser, navigating away from page.
    // We want to see this message if the user is coming here from anywhere except the index page.
    // Test back button, typing the URL, browser history.
    if ( (!isset($_SESSION)) || (session_status() == PHP_SESSION_NONE) || (count($_SESSION) < 1) ) {
        echo "
";
        echo "Your session is not longer active.  Log in again.";
        echo "\n\nPretending to go to a login page...";
        exit;
    }

    ?>

Home Page

Here is the name from the session var: <?php echo $_SESSION["name"]; ?>

<a href= <?php echo "destroy.php"; ?> > Click here to log out

Here is my javascript code:

/***********************
my_scripts.js
************************/

console.log("in js file");

// Before a page unloads, run the destroy code
window.onbeforeunload = function() {
    console.log("inside onbeforeunload");             // I get this to print

    // Try to execute with AJAX call                  // Nothing in the middle seems to be running
    $.ajax({
        type: "GET",
        url: "destroy.php",
        async: false
     });

    // Try with jQuery syntax
    $("container").load("destroy.php");

   console.log("Got this far");                       // I get this to print
}

Here is the destroy code I am trying to load:

<?php

/******************************************************************
Destroy
- Clears the session var and destroys the session if user leaves app.
******************************************************************/

// Unset all of the session variables and destroy the session.
session_start();
$_SESSION = array();
session_destroy();

?>

Body:
You need to be careful with onbeforeunload.  Browsers don't let you do too much in this event.

If you want to make an AJAX call, you need to add async: false.  That's something that's usually discouraged, but here, if the call is asynchronous, then the browser will probably finish the event and close the page before the call is done.

$.ajax({
    type: "GET",
    url: "destroy.php",
    async: false
 });


问:
DH key size must be multiple of 64, and can only range from 512 to 2048 (inclusive)
I have a set-up in which I am executing a build from Jenkins on a Solaris Server connecting via sshexec task in ANT.

On trigerring the build, it is throwing below error:

com.jcraft.jsch.JSchException: Session.connect:
  java.security.InvalidAlgorithmParameterException: DH key size must be
  multiple of 64, and can only range from 512 to 2048 (inclusive). The
  specific key size 2047 is not supported.

After some google search, I came to know that it might be fixed by updating to Java 8. I did that, however, still no success.

Can anyone please let me know how to fix it?

答:
Our fix:

```<code>Security.insertProviderAt(new BouncyCastleProvider(), 1)
</code>```

we were using Jsch 0.1.54 directly to connect to an SFT server and saw:

java.security.InvalidAlgorithmParameterException: DH key size must be multiple of 64, and can only range from 512 to 4096 (inclusive). The specific key size 2047 is not supported

possibly related

JDK-8164963: InvalidAlgorithmParameterException prime size issue after JDK upgrade with JSCH libraries.

DHGEX failing with 2048-bit key under Java 8, but succeeding with 1024-bit key

Body:
Our fix:

Security.insertProviderAt(new BouncyCastleProvider(), 1)

we were using Jsch 0.1.54 directly to connect to an SFT server and saw:

java.security.InvalidAlgorithmParameterException: DH key size must be multiple of 64, and can only range from 512 to 4096 (inclusive). The specific key size 2047 is not supported

possibly related

JDK-8164963: InvalidAlgorithmParameterException prime size issue after JDK upgrade with JSCH libraries.

DHGEX failing with 2048-bit key under Java 8, but succeeding with 1024-bit key


问:
Load CSV into Redshift, injecting additional information
I have some exported_data.csv, and I have some corresponding Redshift table, and I have a COPY:

```<code>COPY(
  c1,
  c2,
  c3,
  ...
) from "s3://bucket/exported_data.csv"
</code>```

What I want to do is add a column source_file to the table, and populate it with arbitrary information defined in the COPY statement (or some other set of statements); in this example, the name of the file the row came from.

I can't use UPDATE due to how much data I'm interacting with (takes just plain too long).

It doesn't look like I can just use DEFAULT, since I need to be able to change the information when the name of the source file is different, but Redshift doesn't let you change the default value of a column. (Otherwise, I'd just change the default val for the column, do the copy, change the default val, do the copy from the next CSV file...)

I'm exploring "staging tables", but figured I'd ask here if someone has a ready-made answer while I explore.

答:
This is not possible. But I can suggest you 2 workaround.

Pre-Process: You would have to add that extra column with data before pushing the data into redshift which sounds like a difficult solution for your business case.

Post-Process: Staging table is the best way to do this. Push your data into redshift staging table - Process data - then push into redshift final table.
Note - Running update on redshift gets expensive as data grows, try to avoid as much as possible or else you will end up vacumming a lot which uses a lot of redshift processing resources.

If you want all your rows added in a single COPY command to have the same value of source_file, then you may COPY data into staging table, then add source_file column into that table, then insert all data from the staging table into final table like:

```<code>CREATE TABLE destination_staging (LIKE destination);
ALTER TABLE destination_staging DROP COLUMN source_file ;
COPY destination_staging FROM 's3://data/destination/(...)' (...)
ALTER TABLE destination_staging ADD COLUM source_file VARCHAR(99);
INSERT INTO destination SELECT * FROM destination_staging;
DROP TABLE destination_staging;
</code>```

If I’ve made a bad assumption please comment and I’ll refocus my answer.

Body:
I have some exported_data.csv, and I have some corresponding Redshift table, and I have a COPY:

COPY(
  c1,
  c2,
  c3,
  ...
) from "s3://bucket/exported_data.csv"

What I want to do is add a column source_file to the table, and populate it with arbitrary information defined in the COPY statement (or some other set of statements); in this example, the name of the file the row came from.

I can't use UPDATE due to how much data I'm interacting with (takes just plain too long).

It doesn't look like I can just use DEFAULT, since I need to be able to change the information when the name of the source file is different, but Redshift doesn't let you change the default value of a column. (Otherwise, I'd just change the default val for the column, do the copy, change the default val, do the copy from the next CSV file...)

I'm exploring "staging tables", but figured I'd ask here if someone has a ready-made answer while I explore.

Body:
This is not possible. But I can suggest you 2 workaround.

Pre-Process: You would have to add that extra column with data before pushing the data into redshift which sounds like a difficult solution for your business case.

Post-Process: Staging table is the best way to do this. Push your data into redshift staging table - Process data - then push into redshift final table.
Note - Running update on redshift gets expensive as data grows, try to avoid as much as possible or else you will end up vacumming a lot which uses a lot of redshift processing resources.

If you want all your rows added in a single COPY command to have the same value of source_file, then you may COPY data into staging table, then add source_file column into that table, then insert all data from the staging table into final table like:

CREATE TABLE destination_staging (LIKE destination);
ALTER TABLE destination_staging DROP COLUMN source_file ;
COPY destination_staging FROM 's3://data/destination/(...)' (...)
ALTER TABLE destination_staging ADD COLUM source_file VARCHAR(99);
INSERT INTO destination SELECT * FROM destination_staging;
DROP TABLE destination_staging;

If I’ve made a bad assumption please comment and I’ll refocus my answer.


问:
How to convert numbers represented as characters for short into numeric in Python
I have a column in my data frame which has values like '3.456B' which actually stands for 3.456 Billion (and similar notation for Million). How to convert this string form to correct numeric representation?

This shows the data frame:

```<code>import pandas as pd
data_csv = pd.read_csv('https://biz.yahoo.com/p/csv/422conameu.csv')
data_csv
</code>```

This is a sample value:

```<code>data_csv['Market Cap'][0]
type(data_csv['Market Cap'][0])
</code>```

I tried this:

```<code>data_csv.loc[data_csv['Market Cap'].str.contains('B'), 'Market Cap'] = data_csv['Market Cap'].str.replace('B', '').astype(float).fillna(0.0)
data_csv
</code>```

But unfortunately there are also values with 'M' at the end which denotes Millions. It returns error as follows:

```<code>ValueError: invalid literal for float(): 6.46M
</code>```

How can I replace both B and M with appropriate values in this column? Is there a better way to do it?

答:
Assuming all entries have a letter at the end, you can do this:

```<code>d = {'K': 1000, 'M': 1000000, 'B': 1000000000}
df.loc[:, 'Market Cap'] = pd.to_numeric(df['Market Cap'].str[:-1]) * \
    df['Market Cap'].str[-1].replace(d)
</code>```

This converts everything but the last character into a numeric value, then multiplies it by the number equivalent to the letter in the last character.

Body:
I have a column in my data frame which has values like '3.456B' which actually stands for 3.456 Billion (and similar notation for Million). How to convert this string form to correct numeric representation?

This shows the data frame:

import pandas as pd
data_csv = pd.read_csv('https://biz.yahoo.com/p/csv/422conameu.csv')
data_csv

This is a sample value:

data_csv['Market Cap'][0]
type(data_csv['Market Cap'][0])

I tried this:

data_csv.loc[data_csv['Market Cap'].str.contains('B'), 'Market Cap'] = data_csv['Market Cap'].str.replace('B', '').astype(float).fillna(0.0)
data_csv

But unfortunately there are also values with 'M' at the end which denotes Millions. It returns error as follows:

ValueError: invalid literal for float(): 6.46M

How can I replace both B and M with appropriate values in this column? Is there a better way to do it?

Body:
Assuming all entries have a letter at the end, you can do this:

d = {'K': 1000, 'M': 1000000, 'B': 1000000000}
df.loc[:, 'Market Cap'] = pd.to_numeric(df['Market Cap'].str[:-1]) * \
    df['Market Cap'].str[-1].replace(d)

This converts everything but the last character into a numeric value, then multiplies it by the number equivalent to the letter in the last character.


问:
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

```<code>/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);
</code>```

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

答:
The others have already pointed out this has undefined behaviour. I'd just add that the really simplest way to accomplish your task (to allow only one thread executing part of code) is to use a simple mutex - you need the threads executing that code to be MUTally EXclusive, and that's where mutex came to its name :-)

If you need the code to be ran in a specific thread (like Java AWT), then you need conditional variables. However, you should think twice whether this solution actually pays off. Imagine, how many context switches you need if you call your "Insert operation" 10000 times per second.

Title: pthread_join - multiple threads waiting

Body:
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

LastEditorDisplayName: Hosam Aly

OwnerDisplayName: jpalecek

ContentLicense: CC BY-SA 2.5


问:
Cannot Get Route Symfony
As the title say explecitly, I don't manage to get some specific route I recently added.
My symfony version : 2.8.18.
So here are the details :

Route I try to match :
 - /platform/cat
 - /platform/cat/{id}

File - app/config/routing.yml :

```<code>gb_platform:
resource: "@GBPlatformBundle/Resources/config/routing.yml"
prefix:   /platform
</code>```

File - GB\PlatformBundle\Resources\config\routing.yml :

```<code>    gb_platform_home_:
    path :   /
      defaults: { _controller: GBPlatformBundle:Advert:index }

gb_platform_home:
    path :   /{page}
    defaults:
        _controller : GBPlatformBundle:Advert:index
        page: 1
    requirements:
        page: \d*

gb_platform_view:
    path :   /advert/{id}
    defaults: { _controller : GBPlatformBundle:Advert:view }
    requirements:
        id: \d+

gb_platform_add:
    path :   /add
    defaults: { _controller : GBPlatformBundle:Advert:add }

gb_platform_edit:
    path :   /edit/{id}
    defaults: { _controller : GBPlatformBundle:Advert:edit }
    requirements:
        id: \d+

gb_platform_delete:
    path :   /delete/{id}
    defaults: { _controller : GBPlatformBundle:Advert:delete }
    requirements:
        id: \d+

gb_platform_cat:
    path :   /cat
    defaults: { _controller : GBPlatformBundle:Category:index }

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: \d+
</code>```

File - GB\PlatformBundle\Resources\controller\CategoryController.php :

```<code>    <?php

namespace GB\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;

use GB\PlatformBundle\Entity\Advert;
use GB\PlatformBundle\Entity\Category;

class CategoryController extends Controller
{
    public function indexAction(Request $request)
    {

    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $catRepo = $em
            ->getRepository('GBPlatformBundle:Category');
        $cat = $catRepo
            ->find($id);

        if($cat === null)
        {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        return $this->render('GBPlatformBundle:Category:view.html.twig', array(
            'category' => $cat,
            ));
    }
}
</code>```

At the origin, the routing.yml of the bundle was invalid. Once it's fixed, I try to get the both command :

php app/console debug:router

php app/console debug:router gb_platform_cat

php app/console debug:router gb_platform_add

Each command were successfull and I saw no difference between /cat and /add while one match and the other don't.
I tried also many times to clear cache with :

php app/console cache:clear --env prod

Still don't work. I'm confused ...
The error is basic : No route found for "GET /platform/cat/7

答:
According to the docs, you need quotes around the pattern for requirements.</p>

```<code>gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: '\d+'
</code>```

Title: Cannot Get Route Symfony

Body:
As the title say explecitly, I don't manage to get some specific route I recently added.
My symfony version : 2.8.18.
So here are the details :

Route I try to match :
 - /platform/cat
 - /platform/cat/{id}

File - app/config/routing.yml :

gb_platform:
resource: "@GBPlatformBundle/Resources/config/routing.yml"
prefix:   /platform

File - GB\PlatformBundle\Resources\config\routing.yml :

    gb_platform_home_:
    path :   /
      defaults: { _controller: GBPlatformBundle:Advert:index }

gb_platform_home:
    path :   /{page}
    defaults:
        _controller : GBPlatformBundle:Advert:index
        page: 1
    requirements:
        page: \d*

gb_platform_view:
    path :   /advert/{id}
    defaults: { _controller : GBPlatformBundle:Advert:view }
    requirements:
        id: \d+

gb_platform_add:
    path :   /add
    defaults: { _controller : GBPlatformBundle:Advert:add }

gb_platform_edit:
    path :   /edit/{id}
    defaults: { _controller : GBPlatformBundle:Advert:edit }
    requirements:
        id: \d+

gb_platform_delete:
    path :   /delete/{id}
    defaults: { _controller : GBPlatformBundle:Advert:delete }
    requirements:
        id: \d+

gb_platform_cat:
    path :   /cat
    defaults: { _controller : GBPlatformBundle:Category:index }

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: \d+

File - GB\PlatformBundle\Resources\controller\CategoryController.php :

    <?php

namespace GB\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;

use GB\PlatformBundle\Entity\Advert;
use GB\PlatformBundle\Entity\Category;

class CategoryController extends Controller
{
    public function indexAction(Request $request)
    {

    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $catRepo = $em
            ->getRepository('GBPlatformBundle:Category');
        $cat = $catRepo
            ->find($id);

        if($cat === null)
        {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        return $this->render('GBPlatformBundle:Category:view.html.twig', array(
            'category' => $cat,
            ));
    }
}

At the origin, the routing.yml of the bundle was invalid. Once it's fixed, I try to get the both command :

php app/console debug:router

php app/console debug:router gb_platform_cat

php app/console debug:router gb_platform_add

Each command were successfull and I saw no difference between /cat and /add while one match and the other don't.
I tried also many times to clear cache with :

php app/console cache:clear --env prod

Still don't work. I'm confused ...
The error is basic : No route found for "GET /platform/cat/7

Body:
According to the docs, you need quotes around the pattern for requirements.

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: '\d+'


问:
How do I overwrite the value of a specific index/column in a DataFrame?
I have a dataframe Exposure with zeros constructed as follows:

```<code>Exposure = pd.DataFrame(0, index=dates, columns=tickers)
</code>```

and a DataFrame df with data.

I want to fill some of the data from df to Exposure:

```<code>    for index, column in df.iterrows():
        # value of df(index,column) to be filled at Exposure(index,column)
</code>```

How do I overwrite the value of at (index,column) of Exposure with the value of df(index,column)?

答:
The best way is:</p>

```<code>df.loc[index, column] = value
</code>```

Body:
I have a dataframe Exposure with zeros constructed as follows:

Exposure = pd.DataFrame(0, index=dates, columns=tickers)

and a DataFrame df with data.

I want to fill some of the data from df to Exposure:

    for index, column in df.iterrows():
        # value of df(index,column) to be filled at Exposure(index,column)

How do I overwrite the value of at (index,column) of Exposure with the value of df(index,column)?

Body:
The best way is:

df.loc[index, column] = value


问:
How to filter an ordered list stored into a string
Is it possible in bash to filter out a part of a string with another given string ?

I have a fixed list of motifs defined in a string. The order IS important and I want to keep only the parts that are passed as a parameter ?

```<code>myDefaultList="s,t,a,c,k"  #order is important
toRetains="k,t,c,u"  #provided by the user, order is not enforced

retained=filter $myDefaultList $toRetains # code to filter

echo $retained  # will print t,c,k"
</code>```

I can write an ugly method that will use IFS, arrays and loops, but I wonder if there's a 'clever' way to do that, using built-in commands ?

答:
Since you mention in your comments that you are open to sed/awk , check also this with GNU awk:</p>

```<code>$ echo "$a"
s,t,a,c,k

$ echo "$b"
k,t,c,u

$ awk -v RS=",|\n" 'NR==FNR{a[$1];next}$1 in a{printf("%s%s",$1,RT)}' <(echo "$b") <(echo "$a")
t,c,k
</code>```

Body:
Is it possible in bash to filter out a part of a string with another given string ?

I have a fixed list of motifs defined in a string. The order IS important and I want to keep only the parts that are passed as a parameter ?

myDefaultList="s,t,a,c,k"  #order is important
toRetains="k,t,c,u"  #provided by the user, order is not enforced

retained=filter $myDefaultList $toRetains # code to filter

echo $retained  # will print t,c,k"

I can write an ugly method that will use IFS, arrays and loops, but I wonder if there's a 'clever' way to do that, using built-in commands ?

Body:
Since you mention in your comments that you are open to sed/awk , check also this with GNU awk:

$ echo "$a"
s,t,a,c,k

$ echo "$b"
k,t,c,u

$ awk -v RS=",|\n" 'NR==FNR{a[$1];next}$1 in a{printf("%s%s",$1,RT)}' <(echo "$b") <(echo "$a")
t,c,k


问:
How to control the language in which model validation errors are displayed
In an ASP.NET MVC application, changing the Thread.CurrentThread.CurrentCulture[UI] can change the way MVC picks messages from resources. In the example application I've created to present the problem, there are two resource file - Res.resx for the English messages and Res.es.resx for the Spanish messages.

However, error messages resulting from the model validation always display in English.

My question is, how can I control the language in which the model validation error messages are displayed?

Below are parts of an example application I've wrote (based on the default ASP.NET MVC application) to demonstrate this problem.

Screenshots of how it looks in the browser:

https://dl.dropboxusercontent.com/u/4453002/SO_LanguageOfValidation.png

ViewModel and Controller - HomeController.cs :

```<code>using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;

namespace SO_ValidationMessageInEnglish.Controllers {

  /// <summary>
  /// A very basic view model.
  /// </summary>
  public class ViewModel {

    [Display(Name = "Message", ResourceType = typeof(Res))]
    [DisplayName("Message")]
    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "MessageRequired", ErrorMessageResourceType = typeof(Res))]
    public string Message { get; set; }

    public string Language { get; set; }
  }

  public class HomeController : Controller {

    public ActionResult Index(string language = "en") {
      Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
      return View();
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult IndexPost(ViewModel foo) {
      Thread.CurrentThread.CurrentCulture = new CultureInfo(foo.Language ?? "en");
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(foo.Language ?? "en");
      return View(foo);
    }

  }
}
</code>```

View - Index.cshtml :

```<code>@model SO_ValidationMessageInEnglish.Controllers.ViewModel
@using SO_ValidationMessageInEnglish
@{ ViewBag.Title = Res.Title; }
@Res.CurrentMessage:<br />
<h2>@((Model != null) ? Model.Message : Res.Default)</h2>
<p />
@using (Html.BeginForm("Index", "Home", FormMethod.Post, null)) {
    @Html.LabelFor(m => m.Message)
    @Html.TextBoxFor(m => m.Message)
    @Html.HiddenFor(m => m.Language)
    @Html.ValidationMessageFor(m => m.Message)
    <input type="submit" value="@Res.Submit" />
}
</code>```

答:
I guess, one way to do that is to use your own model binder (although that might cause other problems in some situations). That will execute only when there is a model on the action, thus you might have to set the culture in two places (one for all actions and this for the model validation in particular):</p>

```<code>public class MyModelBinder : DefaultModelBinder
{

    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
    {
        var un = HttpContext.Current.User.Identity.Name;
        if (!string.IsNullOrWhiteSpace(un))
        {
            var userLanguageCode = .......
            var culture = CultureInfo.GetCultureInfo(userLanguageCode ?? "en-US");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
</code>```

Body:
In an ASP.NET MVC application, changing the Thread.CurrentThread.CurrentCulture[UI] can change the way MVC picks messages from resources. In the example application I've created to present the problem, there are two resource file - Res.resx for the English messages and Res.es.resx for the Spanish messages.

However, error messages resulting from the model validation always display in English.

My question is, how can I control the language in which the model validation error messages are displayed?

Below are parts of an example application I've wrote (based on the default ASP.NET MVC application) to demonstrate this problem.

Screenshots of how it looks in the browser:

https://dl.dropboxusercontent.com/u/4453002/SO_LanguageOfValidation.png

ViewModel and Controller - HomeController.cs :

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;

namespace SO_ValidationMessageInEnglish.Controllers {

  ///
  /// A very basic view model.
  ///
  public class ViewModel {

    [Display(Name = "Message", ResourceType = typeof(Res))]
    [DisplayName("Message")]
    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "MessageRequired", ErrorMessageResourceType = typeof(Res))]
    public string Message { get; set; }

    public string Language { get; set; }
  }

  public class HomeController : Controller {

    public ActionResult Index(string language = "en") {
      Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
      return View();
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult IndexPost(ViewModel foo) {
      Thread.CurrentThread.CurrentCulture = new CultureInfo(foo.Language ?? "en");
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(foo.Language ?? "en");
      return View(foo);
    }

  }
}

View - Index.cshtml :

@model SO_ValidationMessageInEnglish.Controllers.ViewModel
@using SO_ValidationMessageInEnglish
@{ ViewBag.Title = Res.Title; }
@Res.CurrentMessage:

@((Model != null) ? Model.Message : Res.Default)

@using (Html.BeginForm("Index", "Home", FormMethod.Post, null)) {
    @Html.LabelFor(m => m.Message)
    @Html.TextBoxFor(m => m.Message)
    @Html.HiddenFor(m => m.Language)
    @Html.ValidationMessageFor(m => m.Message)
    <input type="submit" value="@Res.Submit" />
}

Body:
I guess, one way to do that is to use your own model binder (although that might cause other problems in some situations). That will execute only when there is a model on the action, thus you might have to set the culture in two places (one for all actions and this for the model validation in particular):

public class MyModelBinder : DefaultModelBinder
{

    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
    {
        var un = HttpContext.Current.User.Identity.Name;
        if (!string.IsNullOrWhiteSpace(un))
        {
            var userLanguageCode = .......
            var culture = CultureInfo.GetCultureInfo(userLanguageCode ?? "en-US");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}


问:
Giving database context to object Factory
There is a question I always ask myself when I'm using a Factory pattern inside my code (C#, but it applies to any language I suppose).

I have a "Service" that takes care of interacting with my database, do stuff with objects and interacts with my object model.

This Service uses a Factory sometimes to delegate the instanciation of an object.
But this factory obviously needs to interact by itself with the database to instanciate my object properly.
Is it a good/bad practice to pass the Database context to the Create method for example?

Like this :

```<code>var myNewObject = MyFactory.Create(myDatabaseContext);
</code>```

the other way would be to let the Service always be the only one to talk with the database.

```<code>var myNewObject = MyFactory.Create();
var extraProperty = myDatabaseContext.Get(something);
myNewObject.extraProp = extraProperty;
</code>```

Any advices?

答:
In the project I am working on, we try to keep all database access inside the Service. If the Factory needs objects that must be loaded from the DB, the Service should load them and pass them to the Factory. If the object returned by the Factory shall be persisted, the Service should add it to the DbContext.

This corresponds to the second way you have shown. The advantage is that the Factory can be unit tested without any need to mock the DbContext.

If you want to keep the DB access inside the Factory anyways, I would inject the DbContext into the constructor of the Factory, instead of passing it to the Create() method.

The Service gets an instance of the Factory injected in turn (instead of accessing static methods of the Factory). Again, this will make mocking much easier.

```<code>public class Service {

    private readonly IMyDbContext _myDatabaseContext;
    private readonly IMyFactory _myfactory;

    public Service (IMyDbContext myDbContext, IMyFactory myfactory) {
        _myDatabaseContext = myDbContext;
        _myfactory = myfactory
    }

    public void Create() {
        var extraProperty = myDatabaseContext.Get(something);
        var myNewObject = _myFactory.Create(extraProperty);
        _myDatabaseContext.Add(myNewObject);
        _myDatabaseContext.SaveChanges();
    }
}
</code>```

Body:
There is a question I always ask myself when I'm using a Factory pattern inside my code (C#, but it applies to any language I suppose).

I have a "Service" that takes care of interacting with my database, do stuff with objects and interacts with my object model.

This Service uses a Factory sometimes to delegate the instanciation of an object.
But this factory obviously needs to interact by itself with the database to instanciate my object properly.
Is it a good/bad practice to pass the Database context to the Create method for example?

Like this :

var myNewObject = MyFactory.Create(myDatabaseContext);

the other way would be to let the Service always be the only one to talk with the database.

var myNewObject = MyFactory.Create();
var extraProperty = myDatabaseContext.Get(something);
myNewObject.extraProp = extraProperty;

Any advices?

Body:
In the project I am working on, we try to keep all database access inside the Service. If the Factory needs objects that must be loaded from the DB, the Service should load them and pass them to the Factory. If the object returned by the Factory shall be persisted, the Service should add it to the DbContext.

This corresponds to the second way you have shown. The advantage is that the Factory can be unit tested without any need to mock the DbContext.

If you want to keep the DB access inside the Factory anyways, I would inject the DbContext into the constructor of the Factory, instead of passing it to the Create() method.

The Service gets an instance of the Factory injected in turn (instead of accessing static methods of the Factory). Again, this will make mocking much easier.

public class Service {

    private readonly IMyDbContext _myDatabaseContext;
    private readonly IMyFactory _myfactory;

    public Service (IMyDbContext myDbContext, IMyFactory myfactory) {
        _myDatabaseContext = myDbContext;
        _myfactory = myfactory
    }

    public void Create() {
        var extraProperty = myDatabaseContext.Get(something);
        var myNewObject = _myFactory.Create(extraProperty);
        _myDatabaseContext.Add(myNewObject);
        _myDatabaseContext.SaveChanges();
    }
}


问:
pitest - PIT requires either JUnit 4 (but can run JUnit 3 tests) or TestNG
I am trying to apply mutation testing on Apache Airavata (v0.16) using pitest. I added the following lines into pom.xml file under build plugins tag:

```<code><plugin>
    <groupId>org.pitest</groupId>
    <artifactId>pitest-maven</artifactId>
    <version>1.1.11</version>
 </plugin>
</code>```

It gives me the following error.

```<code>[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.012 s
[INFO] Finished at: 2017-03-30T14:27:44+03:00
[INFO] Final Memory: 21M/212M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.pitest:pitest-maven:1.1.11:mutationCoverage (default-cli) on project airavata-server-configuration: Execution default-cli of goal org.pitest:pitest-maven:1.1.11:mutationCoverage failed: No test library found on classpath. PIT requires either JUnit 4 (but can run JUnit 3 tests) or TestNG
[ERROR] See http://pitest.org for more details.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :airavata-server-configuration
</code>```

I do not have TestNG but the junit4 path is included in the CLASSPATH. I tried providing some targetted test cases as following but it did not work either.

```<code><plugin>
    <groupId>org.pitest</groupId>
    <artifactId>pitest-maven</artifactId>
    <version>1.1.11</version>
    <configuration>
        <targetTests>
            <param>org.apache.archiva.common.utils*</param>
        </targetTests>
    </configuration>
</plugin>
</code>```

I have also tried the following tag but it did not help at all.

```<code><failWhenNoMutations>false</failWhenNoMutations>
</code>```

答:
Archiva seems to contain a number of modules that contain no source or tests.

The 1.1.12 release of pitest will auto-skip these (see 314), but until that is released you will need to set the skip property in each module that does not contain tests.

Body:
I am trying to apply mutation testing on Apache Airavata (v0.16) using pitest. I added the following lines into pom.xml file under build plugins tag:

<plugin>
    <groupId>org.pitest</groupId>
    <artifactId>pitest-maven</artifactId>
    <version>1.1.11</version>
 </plugin>

It gives me the following error.

[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.012 s
[INFO] Finished at: 2017-03-30T14:27:44+03:00
[INFO] Final Memory: 21M/212M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.pitest:pitest-maven:1.1.11:mutationCoverage (default-cli) on project airavata-server-configuration: Execution default-cli of goal org.pitest:pitest-maven:1.1.11:mutationCoverage failed: No test library found on classpath. PIT requires either JUnit 4 (but can run JUnit 3 tests) or TestNG
[ERROR] See http://pitest.org for more details.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :airavata-server-configuration

I do not have TestNG but the junit4 path is included in the CLASSPATH. I tried providing some targetted test cases as following but it did not work either.

<plugin>
    <groupId>org.pitest</groupId>
    <artifactId>pitest-maven</artifactId>
    <version>1.1.11</version>
    <configuration>
        <targetTests>
            <param>org.apache.archiva.common.utils*</param>
        </targetTests>
    </configuration>
</plugin>

I have also tried the following tag but it did not help at all.

<failWhenNoMutations>false</failWhenNoMutations>


问:
unity C# bool and to set false by time....?
this is My Code:

```<code>if ( run && Input.GetKeyDown (KeyCode.K)) {
    anim.SetInteger ("State", 4);
    slide = true;
}

if (Input.GetKeyUp (KeyCode.K)) {
    slide = false;
    anim.SetInteger ("State", 0);
}
</code>```

My problem: if I hold the (KeyCode.K) than slide is still true which I don´t want.

I need set slide to true just once, or to false after 2 seconds only.

I hope you all understand what I want.

答:
```<code>void Update{

    if ( key_K && run && Input.GetKeyDown (KeyCode.K)) {
            key_K = false;

            StartCoroutine ("coRoutine_keyK");

        }

}

IEnumerator coRoutine_keyK(){
        slide = true;
        anim.SetInteger ("State", 4);
        yield return new WaitForSeconds (0.5f);

        slide = false;
        anim.SetInteger ("State", 0);

        key_K = true;
    }
</code>```

Body:
this is My Code:

if ( run && Input.GetKeyDown (KeyCode.K)) {
    anim.SetInteger ("State", 4);
    slide = true;
}

if (Input.GetKeyUp (KeyCode.K)) {
    slide = false;
    anim.SetInteger ("State", 0);
}

My problem: if I hold the (KeyCode.K) than slide is still true which I don´t want.

I need set slide to true just once, or to false after 2 seconds only.

I hope you all understand what I want.


问:
CSS Animation and Columns in Google Chrome
I've encountered some trouble with animating icons in Google Chrome. I tested this in Safari and Firefox, and my code works there, so I'm not sure if this is an error on my part or an issue with the browser. I'm coding icons in columns so that they stack evenly in a responsive layout, but when I put them in columns, all icons except the first one move down the page.

Any help either identifying what I'm doing wrong or helping to find a workaround would be appreciated. I cut out the media queries in my code for the sake of simplicity posting it here.

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  width: 100%;
  padding: 35px 0px;
  -webkit-columns: 6;
  -moz-columns: 6;
  columns: 6;
}

#pptoc img {}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pptoc">
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im1" class="pptocitem"><br>part 1</a>
  </div>
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im2" class="pptocitem"><span class="test1"><br>part 2</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im3" class="pptocitem"><br>part 3</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im4" class="pptocitem"><br>part 4</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im5" class="pptocitem"><br>part 5</a></div>
<div class="part 6"><img src="http://placehold.it/100x100?text=im6" class="pptocitem"><br>part 6</a></div></code>```

答:
You can either use flexbox as suggested by Michael Coker, or make use will-change CSS property, that hints the browser to expect certain changes in a particular element, and prepare itself for that change.

See how it fixed the flickering of .pptocitem when hovered:

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  width: 100%;
  padding: 35px 0px;
  -webkit-columns: 6;
  -moz-columns: 6;
  columns: 6;
}

#pptoc img {}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem {
  will-change: transform;
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pptoc">
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im1" class="pptocitem"><br>part 1</a>
  </div>
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im2" class="pptocitem"><span class="test1"><br>part 2</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im3" class="pptocitem"><br>part 3</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im4" class="pptocitem"><br>part 4</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im5" class="pptocitem"><br>part 5</a></div>
<div class="part 6"><img src="http://placehold.it/100x100?text=im6" class="pptocitem"><br>part 6</a></div></code>```

Cheers!

Body:
I've encountered some trouble with animating icons in Google Chrome. I tested this in Safari and Firefox, and my code works there, so I'm not sure if this is an error on my part or an issue with the browser. I'm coding icons in columns so that they stack evenly in a responsive layout, but when I put them in columns, all icons except the first one move down the page.

Any help either identifying what I'm doing wrong or helping to find a workaround would be appreciated. I cut out the media queries in my code for the sake of simplicity posting it here.

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  width: 100%;
  padding: 35px 0px;
  -webkit-columns: 6;
  -moz-columns: 6;
  columns: 6;
}

#pptoc img {}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}

part 1

part 2

part 3

part 4

part 5

part 6

Body:
You can either use flexbox as suggested by Michael Coker, or make use will-change CSS property, that hints the browser to expect certain changes in a particular element, and prepare itself for that change.

See how it fixed the flickering of .pptocitem when hovered:

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  width: 100%;
  padding: 35px 0px;
  -webkit-columns: 6;
  -moz-columns: 6;
  columns: 6;
}

#pptoc img {}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem {
  will-change: transform;
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}

<div id="pptoc">
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im1" class="pptocitem"><br>part 1</a>
  </div>
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im2" class="pptocitem"><span class="test1"><br>part 2</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im3" class="pptocitem"><br>part 3</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im4" class="pptocitem"><br>part 4</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im5" class="pptocitem"><br>part 5</a></div>
<div class="part 6"><img src="http://placehold.it/100x100?text=im6" class="pptocitem"><br>part 6</a></div>

Cheers!


问:
PHP how do I get a formated result table of prepared statement as strings
I'm currently working on a small University project and I have to get into PHP. I have a score table where I want to get a ranked list back in PHP. The query works in phpmyadmin, but I just can't get my head around the prepared statement and how to get the results out of it. Here my code:

```<code>    $con = getConnection ();

if (!$con) {
    exit();
}

$stmt = $con -> prepare("SELECT NICKNAME, HIGHSCORE, @curRank := @curRank + 1 AS RANK FROM scores p, (SELECT @curRank := 0) r ORDER BY HIGHSCORE DESC;");

$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows;  //count number of rows in the result

// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if (!$result_array = $result->fetch_assoc()) {
}

for ($j=0; $j<=$num_rows ;$j++){
        $rows[$j]=$result->fetch_row();
        print_r($rows[$j]);
}
mysqli_close($con);
</code>```

}

and this is how the print_r looks like:

Array ( [0] => guvtg [1] => 234 [2] => 2 ) Array ( [0] => guvtgloa [1]
  => 228 [2] => 3 ) Array ( [0] => guvtgloakkschmua [1] => 226 [2] => 4 ) Array ( [0] => guvtgloakk [1] => 182 [2] => 5 )

As you can see I'm getting the whole array, but I just want and output like this:

guvtg , 234 , 2
guvtgloa , 228 , 3
etc..

Does anybody know how to get a proper result? Thank you

答:
You'll allways get arrays from a database query, but it sounds like you just want to format the output differently. You could try this:

change

```<code>print_r($rows[$j]);
</code>```

into

```<code>echo implode(', ', $rows[$j]), "\n";
</code>```

implode will join the elements of every array with a comma+space in between, and by putting a newline after every record, the rows will each go on their own line.

Body:
I'm currently working on a small University project and I have to get into PHP. I have a score table where I want to get a ranked list back in PHP. The query works in phpmyadmin, but I just can't get my head around the prepared statement and how to get the results out of it. Here my code:

    $con = getConnection ();

if (!$con) {
    exit();
}

$stmt = $con -> prepare("SELECT NICKNAME, HIGHSCORE, @curRank := @curRank + 1 AS RANK FROM scores p, (SELECT @curRank := 0) r ORDER BY HIGHSCORE DESC;");

$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows;  //count number of rows in the result

// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if (!$result_array = $result->fetch_assoc()) {
}

for ($j=0; $j<=$num_rows ;$j++){
        $rows[$j]=$result->fetch_row();
        print_r($rows[$j]);
}
mysqli_close($con);

}

and this is how the print_r looks like:

Array ( [0] => guvtg [1] => 234 [2] => 2 ) Array ( [0] => guvtgloa [1]
  => 228 [2] => 3 ) Array ( [0] => guvtgloakkschmua [1] => 226 [2] => 4 ) Array ( [0] => guvtgloakk [1] => 182 [2] => 5 )

As you can see I'm getting the whole array, but I just want and output like this:

guvtg , 234 , 2
guvtgloa , 228 , 3
etc..

Does anybody know how to get a proper result? Thank you

Body:
You'll allways get arrays from a database query, but it sounds like you just want to format the output differently. You could try this:

change

print_r($rows[$j]);

into

echo implode(', ', $rows[$j]), "\n";

implode will join the elements of every array with a comma+space in between, and by putting a newline after every record, the rows will each go on their own line.


问:
Scrapy python json output, clear file before writing
I am currently using Scrapy to gather data and output to a json file with

```<code>scrapy crawl foobar -a category=foo -o bar.json
</code>```

Although this will append to the bar.json file rather than rewriting it. I would like to clear the file and rewrite over it, is this possible with a scrapy argument at all?

Or would I be required to clear it outwith scrapy first?

Many thanks.

答:
Modify script like following:</p>

```<code>class MySpider(Spider):
    """
    Main crawler
    """
    name = "mucrawler"
    allowed_domains = ["sss.com"]
    start_urls = ["https://www.sdsd/rov/"]

    "Empty output file"
    f = open("bar.json", 'w').close()

    def parse(self, response):
        titles = response.css("td.offer")
</code>```

Body:
I am currently using Scrapy to gather data and output to a json file with

scrapy crawl foobar -a category=foo -o bar.json

Although this will append to the bar.json file rather than rewriting it. I would like to clear the file and rewrite over it, is this possible with a scrapy argument at all?

Or would I be required to clear it outwith scrapy first?

Many thanks.

Body:
Modify script like following:

class MySpider(Spider):
    """
    Main crawler
    """
    name = "mucrawler"
    allowed_domains = ["sss.com"]
    start_urls = ["https://www.sdsd/rov/"]

    "Empty output file"
    f = open("bar.json", 'w').close()

    def parse(self, response):
        titles = response.css("td.offer")


问:
how to merge two array objects in javascript
Just wondering what is my best approach to merge these two arrays together.

example

```<code>var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]
</code>```

Looking to merge them into:

```<code>var c = ["ID":11021, ASSET_NAME:"panda", service_name: ['open requests','open tickets']]
</code>```

any help would be great.

Thanks

答:
You can use one object to store ID's and reduce() to create new array of merged objects.

var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]
var obj = {}

var result = a.concat(b).reduce(function(r, e) {
  if (!obj[e.ID]) {
    obj[e.ID] = {
      ID: e.ID,
      ASSET_NAME: e.ASSET_NAME,
      service_name: []
    }
    r.push(obj[e.ID])
  }
  obj[e.ID].service_name.push(e.SERVICE_NAME)
  return r
}, [])

console.log(JSON.stringify(result, 0, 4))```

Body:
Just wondering what is my best approach to merge these two arrays together.

example

var a = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"Open Ticket"}]
var b = [{"ID":11021,"ASSET_NAME":"panda","SERVICE_NAME":"open requests"}]

Looking to merge them into:

var c = ["ID":11021, ASSET_NAME:"panda", service_name: ['open requests','open tickets']]

any help would be great.

Thanks


问:
How can you use a returned result in a new function without using global variables?
How can you use a returned variable in a new function without using global variables?</p>

```<code>def f():
  var1 = 5
  var2 = 10
  return var1, var2

def g():
  var3 = var1*var2
  return var3
</code>```

答:
Simply</p>

```<code>def g():
  var1,var2 = f()
  var3 = var1*var2
  return var3
</code>```

Body:
How can you use a returned variable in a new function without using global variables?

def f():
  var1 = 5
  var2 = 10
  return var1, var2

def g():
  var3 = var1*var2
  return var3

Body:
Simply

def g():
  var1,var2 = f()
  var3 = var1*var2
  return var3


问:
How to pass information in a Jenkins pipeline job
My pipeline script is configed from SCM.  It has some limitation, for example, I can't use hudson.model in my groovy script.  What I'm doing is always trigger python scripts in my groovy scripts so that I can do more things.  Now, the problem is how can I share information among all of my python scripts.  From example, my groovy scripts are

```<code>node('node1') {
  bat 'python a.py'
}
node('node2') {
  bat 'python b.py'
}
</code>```

a.py is retrieving information from a server, and those information will be used in b.py.  What would be the preferred way to share some information between a.py and b.py?

答: I actually figured this on my own.  Well, yes, my description is not accurate.  What I really wanted is to share information among stages and nodes.  I ended up using the http request plugin.</p>

Body:
My pipeline script is configed from SCM.  It has some limitation, for example, I can't use hudson.model in my groovy script.  What I'm doing is always trigger python scripts in my groovy scripts so that I can do more things.  Now, the problem is how can I share information among all of my python scripts.  From example, my groovy scripts are

node('node1') {
  bat 'python a.py'
}
node('node2') {
  bat 'python b.py'
}

a.py is retrieving information from a server, and those information will be used in b.py.  What would be the preferred way to share some information between a.py and b.py?


问:
Replace last character in sql column
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

```<code>abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test
</code>```

Result should be

```<code>abc
123;ghi;789
test123
thisowns
wer;567;457;test
</code>```

答:
Try this:

```<code>UPDATE <YOUR_TABLE>
SET col1 = LEFT(col1, LEN(col1) - 1)
WHERE RIGHT(col1, 1) = ';'
</code>```

Hope this help!

Title: Replace last character in sql column

Body:
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test

Result should be

abc
123;ghi;789
test123
thisowns
wer;567;457;test

Body:
Try this:

UPDATE <YOUR_TABLE>
SET col1 = LEFT(col1, LEN(col1) - 1)
WHERE RIGHT(col1, 1) = ';'

Hope this help!


问:
My app in firefox and internet explorer looks zoomed in. Is there a viewport setting the load the website more zoomed out?
My app in firefox and internet explorer looks zoomed in. Is there a viewport setting the load the website more zoomed out?

This is my current index.html settings in my angular 2 app:

```<code>    <base href="/"></base>

    <meta charset="UTF-8">
    <meta name="fragment" content="!"/>
    <meta name="application-name" content="test"/>
    <meta name="description" content="test"/>
    <meta name="keywords" content="test"/>
    <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible"/>
</code>```

```<code>    <link rel="icon" type="image/png" href="/favicon32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/favicon96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon16.png" sizes="16x16">
</code>```

答:
As per this page, I used the following code to set my viewport to the zoom level (or lack thereof) that I wanted:

```<code>@-ms-viewport {
  width: 1024px;
  height: 768px;
}
</code>```

I'm working on a horizontal scrolling website/infographic, which is just a single page, and having it zoom in was totally ruining the experience. This worked for me!

Body:
My app in firefox and internet explorer looks zoomed in. Is there a viewport setting the load the website more zoomed out?

This is my current index.html settings in my angular 2 app:

    <base href="/"></base>

    <meta charset="UTF-8">
    <meta name="fragment" content="!"/>
    <meta name="application-name" content="test"/>
    <meta name="description" content="test"/>
    <meta name="keywords" content="test"/>
    <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible"/>

    <link rel="icon" type="image/png" href="/favicon32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/favicon96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon16.png" sizes="16x16">

Body:
As per this page, I used the following code to set my viewport to the zoom level (or lack thereof) that I wanted:

@-ms-viewport {
  width: 1024px;
  height: 768px;
}

I'm working on a horizontal scrolling website/infographic, which is just a single page, and having it zoom in was totally ruining the experience. This worked for me!


问:
Running stages in parallel with Jenkins workflow / pipeline

Please note: the question is based on the old, now called "scripted" pipeline format. When using "declarative pipelines", parallel blocks can be nested inside of stage blocks (see Parallel stages with Declarative Pipeline 1.2).

I'm wondering how parallel steps are supposed to work with Jenkins workflow/pipeline plugin, esp. how to mix them with build stages. I know about the general pattern:

parallel(firstTask: {
  // Do some stuff
}, secondTask: {
  // Do some other stuff in parallel
})
```
<p>However, I'd like to run couple of stages in parallel (on the same node, which has multiple executors), so I tried to add stages like this:</p>
<pre class="lang-groovy prettyprint-override"><code>stage 'A'
// Do some preparation stuff

parallel(firstTask: {
  stage 'B1'
  // Do some stuff
}, secondTask: {
  stage 'B2'
  // Do some other stuff in parallel
})

stage 'C'
// Finalizing stuff
</code>```

This does not work as expected. The "do stuff" tasks are executed in parallel, but the parallel stages end immediately and do not incorporate the stuff they should contain. As a consequence, the Stage View does not show the correct result and also does not link the logs.

Can I build different stages in parallel, or is the "parallel" step only meant to be used within a single stage?

答:
I have just tested the following pipeline and it works

parallel firstBranch: {
    stage ('Starting Test')
    {
        build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}, secondBranch: {
    stage ('Starting Test2')
    {
        build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}
```

This Job named 'trigger-test' accepts one parameter named 'Environment'

Job 'test1' and 'test2' are simple jobs:

Example for 'test1'

One parameter named 'Environment'

Pipeline : echo "$env.Environment-TEST1"

On execution, I am able to see both stages running in the same time

Body:
Please note: the question is based on the old, now called "scripted" pipeline format. When using "declarative pipelines", parallel blocks can be nested inside of stage blocks (see Parallel stages with Declarative Pipeline 1.2).

I'm wondering how parallel steps are supposed to work with Jenkins workflow/pipeline plugin, esp. how to mix them with build stages. I know about the general pattern:

parallel(firstTask: {
  // Do some stuff
}, secondTask: {
  // Do some other stuff in parallel
})

However, I'd like to run couple of stages in parallel (on the same node, which has multiple executors), so I tried to add stages like this:

stage 'A'
// Do some preparation stuff

parallel(firstTask: {
  stage 'B1'
  // Do some stuff
}, secondTask: {
  stage 'B2'
  // Do some other stuff in parallel
})

stage 'C'
// Finalizing stuff

This does not work as expected. The "do stuff" tasks are executed in parallel, but the parallel stages end immediately and do not incorporate the stuff they should contain. As a consequence, the Stage View does not show the correct result and also does not link the logs.

Can I build different stages in parallel, or is the "parallel" step only meant to be used within a single stage?

Body:
I have just tested the following pipeline and it works

parallel firstBranch: {
    stage ('Starting Test')
    {
        build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}, secondBranch: {
    stage ('Starting Test2')
    {
        build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}

This Job named 'trigger-test' accepts one parameter named 'Environment'

Job 'test1' and 'test2' are simple jobs:

Example for 'test1'

One parameter named 'Environment'

Pipeline : echo "$env.Environment-TEST1"

On execution, I am able to see both stages running in the same time


问:
Metabase displays wrong time format
My Data are stored in a MySql Database and i use Metabaseto display the data.

In phpMyAdmineverything looks like it should, but in Metabase the Dates are displayed like they should. The two datetimes types do not really matter but the time type looks like a date altough it's a time.

What can i do so that the time is displayed correctly?

Table Structure:

Table Data:

Metabase:

答:
Try to force date format using DATE_FORMAT/TIME_FORMAT in the output fields list:</p>

```<code>DATE_FORMAT(started, '%Y-%m-%d %H:%i:%s') as started,
TIME_FORMAT(testDuration, '%H:%i:%s') as testDuration
</code>```

Title: Metabase displays wrong time format

Body:
Try to force date format using DATE_FORMAT/TIME_FORMAT in the output fields list:

DATE_FORMAT(started, '%Y-%m-%d %H:%i:%s') as started,
TIME_FORMAT(testDuration, '%H:%i:%s') as testDuration


问:
CUDA, cuBLAS and half precision data types
Since CUDA 7.5/8.0 and devices with Pascal GPUs CUDA supports the half precision (FP16) datatype out of the box. Additionally, many of the BLAS calls inside CUBLAS support the half precision types, e.g. the GEMM operation available as cublasHgemm. My problem is that the host does not support half precision types. Is the an already implemented solution like cublasSetMatrix which does the conversion during the upload to the device? Or is it necessary to create a tricky implementation by composition a float upload with a CUDA kernel doing the truncation to float?

答:
There is no function currently provided by the CUDA toolkit which converts float quantities to half quantities in the process of copying data from host to device.

It is possible to convert from float to half either in host code or device code.  There would be advantages and disadvantages of doing it in either place.

Furthermore, there is a cublas<t>gemmEx function available that may be of interest, which can have differing datatypes for input and output (and computation).

Some other half resources that may be of interest:

half conversion library by Christian Rau mentioned by @talonmies below

CUDA half intrinsics.

previous SO question, with links to some other resources


问:
none latin names of variables in c#
I have named my button object (WinForms) with all hebrew letters and then added click event... and it worked.

Is this some new lang feature I've missed?

```<code>this.כפתור = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// כפתור
//
this.כפתור.Location = new System.Drawing.Point(58, 48);
this.כפתור.Name = "כפתור";
this.כפתור.Size = new System.Drawing.Size(75, 23);
this.כפתור.TabIndex = 0;
this.כפתור.Text = "button1";
this.כפתור.UseVisualStyleBackColor = true;
this.כפתור.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
כפתור.Text = "BLAH BLAH";
}
</code>```

答:
It looks like unicode variable names have been supported for some time, though I've never used them.
http://jameskovacs.com/2006/02/16/unicode-variable-names/</p>

Title: none latin names of variables in c#

Body:
I have named my button object (WinForms) with all hebrew letters and then added click event... and it worked.

Is this some new lang feature I've missed?

this.כפתור = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// כפתור
//
this.כפתור.Location = new System.Drawing.Point(58, 48);
this.כפתור.Name = "כפתור";
this.כפתור.Size = new System.Drawing.Size(75, 23);
this.כפתור.TabIndex = 0;
this.כפתור.Text = "button1";
this.כפתור.UseVisualStyleBackColor = true;
this.כפתור.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
כפתור.Text = "BLAH BLAH";
}


问:
Many to Many relationship with ApplicationUser
I am building a Code-First, Many-To-Many relationship between my ApplicationUser class and a Lesson class. When the model is created, Entity Framework builds the two tables and the intersecting pivot table. However, neither table seems to take in data from the pivot table (LessonApplicationUsers). Both List variables do not seem to hold either the list of Students or the list of Lessons. Both entities i'm trying to marry up already exist in the database

ApplicationUser class

```<code>public class ApplicationUser : IdentityUser
{
    public string Address { get; set; }
    public int? Age { get; set; }
    public ClassLevel? ClassLevel { get; set; }
    public string FirstName { get; set; }
    public int? Height { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }
    public string Postcode { get; set; }
    public string Town { get; set; }
    public int? Weight { get; set; }

    public ApplicationUser()
    {
        Lessons = new List<Lesson>();
    }

    public ICollection<Lesson> Lessons { get; set; }
}
</code>```

Lesson Class

```<code>public class Lesson
{
    [Key]
    public int LessonID { get; set; }
    public LessonType ClassType { get; set; }
    public ClassLevel? ClassLevel { get; set; }
    public DateTime ClassStartDate { get; set; }
    public DateTime ClassEndDate { get; set; }
    public float ClassCost { get; set; }
    public int? InstructorID { get; set; }

    public Lesson()
    {
        Students = new List<ApplicationUser>();
    }

    public ICollection<ApplicationUser> Students { get; set; }

    public enum LessonType {Group,Private}
}
</code>```

My DBContext

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Lesson> Lessons { get; set; }
    public DbSet<ApplyViewModel> Applications { get; set; }
</code>```

And finally, the code i'm using to add in the pivot table data. This is activated when the user presses a button on the booking form.

```<code>public ActionResult BookUser()
    {
        //Gather required variables
        ApplicationUser user = db.Users.First(i => i.UserName == User.Identity.Name);
        int classID = int.Parse(Request.Form["classID"]);

        using (db)
        {
            var editedLesson = db.Lessons.Single(s => s.LessonID == classID);
            db.Lessons.Attach(editedLesson);

            var editedUser = db.Users.Single(s => s.Id == user.Id);
            db.Users.Attach(editedUser);

            editedLesson.Students.Add(editedUser);

            db.SaveChanges();
        }
        return View("Index");
</code>```

When I try and run it, when i press my book button, it runs through the code and executes. checking the database it has indeed inserted the key values into the pivot table. When i load the model of the lesson to view its details, the Student attribute has a count of 0. I've been at this for days and i've got the feeling i'm missing something kickself simple....but i've gone over it a dozen times and can't see what i'm doing wrong...

答: Mark your lists with virtual to enable lazy loading. Also is not required to initialize the lists Lessons = new List<Lesson>();

Body:
I am building a Code-First, Many-To-Many relationship between my ApplicationUser class and a Lesson class. When the model is created, Entity Framework builds the two tables and the intersecting pivot table. However, neither table seems to take in data from the pivot table (LessonApplicationUsers). Both List variables do not seem to hold either the list of Students or the list of Lessons. Both entities i'm trying to marry up already exist in the database

ApplicationUser class

public class ApplicationUser : IdentityUser
{
    public string Address { get; set; }
    public int? Age { get; set; }
    public ClassLevel? ClassLevel { get; set; }
    public string FirstName { get; set; }
    public int? Height { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }
    public string Postcode { get; set; }
    public string Town { get; set; }
    public int? Weight { get; set; }

    public ApplicationUser()
    {
        Lessons = new List<Lesson>();
    }

    public ICollection<Lesson> Lessons { get; set; }
}

Lesson Class

public class Lesson
{
    [Key]
    public int LessonID { get; set; }
    public LessonType ClassType { get; set; }
    public ClassLevel? ClassLevel { get; set; }
    public DateTime ClassStartDate { get; set; }
    public DateTime ClassEndDate { get; set; }
    public float ClassCost { get; set; }
    public int? InstructorID { get; set; }

    public Lesson()
    {
        Students = new List<ApplicationUser>();
    }

    public ICollection<ApplicationUser> Students { get; set; }

    public enum LessonType {Group,Private}
}

My DBContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Lesson> Lessons { get; set; }
    public DbSet<ApplyViewModel> Applications { get; set; }

And finally, the code i'm using to add in the pivot table data. This is activated when the user presses a button on the booking form.

public ActionResult BookUser()
    {
        //Gather required variables
        ApplicationUser user = db.Users.First(i => i.UserName == User.Identity.Name);
        int classID = int.Parse(Request.Form["classID"]);

        using (db)
        {
            var editedLesson = db.Lessons.Single(s => s.LessonID == classID);
            db.Lessons.Attach(editedLesson);

            var editedUser = db.Users.Single(s => s.Id == user.Id);
            db.Users.Attach(editedUser);

            editedLesson.Students.Add(editedUser);

            db.SaveChanges();
        }
        return View("Index");

When I try and run it, when i press my book button, it runs through the code and executes. checking the database it has indeed inserted the key values into the pivot table. When i load the model of the lesson to view its details, the Student attribute has a count of 0. I've been at this for days and i've got the feeling i'm missing something kickself simple....but i've gone over it a dozen times and can't see what i'm doing wrong...


问:
How to use MAX() and COUNT() in Oracle SQL?
Suppose i have the following table:

transactions(id, type)

id - id of the costumer (integer 1...n)
 type - what they
  bought (like "apple")

Note that each row refers to buying only ONE of the given type.

How can I select the id of the costumer who bought the most of a given type (like apple)?

I tried to COUNT() the rows where type = apple for each id, but I cannot use MAX() in that query to select only the first ID.

Thanks

答:
This is SQL 101, you should read about group by clause:

```<code>select id,
    count(*) as count_of_apples
from transactions
where type = 'apple'
group by id
order by count(*) desc
</code>```

Body:
This is SQL 101, you should read about group by clause:

select id,
    count(*) as count_of_apples
from transactions
where type = 'apple'
group by id
order by count(*) desc


答:
You can first make a query that for every customer counts the amount of times he bought an 'apple', with:

```<code>SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id
</code>```

Now we only need to ORDER BY that total in DESCending order, and return the first row with FETCH FIRST n ROWS ONLY, like:

```<code>SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id
<b>ORDER BY total DESC
FETCH FIRST 1 ROWS ONLY</b></code>```

Title: How to use MAX() and COUNT() in Oracle SQL?

Body:
Suppose i have the following table:

transactions(id, type)

id - id of the costumer (integer 1...n)
 type - what they
  bought (like "apple")

Note that each row refers to buying only ONE of the given type.

How can I select the id of the costumer who bought the most of a given type (like apple)?

I tried to COUNT() the rows where type = apple for each id, but I cannot use MAX() in that query to select only the first ID.

Thanks

Body:
You can first make a query that for every customer counts the amount of times he bought an 'apple', with:

SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id

Now we only need to ORDER BY that total in DESCending order, and return the first row with FETCH FIRST n ROWS ONLY, like:

SELECT id,COUNT(*) AS total
FROM transactions
WHERE type = 'apple'
GROUP BY id
ORDER BY total DESC
FETCH FIRST 1 ROWS ONLY


问:
Purpose of "with" methods in class
I'm looking at class called Product which includes the following:

```<code>@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}
</code>```

what is the purpose of the withName method and how is it used? Why not just do:

```<code>Product p = new Product();
p.setName("foo");
</code>```

答:
The major difference is that the with method returns the instance of the object is called on.

That allows for "fluent" calls like

```<code> someProductBuilder.withName("bla").withPrice(100)...
</code>```

In that sense: an informal convention to distinguish ordinary setters from those that allow for fluent usage by returning the affected object.

Title: Purpose of "with" methods in class

Body:
I'm looking at class called Product which includes the following:

@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}

what is the purpose of the withName method and how is it used? Why not just do:

Product p = new Product();
p.setName("foo");

Body:
The major difference is that the with method returns the instance of the object is called on.

That allows for "fluent" calls like

 someProductBuilder.withName("bla").withPrice(100)...

In that sense: an informal convention to distinguish ordinary setters from those that allow for fluent usage by returning the affected object.


问:
React Native: Not receiving intent from other Android app
I want my React Native app to be able to receive URL intents from another apps. So for instance, when I scan a URL with a QR code scanner and want to open it, among my installed browsers will also appear my React Native app.

I followed the instructions of Linking:

I implemented componentDidMount() as shown in the Linking documentation.

In android/app/src/main/AndroidManifest.xml, I edited the <intent filter> section according to the Android docs, so that it looks now like this:

```<code><intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="http"
      android:host="www.example.com"
      android:pathPrefix="/gizmos" />
</intent-filter>
</code>```

Having done this, I expected that after scanning a http://www.example.com/gizmos with my QR scanner and trying to open it, the scanner would offer me also my React Native app. However, it does only show my previously installed browsers.

Is my expectation wrong? Or can do something to make this happen?

答:
It's not enough to catch the action android:name="android.intent.action.MAIN" but you need to catch android:name="android.intent.action.VIEW"

```<code><intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:host="www.example.com" android:scheme="http" />
</intent-filter>
</code>```

Body:
I want my React Native app to be able to receive URL intents from another apps. So for instance, when I scan a URL with a QR code scanner and want to open it, among my installed browsers will also appear my React Native app.

I followed the instructions of Linking:

I implemented componentDidMount() as shown in the Linking documentation.

In android/app/src/main/AndroidManifest.xml, I edited the <intent filter> section according to the Android docs, so that it looks now like this:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="http"
      android:host="www.example.com"
      android:pathPrefix="/gizmos" />
</intent-filter>

Having done this, I expected that after scanning a http://www.example.com/gizmos with my QR scanner and trying to open it, the scanner would offer me also my React Native app. However, it does only show my previously installed browsers.

Is my expectation wrong? Or can do something to make this happen?

Body:
It's not enough to catch the action android:name="android.intent.action.MAIN" but you need to catch android:name="android.intent.action.VIEW"

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:host="www.example.com" android:scheme="http" />
</intent-filter>


问:
Python inserts both a carriage return and a line feed after variable, instead of just line feed
I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc.

It works perfectly, however I require only a line feed to be inserted at the end of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

```<code>import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')
</code>```

the problem here is the line

```<code>print("{}\r".format(k), file=text_file, end='')
</code>```

答:
For files opened in text mode (the default), python interprets /n as equivalent to os.linesep, which on Windows is [CR][LF], and vice versa.

```<code>import os
print(os.linesep)
</code>```

Check out http://docs.python.org/library/os.html

To prevent this, open the file in binary mode.

```<code>with open("Output.txt", "wb") as my_file:
</code>```

This tells Python to treat the file as a plain sequence of bytes and you will find that \n gets treated as a single linefeed character.

Body:
I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc.

It works perfectly, however I require only a line feed to be inserted at the end of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')

the problem here is the line

print("{}\r".format(k), file=text_file, end='')

Body:
For files opened in text mode (the default), python interprets /n as equivalent to os.linesep, which on Windows is [CR][LF], and vice versa.

import os
print(os.linesep)

Check out http://docs.python.org/library/os.html

To prevent this, open the file in binary mode.

with open("Output.txt", "wb") as my_file:

This tells Python to treat the file as a plain sequence of bytes and you will find that \n gets treated as a single linefeed character.


问:
Enumerable and Enumerator
Enumerable support foreach and enumerator support movenext, current and reset but this question is having single correct answer what will be the answer I am not getting.

答:
Answers a, b, and c are wrong because the IEnumerator interface doesn't contain any of them.

Answer d is wrong because the question asks which property you need to declare, and Reset is a method, not a property.

Title: Enumerable and Enumerator