问:
Using an ivar inside a method which is called from a block

I want to use an ivar in a method that is being called from a block. Is it fine to call the ivar directly from it without causing a retain cycle?
I have seen other questions related to calling properties- saying that we 'can' use self. Just wanted to make sure about ivars, can we call ivar directly or do we need to use self->_myInstanceVariable explicitly?

```<code>__weak MyClassName *weakSelf = self;
[MyBlockCreator myBlock:^{
   MyClassName *strongSelf = weakSelf;
   [strongSelf doSomething];
}];

- (void) doSomething {
   _myInstanceVariable = someObject

   // is it fine to use the ivar directly above?
   // or do we want use self explicitly?
   // like self->_myInstanceVariable
}
</code>```

答:
In this case you don't need to make the reference weak/strong at all, the only situation in which you can cause a retain cycle is if self references a block and a strong version of self is captured within that block. Since self doesn't retain the block in question, there would be no retain cycle even using a strong reference.

```<code>[Foo doWithBlock:^{
    bar.baz = @"Hello World"; // Totally fine without weak/strong since bar doesn't retain the block here.
}];
</code>```

In situations where self holds a strong reference to a block and the block refers to self, you need to make the reference weak outside the block then make it strong again inside.

```<code>__weak id weakSelf = self;
[self doWithBlock:^{
    id strongSelf = weakSelf;
    strongSelf.baz = @"Ok";
}];
</code>```

Body:
I want to use an ivar in a method that is being called from a block. Is it fine to call the ivar directly from it without causing a retain cycle?
I have seen other questions related to calling properties- saying that we 'can' use self. Just wanted to make sure about ivars, can we call ivar directly or do we need to use self->_myInstanceVariable explicitly?

__weak MyClassName *weakSelf = self;
[MyBlockCreator myBlock:^{
   MyClassName *strongSelf = weakSelf;
   [strongSelf doSomething];
}];

- (void) doSomething {
   _myInstanceVariable = someObject

   // is it fine to use the ivar directly above?
   // or do we want use self explicitly?
   // like self->_myInstanceVariable
}

Body:
In this case you don't need to make the reference weak/strong at all, the only situation in which you can cause a retain cycle is if self references a block and a strong version of self is captured within that block. Since self doesn't retain the block in question, there would be no retain cycle even using a strong reference.

[Foo doWithBlock:^{
    bar.baz = @"Hello World"; // Totally fine without weak/strong since bar doesn't retain the block here.
}];

In situations where self holds a strong reference to a block and the block refers to self, you need to make the reference weak outside the block then make it strong again inside.

__weak id weakSelf = self;
[self doWithBlock:^{
    id strongSelf = weakSelf;
    strongSelf.baz = @"Ok";
}];


来源: stackexchange

问:
FastCGI PHP7.2 always timeouts Nginx Bash ubuntu on Windows
I'm trying to install PHP7.2 and Nginx on my development machine. My development machine is running on Bash Ubuntu 16.04 on Windows.

I've had a working Nginx and PHP7.0 installed before deleting previous versions of PHP and installing PHP7.2.

Error.log output:

```<code>2017/12/07 03:30:33 [error] 32655#32655: *1 upstream timed out (110: Connection timed out) while reading upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET /helloworld.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock:", host: "127.0.0.1"
</code>```

php7.2-fpm.log:

```<code>[07-Dec-2017 03:29:29] NOTICE: Finishing ...
[07-Dec-2017 03:29:29] NOTICE: exiting, bye-bye!
[07-Dec-2017 03:29:30] NOTICE: fpm is running, pid 32683
[07-Dec-2017 03:29:30] NOTICE: ready to handle connections
[07-Dec-2017 03:29:30] NOTICE: systemd monitor interval set to 10000ms
</code>```

sites-available/default:

```<code>    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }
</code>```

The page I'm trying to load:

```<code><?php echo 'Hello World'; ?>
</code>```

I've tried completely removing all PHP7* and Nginx and re-installing with fresh config files but same result.

If I create a page with phpinfo() it does display all information but it keeps loading.

I don't know where to begin as there are no proper errors appearing.

答:
Solved, problem was that WSL doesn't support unix:socket and required me to comment out:

/etc/nginx/sites-available/default.conf

```<code>fastcgi_pass unix:/home/{user}/.valet/valet.sock;
</code>```

and add

```<code>fastcgi_pass 127.0.0.1:9000;
</code>```

and do the same on

/etc/php/7.2/fpm/pool.d/www.conf

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to install PHP7.2 and Nginx on my development machine. My development machine is running on Bash Ubuntu 16.04 on Windows.

I've had a working Nginx and PHP7.0 installed before deleting previous versions of PHP and installing PHP7.2.

Error.log output:

2017/12/07 03:30:33 [error] 32655#32655: *1 upstream timed out (110: Connection timed out) while reading upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET /helloworld.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock:", host: "127.0.0.1"

php7.2-fpm.log:

[07-Dec-2017 03:29:29] NOTICE: Finishing ...
[07-Dec-2017 03:29:29] NOTICE: exiting, bye-bye!
[07-Dec-2017 03:29:30] NOTICE: fpm is running, pid 32683
[07-Dec-2017 03:29:30] NOTICE: ready to handle connections
[07-Dec-2017 03:29:30] NOTICE: systemd monitor interval set to 10000ms

sites-available/default:

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }

The page I'm trying to load:

<?php echo 'Hello World'; ?>

I've tried completely removing all PHP7* and Nginx and re-installing with fresh config files but same result.

If I create a page with phpinfo() it does display all information but it keeps loading.

I don't know where to begin as there are no proper errors appearing.

Body:
Solved, problem was that WSL doesn't support unix:socket and required me to comment out:

/etc/nginx/sites-available/default.conf

fastcgi_pass unix:/home/{user}/.valet/valet.sock;

and add

fastcgi_pass 127.0.0.1:9000;

and do the same on

/etc/php/7.2/fpm/pool.d/www.conf


问:
PL/SQL How to compare an expression in a trigger?
I'm trying to output a message each time a student's new GPA is lower than their old GPA by 1 or more.

```<code>Create or Replace TRIGGER AUGPA
  after update on students
  for each row -- or should I put 'for GPA' the column name
begin
  if (:new.gpa - :old.gpa) >= 1 -- How do I compare these expressions? I get an error here.
    THEN
      dbms_output.put_line ('Old GPA is lower than previous GPA by at least 1 point.')
  End if;
End;
/
</code>```

Students Table

```<code>SNUM  SNAME  STANDING  MAJOR  GPA  MAJORGPA
****  *****  ********  *****  ***  ********
121   Liz      2       FIN   2.8     3.2
</code>```

答:
Your operation is backwards.
Lets use the following new.gpa = 1.5, old.gpa = 3. So the gpa has fallen by by 1.5 so the message should be issued. The message will not be issued: the code is "If new.gpa - old.gpa >= 1 then message ..." However 1.5 - 3 = -1.5 which is not >- 1. Change to "If old.gpa - new.gpa >= 1". </p>

<p>@Anand suggests is not good as it would generate the message if the gpa fell to 2.9 from 3; just a .1 drop </p>

Body:
I'm trying to output a message each time a student's new GPA is lower than their old GPA by 1 or more.

Create or Replace TRIGGER AUGPA
  after update on students
  for each row -- or should I put 'for GPA' the column name
begin
  if (:new.gpa - :old.gpa) >= 1 -- How do I compare these expressions? I get an error here.
    THEN
      dbms_output.put_line ('Old GPA is lower than previous GPA by at least 1 point.')
  End if;
End;
/

Students Table

SNUM  SNAME  STANDING  MAJOR  GPA  MAJORGPA
****  *****  ********  *****  ***  ********
121   Liz      2       FIN   2.8     3.2

Body:
Your operation is backwards.
Lets use the following new.gpa = 1.5, old.gpa = 3. So the gpa has fallen by by 1.5 so the message should be issued. The message will not be issued: the code is "If new.gpa - old.gpa >= 1 then message ..." However 1.5 - 3 = -1.5 which is not >- 1. Change to "If old.gpa - new.gpa >= 1".

@Anand suggests is not good as it would generate the message if the gpa fell to 2.9 from 3; just a .1 drop


问:
I'm trying to get the user to input numbers into an ArrayList. If the user enters 0, sum and average the numbers
This program asks users to input numbers which populates an array list. If the user inputs a 0, then the program sums all of the previous numbers inputted and averages them. It's not working for me, so how could I make this work?</p>

```<code>import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Calculation {
    static Toolkit tools = new Toolkit();
    public static void main(String [] args) {
        double average = 0.0;
        double sum = 0;
        int i =0;
        int num = 0;
        int nElements = 0;
        Scanner console = new Scanner(System.in);

        ArrayList<Integer> value = new ArrayList<Integer>();
        System.out.println("Enter value: ");
        num = console.nextInt();
        while(num != 0) {
            value.add(new Integer(num));
        }

        for(i = 0; i < value.size(); i++) {
             sum += value.size();
        }
        average = sum / value.size();
        System.out.println("Number of values read: " + value.size());
        System.out.println("Values sum: " + sum + "Values average: " + average);
        System.exit(0);
    }
}
</code>```

答:
You need to read inside the loop, here you have:</p>

```<code> public static void main(String [] args) {
     double average = 0.0;
     double sum = 0;
     int i =0;
     int num = 0;
     int nElements = 0;
     Scanner console = new Scanner(System.in);

     ArrayList<Integer> value = new ArrayList<Integer>();

     System.out.println("Enter value: ");
     num = console.nextInt();

     while(num != 0) {
         value.add(new Integer(num));
         num = console.nextInt();
     }

     for(i = 0; i < value.size(); i++) {
         sum += value.get(i);
     }
     average = sum / value.size();
     System.out.println("Number of values read: " + value.size());
     System.out.println("Values sum: " + sum + " Values average: " + average);
     System.exit(0);
}
</code>```

Body:
This program asks users to input numbers which populates an array list. If the user inputs a 0, then the program sums all of the previous numbers inputted and averages them. It's not working for me, so how could I make this work?

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Calculation {
    static Toolkit tools = new Toolkit();
    public static void main(String [] args) {
        double average = 0.0;
        double sum = 0;
        int i =0;
        int num = 0;
        int nElements = 0;
        Scanner console = new Scanner(System.in);

        ArrayList<Integer> value = new ArrayList<Integer>();
        System.out.println("Enter value: ");
        num = console.nextInt();
        while(num != 0) {
            value.add(new Integer(num));
        }

        for(i = 0; i < value.size(); i++) {
             sum += value.size();
        }
        average = sum / value.size();
        System.out.println("Number of values read: " + value.size());
        System.out.println("Values sum: " + sum + "Values average: " + average);
        System.exit(0);
    }
}

Body:
You need to read inside the loop, here you have:

 public static void main(String [] args) {
     double average = 0.0;
     double sum = 0;
     int i =0;
     int num = 0;
     int nElements = 0;
     Scanner console = new Scanner(System.in);

     ArrayList<Integer> value = new ArrayList<Integer>();

     System.out.println("Enter value: ");
     num = console.nextInt();

     while(num != 0) {
         value.add(new Integer(num));
         num = console.nextInt();
     }

     for(i = 0; i < value.size(); i++) {
         sum += value.get(i);
     }
     average = sum / value.size();
     System.out.println("Number of values read: " + value.size());
     System.out.println("Values sum: " + sum + " Values average: " + average);
     System.exit(0);
}


问:
Removal of labels in Prometheus
I'm looking into our company using Prometheus to gather stats from our experiments which run on Kubernetes. There's a plan to use labels to mark the name of specific experiments in our cloud / cluster. This means we will generate a lot of labels which will hog storage over time. When the associated time series have expired, will the labels also be deleted? </p>

答:
tldr; From an operational perspective, Prometheus does not differentiate between time-series names and labels; by deleting your experiment data you will effectively recover the labels you created.

What follows is only relevant to Prometheus >= 2.0

Prometheus stores a times series for each unique combination of metric name, label, and label value. So my_metric{my_tag="a"},  my_metric{my_tag="b"}, and your_metric{} are all just different time series; there is nothing special about labels or label values vs. metrics names.

Furthermore, Prometheus stores data in 2-hour frames on disk. So any labels you've created do not effect operations of your database after two hours, except for on-disk storage size, and query performance if you actually access that older data. Both of these concerns are addressed after your data is purged. Experiment away!

Title: Removal of labels in Prometheus


问:
Python - Remove quotes and double minus using replace
Given a string such as

```<code>--"I like salami. "-I want to walk to the shops"
</code>```

How can I return the string such as

```<code>I like salami. I want to walk to the shops.
</code>```

I can alter each individually but when I use '-"' it fails.

Quotes

```<code>b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops
</code>```

Minus

```<code>b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"
</code>```

Together

```<code>MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"
</code>```

答:
Another solution using regex:

```<code>import re
str = '--"I like salami. "-I want to walk to the shops"'
print re.sub("[-\"]", repl="", string=str)
</code>```

output:

```<code>I like salami. I want to walk to the shops
</code>```

Body:
Given a string such as

--"I like salami. "-I want to walk to the shops"

How can I return the string such as

I like salami. I want to walk to the shops.

I can alter each individually but when I use '-"' it fails.

Quotes

b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops

Minus

b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"

Together

MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"

Body:
Another solution using regex:

import re
str = '--"I like salami. "-I want to walk to the shops"'
print re.sub("[-\"]", repl="", string=str)

output:

I like salami. I want to walk to the shops


问:
iOS 11 MKAnnotationView prepareForReuse dismiss the pin view in Map view
what I want to do is when I deselect an pin, the pin view change it's UI back to unselected state(e.g change color of background of the pin)

```<code>- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
   //do something;

   XLMapItemAnnotation* mapItem = [self annotationForView:view];
   [view prepareForReuse];
}
</code>```

by having this code,  when I run the app in iOS 11, if I deselect a pin, the pin disappear in the map view totally. and if I remove the prepareForReuse, everything would be fine.
and the some code if I run the app in iOS 10, everything is fine, no pin get disappeared.
can sbd give me a hint, what could be wrong?

答: You should not call -prepareForReuse yourself, it's intended for MapKit to call itself.

Body:
what I want to do is when I deselect an pin, the pin view change it's UI back to unselected state(e.g change color of background of the pin)

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
   //do something;

   XLMapItemAnnotation* mapItem = [self annotationForView:view];
   [view prepareForReuse];
}

by having this code,  when I run the app in iOS 11, if I deselect a pin, the pin disappear in the map view totally. and if I remove the prepareForReuse, everything would be fine.
and the some code if I run the app in iOS 10, everything is fine, no pin get disappeared.
can sbd give me a hint, what could be wrong?


问:
Login Page will not open profile activity
After a user registers in the signup activity page I want them to be able to press the login button in the login page and then for the app to go to a profile activity page.  However, the app crashes after typing in the username and password and pressing the login button in the login page. Here is the sets of codes and this first set is the Login Page code in "LoginPageActivity.java" activity.

```<code>package com.example.xxxx.safetyxxxxxxx;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginPageActivity extends AppCompatActivity implements View.OnClickListener{

    FirebaseAuth mAuth;
    EditText editTextEmail, editTextPassword;
    ProgressBar progressBar;

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

        mAuth = FirebaseAuth.getInstance();

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword= (EditText) findViewById(R.id.editTextPassword);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

    findViewById(R.id.textViewSignUp).setOnClickListener(this);
    findViewById(R.id.buttonLogin).setOnClickListener(this);

}

private void userLogin(){

    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(email.isEmpty()){
        editTextEmail.setError("Email is required");
        editTextEmail.requestFocus();
        return;
    }

    if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        editTextEmail.setError("Please enter a valid email");
        editTextEmail.requestFocus();
        return;
    }

    if(password.isEmpty()){
        editTextPassword.setError("Password is required");
        editTextPassword.requestFocus();
        return;
    }

    if(password.length()<6){
        editTextPassword.setError("Minimum length of password should be 6");
        editTextPassword.requestFocus();
        return;
    }

    progressBar.setVisibility(View.VISIBLE);
        mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressBar.setVisibility(View.GONE);
                if (task.isSuccessful()) {
                    Intent intent = new Intent(LoginPageActivity.this, ProfileActivity.class);
                    startActivity(intent);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

}

    @Override
    public void onClick(View view) {
            switch (view.getId()) {
                case R.id.textViewSignUp:

                    startActivity(new Intent(this, SignUpActivity.class));

                    break;

                case R.id.buttonLogin:
                    userLogin();
                    break;
            }
        }
    }
</code>```

Here is the profile activity called "ProfileActivity.java"

```<code>package com.example.xxxx.safetyxxxxxxx;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ProfileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
    }
}
</code>```

Here is the android manifest code.  I have tried many different variations of declaring the ProfileActivity class in this manifest based on research and previous issues in the past with the same logcat error.

```<code>   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xxxx.safetyxxxxxxx">

    <application
        android:name=".Database"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginPageActivity"
            android:label="@string/app_name"/>
        <activity android:name=".Main2Activity" />
        <activity
            android:name=".SignUpActivity"
            android:label="@string/app_name">

    </activity>
        <activity android:name=".ProfileActivity"
        android:label="@string/app_name"/>
    </application>

</manifest>
</code>```

Here is the logcat error

12-02 12:04:56.008 2644-2644/com.example.xxxx.safetyxxxxxxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xxxx.safetyxxxxxxx, PID: 2644
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.xxxx.safetyxxxxxxx/com.example.xxxx.safetyxxxxxxx.ProfileActivity}; have you declared this activity in your AndroidManifest.xml?
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1933)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
    at android.app.Activity.startActivityForResult(Activity.java:4488)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
    at android.app.Activity.startActivityForResult(Activity.java:4446)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
    at android.app.Activity.startActivity(Activity.java:4807)
    at android.app.Activity.startActivity(Activity.java:4775)
    at com.example.xxxx.safetyxxxxxxx.LoginPageActivity$1.onComplete(LoginPageActivity.java:79)
    at com.google.android.gms.tasks.zzf.run(Unknown Source:23)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
```
<p>Finally in case it is needed here is the loginpage layout code called "activity_login_page.xml"</p>
```<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginPageActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Hi, Welcome to Safety xxxxxxx Please Login or Signup"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.66"></TextView>

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Login"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.87" />

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="email"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toTopOf="@+id/editTextPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.95" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPassword"
        android:hint=" Password"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.87" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="219dp"
        android:layout_height="229dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/editTextEmail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.233"
        app:srcCompat="@drawable/safetyxxx" />

    <TextView
        android:id="@+id/textViewSignUp"
        android:layout_width="345dp"
        android:layout_height="35dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Do Not Have An Account?  Click Here"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonLogin" />

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>
```

答:
After many tries all I needed to do was press the rebuild project button.  It worked perfectly after that.

Thanks for all that tried to help.

ContentLicense: CC BY-SA 4.0

Body:
After a user registers in the signup activity page I want them to be able to press the login button in the login page and then for the app to go to a profile activity page.  However, the app crashes after typing in the username and password and pressing the login button in the login page. Here is the sets of codes and this first set is the Login Page code in "LoginPageActivity.java" activity.

package com.example.xxxx.safetyxxxxxxx;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginPageActivity extends AppCompatActivity implements View.OnClickListener{

    FirebaseAuth mAuth;
    EditText editTextEmail, editTextPassword;
    ProgressBar progressBar;

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

        mAuth = FirebaseAuth.getInstance();

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword= (EditText) findViewById(R.id.editTextPassword);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

    findViewById(R.id.textViewSignUp).setOnClickListener(this);
    findViewById(R.id.buttonLogin).setOnClickListener(this);

}

private void userLogin(){

    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(email.isEmpty()){
        editTextEmail.setError("Email is required");
        editTextEmail.requestFocus();
        return;
    }

    if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        editTextEmail.setError("Please enter a valid email");
        editTextEmail.requestFocus();
        return;
    }

    if(password.isEmpty()){
        editTextPassword.setError("Password is required");
        editTextPassword.requestFocus();
        return;
    }

    if(password.length()<6){
        editTextPassword.setError("Minimum length of password should be 6");
        editTextPassword.requestFocus();
        return;
    }

    progressBar.setVisibility(View.VISIBLE);
        mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressBar.setVisibility(View.GONE);
                if (task.isSuccessful()) {
                    Intent intent = new Intent(LoginPageActivity.this, ProfileActivity.class);
                    startActivity(intent);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

}

    @Override
    public void onClick(View view) {
            switch (view.getId()) {
                case R.id.textViewSignUp:

                    startActivity(new Intent(this, SignUpActivity.class));

                    break;

                case R.id.buttonLogin:
                    userLogin();
                    break;
            }
        }
    }

Here is the profile activity called "ProfileActivity.java"

package com.example.xxxx.safetyxxxxxxx;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ProfileActivity extends AppCompatActivity {

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

Here is the android manifest code.  I have tried many different variations of declaring the ProfileActivity class in this manifest based on research and previous issues in the past with the same logcat error.

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xxxx.safetyxxxxxxx">

    <application
        android:name=".Database"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginPageActivity"
            android:label="@string/app_name"/>
        <activity android:name=".Main2Activity" />
        <activity
            android:name=".SignUpActivity"
            android:label="@string/app_name">

    </activity>
        <activity android:name=".ProfileActivity"
        android:label="@string/app_name"/>
    </application>

</manifest>

Here is the logcat error

12-02 12:04:56.008 2644-2644/com.example.xxxx.safetyxxxxxxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xxxx.safetyxxxxxxx, PID: 2644
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.xxxx.safetyxxxxxxx/com.example.xxxx.safetyxxxxxxx.ProfileActivity}; have you declared this activity in your AndroidManifest.xml?
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1933)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
    at android.app.Activity.startActivityForResult(Activity.java:4488)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
    at android.app.Activity.startActivityForResult(Activity.java:4446)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
    at android.app.Activity.startActivity(Activity.java:4807)
    at android.app.Activity.startActivity(Activity.java:4775)
    at com.example.xxxx.safetyxxxxxxx.LoginPageActivity$1.onComplete(LoginPageActivity.java:79)
    at com.google.android.gms.tasks.zzf.run(Unknown Source:23)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Finally in case it is needed here is the loginpage layout code called "activity_login_page.xml"

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginPageActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Hi, Welcome to Safety xxxxxxx Please Login or Signup"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.66"></TextView>

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Login"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.87" />

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="email"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toTopOf="@+id/editTextPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.95" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPassword"
        android:hint=" Password"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.87" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="219dp"
        android:layout_height="229dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/editTextEmail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.233"
        app:srcCompat="@drawable/safetyxxx" />

    <TextView
        android:id="@+id/textViewSignUp"
        android:layout_width="345dp"
        android:layout_height="35dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Do Not Have An Account?  Click Here"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonLogin" />

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>


问:
Pyspark alter column with substring
Pyspark n00b... How do I replace a column with a substring of itself? I'm trying to remove a select number of characters from the start and end of string.

```<code>from pyspark.sql.functions import substring
import pandas as pd
pdf = pd.DataFrame({'COLUMN_NAME':['_string_','_another string_']})
# this is what i'm looking for...
pdf['COLUMN_NAME_fix']=pdf['COLUMN_NAME'].str[1:-1]

df = sqlContext.createDataFrame(pdf)
# following not working... COLUMN_NAME_fix is blank
df.withColumn('COLUMN_NAME_fix', substring('COLUMN_NAME', 1, -1)).show()
</code>```

This is pretty close but slightly different Spark Dataframe column with last character of other column. And then there is this
LEFT and RIGHT function in PySpark SQL

答:
try:

```<code>df.withColumn('COLUMN_NAME_fix', df['COLUMN_NAME'].substr(1, 10)).show()
</code>```

where 1 = start position in the string and
     10 = number of characters to include from start position (inclusive)

Title: Pyspark alter column with substring

Body:
Pyspark n00b... How do I replace a column with a substring of itself? I'm trying to remove a select number of characters from the start and end of string.

from pyspark.sql.functions import substring
import pandas as pd
pdf = pd.DataFrame({'COLUMN_NAME':['_string_','_another string_']})
# this is what i'm looking for...
pdf['COLUMN_NAME_fix']=pdf['COLUMN_NAME'].str[1:-1]

df = sqlContext.createDataFrame(pdf)
# following not working... COLUMN_NAME_fix is blank
df.withColumn('COLUMN_NAME_fix', substring('COLUMN_NAME', 1, -1)).show()

This is pretty close but slightly different Spark Dataframe column with last character of other column. And then there is this
LEFT and RIGHT function in PySpark SQL

Body:
try:

df.withColumn('COLUMN_NAME_fix', df['COLUMN_NAME'].substr(1, 10)).show()

where 1 = start position in the string and
     10 = number of characters to include from start position (inclusive)


问:
Omnis Studio: Return more than 1 value
I'm currently programming with Omnis Studio and I need your help.

I need to return more than 1 value, but Quit Method only allows 1 value.
Is there another option to return more than 1 value?

Thank you for your help!

答:
You can use field reference parameters where the given parameter can be changed itself inside your method.

Another way is to return a row or list variable that contains different return values.
A list is a data structure that contains one or more columns and one or more rows. Each column can have its own data type.
A row variable is simply a list with only one row.

```<code>Calculate myRow as row(myVar1, myVar2, myVar3)
Quit method myRow
</code>```

You can access the columns by name or even by number (in the sample above the columns don’t have a name):

```<code>Calculate mySecondVar as myRow.c2
</code>```

In this case c2 stands for column 2 and refers to the second variable in that row.

This way you can easily return as much values as you like.

Title: Omnis Studio: Return more than 1 value

Body:
You can use field reference parameters where the given parameter can be changed itself inside your method.

Another way is to return a row or list variable that contains different return values.
A list is a data structure that contains one or more columns and one or more rows. Each column can have its own data type.
A row variable is simply a list with only one row.

Calculate myRow as row(myVar1, myVar2, myVar3)
Quit method myRow

You can access the columns by name or even by number (in the sample above the columns don’t have a name):

Calculate mySecondVar as myRow.c2

In this case c2 stands for column 2 and refers to the second variable in that row.

This way you can easily return as much values as you like.


问:
Remove class not working with reference to parent element
I want to remove class with reference to parent as below snippet. Why I am not able to do it

$('div').click(function(){
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red{color:red}</code>```

A

B

C

D

E

F

```

PS: I want modifying html to be the last option.

答:
You may want to modify your selector for click event handler.

$('#parent div').click(function(){
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red{color:red}</code>```

A

B

C

D

E

F

```
</div>
</div>
</p>

<p>or may want to stop the event from propagating.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('div').click(function(e){
    e.stopPropagation();
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});</code>```

.red{color:red}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div id="parent">
    <div class="red">A</div>
    <div class="red">B</div>
    <div class="red">C</div>
    <div class="red">D</div>
    <div class="red">E</div>
    <div class="red">F</div>
<div></code>```

Body:
I want to remove class with reference to parent as below snippet. Why I am not able to do it

$('div').click(function(){
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});

.red{color:red}

A

B

C

D

E

F

PS: I want modifying html to be the last option.

Body:
You may want to modify your selector for click event handler.

$('#parent div').click(function(){
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});

.red{color:red}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div id="parent">
    <div class="red">A</div>
    <div class="red">B</div>
    <div class="red">C</div>
    <div class="red">D</div>
    <div class="red">E</div>
    <div class="red">F</div>
<div>

or may want to stop the event from propagating.

$('div').click(function(e){
    e.stopPropagation();
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});

.red{color:red}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div id="parent">
    <div class="red">A</div>
    <div class="red">B</div>
    <div class="red">C</div>
    <div class="red">D</div>
    <div class="red">E</div>
    <div class="red">F</div>
<div>


问:
App crashes when i use Cursor method to get data from SQlite
This is my code, the Cursor cursor= db.rawQuery is the reason. My app keep crashing

please tell me what's wrong:-

```<code>public QuestionController(Context context) {
    dbHelper= new DBHelper(context);
}

//Lấy danh sách câu hỏi
public ArrayList<Question> getQuestion(int num_exam, String subject){
    ArrayList<Question> lsData= new ArrayList<Question>();
    SQLiteDatabase db= dbHelper.getReadableDatabase();

    Cursor cursor= db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = '"+ num_exam+"' AND subject='"+subject+"' ORDER BY random()",null);
    cursor.moveToFirst();
    do {
        Question item;
        item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
                cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
        lsData.add(item);
    }while (cursor.moveToNext());
    cursor.close();
    return lsData;
</code>```

答:
Not Sure But You Can Try these,</p>

```<code>db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = ? AND subject=? ORDER BY random()", new String[] {num_exam,subject});
</code>```

Body:
This is my code, the Cursor cursor= db.rawQuery is the reason. My app keep crashing

please tell me what's wrong:-

public QuestionController(Context context) {
    dbHelper= new DBHelper(context);
}

//Lấy danh sách câu hỏi
public ArrayList<Question> getQuestion(int num_exam, String subject){
    ArrayList<Question> lsData= new ArrayList<Question>();
    SQLiteDatabase db= dbHelper.getReadableDatabase();

    Cursor cursor= db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = '"+ num_exam+"' AND subject='"+subject+"' ORDER BY random()",null);
    cursor.moveToFirst();
    do {
        Question item;
        item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
                cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
        lsData.add(item);
    }while (cursor.moveToNext());
    cursor.close();
    return lsData;

Body:
Not Sure But You Can Try these,

db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = ? AND subject=? ORDER BY random()", new String[] {num_exam,subject});


问:
What are flip-flops&latches and transmission&switch gates in Verilog?
I've looked everywhere to figure out what flip-flops and latches are. Could you give me a brief description of them in the simplest possible way (as if to a child)?

Also, could you tell me the functionalities, input and output of transmission primitives (buf, bufif0, bufif1, notif0, notif1) and switch primitives (pmos, rpmos, nmos, rnmos, cmos, rcmos, tranif1, tranif0, rtranif1, rtranif0, tran, rtran, pullup, pulldown)?

It is a lot of stuff I am requesting, so if you have a URL with comprehensive description of the given primitives, and any other ones with other introductory level information on Verilog, I would be very grateful. (NOT http://www.asic-world.com because that is precisely where I'm learning this from and I don't understand them)

PS: I'd like to be familiar with more primitives to prepare for my exam.

答:
Could you give me a brief description of them in the simplest possible way (as if to a child)?

Once upon a time a wise genie named Lindley invented a magical box called a Flip-Flop. Whenever the enchanted Clock strikes a chime, if a peasant farmer Mr. D. is feeling high, his neighbor Mrs. Q will see this and suddenly do a "flip", landing upon the rail. And there she stays until the next time the clock chimes.

But instead, if Mr. D. is feeling low when the enchanted clock chimes, Mrs. Q will "flop", quite dejectedly, ending up flat on the ground.

And so this continues on forever as long as the enchanted clock continues to chime, with Q flipping and flopping as to however D feels. But only each time the clock chimes, much to the bemusement of the genie. If the clock were to stop, Q will freeze right where she is, and no matter what is happening to D, there she will stay frozen.

This may seem an singularly odd amusement, but it happens that with enough enchanted boxes and flipping peasants, a wise fellow named Turing is said to be able to compute most nearly anything.

Now a latch is something, not quite different, but also very much not quite the same. It involves some different peasants and in lieu of the magical clock, another peasant simply tells the others when to freeze. For this reason it is not as interesting as the famous flip-flop of Antioch.

if you have a URL with comprehensive description of the given primitives

Please see the following freely download-able reference. This contains comprehensive and authoritative descriptions of all of the primitives you request.

IEEE 1800 System Verilog-2012


问:
How to apply Styles to a HiddenField Shown on a Button
I have a button that when clicked pops up a jquery-ui datepicker.  This works perfectly, is positioned correctly, and all that fun stuff.  The calendar is not used for anything specific - it is just there for reference when people need to look at a calendar.  The problem is, I want to put the glyphicon-calendar on the button to the left of the word "Calendar" (with one or two spaces between), and I want the style of the button to match the button next to it (css id="headerbutton").  Whenever I do anything through the css or html to implement this, my button just disappears!  Any help would be much appreciated.

$("#hiddenField").datepicker({
  showOn: "button",
  buttonText: "Calendar"
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#headerbutton {
  padding: 5px;
  color: #ffffff;
  background: #2f4050;
  border-radius: 5px;
}

#headerbutton:hover {
  background: #586672;
}

#hiddenField {
  display: none;
}</code>```

  <button type="button" id="headerbutton">
    Assigned Tasks
  </button>

  <input type="input" id="hiddenField" class="datepicker" />

```

答:
I spent most of the day getting this button to do what I wanted, and finally found it, between two different posts.

Adding Icons was covered here:
Referencing a Bootstrap icon within jQuery datepicker buttonImage attribute?

Adding CSS successfully to the button came from here:
class for jquery ui datepicker button

And it not only works, it all lines up and looks right!  Love this community, but there is SO MUCH here!

$( "#hiddenField" ).datepicker({
showOn: "button",
buttonText: '  Calendar'
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#headerbutton {
padding: 5px;
color: #ffffff;
background: #2f4050;
border-radius: 5px;
}
#headerbutton:hover {
background: #586672;
}
#hiddenField {
display: none;
}
.ui-datepicker-trigger{
padding: 5px 14px;
color: #ffffff;
background: #2f4050;
border-radius: 5px;
}
.ui-datepicker-trigger:hover{
background: #586672;
}</code>```

<button type="button" id="headerbutton">
Assigned Tasks
</button>

<input type="input" id="hiddenField" class="datepicker" />

```

Body:
I have a button that when clicked pops up a jquery-ui datepicker.  This works perfectly, is positioned correctly, and all that fun stuff.  The calendar is not used for anything specific - it is just there for reference when people need to look at a calendar.  The problem is, I want to put the glyphicon-calendar on the button to the left of the word "Calendar" (with one or two spaces between), and I want the style of the button to match the button next to it (css id="headerbutton").  Whenever I do anything through the css or html to implement this, my button just disappears!  Any help would be much appreciated.

$("#hiddenField").datepicker({
  showOn: "button",
  buttonText: "Calendar"
});

#headerbutton {
  padding: 5px;
  color: #ffffff;
  background: #2f4050;
  border-radius: 5px;
}

#headerbutton:hover {
  background: #586672;
}

#hiddenField {
  display: none;
}

  <button type="button" id="headerbutton">
    Assigned Tasks
  </button>

  <input type="input" id="hiddenField" class="datepicker" />

Body:
I spent most of the day getting this button to do what I wanted, and finally found it, between two different posts.

Adding Icons was covered here:
Referencing a Bootstrap icon within jQuery datepicker buttonImage attribute?

Adding CSS successfully to the button came from here:
class for jquery ui datepicker button

And it not only works, it all lines up and looks right!  Love this community, but there is SO MUCH here!

$( "#hiddenField" ).datepicker({
showOn: "button",
buttonText: '<i class="glyphicon glyphicon-calendar"></i>&nbsp;&nbsp;Calendar'
});

#headerbutton {
padding: 5px;
color: #ffffff;
background: #2f4050;
border-radius: 5px;
}
#headerbutton:hover {
background: #586672;
}
#hiddenField {
display: none;
}
.ui-datepicker-trigger{
padding: 5px 14px;
color: #ffffff;
background: #2f4050;
border-radius: 5px;
}
.ui-datepicker-trigger:hover{
background: #586672;
}

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- Buttons to Right in Lower Bar -->
<div class="col-md-4 col-sm-4 col-xs-5" style="text-align: right; margin-top: 20px;">
<button type="button" id="headerbutton">
<a href="#">Assigned Tasks</a>
</button>
<!-- Calendar Button - DO NOT MESS WITH THIS -->
<input type="input" id="hiddenField" class="datepicker" />
</div>


答:
I am guessing you need to remove red class from all child.

```<code>$('#parent div').click(function(){
    $('#parent *').removeClass('red');
    $(this).addClass('red');
});
</code>```

Title: Remove class not working with reference to parent element

Body:
I am guessing you need to remove red class from all child.

$('#parent div').click(function(){
    $('#parent *').removeClass('red');
    $(this).addClass('red');
});


问:
Create multiple folders with files inside
I am trying to create a simple CLI that will create a folder structure and some files. The structure would look something like this:

```<code>app-name
├── app.py
├── models.py
├── static
│   ├── css
│   ├── img
│   └── js
├── templates
└── views.py
</code>```

I have taken a look at the mkdirp library, but I realized I would have to chain the mkdirp() function for each folder I am trying to make and then use the fs module to create the individual files.

What I have tried so far is to chain the mkdirp() functions back-to-back for each folder that I am trying to create.

```<code>const path = require('path');
const mkdirp = require('mkdirp-promise');

mkdirp(path.join(__dirname, 'app-name', 'static', 'css'))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'js')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'img')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'templates')))
    .then(console.log)
    .catch(console.error);
</code>```

This approach doesn't seem to be very efficient, especially with different types of arguments that could be passed to the CLI.

I have thought about creating a folder that has the entire folder structure in it as well as the contents of the Python files, then just copy those files. But I am unsure if this is doable.

What would be a good approach to creating this folder and file hierarchy?

答:
It's a little hard to follow exactly what you're looking for.  If you just want to reliably create several directories, then I'd say just create a function that takes an array of paths and you can iterate serially through the array using .reduce():

```<code>const path = require('path');
const mkdirp = require('mkdirp-promise');

function makeAllDirs(root, list) {
    return list.reduce((p, item) => {
        return p.then(() => {
            return mkdirp(path.join(root, item));
        });
    }, Promise.resolve());
}

// usage

let dirs = [
    "app-name/static/css",
    "app-name/static/img",
    "app-name/static/js",
    "app-name/templates"
];

makeAllDirs(__dirname, dirs).then(() => {
   // all done here
}).catch(err => {
   // error here
});
</code>```

Body:
I am trying to create a simple CLI that will create a folder structure and some files. The structure would look something like this:

app-name
├── app.py
├── models.py
├── static
│   ├── css
│   ├── img
│   └── js
├── templates
└── views.py

I have taken a look at the mkdirp library, but I realized I would have to chain the mkdirp() function for each folder I am trying to make and then use the fs module to create the individual files.

What I have tried so far is to chain the mkdirp() functions back-to-back for each folder that I am trying to create.

const path = require('path');
const mkdirp = require('mkdirp-promise');

mkdirp(path.join(__dirname, 'app-name', 'static', 'css'))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'js')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'img')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'templates')))
    .then(console.log)
    .catch(console.error);

This approach doesn't seem to be very efficient, especially with different types of arguments that could be passed to the CLI.

I have thought about creating a folder that has the entire folder structure in it as well as the contents of the Python files, then just copy those files. But I am unsure if this is doable.

What would be a good approach to creating this folder and file hierarchy?

Body:
It's a little hard to follow exactly what you're looking for.  If you just want to reliably create several directories, then I'd say just create a function that takes an array of paths and you can iterate serially through the array using .reduce():

const path = require('path');
const mkdirp = require('mkdirp-promise');

function makeAllDirs(root, list) {
    return list.reduce((p, item) => {
        return p.then(() => {
            return mkdirp(path.join(root, item));
        });
    }, Promise.resolve());
}

// usage

let dirs = [
    "app-name/static/css",
    "app-name/static/img",
    "app-name/static/js",
    "app-name/templates"
];

makeAllDirs(__dirname, dirs).then(() => {
   // all done here
}).catch(err => {
   // error here
});


问:
How to start MySQL with --skip-grant-tables?
I locked my root user out from our database. I need to get all privileges back to the root user. I have my password and I can log in to MySQL. But the root user has no all privileges.</p>

答:
On the Linux system you can do following (Should be similar for other OS)

Check if mysql process is running:

```<code>sudo service mysql status
</code>```

If runnning then stop the process:
(Make sure you close all mysql tool)

```<code>sudo service mysql stop
</code>```

If you have issue stopping then do following

Search for process: ps aux | grep mysqld
Kill the process: kill -9 process_id

Now start mysql in safe mode with skip grant

```<code>sudo mysqld_safe --skip-grant-tables &
</code>```

ContentLicense: CC BY-SA 2.5

Body:
On the Linux system you can do following (Should be similar for other OS)

Check if mysql process is running:

sudo service mysql status

If runnning then stop the process:
(Make sure you close all mysql tool)

sudo service mysql stop

If you have issue stopping then do following

Search for process: ps aux | grep mysqld
Kill the process: kill -9 process_id

Now start mysql in safe mode with skip grant

sudo mysqld_safe --skip-grant-tables &


问:
How to append date time for each output sql statement when executing sql file?
I have a sql file test.sql,

```<code>test.sql:
---------
drop table a.table1;
drop table a.table2;
drop table a.table3;
drop table a.table4;
drop table a.table5;
</code>```

Now I want to execute test.sql by

```<code>db2  -tvf test.sql > result.log
</code>```

The goal I want to achieve is to append a date time for output of each sql statement, the date time can be of any format and should be the one when executing the corresponding sql statement, now suppose each drop statement need 1 sec to execute, the result.log should be like this:

```<code>result.log:
-----------
Wed Dec 6 18:46:41 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:42 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:43 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:44 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:45 HKT 2017  DB20000I The SQL Command Completed Successfully.
</code>```

Any idea how to achieve it? Thanks in advance.

答:
Thanks, now I can do it with</p>

```<code>db2 -l result.log -tvf test.sql > /dev/null
</code>```

Body:
I have a sql file test.sql,

test.sql:
---------
drop table a.table1;
drop table a.table2;
drop table a.table3;
drop table a.table4;
drop table a.table5;

Now I want to execute test.sql by

db2  -tvf test.sql > result.log

The goal I want to achieve is to append a date time for output of each sql statement, the date time can be of any format and should be the one when executing the corresponding sql statement, now suppose each drop statement need 1 sec to execute, the result.log should be like this:

result.log:
-----------
Wed Dec 6 18:46:41 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:42 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:43 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:44 HKT 2017  DB20000I The SQL Command Completed Successfully.
Wed Dec 6 18:46:45 HKT 2017  DB20000I The SQL Command Completed Successfully.

Any idea how to achieve it? Thanks in advance.

Body:
Thanks, now I can do it with

db2 -l result.log -tvf test.sql > /dev/null


问:
What is the pivot of these unsorted lists
I am having a hard time understanding what the pivots of these two unsorted lists would be.

```<code>List 1: 2,8,7,1,3,5,6,4
List 2: 4,5,9,1,2,8,7,3
</code>```

I'm think it's 5 for each of them but I'm not really sure. Any help is greatly appreciated!

答:
I am guessing you want to do quicksort.

You choose the first item of the array as pivot (you can also chose the last one if you prefer).

At the end of the Iteration you swap the pivot to where it's supposed to be.

Body:
I am having a hard time understanding what the pivots of these two unsorted lists would be.

List 1: 2,8,7,1,3,5,6,4
List 2: 4,5,9,1,2,8,7,3

I'm think it's 5 for each of them but I'm not really sure. Any help is greatly appreciated!


问:
Why is my function executing twice?
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?

```<code># -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()

displayIntro()
chooseGender()
chooseName()
nameConfirmation()
</code>```

I apologize for not posting the rest of the code sooner.
This is the output.

```<code>Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven
</code>```

答:
As chooseName() is getting called twice first below call of chooseGender() and second inside nameConfirmation() so that's the reason it is getting executed twice. As a fixed you can comment or remove chooseName() which is below chooseGender() as shown.

```<code>displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
</code>```

So updated code will be as follows:

```<code># -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()

displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
</code>```

Title: Why is my function executing twice?

Body:
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?

# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()

displayIntro()
chooseGender()
chooseName()
nameConfirmation()

I apologize for not posting the rest of the code sooner.
This is the output.

Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven

Body:
As chooseName() is getting called twice first below call of chooseGender() and second inside nameConfirmation() so that's the reason it is getting executed twice. As a fixed you can comment or remove chooseName() which is below chooseGender() as shown.

displayIntro()
chooseGender()
# chooseName()
nameConfirmation()

So updated code will be as follows:

# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()

displayIntro()
chooseGender()
# chooseName()
nameConfirmation()


答:
Simply add the .red class to the currently clicked div and remove this very same class from it's siblings using siblings().

$('#parent div').click(function(){
    $(this)
      .addClass('red')
      .siblings()
      .removeClass('red');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red{color:red}</code>```

A

B

C

D

E

F

```

Body:
Simply add the .red class to the currently clicked div and remove this very same class from it's siblings using siblings().

$('#parent div').click(function(){
    $(this)
      .addClass('red')
      .siblings()
      .removeClass('red');
});

.red{color:red}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div id="parent">
    <div class="red">A</div>
    <div class="red">B</div>
    <div class="red">C</div>
    <div class="red">D</div>
    <div class="red">E</div>
    <div class="red">F</div>
<div>


问:
Compare two dates in ASP calender
I am a noob at ASP, I am trying to take take a selected date from an ASP calendar and save that in a textbox or something that I can compare with the second selected date so that the second is larger. I'm not sure if it is possible while just using one calendar. I tried but do not know how to save the first date collection for comparison. I tried both ways but failed miserable. I did do a search but they are using javascript, or java and other languages I do not know.

What I want to do:
I am trying to take two separate inputted dates from user. when 1st date is inputted, store in something, then validate that the user selects a date after the 1st selected date. If not return error message

```<code><asp:TextBox ID="response" runat="server" />
                                <asp:TextBox ID="caldate1" runat="server" />
                                <asp:TextBox ID="caldate2" runat="server" />

                                <asp:CompareValidator ID="calvalidae" runat="server" ControlToCompare="caldate1" ErrorMessage="Date should be later than first date" Type="Date" operator="GreaterThan" ValueToCompare="caldate2"></asp:CompareValidator>
                                <asp:Calendar ID="cal1" runat="server"></asp:Calendar>
                                <asp:Calendar ID="cal2" runat="server" SelectionMode="Day" OnSelectionChanged="cal1_SelectionChanged" ></asp:Calendar>
</code>```

//serverside

```<code>protected void cal1_SelectionChanged(object sender, EventArgs e)
    {
        caldate1.Text = cal1.SelectedDate.ToShortDateString();
        if (cal1.SelectedDate.Date > cal2.SelectedDate.Date)
        {
            caldate1.Text = "You selected ";
            caldate1.Text += cal1.SelectedDate.ToShortDateString();
        }
        else
        {
            caldate1.Text = "Select a valid date";
        }

    }
</code>```

答:
If you just want to compare the dates in code behind do the below

Markup

```<code>            <asp:CompareValidator ID="calvalidae" runat="server"
                                  ControlToValidate ="caldate1"  ValueToCompare="text" ControlToCompare="caldate2"
                ErrorMessage="Date should be later than first date" Type="Date"
                operator="GreaterThan" ></asp:CompareValidator><br/>
            <asp:Calendar ID="cal1" runat="server" OnSelectionChanged="cal1_SelectionChanged1"></asp:Calendar><br/>
            <asp:Calendar ID="cal2" runat="server" SelectionMode="Day" OnSelectionChanged="cal2_SelectionChanged" ></asp:Calendar><br/>
        </div>
</code>```

Code Behind

```<code>    protected void cal1_SelectionChanged1(object sender, EventArgs e)
    {
        caldate1.Text = cal1.SelectedDate.ToShortDateString();
        IsValidDate();
    }

    protected void cal2_SelectionChanged(object sender, EventArgs e)
    {
        caldate2.Text = cal2.SelectedDate.ToShortDateString();
        IsValidDate();
    }

    private void IsValidDate()
    {
        response.Text = string.Empty;
        if (cal1.SelectedDate > cal2.SelectedDate)
        {
            response.Text = "Date should be later than first date";
        }
    }
</code>```

Title: Compare two dates in ASP calender

Body:
I am a noob at ASP, I am trying to take take a selected date from an ASP calendar and save that in a textbox or something that I can compare with the second selected date so that the second is larger. I'm not sure if it is possible while just using one calendar. I tried but do not know how to save the first date collection for comparison. I tried both ways but failed miserable. I did do a search but they are using javascript, or java and other languages I do not know.

What I want to do:
I am trying to take two separate inputted dates from user. when 1st date is inputted, store in something, then validate that the user selects a date after the 1st selected date. If not return error message

<asp:TextBox ID="response" runat="server" />
                                <asp:TextBox ID="caldate1" runat="server" />
                                <asp:TextBox ID="caldate2" runat="server" />

                                <asp:CompareValidator ID="calvalidae" runat="server" ControlToCompare="caldate1" ErrorMessage="Date should be later than first date" Type="Date" operator="GreaterThan" ValueToCompare="caldate2"></asp:CompareValidator>
                                <asp:Calendar ID="cal1" runat="server"></asp:Calendar>
                                <asp:Calendar ID="cal2" runat="server" SelectionMode="Day" OnSelectionChanged="cal1_SelectionChanged" ></asp:Calendar>

//serverside

protected void cal1_SelectionChanged(object sender, EventArgs e)
    {
        caldate1.Text = cal1.SelectedDate.ToShortDateString();
        if (cal1.SelectedDate.Date > cal2.SelectedDate.Date)
        {
            caldate1.Text = "You selected ";
            caldate1.Text += cal1.SelectedDate.ToShortDateString();
        }
        else
        {
            caldate1.Text = "Select a valid date";
        }

    }

Body:
If you just want to compare the dates in code behind do the below

Markup

            <asp:CompareValidator ID="calvalidae" runat="server"
                                  ControlToValidate ="caldate1"  ValueToCompare="text" ControlToCompare="caldate2"
                ErrorMessage="Date should be later than first date" Type="Date"
                operator="GreaterThan" ></asp:CompareValidator><br/>
            <asp:Calendar ID="cal1" runat="server" OnSelectionChanged="cal1_SelectionChanged1"></asp:Calendar><br/>
            <asp:Calendar ID="cal2" runat="server" SelectionMode="Day" OnSelectionChanged="cal2_SelectionChanged" ></asp:Calendar><br/>
        </div>

Code Behind

    protected void cal1_SelectionChanged1(object sender, EventArgs e)
    {
        caldate1.Text = cal1.SelectedDate.ToShortDateString();
        IsValidDate();
    }

    protected void cal2_SelectionChanged(object sender, EventArgs e)
    {
        caldate2.Text = cal2.SelectedDate.ToShortDateString();
        IsValidDate();
    }

    private void IsValidDate()
    {
        response.Text = string.Empty;
        if (cal1.SelectedDate > cal2.SelectedDate)
        {
            response.Text = "Date should be later than first date";
        }
    }


问:
WinForms WebBrowser control's JavaScript execution context
I am using the WinForms WebBrowser control in my C# application and I can interact with the JS code on the web page by setting a COM class in the ObjectForScripting property of the control.

Is it possible to get the JavaScriptContext object from the web browser control that I can use with the ChakraCore API?

答:
No sir, ChakraCore is part of the Microsoft Edge JavaScript engine. It is literally a separate engine.  The web browser control uses IE's engine. Although admittedly it doesn't help that the dev team at MS called The MS Edge Engine Chakra when they were calling the engine from IE 9 forward as Chakra also.

Anyway if you want to use/embed the ChakraCore engine from C# they did create a getting started page. I will link it here.

The API for the winforms Webbrowser control Engine is here. The is a wrapper around the COM API. If you need to get to the COM api to do advanced things, you will need MSHTML, which you add as a COM reference to Microsoft Html Object library. The reference for MSHTML is here.


问:
How should I name my CSS classes?
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

```<code>.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)
</code>```

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

答:
4, 5 and 6 are special

.vote.count-post matches elements with class="vote count-post", or class="count-post vote" or even class="vote something-else count-post".

.vote .count-post matches elements with class="count-post" that are subelements of an element with class="vote"

and .vote .count.post is a mix of those both

Between 1, 2 and 3, all that matters is preference of style. Some people prefer one over another just as they do in programming languages. So just choose whatever you personally prefer, or what is more appropriate for you.

Title: How should I name my CSS classes?

Body:
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?


答:
Some modification in your code , Here is updated code:

First edit :

You are calling chooseName() two times ,

Second edit :

You are returning before main logic of your program.

Here

```<code>def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
</code>```

You should keep in mind that function is not going to execute anything after you return from it so your code from if answer == "yes": is not going to execute even if user type yes or no

So return it at the last of the program or if you want to return at the same place then use print there instead of 'return'.

```<code># -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = input("Right... So your name is " + str(name) + "? (yes or no) ")

    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()
    return answer

displayIntro()
chooseGender()
nameConfirmation()
</code>```

Title: Why is my function executing twice?

Body:
Some modification in your code , Here is updated code:

First edit :

You are calling chooseName() two times ,

Second edit :

You are returning before main logic of your program.

Here

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer

You should keep in mind that function is not going to execute anything after you return from it so your code from if answer == "yes": is not going to execute even if user type yes or no

So return it at the last of the program or if you want to return at the same place then use print there instead of 'return'.

# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = input("Right... So your name is " + str(name) + "? (yes or no) ")

    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()
    return answer

displayIntro()
chooseGender()
nameConfirmation()


答:
you have miss placed your selectors

$("document").ready(function(){
  $('#parent div').click(function(){
        $('#parent div').removeClass('red');
        $(this).addClass('red');
    });

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .red{color:red}</code>```

A

B

C

D

E

F

```

Body:
I want to remove class with reference to parent as below snippet. Why I am not able to do it

$('div').click(function(){
    $('#parent div').removeClass('red');
    $(this).addClass('red');
});

.red{color:red}

A

B

C

D

E

F

PS: I want modifying html to be the last option.

Body:
you have miss placed your selectors

$("document").ready(function(){
  $('#parent div').click(function(){
        $('#parent div').removeClass('red');
        $(this).addClass('red');
    });

})

  .red{color:red}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <div id="parent">
        <div class="red">A</div>
        <div class="red">B</div>
        <div class="red">C</div>
        <div class="red">D</div>
        <div class="red">E</div>
        <div class="red">F</div>
    <div>


答: You call the function choseName() and then right after you call nameConfiguration() wich starts by calling choseName(), that's why it is called twice. You can simply remove the choseName() before nameConfiguration().

Title: Why is my function executing twice?


问:
Can I convert my Cython code to Python?
I have written a cython code to help bridge the gap between a 3rdparty library and python.

I also written some of my code in cython to improve its performance.

Can I convert both of my above use cases into raw python?

example of use case one

```<code>def f(double x):
    return x**2-x

def integrate_f(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0
    dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx
</code>```

example of use case 2

```<code>from libc.stdlib cimport atoi

cdef parse_charptr_to_py_int(char* s):
    assert s is not NULL, "byte string value is NULL"
    return atoi(s)   # note: atoi() has no error detection!
</code>```

答:
Well for you first use case the answer is yes.
All you would need to do is remove the cdef lines like so.

```<code>def f(double x):
    return x**2-x

def integrate_f(double a, double b, int N):
    s = 0
    dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx
</code>```

For your second use case that's where things get tricky because you cant just delete the cdef lines or rename cdef to def. Also since this use case depends on the external library it doesn't have direct to python translation.

You have 2 options you can use besides Cython.

ctypes - the foreign function library built into standard python

cffi - a library that works similar to ctypes but simplifies the library glue code.

Your usage example using ctypes would look like this

```<code>def parse_charptr_to_py_int(test):
    from ctypes import cdll,c_char_p
    cdll.LoadLibrary("libc.so")
    return cdll.libc.atoi(c_char_p(test))
</code>```

Your usage example using cffi would look like this

```<code>def parse_charptr_to_py_int(test):
    from cffi import FFI
    ffi = FFI()
    ffi.cdef("int atoi(const char *str);")
    CLib = ffi.dlopen("libc.so")
    return CLib.atoi(test)
</code>```

Title: Can I convert my Cython code to Python?

Body:
I have written a cython code to help bridge the gap between a 3rdparty library and python.

I also written some of my code in cython to improve its performance.

Can I convert both of my above use cases into raw python?

example of use case one

def f(double x):
    return x**2-x

def integrate_f(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0
    dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx

example of use case 2

from libc.stdlib cimport atoi

cdef parse_charptr_to_py_int(char* s):
    assert s is not NULL, "byte string value is NULL"
    return atoi(s)   # note: atoi() has no error detection!

Body:
Well for you first use case the answer is yes.
All you would need to do is remove the cdef lines like so.

def f(double x):
    return x**2-x

def integrate_f(double a, double b, int N):
    s = 0
    dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx

For your second use case that's where things get tricky because you cant just delete the cdef lines or rename cdef to def. Also since this use case depends on the external library it doesn't have direct to python translation.

You have 2 options you can use besides Cython.

ctypes - the foreign function library built into standard python

cffi - a library that works similar to ctypes but simplifies the library glue code.

Your usage example using ctypes would look like this

def parse_charptr_to_py_int(test):
    from ctypes import cdll,c_char_p
    cdll.LoadLibrary("libc.so")
    return cdll.libc.atoi(c_char_p(test))

Your usage example using cffi would look like this

def parse_charptr_to_py_int(test):
    from cffi import FFI
    ffi = FFI()
    ffi.cdef("int atoi(const char *str);")
    CLib = ffi.dlopen("libc.so")
    return CLib.atoi(test)