问:
Passing parameters into model
Rails 3.0.3
ruby 1.9.2p0

The Problem:

I have a Users table which has many items, the item(s) in turn therefore belongs to the Users.

In my model item.rb i attempt to save the item along with the value for the user.id so i have:

```<code>self.User_ID = @user.id
</code>```

this however give me the error

```<code>Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
</code>```

this is causing some confusion that it can't find this as in the show.html.erb that 'wraps' this page <%= @user.id %>  displays the correct ID on the page

Many thanks in advance

** EDIT **
The Shorten action is the action upon which i want to parameter to be passed

```<code>class ItemsController < ApplicationController

  def redirect
    @item = Item.find_by_shortened(params[:shortened])
    if @item
      #redirect_to @item.original
      redirect_to @item.original
    else
      redirect_to :shorten
    end
  end

  def shorten
    @host = request.host_with_port
    @user = current_user
</code>```

答:
You need to load the @user model in every action that will require access to it. Having it render properly in the show action will not guarantee it is loaded in the update action.

Usually you need to have something like this in your controller:

```<code>class UsersController < ApplicationController
  before_filter :load_user, :except => [ :index, :new, :create ]

  # ...

protected
  def load_user
    @user = User.find(params[:user_id] || params[:id])
  rescue ActiveRecord::RecordNotFound
    render(:text => 'Record not found')
  end
end
</code>```

Title: Passing parameters into model

Body:
Rails 3.0.3
ruby 1.9.2p0

The Problem:

I have a Users table which has many items, the item(s) in turn therefore belongs to the Users.

In my model item.rb i attempt to save the item along with the value for the user.id so i have:

self.User_ID = @user.id

this however give me the error

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

this is causing some confusion that it can't find this as in the show.html.erb that 'wraps' this page <%= @user.id %>  displays the correct ID on the page

Many thanks in advance

** EDIT **
The Shorten action is the action upon which i want to parameter to be passed

class ItemsController < ApplicationController

  def redirect
    @item = Item.find_by_shortened(params[:shortened])
    if @item
      #redirect_to @item.original
      redirect_to @item.original
    else
      redirect_to :shorten
    end
  end

  def shorten
    @host = request.host_with_port
    @user = current_user

Body:
You need to load the @user model in every action that will require access to it. Having it render properly in the show action will not guarantee it is loaded in the update action.

Usually you need to have something like this in your controller:

class UsersController < ApplicationController
  before_filter :load_user, :except => [ :index, :new, :create ]

  # ...

protected
  def load_user
    @user = User.find(params[:user_id] || params[:id])
  rescue ActiveRecord::RecordNotFound
    render(:text => 'Record not found')
  end
end


来源: stackexchange

问:
What would be making this query so incredibly slow? (MySQL 5.6.36)
I have an ever-increasing database table of ~8 million rows running, which my application regularly fetches data from. However, the query has suddenly started locking up the entire system. There are tons of mysqld processes clogging up all CPU cores.

Could it be the ever-increasing size of the database? Or is there something within the query below that could cause it to run for so long? The UNIX_TIMESTAMP, for example? It's an excerpt from the slow query log. The query is executed every minute, and always had a query time of around ~7.

```<code># Query_time: 6.839524  Lock_time: 0.000170 Rows_sent: 277  Rows_examined: 7989334
FROM (
    SELECT @row := @row + 1 AS `row`, `timestamp`, `price`
    FROM (
        SELECT @row := 0
    ) `derived_1`, `items`
    WHERE `price` IS NOT NULL
        AND `timestamp` >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 DAY)
        AND `currency` = 'EUR'
        AND `type` = 'icon'
    ORDER BY `timestamp` ASC
) `derived_2`
WHERE `row` % 8 = 0;
</code>```

It's a bit hard to just try it out, as it's a production environment. I can't reproduce the issue on my development environment either.

If you need any additional information, please let me know!

Thanks a bunch in advance!

答:
The best index is this:

```<code>INDEX(type, currency,  -- The two columns tested via '=' (in either order)
      timestamp,       -- then this, for a range test
      price)           -- finally, the rest of the columns used
</code>```

That will be a "covering" index, so it won't have to bounce between the index BTree and the data BTree.  (The other suggested indexes will be slower because of this.)

Hopefully, that will make the query run faster than 7 seconds.

It is unsafe to run something "every minute".  What will happen if, for whatever reason, one instance fails to finish within a minute?  Probably the multiple invocations will stumble over each other, and possibly get slower and slower.  This may have been clogging you experienced.

To avoid that, have a job running continually -- calculate the query, then sleep, say, 53 seconds.  That will (based on current timings) very closely approximate once a minute.  Or it could pause just enough time to reach the next minute (but not less than 0 seconds).

ContentLicense: CC BY-SA 3.0

Body:
I have an ever-increasing database table of ~8 million rows running, which my application regularly fetches data from. However, the query has suddenly started locking up the entire system. There are tons of mysqld processes clogging up all CPU cores.

Could it be the ever-increasing size of the database? Or is there something within the query below that could cause it to run for so long? The UNIX_TIMESTAMP, for example? It's an excerpt from the slow query log. The query is executed every minute, and always had a query time of around ~7.

# Query_time: 6.839524  Lock_time: 0.000170 Rows_sent: 277  Rows_examined: 7989334
FROM (
    SELECT @row := @row + 1 AS `row`, `timestamp`, `price`
    FROM (
        SELECT @row := 0
    ) `derived_1`, `items`
    WHERE `price` IS NOT NULL
        AND `timestamp` >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 DAY)
        AND `currency` = 'EUR'
        AND `type` = 'icon'
    ORDER BY `timestamp` ASC
) `derived_2`
WHERE `row` % 8 = 0;

It's a bit hard to just try it out, as it's a production environment. I can't reproduce the issue on my development environment either.

If you need any additional information, please let me know!

Thanks a bunch in advance!

Body:
The best index is this:

INDEX(type, currency,  -- The two columns tested via '=' (in either order)
      timestamp,       -- then this, for a range test
      price)           -- finally, the rest of the columns used

That will be a "covering" index, so it won't have to bounce between the index BTree and the data BTree.  (The other suggested indexes will be slower because of this.)

Hopefully, that will make the query run faster than 7 seconds.

It is unsafe to run something "every minute".  What will happen if, for whatever reason, one instance fails to finish within a minute?  Probably the multiple invocations will stumble over each other, and possibly get slower and slower.  This may have been clogging you experienced.

To avoid that, have a job running continually -- calculate the query, then sleep, say, 53 seconds.  That will (based on current timings) very closely approximate once a minute.  Or it could pause just enough time to reach the next minute (but not less than 0 seconds).


问:
If an updated object in S3 serves as a lambda trigger, is there an inherent race condition?
If I update an object in an S3 Bucket, and trigger on that S3 PUT event as my Lambda trigger, is there a chance that the Lambda could operate on the older version of that object given S3’s eventual consistency model?

I’m having a devil of a time parsing out an authoritative answer either way...

答: How does the file get there in the first place? I'm asking, because if you could reverse the order, it'd solve your issue as you put your file in s3 via a lambda that before overwriting the file, can first get the existing version from the bucket and do whatever you need.</p>


问:
Why am I getting a syntax error in setting this Array into a class?
I am getting a syntax error but I don;t understand exactly why, here is my code:

```<code>class VerifyEmail {

     private $ip_pool = array("167.114.48.81","167.114.48.82"....);
     private $ip_to_use = $this->ip_pool[array_rand($this->ip_pool)]; //ERROR HERE
     .....
</code>```

I tried also:

```<code>     private $ip_to_use = $ip_pool[array_rand($ip_pool)];
</code>```

with no luck.

Am I missing something? Or you cannot do an array rand of a private variable when setting up the variables?

Thanks!

答:
I get the following notice in my IDE for that line

expression is not allowed as a field default value

I can only suggest moving your rand call into the __construct() method

```<code>class VerifyEmail {

  private $ip_pool = array( "167.114.48.81", "167.114.48.82");
  private $ip_to_use;

  public function __construct() {
    $this->ip_to_use = $this->ip_pool[ array_rand( $this->ip_pool ) ];
  }

}

var_dump( new VerifyEmail() );
</code>```

Body:
I am getting a syntax error but I don;t understand exactly why, here is my code:

class VerifyEmail {

     private $ip_pool = array("167.114.48.81","167.114.48.82"....);
     private $ip_to_use = $this->ip_pool[array_rand($this->ip_pool)]; //ERROR HERE
     .....

I tried also:

     private $ip_to_use = $ip_pool[array_rand($ip_pool)];

with no luck.

Am I missing something? Or you cannot do an array rand of a private variable when setting up the variables?

Thanks!

Body:
I get the following notice in my IDE for that line

expression is not allowed as a field default value

I can only suggest moving your rand call into the __construct() method

class VerifyEmail {

  private $ip_pool = array( "167.114.48.81", "167.114.48.82");
  private $ip_to_use;

  public function __construct() {
    $this->ip_to_use = $this->ip_pool[ array_rand( $this->ip_pool ) ];
  }

}

var_dump( new VerifyEmail() );


问:
Python: Printing out result from conditional for loop
I have a simple question. I have a small dataframe:

```<code>      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2
</code>```

I need to only print out only Column1 and Column2 only if Column1 equals 1:

```<code>      Column1  Column2
Row2        1        3
</code>```

I have this piece of code that I am stuck at:

```<code>col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])
</code>```

This is printing out the result such that we are having Column1 and Column2 with all the values.

```<code>      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4
</code>```

How can I incorporate the condition such that Column1==1?

Thanks!

答:
Two of the easiest ways to do this are to use .loc with boolean indexing and query with column filtering:

Method 1:

```<code>df.loc[df.Column1 == 1,['Column1','Column2']]
</code>```

Output:

```<code>      Column1  Column2
Row2        1        3
</code>```

Method 2:

```<code>df.query('Column1 == 1')[['Column1','Column2']]
</code>```

Output:

```<code>      Column1  Column2
Row2        1        3
</code>```

Body:
I have a simple question. I have a small dataframe:

      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2

I need to only print out only Column1 and Column2 only if Column1 equals 1:

      Column1  Column2
Row2        1        3

I have this piece of code that I am stuck at:

col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])

This is printing out the result such that we are having Column1 and Column2 with all the values.

      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4

How can I incorporate the condition such that Column1==1?

Thanks!

Body:
Two of the easiest ways to do this are to use .loc with boolean indexing and query with column filtering:

Method 1:

df.loc[df.Column1 == 1,['Column1','Column2']]

Output:

      Column1  Column2
Row2        1        3

Method 2:

df.query('Column1 == 1')[['Column1','Column2']]

Output:

      Column1  Column2
Row2        1        3


问:
Uncaught ReferenceError: value is not defined for imported module
Here is scenario:

index.js

```<code>import test1 from './test1';
window.test1 = test1;
</code>```

test1.js

```<code>import test2 from './test2';
var test1 =  (function (){
  var self = this;
  var x = {};
  x.test2 = test2;
  var testValue = 'TEST VALUE';
  let init = function(){
        console.log ( x.test2() );
  }
  init();
  return {
    x: x,
    testValue: testValue
  }
})();
export default test1;
</code>```

test2.js

```<code>var test2 =  function () {
    return (` value to use ${testValue} ` )
};

export default test2;
</code>```

I am getting the following error in test2.js when running index.js
 Uncaught ReferenceError: testValue is not defined

is there a way to use testValue without having to pass it in?

答:
is there a way to use testValue without having to pass it in?

You'd have to make sure that it is set as global variable before the function is executed. But using globals is often bad design. Passing the value in is much easier to reason about. Since you are not explaining why you want to do that, that's all the advice I can give.

Body:
Here is scenario:

index.js

import test1 from './test1';
window.test1 = test1;

test1.js

import test2 from './test2';
var test1 =  (function (){
  var self = this;
  var x = {};
  x.test2 = test2;
  var testValue = 'TEST VALUE';
  let init = function(){
        console.log ( x.test2() );
  }
  init();
  return {
    x: x,
    testValue: testValue
  }
})();
export default test1;

test2.js

var test2 =  function () {
    return (` value to use ${testValue} ` )
};

export default test2;

I am getting the following error in test2.js when running index.js
 Uncaught ReferenceError: testValue is not defined

is there a way to use testValue without having to pass it in?


问:
C/C++ function using float or double or int
I have seperate functions for reading from a text file (depending on whether its an int,  float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

```<code>float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}

double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}

int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}
</code>```

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.

答:
You can't overload on return types. You either return value by reference as a function parameter:

```<code>void read_column (char * file, int size_of_col, float&);
void read_column (char * file, int size_of_col, int&);
</code>```

...

or create a template:

```<code>template<class T> T read_column (char * file, int size_of_col);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have seperate functions for reading from a text file (depending on whether its an int,  float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}

double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}

int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.

Body:
You can't overload on return types. You either return value by reference as a function parameter:

void read_column (char * file, int size_of_col, float&);
void read_column (char * file, int size_of_col, int&);

...

or create a template:

template<class T> T read_column (char * file, int size_of_col);


问:
Creating a Wind Chill Calculator and not sure what I'm doing wrong here
I'm currently working on a project in my Intro to Java class and I need to create a program that will ask the user for two numbers, calculate the wind chill and convert the temp to Celsius.

The outcome is supposed to look like this identically:

```<code>Ima Java Student
Project 2 – Wind-Chill Calculator

Enter the outside temperature (Fahrenheit) [-58 to 41]: 32
Enter the wind speed [2 to 50]: 10

Outside Temp (F)  Wind Speed  Wind-Chill (F)  Wind-Chill (C)
----------------  ----------  --------------  --------------
              32          10          23.727          -4.596
</code>```

My output is just the following:

```<code>Ima Java Student
Project 2 – Wind-Chill Calculator
</code>```

Here is my code in full. What am I missing here?!

```<code>/**
 * Author:  Dillon Carter
 * Course:  COP2551
 * Project#: 2
 * Title:   Wind Chill Calculator
 * Due Date: 7/9/2017
 *
 * Calculates the Wind Chill based on the outside Temperature and Wind Speed given by the user.
 * Then, converts the outcome from Fahrenheit to Celsius for the user.
*/

import java.util.Scanner;

public class Calculator {

     // Variable Declaration
    int temperature = 0;
    int speed =  0;
    int windChill = 0;
    int celsius = 0;
    double windChill_C = 0;
    double windChill_F = 0;

    public static void main(String[] args) {

    System.out.println("Ima Java Student");
    System.out.println("Project 2 - Wind-Chill Calculator");

    }

    // Gets input from user and saves as variables
    private boolean getInput() {

            Scanner reader = new Scanner(System.in);
            System.out.println("Enter the outside temperature (Fahrenheit) [-58 to 41]:");
            int temperature = reader.nextInt();
            boolean isGoodTemp = (temperature >= -58 && temperature <= 41);

            System.out.println("Enter the wind speed [2 to 50]:");
            int windSpeed = reader.nextInt();
            boolean isGoodSpeed = (windSpeed >= 2 && windSpeed <= 50);
    return true;

    }

    // No clue what this is for....
    private void performCalculations(int temperature, int windSpeed) {

    }

    // Calculates the Wind Chill based on the temperature and wind speed given by the user
    private double calculateWindChill(int temperature, int windSpeed) {

            windChill_F = 35.74 + 0.6215 *temperature - 35.75 * Math.pow(windSpeed, 0.16) + 0.4275*temperature * Math.pow(windSpeed, 0.16);
    return windChill_F;
    }

    // Converts temperature from Fharenheight to Celsius
    private double convertTemperature(double windChill_F) {

            windChill_C = Math.round((temperature - 32) * 5 / 9);
return windChill_C;

}
    // Displays the results to the user
    private void displayResults(int temperature, int windSpeed, double windChill_F, double windChill_C) {

            System.out.println( "Outside Temp (F)  " + "Wind Speed  " + "Wind-Chill (F)  "+ "Wind-Chill (C)  ");
            System.out.println( "---------------  " + "---------------  " + "---------------  " + "---------------  ");
            System.out.println( temperature + "  " + windSpeed + "  " + windChill_F + "  " + windChill_C);
        }
    }
</code>```

It's important to note that I am not allowed to create any more methods, but must used the methods included in my current code. I'm so close to making this work, I can feel it lol.

答:
I did this program. After temperature and speed were entered by user program calculates windChill and converts it to celcium. Finally results are displayed.

```<code>import java.util.Scanner;

public class Calculator {

    // Variable Declaration
    int temperature = 0;
    int speed = 0;
    int windChill = 0;
    int celsius = 0;
    double windChill_C = 0;
    double windChill_F = 0;

    public static void main(String[] args) {

        System.out.println("Ima Java Student");
        System.out.println("Project 2 - Wind-Chill Calculator");

        System.out.println();

        Calculator calc = new Calculator();
        while (!calc.getInput()) {
            System.out.println("Temperature or wind speed is wrong. Try again");
        }
        calc.displayResults(calc.temperature, calc.speed, calc.windChill_F, calc.windChill_C);
    }

    // Gets input from user and saves as variables
    private boolean getInput() {

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the outside temperature (Fahrenheit) [-58 to 41]:");
        temperature = reader.nextInt();
        boolean isGoodTemp = (temperature >= -58 && temperature <= 41);

        System.out.println("Enter the wind speed [2 to 50]:");
        speed = reader.nextInt();
        boolean isGoodSpeed = (speed >= 2 && speed <= 50);

        performCalculations(temperature, speed);
        return isGoodTemp && isGoodSpeed;
    }

    // No clue what this is for....
    private void performCalculations(int temperature, int windSpeed) {
        calculateWindChill(temperature, windSpeed);
        convertTemperature(windChill_F);
    }

    // Calculates the Wind Chill based on the temperature and wind speed given
    // by the user
    private double calculateWindChill(int temperature, int windSpeed) {

        windChill_F = 35.74 + 0.6215 * temperature - 35.75 * Math.pow(windSpeed, 0.16)
                + 0.4275 * temperature * Math.pow(windSpeed, 0.16);
        return windChill_F;
    }

    // Converts temperature from Fharenheight to Celsius
    private double convertTemperature(double windChill_F) {

        windChill_C = Math.round((temperature - 32) * 5 / 9);
        return windChill_C;

    }

    // Displays the results to the user
    private void displayResults(int temperature, int windSpeed, double windChill_F, double windChill_C) {

        System.out.println("Outside Temp (F)  " + "Wind Speed  " + "Wind-Chill (F)  " + "Wind-Chill (C)  ");
        System.out.println("---------------  " + "---------------  " + "---------------  " + "---------------  ");
        System.out.println(temperature + "  " + windSpeed + "  " + windChill_F + "  " + windChill_C);
    }
}
</code>```

Prints:

```<code>Ima Java Student
Project 2 - Wind-Chill Calculator

Enter the outside temperature (Fahrenheit) [-58 to 41]:
40
Enter the wind speed [2 to 50]:
24
Outside Temp (F)  Wind Speed  Wind-Chill (F)  Wind-Chill (C)
---------------  ---------------  ---------------  ---------------
40  24  29.58922393920365  4.0
</code>```

Body:
I'm currently working on a project in my Intro to Java class and I need to create a program that will ask the user for two numbers, calculate the wind chill and convert the temp to Celsius.

The outcome is supposed to look like this identically:

Ima Java Student
Project 2 – Wind-Chill Calculator

Enter the outside temperature (Fahrenheit) [-58 to 41]: 32
Enter the wind speed [2 to 50]: 10

Outside Temp (F)  Wind Speed  Wind-Chill (F)  Wind-Chill (C)
----------------  ----------  --------------  --------------
              32          10          23.727          -4.596

My output is just the following:

Ima Java Student
Project 2 – Wind-Chill Calculator

Here is my code in full. What am I missing here?!

/**
 * Author:  Dillon Carter
 * Course:  COP2551
 * Project#: 2
 * Title:   Wind Chill Calculator
 * Due Date: 7/9/2017
 *
 * Calculates the Wind Chill based on the outside Temperature and Wind Speed given by the user.
 * Then, converts the outcome from Fahrenheit to Celsius for the user.
*/

import java.util.Scanner;

public class Calculator {

     // Variable Declaration
    int temperature = 0;
    int speed =  0;
    int windChill = 0;
    int celsius = 0;
    double windChill_C = 0;
    double windChill_F = 0;

    public static void main(String[] args) {

    System.out.println("Ima Java Student");
    System.out.println("Project 2 - Wind-Chill Calculator");

    }

    // Gets input from user and saves as variables
    private boolean getInput() {

            Scanner reader = new Scanner(System.in);
            System.out.println("Enter the outside temperature (Fahrenheit) [-58 to 41]:");
            int temperature = reader.nextInt();
            boolean isGoodTemp = (temperature >= -58 && temperature <= 41);

            System.out.println("Enter the wind speed [2 to 50]:");
            int windSpeed = reader.nextInt();
            boolean isGoodSpeed = (windSpeed >= 2 && windSpeed <= 50);
    return true;

    }

    // No clue what this is for....
    private void performCalculations(int temperature, int windSpeed) {

    }

    // Calculates the Wind Chill based on the temperature and wind speed given by the user
    private double calculateWindChill(int temperature, int windSpeed) {

            windChill_F = 35.74 + 0.6215 *temperature - 35.75 * Math.pow(windSpeed, 0.16) + 0.4275*temperature * Math.pow(windSpeed, 0.16);
    return windChill_F;
    }

    // Converts temperature from Fharenheight to Celsius
    private double convertTemperature(double windChill_F) {

            windChill_C = Math.round((temperature - 32) * 5 / 9);
return windChill_C;

}
    // Displays the results to the user
    private void displayResults(int temperature, int windSpeed, double windChill_F, double windChill_C) {

            System.out.println( "Outside Temp (F)  " + "Wind Speed  " + "Wind-Chill (F)  "+ "Wind-Chill (C)  ");
            System.out.println( "---------------  " + "---------------  " + "---------------  " + "---------------  ");
            System.out.println( temperature + "  " + windSpeed + "  " + windChill_F + "  " + windChill_C);
        }
    }

It's important to note that I am not allowed to create any more methods, but must used the methods included in my current code. I'm so close to making this work, I can feel it lol.

Body:
I did this program. After temperature and speed were entered by user program calculates windChill and converts it to celcium. Finally results are displayed.

import java.util.Scanner;

public class Calculator {

    // Variable Declaration
    int temperature = 0;
    int speed = 0;
    int windChill = 0;
    int celsius = 0;
    double windChill_C = 0;
    double windChill_F = 0;

    public static void main(String[] args) {

        System.out.println("Ima Java Student");
        System.out.println("Project 2 - Wind-Chill Calculator");

        System.out.println();

        Calculator calc = new Calculator();
        while (!calc.getInput()) {
            System.out.println("Temperature or wind speed is wrong. Try again");
        }
        calc.displayResults(calc.temperature, calc.speed, calc.windChill_F, calc.windChill_C);
    }

    // Gets input from user and saves as variables
    private boolean getInput() {

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the outside temperature (Fahrenheit) [-58 to 41]:");
        temperature = reader.nextInt();
        boolean isGoodTemp = (temperature >= -58 && temperature <= 41);

        System.out.println("Enter the wind speed [2 to 50]:");
        speed = reader.nextInt();
        boolean isGoodSpeed = (speed >= 2 && speed <= 50);

        performCalculations(temperature, speed);
        return isGoodTemp && isGoodSpeed;
    }

    // No clue what this is for....
    private void performCalculations(int temperature, int windSpeed) {
        calculateWindChill(temperature, windSpeed);
        convertTemperature(windChill_F);
    }

    // Calculates the Wind Chill based on the temperature and wind speed given
    // by the user
    private double calculateWindChill(int temperature, int windSpeed) {

        windChill_F = 35.74 + 0.6215 * temperature - 35.75 * Math.pow(windSpeed, 0.16)
                + 0.4275 * temperature * Math.pow(windSpeed, 0.16);
        return windChill_F;
    }

    // Converts temperature from Fharenheight to Celsius
    private double convertTemperature(double windChill_F) {

        windChill_C = Math.round((temperature - 32) * 5 / 9);
        return windChill_C;

    }

    // Displays the results to the user
    private void displayResults(int temperature, int windSpeed, double windChill_F, double windChill_C) {

        System.out.println("Outside Temp (F)  " + "Wind Speed  " + "Wind-Chill (F)  " + "Wind-Chill (C)  ");
        System.out.println("---------------  " + "---------------  " + "---------------  " + "---------------  ");
        System.out.println(temperature + "  " + windSpeed + "  " + windChill_F + "  " + windChill_C);
    }
}

Prints:

Ima Java Student
Project 2 - Wind-Chill Calculator

Enter the outside temperature (Fahrenheit) [-58 to 41]:
40
Enter the wind speed [2 to 50]:
24
Outside Temp (F)  Wind Speed  Wind-Chill (F)  Wind-Chill (C)
---------------  ---------------  ---------------  ---------------
40  24  29.58922393920365  4.0


问:
What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?
What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

About FragmentPagerAdapter Google's guide says:

This version of the pager is best for use when there are a handful of
  typically more static fragments to be paged through, such as a set of
  tabs. The fragment of each page the user visits will be kept in
  memory, though its view hierarchy may be destroyed when not visible.
  This can result in using a significant amount of memory since fragment
  instances can hold on to an arbitrary amount of state. For larger sets
  of pages, consider FragmentStatePagerAdapter.

And about FragmentStatePagerAdapter:

This version of the pager is more useful when there are a large number
  of pages, working more like a list view. When pages are not visible to
  the user, their entire fragment may be destroyed, only keeping the
  saved state of that fragment. This allows the pager to hold on to much
  less memory associated with each visited page as compared to
  FragmentPagerAdapter at the cost of potentially more overhead when
  switching between pages.

So I have just 3 fragments. But all of them are separate modules with a large amount of data.

Fragment1 handles some data (which users enter) and passes it via activity into Fragment2, which is just a simple ListFragment. Fragment3 is also a ListFragment.

So my questions are: Which adapter should I use? FragmentPagerAdapter or FragmentStatePagerAdapter?

答: FragmentStatePagerAdapter = To accommodate a large number of fragments in ViewPager. As this adapter destroys the fragment when it is not visible to the user and only savedInstanceState of the fragment is kept for further use. This way a low amount of memory is used and a better performance is delivered in case of dynamic fragments.</p>

ContentLicense: CC BY-SA 4.0


问:
Write back or write through to main memory
write-through :  data is written to the main memory through the cache immediately

write-back :   data is written in a latter time .

I have  a shared memory , which is located in NUMA node 1 , suppose that Process A executed in Node 0 which modify the contents of shared memory , then the process B executed in Node 1 which like to read the contents of shared meory .

if it is in write-through mode , then the contents modified by process A will be in main memory in Node 1 , since while Node 0 write data to Node 1 main memory will go through L3 cache  of Node 1 , then Process B can get the contents which modified by process A from  L3 cache of Node 1 , not  from main memory of Node 1.

if it is write-back mode , then while process B in Node 1 like to read the contents of shared memory , the cache line will be in L3 cache of Node 0 ,
get it will cost more since it is in Node 0 cache .

I like to know in Intel(R) Xeon(R) CPU E5-2643 , which mode it will choose ?!
or Xeon will decide which mode it will use on its own and nothing programmer can do ?!

Edit :

dmidecode -t cache

showes Xeon cache operational mode is  write back ,look reasonable , refering to

http://www.cs.cornell.edu/courses/cs3410/2013sp/lecture/18-caches3-w.pdf

答:
Cache coherency on Intel (and AMD) x86-64 NUMA architectures does not work like that of a RAID array... Instead of having a single write-through or write-back cache, the two or four processor packages have a snooping & transfer protocol for synchronizing and sharing their L3 caches. OS level support for controlling such things is generally very rough, even though though NUMA has been mainstream for about ten years now.

Speaking specifically about Linux, control over the cache settings really boil down to a handful of process-level settings:

What core(s) your code is allowed to run on.

Whether your process is allowed to allocate non-local node memory.

Whether your process interleaves all of its allocations between Numa nodes.

By default, the Linux kernel will allocate process memory from the NUMA node the process is actively running on, falling back to allocations on the other node if there's memory pressure on the local node.

You can control the pushing of data in and out of the L3 cache of the local node using x86 assembly primitives like LOCK, but in general you really, really, really should not care about anything more than your process running locally with its allocated memory.

For more information on this, I'd encourage you to read some of the Linux documentation on NUMA, and possibly also Intel's (QPI is the name of the cache-sharing technology).

A good start for you would probably be the Linux 'numactl' manpage (https://linux.die.net/man/8/numactl)


问:
How to use SparkSQL Convert ".txt" to ".parquet" in Spark 2.1.0?
Look, I used "spark-shell" command to test it.(https://spark.apache.org/docs/latest/sql-programming-guide.html)

```<code>
scala> case class IP(country: String) extends Serializable
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:42868 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:40888 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 0
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 1
defined class IP

scala> import spark.implicits._
import spark.implicits._

scala> import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.SaveMode

scala> val df = spark.sparkContext.textFile("/test/guchao/ip.txt").map(x => x.split("\\|", -1)).map(x => IP(x(0))).toDF()
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2 stored as values in memory (estimated size 216.5 KB, free 92.9 MB)
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2_piece0 stored as bytes in memory (estimated size 20.8 KB, free 92.8 MB)
17/07/05 11:20:36 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:42868 (size: 20.8 KB, free: 93.3 MB)
17/07/05 11:20:36 INFO SparkContext: Created broadcast 2 from textFile at :33
df: org.apache.spark.sql.DataFrame = [country: string]

scala> df.write.mode(SaveMode.Overwrite).save("/test/guchao/ip.parquet")
17/07/05 11:20:44 INFO ParquetFileFormat: Using default output committer for Parquet: org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using user defined output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO CodeGenerator: Code generated in 88.405717 ms
17/07/05 11:20:44 INFO FileInputFormat: Total input paths to process : 1
17/07/05 11:20:44 INFO SparkContext: Starting job: save at :36
17/07/05 11:20:44 INFO DAGScheduler: Got job 1 (save at :36) with 2 output partitions
17/07/05 11:20:44 INFO DAGScheduler: Final stage: ResultStage 1 (save at :36)
17/07/05 11:20:44 INFO DAGScheduler: Parents of final stage: List()
17/07/05 11:20:44 INFO DAGScheduler: Missing parents: List()
17/07/05 11:20:44 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[12] at save at :36), which has no missing parents
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3 stored as values in memory (estimated size 77.3 KB, free 92.8 MB)
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3_piece0 stored as bytes in memory (estimated size 29.3 KB, free 92.7 MB)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:42868 (size: 29.3 KB, free: 93.2 MB)
17/07/05 11:20:44 INFO SparkContext: Created broadcast 3 from broadcast at DAGScheduler.scala:996
17/07/05 11:20:44 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 1 (MapPartitionsRDD[12] at save at :36)
17/07/05 11:20:44 INFO TaskSchedulerImpl: Adding task set 1.0 with 2 tasks
17/07/05 11:20:44 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 2, 192.168.50.3, executor 0, partition 0, ANY, 6027 bytes)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:40888 (size: 29.3 KB, free: 93.3 MB)
17/07/05 11:20:45 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:40888 (size: 20.8 KB, free: 93.2 MB)
17/07/05 11:20:45 INFO TaskSetManager: Starting task 1.0 in stage 1.0 (TID 3, 192.168.50.3, executor 0, partition 1, ANY, 6027 bytes)
17/07/05 11:20:45 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 2) in 679 ms on 192.168.50.3 (executor 0) (1/2)
17/07/05 11:20:46 INFO DAGScheduler: ResultStage 1 (save at :36) finished in 1.476 s
17/07/05 11:20:46 INFO DAGScheduler: Job 1 finished: save at :36, took 1.597097 s
17/07/05 11:20:46 INFO TaskSetManager: Finished task 1.0 in stage 1.0 (TID 3) in 804 ms on 192.168.50.3 (executor 0) (2/2)
17/07/05 11:20:46 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
17/07/05 11:20:46 INFO FileFormatWriter: Job null committed.
</code>```

but the result is:

[root@master ~]# hdfs dfs -ls -h /test/guchao
17/07/05 11:20:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Found 2 items
drwxr-xr-x   - root supergroup          0 2017-07-05 11:20 /test/guchao/ip.parquet
-rw-r--r--   1 root supergroup     23.9 M 2017-07-05 10:05 /test/guchao/ip.txt

Why does this size of "ip.parquet" is 0?  I don't understand and confuse.

Thanks!

答:
/test/guchao/ip.parquet is a directory, get into the directory and you should find something like part-00000 which will be the file you are looking for.

hadoop fs -ls /test/guchao/ip.parquet

Body:
Look, I used "spark-shell" command to test it.(https://spark.apache.org/docs/latest/sql-programming-guide.html)

scala> case class IP(country: String) extends Serializable
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:42868 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:40888 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 0
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 1
defined class IP

scala> import spark.implicits._
import spark.implicits._

scala> import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.SaveMode

scala> val df = spark.sparkContext.textFile("/test/guchao/ip.txt").map(x => x.split("\\|", -1)).map(x => IP(x(0))).toDF()
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2 stored as values in memory (estimated size 216.5 KB, free 92.9 MB)
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2_piece0 stored as bytes in memory (estimated size 20.8 KB, free 92.8 MB)
17/07/05 11:20:36 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:42868 (size: 20.8 KB, free: 93.3 MB)
17/07/05 11:20:36 INFO SparkContext: Created broadcast 2 from textFile at :33
df: org.apache.spark.sql.DataFrame = [country: string]

scala> df.write.mode(SaveMode.Overwrite).save("/test/guchao/ip.parquet")
17/07/05 11:20:44 INFO ParquetFileFormat: Using default output committer for Parquet: org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using user defined output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO CodeGenerator: Code generated in 88.405717 ms
17/07/05 11:20:44 INFO FileInputFormat: Total input paths to process : 1
17/07/05 11:20:44 INFO SparkContext: Starting job: save at :36
17/07/05 11:20:44 INFO DAGScheduler: Got job 1 (save at :36) with 2 output partitions
17/07/05 11:20:44 INFO DAGScheduler: Final stage: ResultStage 1 (save at :36)
17/07/05 11:20:44 INFO DAGScheduler: Parents of final stage: List()
17/07/05 11:20:44 INFO DAGScheduler: Missing parents: List()
17/07/05 11:20:44 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[12] at save at :36), which has no missing parents
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3 stored as values in memory (estimated size 77.3 KB, free 92.8 MB)
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3_piece0 stored as bytes in memory (estimated size 29.3 KB, free 92.7 MB)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:42868 (size: 29.3 KB, free: 93.2 MB)
17/07/05 11:20:44 INFO SparkContext: Created broadcast 3 from broadcast at DAGScheduler.scala:996
17/07/05 11:20:44 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 1 (MapPartitionsRDD[12] at save at :36)
17/07/05 11:20:44 INFO TaskSchedulerImpl: Adding task set 1.0 with 2 tasks
17/07/05 11:20:44 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 2, 192.168.50.3, executor 0, partition 0, ANY, 6027 bytes)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:40888 (size: 29.3 KB, free: 93.3 MB)
17/07/05 11:20:45 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:40888 (size: 20.8 KB, free: 93.2 MB)
17/07/05 11:20:45 INFO TaskSetManager: Starting task 1.0 in stage 1.0 (TID 3, 192.168.50.3, executor 0, partition 1, ANY, 6027 bytes)
17/07/05 11:20:45 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 2) in 679 ms on 192.168.50.3 (executor 0) (1/2)
17/07/05 11:20:46 INFO DAGScheduler: ResultStage 1 (save at :36) finished in 1.476 s
17/07/05 11:20:46 INFO DAGScheduler: Job 1 finished: save at :36, took 1.597097 s
17/07/05 11:20:46 INFO TaskSetManager: Finished task 1.0 in stage 1.0 (TID 3) in 804 ms on 192.168.50.3 (executor 0) (2/2)
17/07/05 11:20:46 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
17/07/05 11:20:46 INFO FileFormatWriter: Job null committed.

but the result is:

[root@master ~]# hdfs dfs -ls -h /test/guchao
17/07/05 11:20:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Found 2 items
drwxr-xr-x   - root supergroup          0 2017-07-05 11:20 /test/guchao/ip.parquet
-rw-r--r--   1 root supergroup     23.9 M 2017-07-05 10:05 /test/guchao/ip.txt

Why does this size of "ip.parquet" is 0?  I don't understand and confuse.

Thanks!


问:
SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?
When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a script, is there a way to monitor the progress, or do I just sit back and wait for it to finish (hoping that nothing has gone wrong?)

Edited: My need is specifically to be able to monitor the backup or restore progress completely separate from the session where the backup or restore was initiated.

答: simply run bkp_status on master db you will get backup status</p>

LastEditorDisplayName: Nigel Campbell


Title: How to replace space between a number with comma using SQL Server?

Body:
SELECT REPLACE('245 289 252 722 265,420 (22,791) (23,482) (24,662)', '^[0-9]', ',')

Raw Result      : 245 289 252 722 265,420 (22,791) (23,482) (24,662)

Need Result     : 245,289 252,722 265,420 (22,791) (23,482) (24,662)

Body:
Just replace space with a comma. To deal with commas between parenthesis, use another replace:

SELECT REPLACE(REPLACE('245 289 252 722 265,420 (22,791) (23,482) (24,662)', ' ', ','), '),(', ') (')

Result:

 245,289,252,722,265,420,(22,791) (23,482) (24,662)


问:
how to set where condition under if result
I have four different where condition.

And I get 2 values(A,B) from outside.

If both A and B are null

I want to select rows under first where condition.

If A is null and B is not, the second where condition.

If A is not null and B is null, the third.

If Both A and B are not null, the fourth.

Let me show it to you briefly.

```<code>select * from mytable
if(A ==null and B == null)
   first where condition
if(A == null and B != null)
   second where condition

  ......
</code>```

How can I do this with SQL

答:
Maybe you can use case clause, and i think it will be easier for you.
This is the example for your problem, i hope this code can help you.

SELECT * FROM mytable
WHERE name =
CASE WHEN A IS NULL AND B IS NULL THEN 'john'
     WHEN A IS NULL AND B IS NOT NULL THEN 'doe'
     ...
END;

Body:
I have four different where condition.

And I get 2 values(A,B) from outside.

If both A and B are null

I want to select rows under first where condition.

If A is null and B is not, the second where condition.

If A is not null and B is null, the third.

If Both A and B are not null, the fourth.

Let me show it to you briefly.

select * from mytable
if(A ==null and B == null)
   first where condition
if(A == null and B != null)
   second where condition

  ......

How can I do this with SQL


问:
SetTimout not properly functioning
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                console.log("hello world")
            },5000)
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button></code>```

The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?

答:
Please check below mentioned solution.

var i = 1;
var interval = setInterval(
  function(){
  if(i<=5){
    alert('Hello World!');
    i++;
  }else{
     clearInterval(interval);
  }
}, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Let me know if it not works

Title: SetTimout not properly functioning

Body:
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                console.log("hello world")
            },5000)
        }
    })
})

<button id="start">
start
</button>

The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?

Body:
Please check below mentioned solution.

var i = 1;
var interval = setInterval(
  function(){
  if(i<=5){
    alert('Hello World!');
    i++;
  }else{
     clearInterval(interval);
  }
}, 5000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Let me know if it not works


问:
How to create a button with round edges programatically in Java?
Is it possible to create a button with round edges without using a shape XML in my drawable folder?

My app has a lot of buttons that will change colors based on what the user assigns and touches. This will mean I will have to create a lot of shapes in my xml for it's specific color (have about 20 colors).

Or is there a way I can easily change the background color of my shape's button? I have about 45 buttons on one page of in my app.

答:
You can use imageView.setColorFilter(Color.RED) function to change color of xml drawable

here are some example

```<code>ImageView redCircle = (ImageView) findViewById(R.id.circle_red_imageview);
ImageView greenCircle = (ImageView) findViewById(R.id.circle_green_imageview);
ImageView blueCircle = (ImageView) findViewById(R.id.circle_blue_imageview);

// we can create the color values in different ways:
redCircle.getDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY );
greenCircle.getDrawable().setColorFilter(0xff00ff00, PorterDuff.Mode.MULTIPLY );
blueCircle.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );
</code>```

Body:
You can use imageView.setColorFilter(Color.RED) function to change color of xml drawable

here are some example

ImageView redCircle = (ImageView) findViewById(R.id.circle_red_imageview);
ImageView greenCircle = (ImageView) findViewById(R.id.circle_green_imageview);
ImageView blueCircle = (ImageView) findViewById(R.id.circle_blue_imageview);

// we can create the color values in different ways:
redCircle.getDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY );
greenCircle.getDrawable().setColorFilter(0xff00ff00, PorterDuff.Mode.MULTIPLY );
blueCircle.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );


问:
Adding transition to pseudo element (SASS)
I am trying to gradually change the background of a div on hover instead of immediately, however I am having trouble applying transition to my pseudo element. This is what I tried - </p>

```<code>@mixin project-styling($url) {
  background: url($url);
  background-size: cover;
  overflow: hidden;
  transition: all 2s;

  &:hover:after {
    background-color: rgba(0, 0, 0, 0.7);
    content: '';
    width: 400px;
    height: 300px;
  }
}

div {
  @include project-styling('image.png');
}
</code>```

答:
The transition needs to be on the pseudo element as well. You also did not include the pseudo element when the div is not being hovered.</p>

```<code>    @mixin project-styling($url) {
      background: url($url);
      background-size: cover;
      overflow: hidden;
      transition: all 2s;

      &::after {
         background-color: rgba(0, 0, 0, 0.7);
         content: '';
         width: 400px;
         height: 300px;
         transition: all 2s;
      }

      &:hover::after {
        background-color: rgba(0, 0, 0, 1);
      }
    }

    div {
      @include project-styling('image.png');
    }
</code>```

Body:
I am trying to gradually change the background of a div on hover instead of immediately, however I am having trouble applying transition to my pseudo element. This is what I tried -

@mixin project-styling($url) {
  background: url($url);
  background-size: cover;
  overflow: hidden;
  transition: all 2s;

  &:hover:after {
    background-color: rgba(0, 0, 0, 0.7);
    content: '';
    width: 400px;
    height: 300px;
  }
}

div {
  @include project-styling('image.png');
}

Body:
The transition needs to be on the pseudo element as well. You also did not include the pseudo element when the div is not being hovered.

    @mixin project-styling($url) {
      background: url($url);
      background-size: cover;
      overflow: hidden;
      transition: all 2s;

      &::after {
         background-color: rgba(0, 0, 0, 0.7);
         content: '';
         width: 400px;
         height: 300px;
         transition: all 2s;
      }

      &:hover::after {
        background-color: rgba(0, 0, 0, 1);
      }
    }

    div {
      @include project-styling('image.png');
    }


问:
Best way for ASP.NET MVC routing for not-so common scenarios?
UPDATE - 1/21/09:

The only way I've been able to get this working moderately well is to create routes that have additional path info... in other words instead of http://company.com/myDepartment/myTeam/action/id, the routes need to be built to handle paths
like http://company.com/department/myDepartment/team/myTeam and so on.

END UPDATE - 1/21/09:

I have two possible URL conventions that I need to be able to route to the same controllers/views

http://team.department.company.com/Action/id

http://department.company.com/Action/id

http://company.com/Action/id

The above has been pretty easy to handle, since the department/team aliases are in the hostname of the Uri.

However, when I want to implement the following, I've been unable to get it working satisfactorily:

http://company.com/department/team/Action/id

http://company.com/department/Action/id

http://company.com/Action/id

Here are the routes I've defined:

```<code>routes.MapRoute("departmentAndTeam1", "{departmentId}/{teamId}/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

routes.MapRoute("departmentAndTeam2", "{departmentId}/{teamId}/{controller}/{action}", new { controller = "Home", action = "Index" });

routes.MapRoute("departmentAndTeam3", "{departmentId}/{teamId}/{controller}", new { controller = "Home", action = "Index" });

routes.MapRoute("department", "{department}/{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = ""});

routes.MapRoute("departmentAndTeam4", "{departmentId}/{teamId}/", new { controller = "Home", action = "Index"});

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });
</code>```

The problem I'm having is now every action method in my controllers require a departmentId & teamId parameter.  I would really prefer just to be able to "pre-process" the department/team id values in the base controller class that I've got in the OnActionExecuting event handler.  Am I barking up the wrong tree?  Do I need to implement my own Mvc Route handler?

Note:  This is replacing a legacy app and the URL formats need to be kept/maintained.

EDIT:  First off, thanks for the responses so far.  Based on the responses I've received I think I've not been clear enough on one point.  This is (loosely) what my controller looks like:

```<code>public class ControllerBase : Controller
{
    DepartmentDTO department;
    TeamDTO team;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        PopulateDept(filterContext.ActionParameters("departmentId");
        PopulateTeam(filterContext.ActionParameters("teamId");
    }
}
</code>```

However, with this scheme, all controllers that inherit from this class (and are routed appropriately with the routes listed above) expect (what I perceive to be redundant/uneeded) parameters in their action handlers.  I want to avoid having each handler require these "extra" parameters and am looking for suggestions.

Thanks!
-Giorgio

答:
How about this (I haven't tested because I'm not sure what requirements you have other than those 3 particular urls mapping)?</p>

```<code>routes.MapRoute("1", "{department}/{team}/{action}/{id}", new { controller = "Home" });
routes.MapRoute("2", "{department}/{action}/{id}", new { controller = "Home" });
routes.MapRoute("3", "{action}/{id}", new { controller = "Home" });
</code>```

OwnerDisplayName: Giorgio Galante

Body:
UPDATE - 1/21/09:

The only way I've been able to get this working moderately well is to create routes that have additional path info... in other words instead of http://company.com/myDepartment/myTeam/action/id, the routes need to be built to handle paths
like http://company.com/department/myDepartment/team/myTeam and so on.

END UPDATE - 1/21/09:

I have two possible URL conventions that I need to be able to route to the same controllers/views

http://team.department.company.com/Action/id

http://department.company.com/Action/id

http://company.com/Action/id

The above has been pretty easy to handle, since the department/team aliases are in the hostname of the Uri.

However, when I want to implement the following, I've been unable to get it working satisfactorily:

http://company.com/department/team/Action/id

http://company.com/department/Action/id

http://company.com/Action/id

Here are the routes I've defined:

routes.MapRoute("departmentAndTeam1", "{departmentId}/{teamId}/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

routes.MapRoute("departmentAndTeam2", "{departmentId}/{teamId}/{controller}/{action}", new { controller = "Home", action = "Index" });

routes.MapRoute("departmentAndTeam3", "{departmentId}/{teamId}/{controller}", new { controller = "Home", action = "Index" });

routes.MapRoute("department", "{department}/{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = ""});

routes.MapRoute("departmentAndTeam4", "{departmentId}/{teamId}/", new { controller = "Home", action = "Index"});

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

The problem I'm having is now every action method in my controllers require a departmentId & teamId parameter.  I would really prefer just to be able to "pre-process" the department/team id values in the base controller class that I've got in the OnActionExecuting event handler.  Am I barking up the wrong tree?  Do I need to implement my own Mvc Route handler?

Note:  This is replacing a legacy app and the URL formats need to be kept/maintained.

EDIT:  First off, thanks for the responses so far.  Based on the responses I've received I think I've not been clear enough on one point.  This is (loosely) what my controller looks like:

public class ControllerBase : Controller
{
    DepartmentDTO department;
    TeamDTO team;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        PopulateDept(filterContext.ActionParameters("departmentId");
        PopulateTeam(filterContext.ActionParameters("teamId");
    }
}

However, with this scheme, all controllers that inherit from this class (and are routed appropriately with the routes listed above) expect (what I perceive to be redundant/uneeded) parameters in their action handlers.  I want to avoid having each handler require these "extra" parameters and am looking for suggestions.

Thanks!
-Giorgio

LastEditorDisplayName: Giorgio Galante

Body:
How about this (I haven't tested because I'm not sure what requirements you have other than those 3 particular urls mapping)?

routes.MapRoute("1", "{department}/{team}/{action}/{id}", new { controller = "Home" });
routes.MapRoute("2", "{department}/{action}/{id}", new { controller = "Home" });
routes.MapRoute("3", "{action}/{id}", new { controller = "Home" });

OwnerDisplayName: Kevin Pang


问:
SQL Query slow in .NET application but instantaneous in SQL Server Management Studio
Here is the SQL

```<code>SELECT tal.TrustAccountValue
FROM TrustAccountLog AS tal
INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
INNER JOIN Users usr ON usr.UserID = ta.UserID
WHERE usr.UserID = 70402 AND
ta.TrustAccountID = 117249 AND
tal.trustaccountlogid =
(
 SELECT MAX (tal.trustaccountlogid)
 FROM  TrustAccountLog AS tal
 INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
 INNER JOIN Users usr ON usr.UserID = ta.UserID
 WHERE usr.UserID = 70402 AND
 ta.TrustAccountID = 117249 AND
 tal.TrustAccountLogDate < '3/1/2010 12:00:00 AM'
)
</code>```

Basicaly there is a Users table a TrustAccount table and a TrustAccountLog table.

Users: Contains users and their details

TrustAccount: A User can have multiple TrustAccounts.

TrustAccountLog: Contains an audit of all TrustAccount "movements". A
 TrustAccount is associated with multiple TrustAccountLog entries.
Now this query executes in milliseconds inside SQL Server Management Studio, but for some strange reason it takes forever in my C# app and even timesout (120s) sometimes.

Here is the code in a nutshell. It gets called multiple times in a loop and the statement gets prepared.

cmd.CommandTimeout = Configuration.DBTimeout;
cmd.CommandText = @"SELECT tal.TrustAccountValue FROM TrustAccountLog AS tal
INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
INNER JOIN Users usr ON usr.UserID = ta.UserID
WHERE usr.UserID = @UserID1 AND
ta.TrustAccountID = @TrustAccountID1 AND
tal.trustaccountlogid =
(
    SELECT MAX (tal.trustaccountlogid) FROM  TrustAccountLog AS tal
    INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
    INNER JOIN Users usr ON usr.UserID = ta.UserID
    WHERE usr.UserID = @UserID2 AND
    ta.TrustAccountID = @TrustAccountID2 AND
    tal.TrustAccountLogDate < @TrustAccountLogDate2
)";
cmd.Parameters.Add("@TrustAccountID1", SqlDbType.Int).Value = trustAccountId;
cmd.Parameters.Add("@UserID1", SqlDbType.Int).Value = userId;
cmd.Parameters.Add("@TrustAccountID2", SqlDbType.Int).Value = trustAccountId;
cmd.Parameters.Add("@UserID2", SqlDbType.Int).Value = userId;
cmd.Parameters.Add("@TrustAccountLogDate2", SqlDbType.DateTime).Value =TrustAccountLogDate;

// And then...

reader = cmd.ExecuteReader();
if (reader.Read())
{
   double value = (double)reader.GetValue(0);
   if (System.Double.IsNaN(value))
      return 0;
   else
      return value;
}
else
   return 0;
```

答:
I had a problem with a different root cause that exactly matched the title of this question's symptoms.

In my case the problem was that the result set was held open by the application's .NET code while it looped through every returned record and executed another three queries against the database! Over several thousand rows this misleadingly made the original query look like it had been slow to complete based on timing information from SQL Server.

The fix was therefore to refactor the .NET code making the calls so that it doesn't hold the result set open while processing each row.

Body:
Here is the SQL

SELECT tal.TrustAccountValue
FROM TrustAccountLog AS tal
INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
INNER JOIN Users usr ON usr.UserID = ta.UserID
WHERE usr.UserID = 70402 AND
ta.TrustAccountID = 117249 AND
tal.trustaccountlogid =
(
 SELECT MAX (tal.trustaccountlogid)
 FROM  TrustAccountLog AS tal
 INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
 INNER JOIN Users usr ON usr.UserID = ta.UserID
 WHERE usr.UserID = 70402 AND
 ta.TrustAccountID = 117249 AND
 tal.TrustAccountLogDate < '3/1/2010 12:00:00 AM'
)

Basicaly there is a Users table a TrustAccount table and a TrustAccountLog table.

Users: Contains users and their details

TrustAccount: A User can have multiple TrustAccounts.

TrustAccountLog: Contains an audit of all TrustAccount "movements". A
 TrustAccount is associated with multiple TrustAccountLog entries.
Now this query executes in milliseconds inside SQL Server Management Studio, but for some strange reason it takes forever in my C# app and even timesout (120s) sometimes.

Here is the code in a nutshell. It gets called multiple times in a loop and the statement gets prepared.

cmd.CommandTimeout = Configuration.DBTimeout;
cmd.CommandText = @"SELECT tal.TrustAccountValue FROM TrustAccountLog AS tal
INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
INNER JOIN Users usr ON usr.UserID = ta.UserID
WHERE usr.UserID = @UserID1 AND
ta.TrustAccountID = @TrustAccountID1 AND
tal.trustaccountlogid =
(
    SELECT MAX (tal.trustaccountlogid) FROM  TrustAccountLog AS tal
    INNER JOIN TrustAccount ta ON ta.TrustAccountID = tal.TrustAccountID
    INNER JOIN Users usr ON usr.UserID = ta.UserID
    WHERE usr.UserID = @UserID2 AND
    ta.TrustAccountID = @TrustAccountID2 AND
    tal.TrustAccountLogDate < @TrustAccountLogDate2
)";
cmd.Parameters.Add("@TrustAccountID1", SqlDbType.Int).Value = trustAccountId;
cmd.Parameters.Add("@UserID1", SqlDbType.Int).Value = userId;
cmd.Parameters.Add("@TrustAccountID2", SqlDbType.Int).Value = trustAccountId;
cmd.Parameters.Add("@UserID2", SqlDbType.Int).Value = userId;
cmd.Parameters.Add("@TrustAccountLogDate2", SqlDbType.DateTime).Value =TrustAccountLogDate;

// And then...

reader = cmd.ExecuteReader();
if (reader.Read())
{
   double value = (double)reader.GetValue(0);
   if (System.Double.IsNaN(value))
      return 0;
   else
      return value;
}
else
   return 0;


问:
how to reduce the height of the navigation bar in css
I'm trying to reduce the height of my navigation bar.  when I use min-height property, it adds a scrollbar to the navigation bar which makes it not so appealing. I would like to align the logo to the extreme left and the rest of the contents to the extreme right.I have attached the code below. Please help me to fix it.

  .navigation {
      background-color: rgba(15,58,114,0.9);
      overflow-y: auto;
      position: fixed;
      left: 0;
      top: 0;
      text-align: left;
      width: 100%;
      z-index: 10000;
      box-sizing: border-box;
    }
     .log {
     text-align: right;
     top: 0;
     margin: 0 auto;
     right: 0;

     }
         ul {
         padding: 0;
       }
         li {
        color: White;
        display: inline-block;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        margin: 16px 20px;
        text-transform: uppercase;
       }
         li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoraton: none;
       }
        li a:hover {
        background-color: rgba(0,0,0,0);
       }
        #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
       }

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navigation">
    <ul>
       <li id="logo">LOGO</li>
       <div class="log">
       <li>LOGIN</li>
       <li>JOIN WITH US</li>
       </div>
     </ul>
  </div></code>```

答:
You had the scroll bar because the contents were too big and you had overflow-y: auto; Overflow controls the behavior when the contents are too big for the parent div size.

The float property can be used to move elements to different sides of the viewer in a consistent manner.

Your code is still not responsive and will not display correctly on screens smaller that 365px wide. The support range will get smaller if you add more menu items.

There are a lot of resources you can check out for making a responsive menu

Is this what you wanted?

body {
  margin: 0 auto;
  padding: 0
}

.navigation {
  background-color: rgba(15, 58, 114, 0.9);
  position: fixed;
  height: 60px;
  line-height: 60px; /* needs to be the same height as your navigation div */
  top: 0;
  width: 100%;
  z-index: 10000;
}

.log {
  float: right; /* pulls the div to the right side */
}

ul {
  padding: 0;
  margin: 0 auto;
}

li {
  color: White;
  display: inline-block;
  font-family: 'Raleway', sans-serif;
  font-size: 18px;
  font-weight: 300;
  margin: 0 auto;
  text-transform: uppercase;
}

li a {
  color: White;
  text-align: Center;
  padding: 0 10px;
  text-decoration: none;
}

li a:hover {
  color:wheat;
}

#logo {
  color: #FFFFFF;
  font-family: 'Vollkorn';
  font-size: 34px;
  padding: 0px 10px;
  float: left; /* pulls the div to the left side */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navigation">
  <ul>
    <li id="logo">LOGO</li>
    <div class="log">
      <li>LOGIN</li>
      <li>JOIN WITH US</li>
    </div>
  </ul></code>```

Body:
I'm trying to reduce the height of my navigation bar.  when I use min-height property, it adds a scrollbar to the navigation bar which makes it not so appealing. I would like to align the logo to the extreme left and the rest of the contents to the extreme right.I have attached the code below. Please help me to fix it.

  .navigation {
      background-color: rgba(15,58,114,0.9);
      overflow-y: auto;
      position: fixed;
      left: 0;
      top: 0;
      text-align: left;
      width: 100%;
      z-index: 10000;
      box-sizing: border-box;
    }
     .log {
     text-align: right;
     top: 0;
     margin: 0 auto;
     right: 0;

     }
         ul {
         padding: 0;
       }
         li {
        color: White;
        display: inline-block;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        margin: 16px 20px;
        text-transform: uppercase;
       }
         li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoraton: none;
       }
        li a:hover {
        background-color: rgba(0,0,0,0);
       }
        #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
       }

LOGO

LOGIN

JOIN WITH US

Body:
You had the scroll bar because the contents were too big and you had overflow-y: auto; Overflow controls the behavior when the contents are too big for the parent div size.

The float property can be used to move elements to different sides of the viewer in a consistent manner.

Your code is still not responsive and will not display correctly on screens smaller that 365px wide. The support range will get smaller if you add more menu items.

There are a lot of resources you can check out for making a responsive menu

Is this what you wanted?

body {
  margin: 0 auto;
  padding: 0
}

.navigation {
  background-color: rgba(15, 58, 114, 0.9);
  position: fixed;
  height: 60px;
  line-height: 60px; /* needs to be the same height as your navigation div */
  top: 0;
  width: 100%;
  z-index: 10000;
}

.log {
  float: right; /* pulls the div to the right side */
}

ul {
  padding: 0;
  margin: 0 auto;
}

li {
  color: White;
  display: inline-block;
  font-family: 'Raleway', sans-serif;
  font-size: 18px;
  font-weight: 300;
  margin: 0 auto;
  text-transform: uppercase;
}

li a {
  color: White;
  text-align: Center;
  padding: 0 10px;
  text-decoration: none;
}

li a:hover {
  color:wheat;
}

#logo {
  color: #FFFFFF;
  font-family: 'Vollkorn';
  font-size: 34px;
  padding: 0px 10px;
  float: left; /* pulls the div to the left side */
}

<div class="navigation">
  <ul>
    <li id="logo"><a href="#logo">LOGO</a></li>
    <div class="log">
      <li><a href="/login.html">LOGIN</a></li>
      <li><a href="#join">JOIN WITH US</a></li>
    </div>
  </ul>


问:
Type UIRectCorner has no member isRightPage in Swift 3
We have the following variable of type UIImage that no longer works in Swift 3. Is there anyone with this same issue facing with UIImage class in such a way. Here is the code:

```<code>var image: UIImage? {
        didSet {
            var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft
            imageView.image = image!.imageByScalingAndCroppingForSize(bounds.size).imageWithRoundedCornersSize(20, corners: corners)
        }
    }
</code>```

The error we're getting is "Type of expression is ambigouos without more context" for var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft

答:
You're not actually getting the int value from the enum therefore the statement was failing.

Try this:

```<code>var corners: UIRectCorner = UIRectCorner(rawValue: isRightPage ? (UIRectCorner.topRight.rawValue | UIRectCorner.bottomRight.rawValue) : (UIRectCorner.topLeft.rawValue | UIRectCorner.bottomLeft.rawValue))
</code>```

Body:
We have the following variable of type UIImage that no longer works in Swift 3. Is there anyone with this same issue facing with UIImage class in such a way. Here is the code:

var image: UIImage? {
        didSet {
            var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft
            imageView.image = image!.imageByScalingAndCroppingForSize(bounds.size).imageWithRoundedCornersSize(20, corners: corners)
        }
    }

The error we're getting is "Type of expression is ambigouos without more context" for var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft

Body:
You're not actually getting the int value from the enum therefore the statement was failing.

Try this:

var corners: UIRectCorner = UIRectCorner(rawValue: isRightPage ? (UIRectCorner.topRight.rawValue | UIRectCorner.bottomRight.rawValue) : (UIRectCorner.topLeft.rawValue | UIRectCorner.bottomLeft.rawValue))


问:
Vaadin custom client side widget cannot compile 'No plugin found for prefix 'vaadin''
I trying to create a custom client side widget with eclipse IDE. when i click compile widgetset option from the toolbar it stops with following error. This topic is a duplicate, but no suitable answer.

```<code>[INFO] Scanning for projects...
[INFO] Downloading:
https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
metadata.xml
[INFO] Downloading:
https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
[INFO] Downloaded:
https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
metadata.xml (13 KB at 6.2 KB/sec)
[INFO] Downloaded:
https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
(20 KB at 8.4 KB/sec)
[INFO] ---------------------------------------------------------------------
---
[INFO] BUILD FAILURE
[INFO] ---------------------------------------------------------------------
---
[INFO] Total time: 5.004 s
[INFO] Finished at: 2017-07-04T15:48:53+05:30
[INFO] Final Memory: 15M/143M
[INFO] ---------------------------------------------------------------------
---
[ERROR] No plugin found for prefix 'vaadin' in the current project and in
the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available
from the repositories [local (C:\Users\xxxx\.m2\repository), central
(https://repo.maven.apache.org/maven2)] -> [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]
</code>```

My Pom.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>logicalintelligence.widget.navigationdrawer</groupId>
    <artifactId>navigationdrawer</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Navigationdrawer Add-on</name>

    <prerequisites>
        <maven>3</maven>
    </prerequisites>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <vaadin.version>7.7.10</vaadin.version>
        <vaadin.plugin.version>7.7.10</vaadin.plugin.version>

        <!-- ZIP Manifest fields -->
        <Implementation-Version>${project.version}</Implementation-Version>
        <!-- Must not change this because of the Directory -->
        <Implementation-Title>${project.name}</Implementation-Title>
        <Implementation-Vendor>${project.organization.name}</Implementation-Vendor>
        <Vaadin-License-Title>Apache License 2.0</Vaadin-License-Title>
        <Vaadin-Addon>${project.artifactId}-${project.version}.jar</Vaadin-Addon>
    </properties>

    <licenses>
        <license>
            <name>Apache 2</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <repositories>
        <repository>
            <id>vaadin-addons</id>
            <url>http://maven.vaadin.com/vaadin-addons</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-server</artifactId>
            <version>${vaadin.version}</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-client</artifactId>
            <version>${vaadin.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- This can be replaced with TestNG or some other test framework supported by the surefire plugin -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <archive>
                        <index>true</index>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                        <manifestEntries>
                            <!-- Package format version - do not change -->
                            <Vaadin-Package-Version>1</Vaadin-Package-Version>
                            <Vaadin-License-Title>${Vaadin-License-Title}</Vaadin-License-Title>
                            <Vaadin-Widgetsets>logicalintelligence.widget.navigationdrawer.navigationdrawer.WidgetSet</Vaadin-Widgetsets>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <executions>
                    <execution>
                        <id>attach-javadoc</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <appendAssemblyId>false</appendAssemblyId>
                    <descriptors>
                        <descriptor>assembly/assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <phase>install</phase>
                    </execution>
                </executions>
            </plugin>

            <!-- Testing -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
            </plugin>
        </plugins>

        <!-- This is needed for the sources required by the client-side compiler to be
            included in the produced JARs -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <excludes>
                    <exclude>rebel.xml</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

    </build>

    <profiles>
        <profile>
            <!-- Vaadin pre-release repositories -->
            <id>vaadin-prerelease</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>

            <repositories>
                <repository>
                    <id>vaadin-prereleases</id>
                    <url>http://maven.vaadin.com/vaadin-prereleases</url>
                </repository>
                <repository>
                    <id>vaadin-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>vaadin-prereleases</id>
                    <url>http://maven.vaadin.com/vaadin-prereleases</url>
                </pluginRepository>
                <pluginRepository>
                    <id>vaadin-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>

</project>
</code>```

答:
Yes Morfic is right, I solved the problem by adding followings to the pom.xml</p>

```<code>     <plugin>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-maven-plugin</artifactId>
            <version>${vaadin.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>update-theme</goal>
                        <goal>update-widgetset</goal>
                        <goal>compile</goal>
                        <!-- Comment out compile-theme goal to use on-the-fly theme compilation -->
                        <goal>compile-theme</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

Body:
I trying to create a custom client side widget with eclipse IDE. when i click compile widgetset option from the toolbar it stops with following error. This topic is a duplicate, but no suitable answer.

[INFO] Scanning for projects...
[INFO] Downloading:
https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
metadata.xml
[INFO] Downloading:
https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
[INFO] Downloaded:
https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
metadata.xml (13 KB at 6.2 KB/sec)
[INFO] Downloaded:
https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
(20 KB at 8.4 KB/sec)
[INFO] ---------------------------------------------------------------------
---
[INFO] BUILD FAILURE
[INFO] ---------------------------------------------------------------------
---
[INFO] Total time: 5.004 s
[INFO] Finished at: 2017-07-04T15:48:53+05:30
[INFO] Final Memory: 15M/143M
[INFO] ---------------------------------------------------------------------
---
[ERROR] No plugin found for prefix 'vaadin' in the current project and in
the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available
from the repositories [local (C:\Users\xxxx\.m2\repository), central
(https://repo.maven.apache.org/maven2)] -> [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]

My Pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>logicalintelligence.widget.navigationdrawer</groupId>
    <artifactId>navigationdrawer</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Navigationdrawer Add-on</name>

    <prerequisites>
        <maven>3</maven>
    </prerequisites>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <vaadin.version>7.7.10</vaadin.version>
        <vaadin.plugin.version>7.7.10</vaadin.plugin.version>

        <Implementation-Version>${project.version}</Implementation-Version>

        <Implementation-Title>${project.name}</Implementation-Title>
        <Implementation-Vendor>${project.organization.name}</Implementation-Vendor>
        <Vaadin-License-Title>Apache License 2.0</Vaadin-License-Title>
        <Vaadin-Addon>${project.artifactId}-${project.version}.jar</Vaadin-Addon>
    </properties>

    <licenses>
        <license>
            <name>Apache 2</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <repositories>
        <repository>
            <id>vaadin-addons</id>
            <url>http://maven.vaadin.com/vaadin-addons</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-server</artifactId>
            <version>${vaadin.version}</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-client</artifactId>
            <version>${vaadin.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <archive>
                        <index>true</index>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                        <manifestEntries>

                            <Vaadin-Package-Version>1</Vaadin-Package-Version>
                            <Vaadin-License-Title>${Vaadin-License-Title}</Vaadin-License-Title>
                            <Vaadin-Widgetsets>logicalintelligence.widget.navigationdrawer.navigationdrawer.WidgetSet</Vaadin-Widgetsets>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <executions>
                    <execution>
                        <id>attach-javadoc</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <appendAssemblyId>false</appendAssemblyId>
                    <descriptors>
                        <descriptor>assembly/assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <phase>install</phase>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <excludes>
                    <exclude>rebel.xml</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

    </build>

    <profiles>
        <profile>

            <id>vaadin-prerelease</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>

            <repositories>
                <repository>
                    <id>vaadin-prereleases</id>
                    <url>http://maven.vaadin.com/vaadin-prereleases</url>
                </repository>
                <repository>
                    <id>vaadin-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>vaadin-prereleases</id>
                    <url>http://maven.vaadin.com/vaadin-prereleases</url>
                </pluginRepository>
                <pluginRepository>
                    <id>vaadin-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>

</project>

Body:
Yes Morfic is right, I solved the problem by adding followings to the pom.xml

     <plugin>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-maven-plugin</artifactId>
            <version>${vaadin.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>update-theme</goal>
                        <goal>update-widgetset</goal>
                        <goal>compile</goal>
                        <!-- Comment out compile-theme goal to use on-the-fly theme compilation -->
                        <goal>compile-theme</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>


问:
Creating a regex to replace each matched character of a string with same character
In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).

For example

```<code>Input: HGHG8686HGHG8686H

Output: XXXXXXXXXXXXX686H
</code>```

The Regex I wrote to perform the replace on the string is as follows

```<code>[a-zA-Z0-9].{12}
</code>```

Code:

```<code>const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');
</code>```

The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?

答:
you can use a function inside replace to do this, something like this will do:

var str = "HGHG8686HGHG8686H"
var regexp = /[a-zA-Z0-9]+(?=....)/g;
var modifiedStr = str.replace(regexp, function ($2) {
    return ('X'.repeat($2.length +1));
});
console.log(modifiedStr);```

Body:
In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).

For example

Input: HGHG8686HGHG8686H

Output: XXXXXXXXXXXXX686H

The Regex I wrote to perform the replace on the string is as follows

[a-zA-Z0-9].{12}

Code:

const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');

The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?


答:
You can achieve using following method:

      var str = "HGHG8686HGHG8686H"

      var replaced=''

      var match = str.match(/.+/)

      for(i=0;i<match[0].length-4;i++){

          str = match[0][i]

          replaced += "X"

      }

      replaced += match[0].substr(match[0].length-4)

      console.log(replaced);```

Title: Creating a regex to replace each matched character of a string with same character


问:
What is the difference between clean project and delete build directory of Android?
Directly delete the build folder much faster than the clean project, I would like to know what the clean project has done.</p>

答:
Clean the project does the same operation(delete the bin and obj folders for the respective solution or projects). But it sometimes not delete the complete folders.

So, the recommendation is to rebuild the solution or project which will perform both the clean and build operation simultaneously.


问:
SQL Server 2008: Rename an element using XML DML?
Is it possible to use an XML DML statement to rename an element in an untyped XML column?

I am in the process of updating an XML Schema Collection on an XML column and need to patch the existing XML instances by renaming one element before I can apply the latest schema.

As far as I can tell from the docs you can only insert / delete nodes or replace their value.

答:
As the saying goes, "Where there's a will there's a way"

Here's two methods:
the first is to simply replace the previous xml with a new xml constructed from the original with the new element name. In my example I've changed Legs/Leg to Limbs/Limb this could get very complicated for anything but the simplest schema

And secondly, a more appropriate approach of combining insert and delete.

I've combined them into one simple example:

```<code>declare @xml as xml = '<animal species="Mouse">
  <legs>
    <leg>Front Right</leg>
    <leg>Front Left</leg>
    <leg>Back Right</leg>
    <leg>Back Left</leg>
  </legs>
</animal>'

set @xml = (select
     t.c.value('@species', 'varchar(max)') as '@species'
    ,(select
     ti.C.value('.', 'varchar(max)')
from @Xml.nodes('//animal/legs/leg') ti(c) for xml path('limb'), /* root('limb'), */type) as    limbs
from @xml.nodes('//*:animal') t(c) for xml path('animal'), type)

select @xml;

while (@xml.exist('/animal/limbs/limb') = 1) begin
    /*insert..*/
    set @xml.modify('
            insert <leg>{/animal/limbs/limb[1]/text()}</leg>
            before (/animal/limbs/limb)[1]
        ');
    /*delete..*/
    set @xml.modify('delete (/animal/limbs/limb)[1]');
end

set @xml.modify('
        insert <legs>{/animal/limbs/leg}</legs>
        before (/animal/limbs)[1]
    ');
set @xml.modify('delete (/animal/limbs)[1]');

select @xml;
</code>```

Body:
As the saying goes, "Where there's a will there's a way"

Here's two methods:
the first is to simply replace the previous xml with a new xml constructed from the original with the new element name. In my example I've changed Legs/Leg to Limbs/Limb this could get very complicated for anything but the simplest schema

And secondly, a more appropriate approach of combining insert and delete.

I've combined them into one simple example:

declare @xml as xml = '<animal species="Mouse">
  <legs>
    <leg>Front Right</leg>
    <leg>Front Left</leg>
    <leg>Back Right</leg>
    <leg>Back Left</leg>
  </legs>
</animal>'

set @xml = (select
     t.c.value('@species', 'varchar(max)') as '@species'
    ,(select
     ti.C.value('.', 'varchar(max)')
from @Xml.nodes('//animal/legs/leg') ti(c) for xml path('limb'), /* root('limb'), */type) as    limbs
from @xml.nodes('//*:animal') t(c) for xml path('animal'), type)

select @xml;

while (@xml.exist('/animal/limbs/limb') = 1) begin
    /*insert..*/
    set @xml.modify('
            insert <leg>{/animal/limbs/limb[1]/text()}</leg>
            before (/animal/limbs/limb)[1]
        ');
    /*delete..*/
    set @xml.modify('delete (/animal/limbs/limb)[1]');
end

set @xml.modify('
        insert <legs>{/animal/limbs/leg}</legs>
        before (/animal/limbs)[1]
    ');
set @xml.modify('delete (/animal/limbs)[1]');

select @xml;