问:
SQL Server Full Text Search to find containing characters
I have a table with a column Document that is FullText Index.
Let say I have this in this table:

```<code>| ID | Document                    |
| 1  | WINTER  SUMMER SPRING OTHER |
</code>```

My requirement is to find rows that contains 'ER'.

For this I am querying like this:

```<code>SELECT TOP 100
    [FullTextSearch].[Document], [FullTextSearch].[ID]
FROM
    [FullTextSearch]
WHERE
    CONTAINS(Document, '"*ER*"')
</code>```

But this is not working.

Please suggest what should be best way to do this using FullTextSearch.

I am expecting id 1 should be returned.

答:
It's a wildcard query...This should work.

```<code> SELECT TOP 100
[FullTextSearch].[Document], [FullTextSearch].[ID]
FROM
[FullTextSearch]
WHERE
Document like '%ER%'
</code>```

========OR=============

```<code>   SELECT TOP 100
        [FullTextSearch].[Document], [FullTextSearch].[ID]
    FROM
    [FullTextSearch]
    WHERE
    CONTAINS(Document, '%ER%')
</code>```

Body:
I have a table with a column Document that is FullText Index.
Let say I have this in this table:

| ID | Document                    |
| 1  | WINTER  SUMMER SPRING OTHER |

My requirement is to find rows that contains 'ER'.

For this I am querying like this:

SELECT TOP 100
    [FullTextSearch].[Document], [FullTextSearch].[ID]
FROM
    [FullTextSearch]
WHERE
    CONTAINS(Document, '"*ER*"')

But this is not working.

Please suggest what should be best way to do this using FullTextSearch.

I am expecting id 1 should be returned.

Body:
It's a wildcard query...This should work.

 SELECT TOP 100
[FullTextSearch].[Document], [FullTextSearch].[ID]
FROM
[FullTextSearch]
WHERE
Document like '%ER%'

========OR=============

   SELECT TOP 100
        [FullTextSearch].[Document], [FullTextSearch].[ID]
    FROM
    [FullTextSearch]
    WHERE
    CONTAINS(Document, '%ER%')


来源: stackexchange

问:
Connection to URL
This is my code

```<code>try{
URL url = new URL("url to tes");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();

if(urlConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
   test=true
}catch()...

if(test){
    tv.setText("yesssss");
}else{
    tv.setText("noooo");
</code>```

info: so I put this code on my mainActivity to test if I know how to connect on a url. My goal is to connect to web service that return me a json. But first I want to know how to connect.

Do you know a url that I can test with this code?
   And my code here, is he good for connection?

Also tv is my TextView it work. It was to minimise the code.

I know after that I got to catch the InputStream and work with it to catch my json.

答:
Use URLUtil to validate the URL as below.

```<code>URLUtil.isValidUrl(url)
</code>```

It will return True if URL is valid and false if URL is invalid.

ContentLicense: CC BY-SA 3.0

Title: Connection to URL

Body:
This is my code

try{
URL url = new URL("url to tes");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();

if(urlConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
   test=true
}catch()...

if(test){
    tv.setText("yesssss");
}else{
    tv.setText("noooo");

info: so I put this code on my mainActivity to test if I know how to connect on a url. My goal is to connect to web service that return me a json. But first I want to know how to connect.

Do you know a url that I can test with this code?
   And my code here, is he good for connection?

Also tv is my TextView it work. It was to minimise the code.

I know after that I got to catch the InputStream and work with it to catch my json.

Body:
Use URLUtil to validate the URL as below.

URLUtil.isValidUrl(url)

It will return True if URL is valid and false if URL is invalid.


问:
Iterate through two dimensional array while changing each element
I want to fill a two dimensional array with certain values. I want to get:

```<code>[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]
</code>```

How can I do it?

This is my code:

```<code>game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field
</code>```

Body:
I want to fill a two dimensional array with certain values. I want to get:

[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]

How can I do it?

This is my code:

game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field

Body:
Ternary numbers?

(0...9).map{|n| "Num#{n.to_s(3).rjust(2,"0")}"}.each_slice(3).to_a


问:
How to send email from localhost using CodeIgniter with Gmail

Hello everyone, I'm currently working on a CodeIgniter application in which user will be able to create their own accounts,etc.

I'm trying to create a function to recover password in case is lost or forgotten.

Here is my code:

```<code>    public function admin_recover(){

        $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[7]|valid_email');

        if($this->form_validation->run() == FALSE){
        //Load View Into Template

        $this->template->load('admin', 'login', 'users/recover');

    } else {
        //Get Post Data
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        $user_email = $this->User_model->get_list();

        if($user_email){
            $user_email_data = array(
                'email' => true
            );
        ///////// Sending email
        // Configure email library

        $config['wordwrap'] = FALSE;
        $config['mailtype'] = 'html';
        $config['crlf'] = '\r\n';
        $config['charset']='utf-8';
        $config['newline']="\r\n";
        $config['priority']=1;
        $config['protocol']='smtp';
        $config['smtp_host']='ssl://smtp.gmail.com';
        $config['smtp_port']='25';
        $config['smtp_timeout']='30';
        $config['smtp_user']='kuaf1998@gmail.com';
        $config['smtp_pass']='mypassword';
        $config['newline']="\r\n";

        $this->load->library('email',$config);
        $this->email->set_newline("\r\n");

        $this->email->from('no-reply@socialgeek.com', 'Social Geek');
        $this->email->to('kebin1421@hotmail.com');
        $this->email->subject('Email Test');
        $this->email->message('Testing the email class.');
        $this->email->send();

        if($this->email->send())
        $this->session->set_flashdata("success","Email sent successfully.");
        else
        $this->session->set_flashdata("error","Error in sending Email.");

        echo $this->email->print_debugger();
        //////////////
        }
    }
}
</code>```

I'm using the gmail smtp service to send emails from my localhost but I'm still unable to make it happen. Any idea how can I fix this?

I already did some changes on(I'm using xampp) the ini file which is found on my xampp>php>php.ini

When I go to the view, I get this error:

Thanks for helping.

答:
Try to use these configuration settings below and let me know if it works for you.</p>

```<code>$config = array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com',
    'smtp_port' => 465,
    'smtp_user' => 'user@gmail.com',
    'smtp_pass' => 'yourpassword',
    'mailtype' => 'html',
    'charset' => 'iso-8859-1'
);
</code>```

Body:
Hello everyone, I'm currently working on a CodeIgniter application in which user will be able to create their own accounts,etc.

I'm trying to create a function to recover password in case is lost or forgotten.

Here is my code:

    public function admin_recover(){

        $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[7]|valid_email');

        if($this->form_validation->run() == FALSE){
        //Load View Into Template

        $this->template->load('admin', 'login', 'users/recover');

    } else {
        //Get Post Data
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        $user_email = $this->User_model->get_list();

        if($user_email){
            $user_email_data = array(
                'email' => true
            );
        ///////// Sending email
        // Configure email library

        $config['wordwrap'] = FALSE;
        $config['mailtype'] = 'html';
        $config['crlf'] = '\r\n';
        $config['charset']='utf-8';
        $config['newline']="\r\n";
        $config['priority']=1;
        $config['protocol']='smtp';
        $config['smtp_host']='ssl://smtp.gmail.com';
        $config['smtp_port']='25';
        $config['smtp_timeout']='30';
        $config['smtp_user']='kuaf1998@gmail.com';
        $config['smtp_pass']='mypassword';
        $config['newline']="\r\n";

        $this->load->library('email',$config);
        $this->email->set_newline("\r\n");

        $this->email->from('no-reply@socialgeek.com', 'Social Geek');
        $this->email->to('kebin1421@hotmail.com');
        $this->email->subject('Email Test');
        $this->email->message('Testing the email class.');
        $this->email->send();

        if($this->email->send())
        $this->session->set_flashdata("success","Email sent successfully.");
        else
        $this->session->set_flashdata("error","Error in sending Email.");

        echo $this->email->print_debugger();
        //////////////
        }
    }
}

I'm using the gmail smtp service to send emails from my localhost but I'm still unable to make it happen. Any idea how can I fix this?

I already did some changes on(I'm using xampp) the ini file which is found on my xampp>php>php.ini

When I go to the view, I get this error:

Thanks for helping.

Body:
Try to use these configuration settings below and let me know if it works for you.

$config = array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com',
    'smtp_port' => 465,
    'smtp_user' => 'user@gmail.com',
    'smtp_pass' => 'yourpassword',
    'mailtype' => 'html',
    'charset' => 'iso-8859-1'
);


问:
group by a pair of a column sql
I have a table in SQL name: pgcPhieuThu

I want to creat a stored procedure for SoPhieu with:
+ if parameter = 0 then SoPhieu= 'PT-1->n'
else parameter = 1 then SoPhieu= 'BC-1->n'

```<code>ALTER proc pgcPhieuThu_TaoSoPhieu3
 @HinhThuc int,@SoPhieu NVARCHAR(50) OUTPUT
as
declare @MaPT INT
SELECT  @MaPT= ISNULL(SUBSTRING(MAX(pgcPhieuThu.SoPhieu),4, LEN(pgcPhieuThu.SoPhieu)),0) + 1
FROM pgcphieuthu
    GROUP BY SUBSTRING(pgcPhieuThu.SoPhieu,1,3)
SET @SoPhieu = CASE WHEN @HinhThuc = 0 then 'PT-'+ CAST(@MaPT AS NVARCHAR(50))
                    ELSE 'BC-'+ CAST(@MaPT AS NVARCHAR(50))
</code>```

but Column 'pgcphieuthu.SoPhieu' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

答:
SoPhieu is not an column in the table. Its an parameter to the stored procedure.
so replace the 'SoPhieu' to 'SoPhieu'with in the stored procedure. It should work then on. </p>

Title: group by a pair of a column sql

Body:
I have a table in SQL name: pgcPhieuThu

I want to creat a stored procedure for SoPhieu with:
+ if parameter = 0 then SoPhieu= 'PT-1->n'
else parameter = 1 then SoPhieu= 'BC-1->n'

ALTER proc pgcPhieuThu_TaoSoPhieu3
 @HinhThuc int,@SoPhieu NVARCHAR(50) OUTPUT
as
declare @MaPT INT
SELECT  @MaPT= ISNULL(SUBSTRING(MAX(pgcPhieuThu.SoPhieu),4, LEN(pgcPhieuThu.SoPhieu)),0) + 1
FROM pgcphieuthu
    GROUP BY SUBSTRING(pgcPhieuThu.SoPhieu,1,3)
SET @SoPhieu = CASE WHEN @HinhThuc = 0 then 'PT-'+ CAST(@MaPT AS NVARCHAR(50))
                    ELSE 'BC-'+ CAST(@MaPT AS NVARCHAR(50))

but Column 'pgcphieuthu.SoPhieu' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.


问:
In PHP how do i use a function where one of the parameters is a class:
In magento 2.2.1 there is a function that i am trying to use that has a class as a parameter:

```<code>public function add($sku, \Magento\Catalog\Api\Data\ProductTierPriceInterface $tierPrice);
</code>```

This used to just have 4 parameters that were passed to it and was used like below:

```<code>$this->tierInterface->add($sku,$groupId,$price, '1');
</code>```

Now however the second parameter needs to be used in place of these old parameters where \Magento\Catalog\Api\Data\ProductTierPriceInterface $tierPrice has within the below methods that i need to use instead:

public function setQty($qty);

public function setValue($value);

public function setCustomerGroupId($customerGroupId);

How can i use these new methods to correctly pass the values to the function?

答:
In Magento 2 there is a concrete implementation of ProductTierPriceInterface that you should use which is named TierPrice.

Your new code would look like this :

```<code># Pretty sure dependency injection should be needed there.
$tierPrice = new TierPrice();
$tierPrice->setQty(1);
$tierPrice->setValue($price);
$tierPrice->setCustomerGroupId($groupId);

$this->tierInterface->add($sku, $tierPrice);
</code>```

Body:
In magento 2.2.1 there is a function that i am trying to use that has a class as a parameter:

public function add($sku, \Magento\Catalog\Api\Data\ProductTierPriceInterface $tierPrice);

This used to just have 4 parameters that were passed to it and was used like below:

$this->tierInterface->add($sku,$groupId,$price, '1');

Now however the second parameter needs to be used in place of these old parameters where \Magento\Catalog\Api\Data\ProductTierPriceInterface $tierPrice has within the below methods that i need to use instead:

public function setQty($qty);

public function setValue($value);

public function setCustomerGroupId($customerGroupId);

How can i use these new methods to correctly pass the values to the function?

Body:
In Magento 2 there is a concrete implementation of ProductTierPriceInterface that you should use which is named TierPrice.

Your new code would look like this :

# Pretty sure dependency injection should be needed there.
$tierPrice = new TierPrice();
$tierPrice->setQty(1);
$tierPrice->setValue($price);
$tierPrice->setCustomerGroupId($groupId);

$this->tierInterface->add($sku, $tierPrice);


问:
Android gradle sync issue
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

```<code>C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project
</code>```

build.gradle  (app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle  (project)

```<code>buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

i didnt update android studio or gradle. Android support repository is installed.

答:
use this </p>

```<code>repositories {
        maven { url 'https://maven.google.com/' }
    }
</code>```

Title: Android gradle sync issue

Body:
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project

build.gradle  (app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'

build.gradle  (project)

buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

i didnt update android studio or gradle. Android support repository is installed.

Body:
use this

repositories {
        maven { url 'https://maven.google.com/' }
    }


问:
Guava Cache property update on the fly
Can I update the Guava cache properties like initialCapacity, concurrencyLevel, durationInSeconds, maximumSize etc on the fly? For example, can I update maximumSize of the cache Once the cache is already up and initialized from a program? </p>

答: No, these properties can only be set when first creating your cache via CacheBuilder. If you need to change the caching semantics the easiest option is to create a new cache instance and copy the contents of the old cache to the new one.

Title: Guava Cache property update on the fly


问:
Simple explanation of "Unified Modelling Language", why is it important?
i am new to asp.net and i was told that i need to know UML thoroughly to build successful software, is this correct? i mean cant i just "code and fix" and "model" in my brain. how important is UML and what is the best way to learn it?</p>

答:
UML is a standard used to convey information about the design of an object oriented software system in a (mostly) graphical format.

It is important as it makes communicating about such a system easier.

ContentLicense: CC BY-SA 2.5


问:
AsyncTask vs new Thread
I have an app that use with web service.

The action with the web service maybe will take a few seconds, when i search in google a way for handler with this concept i saw that i can use AsyncTask or new Thread.

I explain my basic action app.
In the MainActivity i have two fields username and password.
The MainActivity get from the user the inputs and send those inputs to function in ActionClass and there I use with WSClass.
In the function class i sent to web service and wait to the response.

How can i create the white circle when the user wait to my
actions app?

What the best option to use?(AsyncTask/new Thread)

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ActionClass = ActionClass.getInstans();
        ActionClass.setContext(this);
        ActionClass.login("username","password");// in the future in put a PlainText for username and password.
        if(isLogin == true)
        {
            //here i move to another activity....
        }
    }
}

public class ActionClass
{
    public void setContext(Context context) {
        if (this.context == null) {
            this.context = context;
            WSClass = new WSClass();
        }
    }
  public static ActionClass getInstans() {
        if (instans == null) {
            synchronized (ActionClass.class) {
                if (instans == null)
                    instans = new ActionClass();
            }
        }

        return instans;
    }

    public boolean login(String username, String password) {
    {
        WSClass.loginWs(url,username, password, object.class);
    }
}

     public class WSClass
     {
          public <T> T login(String URL,String username,String  password,
          Class<T> output)
          {

          //...Do Something...
          }
     }
</code>```

Update the qustion
The WsClass use with generic function that get and return <T> variable.

After i checked the AsyncTask... AsyncTask can be use as generic if not how can i resolve this?

The function in WSClass updated above.

Thanks,

Tal

答: if you just do simple task(in your example,it is do login),you'd better choose AsyncTask,but if you want do some more work,and these work are relative,or the task need restart frequently,you'd better choose thread</p>

Title: AsyncTask vs new Thread

Body:
I have an app that use with web service.

The action with the web service maybe will take a few seconds, when i search in google a way for handler with this concept i saw that i can use AsyncTask or new Thread.

I explain my basic action app.
In the MainActivity i have two fields username and password.
The MainActivity get from the user the inputs and send those inputs to function in ActionClass and there I use with WSClass.
In the function class i sent to web service and wait to the response.

How can i create the white circle when the user wait to my
actions app?

What the best option to use?(AsyncTask/new Thread)

MainActivity:

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ActionClass = ActionClass.getInstans();
        ActionClass.setContext(this);
        ActionClass.login("username","password");// in the future in put a PlainText for username and password.
        if(isLogin == true)
        {
            //here i move to another activity....
        }
    }
}

public class ActionClass
{
    public void setContext(Context context) {
        if (this.context == null) {
            this.context = context;
            WSClass = new WSClass();
        }
    }
  public static ActionClass getInstans() {
        if (instans == null) {
            synchronized (ActionClass.class) {
                if (instans == null)
                    instans = new ActionClass();
            }
        }

        return instans;
    }

    public boolean login(String username, String password) {
    {
        WSClass.loginWs(url,username, password, object.class);
    }
}

     public class WSClass
     {
          public <T> T login(String URL,String username,String  password,
          Class<T> output)
          {

          //...Do Something...
          }
     }

Update the qustion
The WsClass use with generic function that get and return <T> variable.

After i checked the AsyncTask... AsyncTask can be use as generic if not how can i resolve this?

The function in WSClass updated above.

Thanks,

Tal


问:
Modifying specific array elements in Python 3.1
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

```<code> for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))
</code>```

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

答:
Why not this:</p>

```<code>least_common_set = frozenset(x[0] for x in least_common)
for e in array:
    if e is not in least_common_set:
        new_array.append(e + (e * (mod[1]/100)))
</code>```

Body:
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

 for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

Body:
Why not this:

least_common_set = frozenset(x[0] for x in least_common)
for e in array:
    if e is not in least_common_set:
        new_array.append(e + (e * (mod[1]/100)))


问:
I want to draw an ellipse on top of my button, form application C#
I have some problems with drawing a circle/ellipse on top of my buttons since i draw them onto the form and not the button itself meaning they end up getting covered by the buttons.

right now I draw the ellipse like this

```<code>   Pen green = new Pen(Color.Green, 1);
   Rectangle rectEllipse = new Rectangle(100, 40, 30, 30);
   e.Graphics.DrawEllipse(black, rectEllipse);
</code>```

答:
You have to draw on Button, not on Form:

```<code>private void myButton_Paint(object sender, PaintEventArgs e) {
  //DONE: wrap IDisposable into using
  using (Pen green = new Pen(Color.Green, 1)) {
    Rectangle rectEllipse = new Rectangle(10, 10, 30, 30);
    // typo? You, probably, mean "green", not "black"
    e.Graphics.DrawEllipse(green, rectEllipse);
  }
}
</code>```

Body:
I have some problems with drawing a circle/ellipse on top of my buttons since i draw them onto the form and not the button itself meaning they end up getting covered by the buttons.

right now I draw the ellipse like this

   Pen green = new Pen(Color.Green, 1);
   Rectangle rectEllipse = new Rectangle(100, 40, 30, 30);
   e.Graphics.DrawEllipse(black, rectEllipse);

Body:
You have to draw on Button, not on Form:

private void myButton_Paint(object sender, PaintEventArgs e) {
  //DONE: wrap IDisposable into using
  using (Pen green = new Pen(Color.Green, 1)) {
    Rectangle rectEllipse = new Rectangle(10, 10, 30, 30);
    // typo? You, probably, mean "green", not "black"
    e.Graphics.DrawEllipse(green, rectEllipse);
  }
}


问:
Calculate total elapsed time of Promises till reject?
I want to test how much requests i can do and get their total time elapsed. My Promise function

```<code>async execQuery(response, query) {
    let request = new SQL.Request();

    return new Promise((resolve, reject) => {
        request.query(query, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}
</code>```

And my api

```<code>app.get('/api/bookings/:uid', (req, res) => {
    let st = new stopwatch();
    let id = req.params.uid;

    let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${id}'`;
    for (let i = 0; i < 10000; i++) {
        st.start();
        db.execQuery(res, query);
    }
});
</code>```

I can't stop the for loop since its async but I also don't know how can I stop executing other calls after the one which first rejects so i can get the counter and the elapsed time of all successful promises. How can i achieve that?

答:
Wouldn't this work in your promise ?

```<code>new Promise((resolve, reject) => {
    var time = Date.now();
    request.query(query, (error, result) => {
        if (error) {
            reject(error);
        } else {
            resolve(result);
        }
    });
}).then(function(r){
    //code
}).catch(function(e){
    console.log('it took : ', Date.now() - time);
});
</code>```

Or put the .then and .catch after your db.execQuery() call

Body:
I want to test how much requests i can do and get their total time elapsed. My Promise function

async execQuery(response, query) {
    let request = new SQL.Request();

    return new Promise((resolve, reject) => {
        request.query(query, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}

And my api

app.get('/api/bookings/:uid', (req, res) => {
    let st = new stopwatch();
    let id = req.params.uid;

    let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${id}'`;
    for (let i = 0; i < 10000; i++) {
        st.start();
        db.execQuery(res, query);
    }
});

I can't stop the for loop since its async but I also don't know how can I stop executing other calls after the one which first rejects so i can get the counter and the elapsed time of all successful promises. How can i achieve that?

Body:
Wouldn't this work in your promise ?

new Promise((resolve, reject) => {
    var time = Date.now();
    request.query(query, (error, result) => {
        if (error) {
            reject(error);
        } else {
            resolve(result);
        }
    });
}).then(function(r){
    //code
}).catch(function(e){
    console.log('it took : ', Date.now() - time);
});

Or put the .then and .catch after your db.execQuery() call


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()'

When I call this method sometimes it's shows exception

```<code>public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}
</code>```

My error :

```<code>Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1197)
       at com.utils.Utils.getTimestampFromDate(SourceFile:105)
       at com.fragment.MyProfileFragment.onViewClicked(SourceFile:768)
       at com.fragment.MyProfileFragment_ViewBinding$4.doClick(SourceFile:79)
       at butterknife.internal.DebouncingOnClickListener.onClick(SourceFile:22)
       at android.view.View.performClick(View.java:5205)
       at android.view.View$PerformClick.run(View.java:21162)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5453)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
</code>```

Date format :

```<code>public static String SLASH_MM_DD_YYYY = "dd-MMM-yyyy";
</code>```

Any solutions for this?

答:
This should fix it:

```<code>public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 1);
        return calendar.getTimeInMillis();
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
}
</code>```

the problem is that your d is not being parsed, so you can catch that or you can make sure its being parsed by changing the way you are parsing it or recieving it.
You can also do it this way :

```<code>public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return 0;
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}
</code>```

this way you will return the call upon exception

Body:
When I call this method sometimes it's shows exception

public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}

My error :

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1197)
       at com.utils.Utils.getTimestampFromDate(SourceFile:105)
       at com.fragment.MyProfileFragment.onViewClicked(SourceFile:768)
       at com.fragment.MyProfileFragment_ViewBinding$4.doClick(SourceFile:79)
       at butterknife.internal.DebouncingOnClickListener.onClick(SourceFile:22)
       at android.view.View.performClick(View.java:5205)
       at android.view.View$PerformClick.run(View.java:21162)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5453)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

Date format :

public static String SLASH_MM_DD_YYYY = "dd-MMM-yyyy";

Any solutions for this?

Body:
This should fix it:

public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 1);
        return calendar.getTimeInMillis();
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
}

the problem is that your d is not being parsed, so you can catch that or you can make sure its being parsed by changing the way you are parsing it or recieving it.
You can also do it this way :

public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return 0;
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}

this way you will return the call upon exception


问:
Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:

Uncaught TypeError: Cannot read property 'checked' of undefined.

Here is part of the HTML:

```<code><form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery@worldbook.com" method="post">
  Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
  <br>
  <p>Please choose your favourite types of books.(check all that apply)</p>
  <input type="checkbox" name="books" value="Science Fiction">Science Fiction
  <input type="checkbox" name="books" value="Travel Guide">Travel Guide
  <input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
  <input type="checkbox" name="books" value="Other">Other <br>
  <textarea></textarea><br>
  <input type="submit" name="submit">
  <input type="reset" name="reset">
</form>
</code>```

and part of the JavaScript for the checkboxes:

```<code>function validChoice()
    {
        var bookChoice = document.userSurvey.books.value;
        var x= "";

        for (i=0;i< 4;i++)
        {
            if (document.userSurvey['bookChoice'+i].checked)
            {
                bookChoice = document.userSurvey['bookChoice'+i].value;
                x = x +"\n"+ bookChoice;
            }
        }

        if (bookChoice == "")
        {
            window.alert("You must select at least one book category.");
                return false;
            }
        else
        {
            var userName = document.userSurvey.userName.value;
            var eMail = document.userSurvey.email.value;
            var phoneNo = document.userSurvey.phone.value;
            return true;
    }
}
</code>```

I am currently learning in JavaScript therefore I would prefer help in JavaScript only.

Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/

答:
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.

```<code>function validChoice() {
  var bookChoices = "";

  var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array

  for (i = 0; i < checkboxes.length; i++) { //loop the array
    if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
      bookChoices += "\n" + checkboxes[i].value;
    }
  }

  if (bookChoices == "") {
    window.alert("You must select at least one book category.");
    return false;
  } else {
    alert(bookChoices); //just for testing
    return true;
  }
}
</code>```

See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.

Body:
I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:

Uncaught TypeError: Cannot read property 'checked' of undefined.

Here is part of the HTML:

<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery@worldbook.com" method="post">
  Name (Required): <input type="text" name="userName" id="userName" required="">
 E-Mail (Required): <input type="text" name="mail" id="mail" required="">
 Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()">

Please choose your favourite types of books.(check all that apply)

  <input type="checkbox" name="books" value="Science Fiction">Science Fiction
  <input type="checkbox" name="books" value="Travel Guide">Travel Guide
  <input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
  <input type="checkbox" name="books" value="Other">Other

  <textarea></textarea>

  <input type="submit" name="submit">
  <input type="reset" name="reset">
</form>

and part of the JavaScript for the checkboxes:

function validChoice()
    {
        var bookChoice = document.userSurvey.books.value;
        var x= "";

        for (i=0;i< 4;i++)
        {
            if (document.userSurvey['bookChoice'+i].checked)
            {
                bookChoice = document.userSurvey['bookChoice'+i].value;
                x = x +"\n"+ bookChoice;
            }
        }

        if (bookChoice == "")
        {
            window.alert("You must select at least one book category.");
                return false;
            }
        else
        {
            var userName = document.userSurvey.userName.value;
            var eMail = document.userSurvey.email.value;
            var phoneNo = document.userSurvey.phone.value;
            return true;
    }
}

I am currently learning in JavaScript therefore I would prefer help in JavaScript only.

Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/

Body:
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.

function validChoice() {
  var bookChoices = "";

  var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array

  for (i = 0; i < checkboxes.length; i++) { //loop the array
    if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
      bookChoices += "\n" + checkboxes[i].value;
    }
  }

  if (bookChoices == "") {
    window.alert("You must select at least one book category.");
    return false;
  } else {
    alert(bookChoices); //just for testing
    return true;
  }
}

See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.


问:
Server side rendering with Material UI 1 and Nodejs/React
Problem: Cant seem to get styles to get sent down or loaded intially through ssr.

I'm following the docs and trying to do as it says, but styleSheets variable seems to be empty anyways. In my Navigation component i use JSS and use withStyles. From reading some of the documentation, using withStyles should populate my style sheets on my server right? However the variable that holds these styles ends up empty for some reason. Am i misinterpreting something?

serverRender.jsx

```<code>import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { RouterContext } from 'react-router';
import Helmet from 'react-helmet';
import serialize from 'serialize-javascript';
import { create } from 'jss';
import preset from 'jss-preset-default';
import { SheetsRegistry } from 'react-jss/lib/jss';
import JssProvider from 'react-jss/lib/JssProvider';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import createGenerateClassName from 'material-ui/styles/createGenerateClassName';
import { deepOrange, lightBlue, red } from 'material-ui/colors';
import staticAssets from './static-assets';
// import rtl from 'jss-rtl'; // in-case you're supporting rtl

const sheetsRegistry = new SheetsRegistry();

const theme = createMuiTheme({
  palette: {
    primary: deepOrange,
    secondary: lightBlue,
    error: red,
  },
});

// Configure JSS
const jss = create(preset());
jss.options.createGenerateClassName = createGenerateClassName;

const createApp = (store, props) => renderToString(
  <JssProvider registry={sheetsRegistry} jss={jss}>
    <MuiThemeProvider theme={theme} sheetsManager={new Map()}>
      <Provider store={store}>
        <RouterContext {...props} />
      </Provider>
    </MuiThemeProvider>
  </JssProvider>
);

//Grab our css from our sheetsRegistry
const registeredCss = sheetsRegistry.toString();

const buildPage = ({ componentHTML, initialState, headAssets, css }) => {
  return `
<!doctype html>
<html>
  <head>
    ${headAssets.title.toString()}
    ${headAssets.meta.toString()}
    ${headAssets.link.toString()}
    ${staticAssets.createStylesheets()}
    ${staticAssets.createTrackingScript()}
  </head>
  <body>
    <div id="app">${componentHTML}</div>
    <script>window.__INITIAL_STATE__ = ${serialize(initialState)}</script>
    ${staticAssets.createAppScript()}
    <style id="jss-server-side" type="text/css">${css}</style>
  </body>
</html>`;
};

export default (store, props) => {
  const initialState = store.getState();
  const componentHTML = createApp(store, props);
  const headAssets = Helmet.renderStatic();
  const css = registeredCss;
  console.log(css);
  return buildPage({ componentHTML, initialState, headAssets, css });
};
</code>```

Here is where it should grab what we need for styling.

Where Navigation may look something like this:

```<code>import React, { Component } from 'react';
import { Link } from 'react-router';
import classNames from 'classnames/bind';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';
import { withStyles } from 'material-ui/styles';
import styles from '../css/components/navigation.css';

// import passTheAuxLogo from '../images/PassTheAux.png';

const styleSheet = ({
appbar: {
  width: '100%',
},

flex: {

},

menuButton: {
  marginLeft: -12,
  marginRight: 20,
},

navCenter: {
  display: 'flex',
  flex: 1
},
});

const cx = classNames.bind(styles);

class Navigation extends Component {

  constructor(props) {
    super(props);
    this.mobile = false;
  }
  render() {
    const mobile = this.mobile;
    const { classes } = this.props;
    return (
      <div className={classes.appbar}>
        <AppBar position="static" color="primary">
          <Toolbar>
            {mobile && (
            <IconButton className={classes.menuButton} color="contrast" aria-label="Menu">
              <MenuIcon />
            </IconButton>)}
            <Typography type="title" color="inherit" className={cx('flex')}>
              PassTheAux
            </Typography>
            <div className={classes.navCenter}>
              <Link to="/dashboard">
                <Button color="contrast">Dashboard</Button>
              </Link>

              <Link to="/about">
                <Button color="contrast">About</Button>
              </Link>

              <Link to="/404notfound">
                <Button color="contrast">404 Not Found</Button>
              </Link>
            </div>
            <Button color="contrast">Log In</Button>
            |
            <Button color="contrast">Sign up</Button>
          </Toolbar>
        </AppBar>
      </div>
    );
  }
}

export default withStyles(styleSheet)(Navigation);
</code>```

Should the provider go around my app as well on the client?
https://github.com/kkotwal94/KaranPRNB

EDIT: I guess another question on top of this one would be do I have to use JSS, can this be done if i wanted to use PostCSS?

答:
You need to make sure the following flow of execution is respected:

ReactDOM.renderToString() is called

sheetsRegistry.toString() is called

It won't work the other way around as it's done in your GitHub repository.

Body:
Problem: Cant seem to get styles to get sent down or loaded intially through ssr.

I'm following the docs and trying to do as it says, but styleSheets variable seems to be empty anyways. In my Navigation component i use JSS and use withStyles. From reading some of the documentation, using withStyles should populate my style sheets on my server right? However the variable that holds these styles ends up empty for some reason. Am i misinterpreting something?

serverRender.jsx

import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { RouterContext } from 'react-router';
import Helmet from 'react-helmet';
import serialize from 'serialize-javascript';
import { create } from 'jss';
import preset from 'jss-preset-default';
import { SheetsRegistry } from 'react-jss/lib/jss';
import JssProvider from 'react-jss/lib/JssProvider';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import createGenerateClassName from 'material-ui/styles/createGenerateClassName';
import { deepOrange, lightBlue, red } from 'material-ui/colors';
import staticAssets from './static-assets';
// import rtl from 'jss-rtl'; // in-case you're supporting rtl

const sheetsRegistry = new SheetsRegistry();

const theme = createMuiTheme({
  palette: {
    primary: deepOrange,
    secondary: lightBlue,
    error: red,
  },
});

// Configure JSS
const jss = create(preset());
jss.options.createGenerateClassName = createGenerateClassName;

const createApp = (store, props) => renderToString(
  <JssProvider registry={sheetsRegistry} jss={jss}>
    <MuiThemeProvider theme={theme} sheetsManager={new Map()}>
      <Provider store={store}>
        <RouterContext {...props} />
      </Provider>
    </MuiThemeProvider>
  </JssProvider>
);

//Grab our css from our sheetsRegistry
const registeredCss = sheetsRegistry.toString();

const buildPage = ({ componentHTML, initialState, headAssets, css }) => {
  return `
<!doctype html>

    ${headAssets.title.toString()}
    ${headAssets.meta.toString()}
    ${headAssets.link.toString()}
    ${staticAssets.createStylesheets()}
    ${staticAssets.createTrackingScript()}

${componentHTML}

    ${staticAssets.createAppScript()}

`;
};

export default (store, props) => {
  const initialState = store.getState();
  const componentHTML = createApp(store, props);
  const headAssets = Helmet.renderStatic();
  const css = registeredCss;
  console.log(css);
  return buildPage({ componentHTML, initialState, headAssets, css });
};

Here is where it should grab what we need for styling.

Where Navigation may look something like this:

import React, { Component } from 'react';
import { Link } from 'react-router';
import classNames from 'classnames/bind';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';
import { withStyles } from 'material-ui/styles';
import styles from '../css/components/navigation.css';

// import passTheAuxLogo from '../images/PassTheAux.png';

const styleSheet = ({
appbar: {
  width: '100%',
},

flex: {

},

menuButton: {
  marginLeft: -12,
  marginRight: 20,
},

navCenter: {
  display: 'flex',
  flex: 1
},
});

const cx = classNames.bind(styles);

class Navigation extends Component {

  constructor(props) {
    super(props);
    this.mobile = false;
  }
  render() {
    const mobile = this.mobile;
    const { classes } = this.props;
    return (

        <AppBar position="static" color="primary">
          <Toolbar>
            {mobile && (
            <IconButton className={classes.menuButton} color="contrast" aria-label="Menu">
              <MenuIcon />
            </IconButton>)}
            <Typography type="title" color="inherit" className={cx('flex')}>
              PassTheAux
            </Typography>

              <Link to="/dashboard">
                <Button color="contrast">Dashboard</Button>
              </Link>

              <Link to="/about">
                <Button color="contrast">About</Button>
              </Link>

              <Link to="/404notfound">
                <Button color="contrast">404 Not Found</Button>
              </Link>

            <Button color="contrast">Log In</Button>
            |
            <Button color="contrast">Sign up</Button>
          </Toolbar>
        </AppBar>

    );
  }
}

export default withStyles(styleSheet)(Navigation);

Should the provider go around my app as well on the client?
https://github.com/kkotwal94/KaranPRNB

EDIT: I guess another question on top of this one would be do I have to use JSS, can this be done if i wanted to use PostCSS?


问:
Overlaping elements on different columns with bootstrap
I'm trying to create a menu layout (design layout below) but I am having trouble trying stop elements inside from overlapping. I'm using bootstrap 3.3.7. The problem only occurs on desktop and not mobile. I made one "menubox" (basically one dish) and made two copies of the whole thing (3 in a row), each taking 4 columns. The one on the right ends up overlapping the one on it's left a little, and they're not centered as 3. Included is an image of the problem.

@charset "UTF-8";
* {
  margin: 0;
}

html body {
  height: 100%;
}

.nopadding {
  padding: 0;
}

.navbar {
  background-color: #ff8300;
  border-radius: 0 0 10px 10px;
  border: 0;
  height: 100px;
  width: 100%;
  max-width: 980px;
  margin: 0 auto;
}

.navspace {

  right: 50px;
  margin-top: 25px;
  position: relative;
  font-size: 18px;
  color: #fff;

}

.navbar-brand {
  padding: 0;
  position: relative;
  left: 40px;
  top: 10px;
}

.thumbnails {
  position: relative;
  margin-top: 150px;
}

#myCarousel {
  width: 980px;
  max-width: 100%;
  height: 654px;
  bottom: 25px;
  border-radius: 0 0 10px 10px;

}

.carousel-control {
  height: 600px;
  opacity: 0;
  border-radius: 0 0 10px 10px;
}

.banner {
  background: url(../images/banner1.jpg) no-repeat top center;
  background-size: cover;
  width: 980px;
  height: 654px;
  background-size: 100% auto;
}

.banner2 {
  background: url(../images/banner2.jpg) no-repeat top center;
  background-size: cover;
  width: 980px;
  height: 654px;
  background-size: 100% auto;

}

.banner3 {
  background: url(../images/banner3.jpg) no-repeat top center;
  background-size: cover;
  width: 980px;
  height: 654px;
  background-size: 100% auto;

}

.banner p {
  position: relative;
  font-size: 25px;
  color: #fff;
  top: 440px;
  left: 20px;
}

.banner h1 {
  position: relative;
  font-size: 50px;
  color: #fff;
  left: 20px;
  top: 420px;
}

.bodyimg {
  max-width: 100%;
}

.bodytext1 {
  color: #ff8300;
}

.bodytext2 {
  color: #ff8300;
  width: 160px;
  margin-top: 37px;
}

.bodytext3 {
  color: #ff8300;
  margin-top: 60px
}

.bodytext4 {
  color: #ff8300;
  margin-top: 60px
}

.socialpadding {
  padding: 0px 10px 0px 10px;
  position: relative;
}

.centersocial {
  margin: 0 auto;
  text-align: center;
  position: absolute;
}

.contactinfo {
  color: #ff8300;
  margin: 200px 0px 0px auto;

}

/* Add a background color and some padding around the form */

.formarea {
  background-color: #ff8300;
  border-radius: 10px;
  width: 400px;
  height: 484px;
  margin: 50px auto 0px auto;
  padding: 15px;
}

.formlabel {
  color: #fff;
}

#inputMessage {
  height: 200px;
}

.btn {
  background-color: #fcb972;
  border-color: #ff9300;
  margin-top: 20px;
}

.btn:hover {
  background-color: #fff;
  border-color: #ff9300;
  color: #ff8300;
}

.btn:onclick {
  background-color: #fff;
  border-color: #ff9300;
  color: #ff8300;
}

.messageform {
  height: 50px;
}

.google-maps {
  position: relative;
  padding-bottom: 75%;
  height: 0;
  overflow: hidden;
  margin-top: 50px;
}

.google-maps iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.formarea2 {
  background-color: #fff;
  border-radius: 10px;
  width: 400px;
  height: 50px;
  margin: 50px auto 0px auto;
  padding: 15px;
  display: inline;
  text-align: center;
}

#inputPostal {
  display: inline-block;
  width: 30%;
  margin-left:3%;
}

.formpostal {
  color: #ff8300;
  font-size: 30px;
  display: inline-block;
}

.menubg {
  background-color: #ff8300;
  height: 100%;
  width: 100%;
  max-width: 980px;
  border-radius: 10px;
  margin: 125px;

}

.col-centered {
  float: none;
  margin-right: auto;
  margin-left: auto;
}

.cartbtn {
  margin-top: 20px;
  position: relative;
  left: 96%;

}

h2 {
  font-size: 24px;
  color: #fff;
  text-align: center;
  margin-top: 30px;

}

.menubox {
  background-color: #fff;
  border-radius: 10px;
  width: 321px;
  height: 320px;
  margin-top: 30px;
  position: relative;

}

.menubox a {
  text-decoration: none;
}

.item1 {
  background: url(../images/menu1.jpg) no-repeat center;
  border-radius: 10px 10px 0px 0px;

}

.menubox img {
  border-radius: 10px 10px 0px 0px;
  opacity: 0;
  transition: .5s ease;
  backface-visibility: hidden;
}

.menubox:hover .item1 {
  opacity: 0.7;
  transition: .5s ease;
}

.menubox:hover img {
  opacity: 1;
  transition: .5s ease;
}

h3 {
  font-size: 16;
  color: #ff8300;
}

.foot {
  background-image: none;
  background-color: #ff8300;
  border-radius: 10px 10px 0 0;
  height: 50px;
  margin: 150px auto 0 auto;
  position: absolute;
  width: 100%;
  max-width: 980px;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow: hidden;
}

footer {
  position: relative;
  color: #fff;
  text-align: right;
  margin-top: 30px;
  font-size: 10px;
  width: 100%;
  max-width: 980px;
}

@media only screen and (max-width: 992px) {
  .navbar {
    background-image: none;
    background-color: #ff8300;
    width: 100%;
    border-radius: 0px;
    margin: 0;
  }

  .navspace {
    padding: 0px 20px 0px 0px;
    left: 120px;
    top: 30px;
  }

  .navbar-collapse {
    background: rgba(255, 255, 255, 0.75);
    height: 300px;

  }

  .foot {
    background-image: none;
    background-color: #ff8300;
    border-radius: 0;
    overflow: hidden;
  }

  footer {
    position: relative;
    color: #fff;
    display: block;
    text-align: right;
    font-size: 10px;
  }

  .contactinfo {
    margin: 40px auto 0px auto;
    text-align: center;
  }
}

@media only screen and (max-width: 767px) {
  #myCarousel.carousel {
    max-width: 100%;
    width: 100%;
    max-height: 100%;
    overflow: hidden;
    border-radius: 0 0 10px 10px;
  }

  .carousel-control {
    height: 600px;
    opacity: 0;
  }

  .findus {
    margin: 0 auto;
  }
  .centersocial {
    position: relative;
  }
  .bodytext4 {
    text-align: center;
    width: 250px;
    margin: 100px auto 5px auto;
  }
  .bodytext3 {
    text-align: center;
    width: 250px;
    margin: 60px auto 5px auto;
  }

}

@media only screen and (max-width: 576px) {
  .formarea {
    background-color: #ff8300;
    border-radius: 10px;
    width: 350px;
    height: 484px;
    margin: 50px auto 0px auto;
    padding: 15px;
  }

}

html[xmlns] .clearfix {
  display: block;
}

* html .clearfix {
  height: 1%;
}

/* additional */

.row, #myCarousel, .container {
  max-width: 100%;
  margin: 0 auto;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <title>Peperoni Pizzeria</title>

  <!-- Bootstrap -->
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link href="css/styles.css" rel="stylesheet">
  <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
      <![endif]-->
    </head>
    <body>

      <div class="container">

        <nav class="navbar navbar-default navbar-static-top rounded-bottom">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <img src="images/logo.png" alt="">
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav navbar-right">
                <li>Home</li>
                <li>Menu</li>
                <li>Locations</li>
                <li>Contact Us</li>
                <!-- Put here your menu items -->
              </ul>

            </div><!--/.navbar-collapse -->
          </div>
        </nav>

        <div class="row">
          <div class="col-sm-offset-3 col-sm-6">

            <div class="formarea2">
              <form>

                <div class="form-group">
                  <label class="formpostal" for="inputPostal">Input Postal Code:</label>
                  <input type="postal" class="form-control" id="inputPostal" placeholder="i.e 450894">

                </form>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-sm-12 menubg col-centered">

              <div class="row">
                <div class="col-sm-12">
                  <img class="cartbtn" src="images/cart.png" alt="cart">
                </div>
              </div>

              <div class="row">
                <div class="col-sm-12">
                  <h2>Appetisers/Sides</h2>
                </div>
              </div>

              <div class="row">

                <div class="row">

                <div class="col-sm-4">
                  <div class="menubox">

                      <div class="item1">
                        <img href="#" src="images/addtocart.png" alt="">
                      </div>
                      <h3>   Rucola Salad               $10</h3>

                  </div>
                </div>

                <div class="col-sm-4">
                  <div class="menubox">

                      <div class="item1">
                        <img href="#" src="images/addtocart.png" alt="">
                      </div>
                      <h3>   Rucola Salad               $10</h3>

                  </div>
                </div>

                <div class="col-sm-4">
                  <div class="menubox">

                      <div class="item1">
                        <img href="#" src="images/addtocart.png" alt="">
                      </div>
                      <h3>   Rucola Salad               $10</h3>

                  </div>
                </div>

              </div>
            </div>

            <div class="row">
              <div class="col-sm-12 foot img-responsive">

                <footer class="navbar-fixed-bottom">
                  Copyright © 2017 Peperoni Pizzeria. All Rights Reserved.
                </footer>

              </div>
            </div>

          </div>
        </div>

        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
      </body>
      </html></code>```

答:
```<code>.col-centered {
  padding:0px;
}
.col-sm-4.add-some-class {
  padding-left:0px;
  padding-right:0px;
}
.menubox{
  background-color: #fff;
  border-radius: 10px;
  width: 315px;
  height: 320px;
  position: relative;
  margin: 0px auto 30px auto;
}
</code>```

1-This will 100% work for you
i applied this then send you the final code.
thankyou.

Body:
I'm trying to create a menu layout (design layout below) but I am having trouble trying stop elements inside from overlapping. I'm using bootstrap 3.3.7. The problem only occurs on desktop and not mobile. I made one "menubox" (basically one dish) and made two copies of the whole thing (3 in a row), each taking 4 columns. The one on the right ends up overlapping the one on it's left a little, and they're not centered as 3. Included is an image of the problem.

@charset "UTF-8";
* {
  margin: 0;
}

html body {
  height: 100%;
}

.nopadding {
  padding: 0;
}

.navbar {
  background-color: #ff8300;
  border-radius: 0 0 10px 10px;
  border: 0;
  height: 100px;
  width: 100%;
  max-width: 980px;
  margin: 0 auto;
}

.navspace {

  right: 50px;
  margin-top: 25px;
  position: relative;
  font-size: 18px;
  color: #fff;

}

.navbar-brand {
  padding: 0;
  position: relative;
  left: 40px;
  top: 10px;
}

.thumbnails {
  position: relative;
  margin-top: 150px;
}

#myCarousel {
  width: 980px;
  max-width: 100%;
  height: 654px;
  bottom: 25px;
  border-radius: 0 0 10px 10px;

}

.carousel-control {
  height: 600px;
  opacity: 0;
  border-radius: 0 0 10px 10px;
}

.banner {
  background: url(../images/banner1.jpg) no-repeat top center;
  background-size: cover;
  width: 980px;
  height: 654px;
  background-size: 100% auto;
}

.banner2 {
  background: url(../images/banner2.jpg) no-repeat top center;
  background-size: cover;
  width: 980px;
  height: 654px;
  background-size: 100% auto;

}

.banner3 {
  background: url(../images/banner3.jpg) no-repeat top center;
  background-size: cover;
  width: 980px;
  height: 654px;
  background-size: 100% auto;

}

.banner p {
  position: relative;
  font-size: 25px;
  color: #fff;
  top: 440px;
  left: 20px;
}

.banner h1 {
  position: relative;
  font-size: 50px;
  color: #fff;
  left: 20px;
  top: 420px;
}

.bodyimg {
  max-width: 100%;
}

.bodytext1 {
  color: #ff8300;
}

.bodytext2 {
  color: #ff8300;
  width: 160px;
  margin-top: 37px;
}

.bodytext3 {
  color: #ff8300;
  margin-top: 60px
}

.bodytext4 {
  color: #ff8300;
  margin-top: 60px
}

.socialpadding {
  padding: 0px 10px 0px 10px;
  position: relative;
}

.centersocial {
  margin: 0 auto;
  text-align: center;
  position: absolute;
}

.contactinfo {
  color: #ff8300;
  margin: 200px 0px 0px auto;

}

/* Add a background color and some padding around the form */

.formarea {
  background-color: #ff8300;
  border-radius: 10px;
  width: 400px;
  height: 484px;
  margin: 50px auto 0px auto;
  padding: 15px;
}

.formlabel {
  color: #fff;
}

#inputMessage {
  height: 200px;
}

.btn {
  background-color: #fcb972;
  border-color: #ff9300;
  margin-top: 20px;
}

.btn:hover {
  background-color: #fff;
  border-color: #ff9300;
  color: #ff8300;
}

.btn:onclick {
  background-color: #fff;
  border-color: #ff9300;
  color: #ff8300;
}

.messageform {
  height: 50px;
}

.google-maps {
  position: relative;
  padding-bottom: 75%;
  height: 0;
  overflow: hidden;
  margin-top: 50px;
}

.google-maps iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.formarea2 {
  background-color: #fff;
  border-radius: 10px;
  width: 400px;
  height: 50px;
  margin: 50px auto 0px auto;
  padding: 15px;
  display: inline;
  text-align: center;
}

#inputPostal {
  display: inline-block;
  width: 30%;
  margin-left:3%;
}

.formpostal {
  color: #ff8300;
  font-size: 30px;
  display: inline-block;
}

.menubg {
  background-color: #ff8300;
  height: 100%;
  width: 100%;
  max-width: 980px;
  border-radius: 10px;
  margin: 125px;

}

.col-centered {
  float: none;
  margin-right: auto;
  margin-left: auto;
}

.cartbtn {
  margin-top: 20px;
  position: relative;
  left: 96%;

}

h2 {
  font-size: 24px;
  color: #fff;
  text-align: center;
  margin-top: 30px;

}

.menubox {
  background-color: #fff;
  border-radius: 10px;
  width: 321px;
  height: 320px;
  margin-top: 30px;
  position: relative;

}

.menubox a {
  text-decoration: none;
}

.item1 {
  background: url(../images/menu1.jpg) no-repeat center;
  border-radius: 10px 10px 0px 0px;

}

.menubox img {
  border-radius: 10px 10px 0px 0px;
  opacity: 0;
  transition: .5s ease;
  backface-visibility: hidden;
}

.menubox:hover .item1 {
  opacity: 0.7;
  transition: .5s ease;
}

.menubox:hover img {
  opacity: 1;
  transition: .5s ease;
}

h3 {
  font-size: 16;
  color: #ff8300;
}

.foot {
  background-image: none;
  background-color: #ff8300;
  border-radius: 10px 10px 0 0;
  height: 50px;
  margin: 150px auto 0 auto;
  position: absolute;
  width: 100%;
  max-width: 980px;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow: hidden;
}

footer {
  position: relative;
  color: #fff;
  text-align: right;
  margin-top: 30px;
  font-size: 10px;
  width: 100%;
  max-width: 980px;
}

@media only screen and (max-width: 992px) {
  .navbar {
    background-image: none;
    background-color: #ff8300;
    width: 100%;
    border-radius: 0px;
    margin: 0;
  }

  .navspace {
    padding: 0px 20px 0px 0px;
    left: 120px;
    top: 30px;
  }

  .navbar-collapse {
    background: rgba(255, 255, 255, 0.75);
    height: 300px;

  }

  .foot {
    background-image: none;
    background-color: #ff8300;
    border-radius: 0;
    overflow: hidden;
  }

  footer {
    position: relative;
    color: #fff;
    display: block;
    text-align: right;
    font-size: 10px;
  }

  .contactinfo {
    margin: 40px auto 0px auto;
    text-align: center;
  }
}

@media only screen and (max-width: 767px) {
  #myCarousel.carousel {
    max-width: 100%;
    width: 100%;
    max-height: 100%;
    overflow: hidden;
    border-radius: 0 0 10px 10px;
  }

  .carousel-control {
    height: 600px;
    opacity: 0;
  }

  .findus {
    margin: 0 auto;
  }
  .centersocial {
    position: relative;
  }
  .bodytext4 {
    text-align: center;
    width: 250px;
    margin: 100px auto 5px auto;
  }
  .bodytext3 {
    text-align: center;
    width: 250px;
    margin: 60px auto 5px auto;
  }

}

@media only screen and (max-width: 576px) {
  .formarea {
    background-color: #ff8300;
    border-radius: 10px;
    width: 350px;
    height: 484px;
    margin: 50px auto 0px auto;
    padding: 15px;
  }

}

html[xmlns] .clearfix {
  display: block;
}

* html .clearfix {
  height: 1%;
}

/* additional */

.row, #myCarousel, .container {
  max-width: 100%;
  margin: 0 auto;

}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Peperoni Pizzeria</title>

  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link href="css/styles.css" rel="stylesheet">

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>

Home

Menu

Locations

Contact Us

              <form>

                  Input Postal Code:
                  <input type="postal" class="form-control" id="inputPostal" placeholder="i.e 450894">

                </form>

Appetisers/Sides

   Rucola Salad               $10

   Rucola Salad               $10

   Rucola Salad               $10

                  Copyright © 2017 Peperoni Pizzeria. All Rights Reserved.

Body:
.col-centered {
  padding:0px;
}
.col-sm-4.add-some-class {
  padding-left:0px;
  padding-right:0px;
}
.menubox{
  background-color: #fff;
  border-radius: 10px;
  width: 315px;
  height: 320px;
  position: relative;
  margin: 0px auto 30px auto;
}

1-This will 100% work for you
i applied this then send you the final code.
thankyou.


问:
Why do method breakpoints impact performance so negatively?
Why does adding a method level breakpoint have such a negative impact on program performance in debug mode?

Take the following (somewhat contrived) example:

```<code>public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for(int a = 0; a <Integer.MAX_VALUE; a++) {
        long v = a * a;
        if(v == 100) {
            doSomething();
        }
    }
    System.out.println("Time: " + (System.currentTimeMillis() - start) + " ms");
}

private static void doSomething() {          //*** BREAKPOINT 2
    System.out.println("done something");    //*** BREAKPOINT 1
}
</code>```

The performance of this is approximately:

Not in debug:            4.5 seconds

Debug, breakpoint 1:     6.0 seconds

Debug, breakpoint 2:     47.0 seconds

What's going on?  What benefit does the method level debug give us that normal ones can't?

Thanks!

EDIT

The timings are only approximations and include the time it takes me to react to the breakpoint and continue the application (which looks to be roughly about 1 second).

I appreciate that System.currentTimeMillis() is not 100% accurate, however the results are consistent over multiple tests and the difference in performance is massive!  In fact, adding the method level breakpoint results in a warning from IntelliJ that it will have an impact on performance.

答:
Recently I made a research regarding Method Breakpoint Slowness issue.
My conclusion was that the root issue is that Method Breakpoints are implemented by using JDPA Method Entry & Method Exit feature. This implementation requires the JVM to fire an event each time any thread enters any method and when any thread exits any method.

click  here to read the entire article

Body:
Why does adding a method level breakpoint have such a negative impact on program performance in debug mode?

Take the following (somewhat contrived) example:

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for(int a = 0; a <Integer.MAX_VALUE; a++) {
        long v = a * a;
        if(v == 100) {
            doSomething();
        }
    }
    System.out.println("Time: " + (System.currentTimeMillis() - start) + " ms");
}

private static void doSomething() {          //*** BREAKPOINT 2
    System.out.println("done something");    //*** BREAKPOINT 1
}

The performance of this is approximately:

Not in debug:            4.5 seconds

Debug, breakpoint 1:     6.0 seconds

Debug, breakpoint 2:     47.0 seconds

What's going on?  What benefit does the method level debug give us that normal ones can't?

Thanks!

EDIT

The timings are only approximations and include the time it takes me to react to the breakpoint and continue the application (which looks to be roughly about 1 second).

I appreciate that System.currentTimeMillis() is not 100% accurate, however the results are consistent over multiple tests and the difference in performance is massive!  In fact, adding the method level breakpoint results in a warning from IntelliJ that it will have an impact on performance.


问:
Does indexing in Postgres improve ordering speed?
Let's say you have a table with a primary key A, and two columns B and C.

When querying we want to do SELECT * FROM table WHERE A = 'thing' ORDER BY B, C

Since A is a primary key, it already has an index. Is there any benefit to adding an index on B and C in terms of speeding up ordering?

答:
This query cannot benefit from additional indexes.

If a is the primary key, then the query can only return zero or one rows, so ordering is trivial and cannot be made faster.

In fact, you should omit the ORDER BY clause.

ContentLicense: CC BY-SA 4.0


问:
Swift optional binding with check for several types
I have model for my class that may be instance of 2 different classes. Now i check that model is class i need with following:

```<code> guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }
</code>```

Now i want to check if model is class one OR model is class two. Is that possible to achieve?

Now i ended up with this (but without optional binding):

```<code>   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }
</code>```

答:
Try this</p>

```<code>if let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route){
    if unwrappedModel is MyClassOne{
        print("MyClassOne")
    }
    else if unwrappedModel is MyClassTwo{
        print("MyClassTwo")
    }
}
</code>```

Body:
I have model for my class that may be instance of 2 different classes. Now i check that model is class i need with following:

 guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }

Now i want to check if model is class one OR model is class two. Is that possible to achieve?

Now i ended up with this (but without optional binding):

   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }

Body:
Try this

if let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route){
    if unwrappedModel is MyClassOne{
        print("MyClassOne")
    }
    else if unwrappedModel is MyClassTwo{
        print("MyClassTwo")
    }
}


问:
md-toggle-button not toggling in angular
I need to show some toggle buttons, as the ones presents in the documentation page of angular material https://material.angular.io/components/button-toggle/overview . I followed the code, tryied both

```<code><md-button-toggle ng-click="vm.callAlert()">Hello</md-button-toggle>
</code>```

and

```<code><mat-button-toggle ng-click="vm.callAlert()">Hello</mat-button-toggle>
</code>```

and the function is called. The problem is that the button not stay focused. Can someone help me with that ?

答:
Firstly, please do not use ng-click in your template. Use the (click) event instead. For more info, visit the documentation for template syntaxes.

Secondly, note that Angular no longer uses controller syntax.

Thirdly, import MatButtonToggleModule from @angular/material in your app's module file.

Update your code to the following:

HTML code (app.component.html):

<mat-button-toggle (click)="clickActn()">Toggle me!</mat-button-toggle>
```

<p>Component code (<code>app.component.ts</code>):</p>

<pre class="lang-ts prettyprint-override"><code>@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent {
    clickActn() {
        console.log('clicked');
    }
}
</code>```

For more info about Angular, visit the official documentation site to learn more!

Angular Migration Guide

Body:
I need to show some toggle buttons, as the ones presents in the documentation page of angular material https://material.angular.io/components/button-toggle/overview . I followed the code, tryied both

<md-button-toggle ng-click="vm.callAlert()">Hello</md-button-toggle>

and

<mat-button-toggle ng-click="vm.callAlert()">Hello</mat-button-toggle>

and the function is called. The problem is that the button not stay focused. Can someone help me with that ?

Body:
Firstly, please do not use ng-click in your template. Use the (click) event instead. For more info, visit the documentation for template syntaxes.

Secondly, note that Angular no longer uses controller syntax.

Thirdly, import MatButtonToggleModule from @angular/material in your app's module file.

Update your code to the following:

HTML code (app.component.html):

<mat-button-toggle (click)="clickActn()">Toggle me!</mat-button-toggle>

Component code (app.component.ts):

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent {
    clickActn() {
        console.log('clicked');
    }
}

For more info about Angular, visit the official documentation site to learn more!

Angular Migration Guide


问:
Emacs, ESS, R -How did i do this?
http://picasaweb.google.com/lh/photo/F-p2qK3itxJsgj1tLLGsow?feat=directlink

If you look at the picture, theres this usage bit from the R help files at the bottom in the minbuffer.

howd i do that? it somehow just appeared, maybe cos i mashed the keyboard trying to run the commands.
It disappeared when i restarted emacs:(

thanks

答:
There is an ess-eldoc package which would display the args whenever you are inside the parenthesis. To activate put:

```<code>(require 'ess-eldoc)
</code>```

in your emacs after you load the ess-site.

[Edit]: ess-eldoc package does not exist anymore. Eldoc is activated by default in ESS.

Title: Emacs, ESS, R -How did i do this?

Body:
There is an ess-eldoc package which would display the args whenever you are inside the parenthesis. To activate put:

(require 'ess-eldoc)

in your emacs after you load the ess-site.

[Edit]: ess-eldoc package does not exist anymore. Eldoc is activated by default in ESS.


问:
explicit instantiation of static variable of a template class in different translation units
I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

```<code>template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;
</code>```

Source.cpp

```<code>#include "Header.h"
template<> int Foo<int>::count = 5;
</code>```

main.cpp

```<code>#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}
</code>```

the output on xcode8.3.3 is:

```<code> 7
 7
</code>```

whereas the output on Visual Studio 2015 is:

```<code>2
2
</code>```

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015.
Could someone explain this difference in behavior?
Thanks in advance.

答:
While your code contains a constraint violation, it is in fact not too difficult to make it well formed and maintain the one place where the static is initialized. For the C++ standard says at [temp.expl.spec]/13:

An explicit specialization of a static data member of a template or an
  explicit specialization of a static data member template is a
  definition if the declaration includes an initializer; otherwise, it
  is a declaration. [ Note: The definition of a static data member of a
  template that requires default-initialization must use a
  braced-init-list:

```<code>template<> X Q<int>::x;                         // declaration
template<> X Q<int>::x ();                      // error: declares a function
template<> X Q<int>::x { };                     // definition
</code>```

 — end note ]

The above implies that merely adding this line

```<code>template<> int Foo<int>::count; // declaration
</code>```

At the bottom of Header.h is enough to let all translation units know that the Foo<int>::count exists "somewhere". The one true definition may remain in Source.cpp.

Body:
I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;

Source.cpp

#include "Header.h"
template<> int Foo<int>::count = 5;

main.cpp

#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}

the output on xcode8.3.3 is:

 7
 7

whereas the output on Visual Studio 2015 is:

2
2

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015.
Could someone explain this difference in behavior?
Thanks in advance.

Body:
While your code contains a constraint violation, it is in fact not too difficult to make it well formed and maintain the one place where the static is initialized. For the C++ standard says at [temp.expl.spec]/13:

An explicit specialization of a static data member of a template or an
  explicit specialization of a static data member template is a
  definition if the declaration includes an initializer; otherwise, it
  is a declaration. [ Note: The definition of a static data member of a
  template that requires default-initialization must use a
  braced-init-list:

template<> X Q<int>::x;                         // declaration
template<> X Q<int>::x ();                      // error: declares a function
template<> X Q<int>::x { };                     // definition

 — end note ]

The above implies that merely adding this line

template<> int Foo<int>::count; // declaration

At the bottom of Header.h is enough to let all translation units know that the Foo<int>::count exists "somewhere". The one true definition may remain in Source.cpp.


问:
Apply CSS class only to the button that was clicked
I'm trying to apply a CSS class only to the button that was clicked (to set it active).

Here's my code:

filter.component.html

```<code><div class="button-container">
    <button class="rules" [class.active]="active" (click)="toggleActive()" type="button">Rules</button>
    <button class="dailies" [class.active]="active" (click)="toggleActive()" type="button">Dailies</button>
    <button class="emotions" [class.active]="active" (click)="toggleActive()" type="button">Emotions</button>
</div>
</code>```

filter.component.ts

```<code>export class FilterComponent {
    active: boolean = false;

    toggleActive(): void {
      this.active = !this.active;
    }
  constructor() {}
}
</code>```

My problem is, the class gets applied to all 3 buttons. And the active class looks different on each of the buttons. How can I fix this?

答:
Try using an event to get the current clicked element as follows:</p>

```<code>toggleActive($event) {
   var element = $event.target;
   element.active = !element.active;
};
</code>```

Body:
I'm trying to apply a CSS class only to the button that was clicked (to set it active).

Here's my code:

filter.component.html

    <button class="rules" [class.active]="active" (click)="toggleActive()" type="button">Rules</button>
    <button class="dailies" [class.active]="active" (click)="toggleActive()" type="button">Dailies</button>
    <button class="emotions" [class.active]="active" (click)="toggleActive()" type="button">Emotions</button>

filter.component.ts

export class FilterComponent {
    active: boolean = false;

    toggleActive(): void {
      this.active = !this.active;
    }
  constructor() {}
}

My problem is, the class gets applied to all 3 buttons. And the active class looks different on each of the buttons. How can I fix this?

Body:
Try using an event to get the current clicked element as follows:

toggleActive($event) {
   var element = $event.target;
   element.active = !element.active;
};


问:
unable to integrate ngx-uploader module with angular 2
I am trying to use the ngx-uploader module with my angular 2 application but i keep getting the error below. I also got the similar errors when using other libraries like angular2-image-upload.i'm new to angular2 so i don't really understand the error.

答:
first. you must create an input element of type file:

```<code><input #uploader  accept=".txt, .zip, .rar" type="file" #myUploader ng2FileSelect [uploader]="uploader" />
</code>```

then in your component (typescript file) import ng2fileselect module:

```<code>import { FileUploader, FileUploaderOptions} from 'ng2-file-upload/ng2-file-upload';
</code>```

then in ngOnInit method place this code

```<code>const options = {
        url: yourUploadURL,
        isHTML5: true,
        autoUpload: true,
        queueLimit: 1,
        allowedMimeType: yourallowedMimeType,
        maxFileSize: yourmaxFileSize
      };
      const uploader = new FileUploader(options);
</code>```

Body:
first. you must create an input element of type file:

<input #uploader  accept=".txt, .zip, .rar" type="file" #myUploader ng2FileSelect [uploader]="uploader" />

then in your component (typescript file) import ng2fileselect module:

import { FileUploader, FileUploaderOptions} from 'ng2-file-upload/ng2-file-upload';

then in ngOnInit method place this code

const options = {
        url: yourUploadURL,
        isHTML5: true,
        autoUpload: true,
        queueLimit: 1,
        allowedMimeType: yourallowedMimeType,
        maxFileSize: yourmaxFileSize
      };
      const uploader = new FileUploader(options);


问:
How to add data of csv column to G.Edges

I have a csv file in with these column

```<code>column1      column2      column3
  1            2            3
</code>```

and G.Edges in this format

```<code>   1            2           3         4
EndNodes      Weight      Name     Distance
</code>```

what I would like to do is read the grocerydb.csv file and add all the data in column2 of the csv file to column 5 of G.Edges

i tried this code

```<code> fid = fopen('grocerydb.csv');
 productUPC = textscan(fid,1);
 productName = textscan(fid,'%s',2);
 fclose(fid);
</code>```

but it reads the second row not the column.
I have review some answers to similar questions such as this Reading specific column from CSV file in matlab. which gave instruction for rows, what I want is a column data not row

how can i implement reading the second column and add it to G.Edges?

答:
I assume that the G.Edges is a table in MATLAB for this makes life easier. As far as I know, MATLAB do not like csv files as Python do. So, we read csv as a table. Suppose that we have a table TARGETTable with variables acct, num_courses_visited, total_minutes_visited, and lessons_completed which like your G.Edges., Furthermore, there are many columns in a csv file ‘daily-engagement.csv’, we just need the data in second column utc_date. The csv file is very large, we need a few lines. At last, we note that the column utc_date is data, we should transform it to right type in MATLAB.

```<code>filename = 'D:\Temp\daily-engagement.csv';
delimiter = ',';
startRow = 2;
endRow = 9;
formatSpec = '%*q%{yyyy-MM-dd}D%*s%*s%*s%*s%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, endRow-startRow+1, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines', startRow-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');
fclose(fileID);
dailyengagement = table(dataArray{1:end-1}, 'VariableNames', {'utc_date'});
</code>```

Now, we can combine this dailyengagement to TARGETTable.

```<code>TARGETTable = [TARGETTable dailyengagement]
</code>```

Body:
I have a csv file in with these column

column1      column2      column3
  1            2            3

and G.Edges in this format

   1            2           3         4
EndNodes      Weight      Name     Distance

what I would like to do is read the grocerydb.csv file and add all the data in column2 of the csv file to column 5 of G.Edges

i tried this code

 fid = fopen('grocerydb.csv');
 productUPC = textscan(fid,1);
 productName = textscan(fid,'%s',2);
 fclose(fid);

but it reads the second row not the column.
I have review some answers to similar questions such as this Reading specific column from CSV file in matlab. which gave instruction for rows, what I want is a column data not row

how can i implement reading the second column and add it to G.Edges?

Body:
I assume that the G.Edges is a table in MATLAB for this makes life easier. As far as I know, MATLAB do not like csv files as Python do. So, we read csv as a table. Suppose that we have a table TARGETTable with variables acct, num_courses_visited, total_minutes_visited, and lessons_completed which like your G.Edges., Furthermore, there are many columns in a csv file ‘daily-engagement.csv’, we just need the data in second column utc_date. The csv file is very large, we need a few lines. At last, we note that the column utc_date is data, we should transform it to right type in MATLAB.

filename = 'D:\Temp\daily-engagement.csv';
delimiter = ',';
startRow = 2;
endRow = 9;
formatSpec = '%*q%{yyyy-MM-dd}D%*s%*s%*s%*s%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, endRow-startRow+1, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines', startRow-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');
fclose(fileID);
dailyengagement = table(dataArray{1:end-1}, 'VariableNames', {'utc_date'});

Now, we can combine this dailyengagement to TARGETTable.

TARGETTable = [TARGETTable dailyengagement]


问:
Android app, showing a keyboard
I recently wrote my first app for android, and I created a listview for selecting an element from a list of about 500 items.  Since it's basically the default listview, it's searchable, and I can bring up the onscreen keyboard by holding down the menu button, but I was wondering if there was a way to bring up the keyboard automatically (and not make it freak out if the phone has a physical keyboard).  Does anyone know how I can do this?  I've been searching around and haven't found anything.</p>

答:
Maybe not exactly what you want, nevertheless; you could add a EditText above your list. When this EditText gets focus (which it will by default when you show your activity, presuming it's the first GUI component on the layout) it will also automatically trigger the software keyboard.

The neat thing of this approach is that it gets even more intuitive for the user that he or she can actually search the list by entering a search criteria.

Title: Android app, showing a keyboard