问:
Zero margin between labels in bootstrap modal
I've using bootstrap labels in web page but in normal page its looking good but in modal there is no margin b/w two labels:

$('.task').dblclick(function (e) {
$('#Modal_Task_View').modal({keyboard: true, show: true});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Common styles for all types */
.task {
  padding: 10px 15px;
  margin: 10px 0;
  border: 1px solid #eee;
  border-left-width: 10px;
  border-radius: 3px;
}
.task h4 {
  margin-top: 0;
  margin-bottom: 5px;
}</code>```

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

Title 2
                                (First Category)

                        Assigned to :

                Gobind Samrow(admindddd)

                Chris Walker(CW)

                Due Date: 26-Jun-2017

                Days Left: 0

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task 2 Wishlist

                DueNormal
                Due Date : 08-Jul-2017

                         Category : Second Category

                        Description :
                        Description Description Description

                        Assigned To :
                        StandardAsh Wilde(ACW)admin admin(admin)

Linked TasksTitle 4Title 3

Documents

```

答:
The label class ".label" is an inline element by default so when you place two or more together there should be some space inbetween by default. This should also work inside a modal.

Also, you should not be using the  element for this. The  tag defines a label for an <input> element. Use a  instead.

Body:
I've using bootstrap labels in web page but in normal page its looking good but in modal there is no margin b/w two labels:

$('.task').dblclick(function (e) {
$('#Modal_Task_View').modal({keyboard: true, show: true});
});

/* Common styles for all types */
.task {
  padding: 10px 15px;
  margin: 10px 0;
  border: 1px solid #eee;
  border-left-width: 10px;
  border-radius: 3px;
}
.task h4 {
  margin-top: 0;
  margin-bottom: 5px;
}

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

Title 2
                                (First Category)

                        Assigned to :

                Gobind Samrow(admindddd)

                Chris Walker(CW)

                Due Date: 26-Jun-2017

                Days Left: 0

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task 2 Wishlist

                DueNormal
                Due Date : 08-Jul-2017

                         Category : Second Category

                        Description :
                        Description Description Description

                        Assigned To :
                        StandardAsh Wilde(ACW)admin admin(admin)

Linked TasksTitle 4Title 3

Documents

Body:
The label class ".label" is an inline element by default so when you place two or more together there should be some space inbetween by default. This should also work inside a modal.

Also, you should not be using the <label> element for this. The <label> tag defines a label for an <input> element. Use a <span> instead.


来源: stackexchange

问:
Where best to throw exception in this example?
In a library I am writing, I have some methods which would only be executed very rarely and on the fly. As I am modelling a vehicle, one of the (Exceptional) methods is a cracked engine, which would be very rare. Should  I throw an exception in this method? This will stop a vehicle from being usable.

I read the .NET Design Framework Guidelines book and it states that an exception should only occur when a method cannot complete execution. The actual engine cracked method will always complete, but if one of my methods, such as start engine (this method will store the amount of engine starts as a means of accruing stress to the engine), is called and results in a call to cracked engine, where (if anywhere) should I throw an exception?

答:
If you system (or subsystem) is designed to test engines, and the state of an engine being cracked is a normal state within the system, expected as a result of normal system processing, then it is not an exception.  if the system is one for use in a production engine, where, when the engine is cracked, the overall system can no longer perform it;s design function (Lift crates, move the vehicle forward, whatever)  then a cracked engine is an exception.

if the overall system is some combination of both, then within the subsystem that functions as an engine tester, (where a cracked engine is one of the states the system is designed to manage, monitor, report on and diagnose etc.), it should be a defined state, not an exception, and within the rest of the system it should be an exception... Then it is in the interface between these two subsystems that you will need to detect the cracked Engine State, and transform it into an exception (and/or vice versa)

ContentLicense: CC BY-SA 2.5


问:
How to get symfony validator violations as a multidimensional array?
By default symfony validator violations looks like this

```<code>  [0] => -message: "This value should not be blank."
         -propertyPath: "name"
  [1] => -message: "This value should not be blank."
         -propertyPath: "productVarieties[0].name"
</code>```

How can I convert this to a multidimensional array, so that productVarieties[0] will be nested inside a root array key?

I've tried using the property access component, but it seems like property path is in the wrong format

```<code>foreach ($violations as $violation) {
    $this->propertyAccessor->setValue($errors, $violation->getPropertyPath(), $violation->getMessage());
}
</code>```

Exception class:
  "Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException"
  message: "Cannot write property "name" to an array. Maybe you should
  write the property path as "[name]" instead?"

答:
The problem is you are trying to add a object property to an array which can not be done.

According to the error the element 0 of array productVarieties is an array itself. It needs to be a object to assign a property to it.

For workaround you can initialize it as a stdclass object first like

```<code>$this->propertyAccessor->setValue($errors, 'productVarieties[0]', new \stdClass);
</code>```

or you can replace productVarieties[0].name with productVarieties[0][name].

I haven't worked with symphony but it should help.

ContentLicense: CC BY-SA 3.0

Body:
By default symfony validator violations looks like this

  [0] => -message: "This value should not be blank."
         -propertyPath: "name"
  [1] => -message: "This value should not be blank."
         -propertyPath: "productVarieties[0].name"

How can I convert this to a multidimensional array, so that productVarieties[0] will be nested inside a root array key?

I've tried using the property access component, but it seems like property path is in the wrong format

foreach ($violations as $violation) {
    $this->propertyAccessor->setValue($errors, $violation->getPropertyPath(), $violation->getMessage());
}

Exception class:
  "Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException"
  message: "Cannot write property "name" to an array. Maybe you should
  write the property path as "[name]" instead?"

Body:
The problem is you are trying to add a object property to an array which can not be done.

According to the error the element 0 of array productVarieties is an array itself. It needs to be a object to assign a property to it.

For workaround you can initialize it as a stdclass object first like

$this->propertyAccessor->setValue($errors, 'productVarieties[0]', new \stdClass);

or you can replace productVarieties[0].name with productVarieties[0][name].

I haven't worked with symphony but it should help.


问:
ButterKnife 8.0.1 @OnClick not working in Fragment - Android Studio
I am using ButterKnife 8.0.1 in my android studio project. Below is my gradle file and snippet of fragment class. I am unable to see Toast message in button click. But I am able to see Toast if I use onCLicklistener .

Please help me find out what I am doing wrong I am stuck

My Gradle

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "tdd.serveroverload.com.tdd"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.jakewharton:butterknife:8.0.1'
}
</code>```

Fragment class

```<code> @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View calcView = inflater.inflate(R.layout.content_main, container, false);

        calcView.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 //It Works
                Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
            }
        });

        unbinder = ButterKnife.bind(this, calcView);

        return calcView;
    }

    @OnClick(R.id.one)
    public void one(View view) {

         //It Does not Works
        if (view.getId() == R.id.one) {

            Toast.makeText(getActivity(), "Click", Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
        result.setText(result.getText().toString() + 1);
    }
</code>```

答:
Same website https://github.com/JakeWharton/butterknife#download
Please add same below</p>

```<code>dependencies {
  compile 'com.jakewharton:butterknife:8.6.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
</code>```

Body:
I am using ButterKnife 8.0.1 in my android studio project. Below is my gradle file and snippet of fragment class. I am unable to see Toast message in button click. But I am able to see Toast if I use onCLicklistener .

Please help me find out what I am doing wrong I am stuck

My Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "tdd.serveroverload.com.tdd"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.jakewharton:butterknife:8.0.1'
}

Fragment class

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View calcView = inflater.inflate(R.layout.content_main, container, false);

        calcView.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 //It Works
                Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
            }
        });

        unbinder = ButterKnife.bind(this, calcView);

        return calcView;
    }

    @OnClick(R.id.one)
    public void one(View view) {

         //It Does not Works
        if (view.getId() == R.id.one) {

            Toast.makeText(getActivity(), "Click", Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
        result.setText(result.getText().toString() + 1);
    }

Body:
Same website https://github.com/JakeWharton/butterknife#download
Please add same below

dependencies {
  compile 'com.jakewharton:butterknife:8.6.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}


问:
Unable to connect to all storage backends successfully with PredictionIO and Elasticsearch on Localhost
I'm trying to setup PredictionIO locally following these instructions.

Unfortunately I'm unable to get it to work. When I try to install a template or run "pio status" I get the error saying that PredictionIO is unable to connect to elasticsearch:

```<code>[ERROR] [Console$] Unable to connect to all storage backends successfully. The following shows the error message from the storage backend.
[ERROR] [Console$] None of the configured nodes are available: [] (org.elasticsearch.client.transport.NoNodeAvailableException)
[ERROR] [Console$] Dumping configuration of initialized storage backend sources. Please make sure they are correct.
[ERROR] [Console$] Source Name: ELASTICSEARCH; Type: elasticsearch; Configuration: HOME -> /Users/tomasz/Documents/PredictionIO/apache-predictionio-0.10.0-incubating/PredictionIO-0.10.0-incubating/vendors/elasticsearch-1.4.4, HOSTS -> localhost, PORTS -> 9200, TYPE -> elasticsearch
</code>```

My pio-env.sh file is setup like so:

```<code>PIO_STORAGE_REPOSITORIES_METADATA_NAME=pio_meta
PIO_STORAGE_REPOSITORIES_METADATA_SOURCE=ELASTICSEARCH

PIO_STORAGE_REPOSITORIES_EVENTDATA_NAME=pio_event
PIO_STORAGE_REPOSITORIES_EVENTDATA_SOURCE=HBASE

PIO_STORAGE_REPOSITORIES_MODELDATA_NAME=pio_model
PIO_STORAGE_REPOSITORIES_MODELDATA_SOURCE=LOCALFS

PIO_STORAGE_SOURCES_ELASTICSEARCH_TYPE=elasticsearch
PIO_STORAGE_SOURCES_ELASTICSEARCH_HOSTS=localhost
PIO_STORAGE_SOURCES_ELASTICSEARCH_PORTS=9200
PIO_STORAGE_SOURCES_ELASTICSEARCH_HOME=$PIO_HOME/vendors/elasticsearch-1.4.4

PIO_STORAGE_SOURCES_LOCALFS_TYPE=localfs
PIO_STORAGE_SOURCES_LOCALFS_PATH=$PIO_FS_BASEDIR/models

PIO_STORAGE_SOURCES_HBASE_TYPE=hbase
PIO_STORAGE_SOURCES_HBASE_HOME=$PIO_HOME/vendors/hbase-1.0.0
</code>```

Any help would be appreciated.

答: I encountered this when I was using Elasticsearch 5.4.x on PredictionIO version 0.11.0-incubating. It worked when I used Elasticsearch 1.7.x  </p>

Body:
I'm trying to setup PredictionIO locally following these instructions.

Unfortunately I'm unable to get it to work. When I try to install a template or run "pio status" I get the error saying that PredictionIO is unable to connect to elasticsearch:

[ERROR] [Console$] Unable to connect to all storage backends successfully. The following shows the error message from the storage backend.
[ERROR] [Console$] None of the configured nodes are available: [] (org.elasticsearch.client.transport.NoNodeAvailableException)
[ERROR] [Console$] Dumping configuration of initialized storage backend sources. Please make sure they are correct.
[ERROR] [Console$] Source Name: ELASTICSEARCH; Type: elasticsearch; Configuration: HOME -> /Users/tomasz/Documents/PredictionIO/apache-predictionio-0.10.0-incubating/PredictionIO-0.10.0-incubating/vendors/elasticsearch-1.4.4, HOSTS -> localhost, PORTS -> 9200, TYPE -> elasticsearch

My pio-env.sh file is setup like so:

PIO_STORAGE_REPOSITORIES_METADATA_NAME=pio_meta
PIO_STORAGE_REPOSITORIES_METADATA_SOURCE=ELASTICSEARCH

PIO_STORAGE_REPOSITORIES_EVENTDATA_NAME=pio_event
PIO_STORAGE_REPOSITORIES_EVENTDATA_SOURCE=HBASE

PIO_STORAGE_REPOSITORIES_MODELDATA_NAME=pio_model
PIO_STORAGE_REPOSITORIES_MODELDATA_SOURCE=LOCALFS

PIO_STORAGE_SOURCES_ELASTICSEARCH_TYPE=elasticsearch
PIO_STORAGE_SOURCES_ELASTICSEARCH_HOSTS=localhost
PIO_STORAGE_SOURCES_ELASTICSEARCH_PORTS=9200
PIO_STORAGE_SOURCES_ELASTICSEARCH_HOME=$PIO_HOME/vendors/elasticsearch-1.4.4

PIO_STORAGE_SOURCES_LOCALFS_TYPE=localfs
PIO_STORAGE_SOURCES_LOCALFS_PATH=$PIO_FS_BASEDIR/models

PIO_STORAGE_SOURCES_HBASE_TYPE=hbase
PIO_STORAGE_SOURCES_HBASE_HOME=$PIO_HOME/vendors/hbase-1.0.0

Any help would be appreciated.


问:
How to solve "String interpolation produces a debug description for an optional value; did you mean to make this explicit?" in Xcode 8.3 beta?
Since beta 8.3, zillions warnings "String interpolation produces a debug description for an optional value; did you mean to make this explicit?" appeared in my code.

For example, the warning popped in the following situation up, where options could lead to nil:

```<code>let msg = "*** Error \(options["taskDescription"]): cannot load \(sUrl) \(error)"
</code>```

As previously designed, it was ok for me (and the compiler) the optionals to be interpolated as 'nil'. But compiler changed its mind.

What the compiler suggests is to add a String constructor with description as follows:

```<code>let msg = "*** Error \(String(describing: options["taskDescription"])): cannot load \(sUrl) \(error)"
</code>```

Obviously, the results is explicit but also very very cumbersome in my opinion. Is there a better option? Do I have to fix all those warning or better wait for the next beta?

答:
Double click on the yellow triangle displayed on line containing this warning. This will show FixIt with two solutions.

Use String(describing:) to silence this warning :

Using this it will become String(describing:<Variable>)

Eg. : String(describing: employeeName)

Provide a default value to avoid this warning :

Using this it will become (<Variable> ?? default value)

Eg.: employeeName ?? “Anonymous” as! String

Body:
Since beta 8.3, zillions warnings "String interpolation produces a debug description for an optional value; did you mean to make this explicit?" appeared in my code.

For example, the warning popped in the following situation up, where options could lead to nil:

let msg = "*** Error \(options["taskDescription"]): cannot load \(sUrl) \(error)"

As previously designed, it was ok for me (and the compiler) the optionals to be interpolated as 'nil'. But compiler changed its mind.

What the compiler suggests is to add a String constructor with description as follows:

let msg = "*** Error \(String(describing: options["taskDescription"])): cannot load \(sUrl) \(error)"

Obviously, the results is explicit but also very very cumbersome in my opinion. Is there a better option? Do I have to fix all those warning or better wait for the next beta?


问:
Unable to use XPath to select input element based on content
I have a Selenium Webdriver test where I want to wait for a text input field to contain a specific value before moving to the next step. I know what the value will be ("Town of Oakura") and it is set by JavaScript. I tried using the following c# code:

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElement(DpNumber, "Town of Oakura"));
</code>```

This just timed out every time. So I thought I would try XPath to wait for the field to be updated:

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER'
                                                        and text()='Town of Oakura']")));
</code>```

Which also didn't work. Using the console in Chrome I can use XPath to identify the element, defined as:

```<code><input id="DP_NUMBER" type="text" name="DP_NUMBER"
     data-bind="textInput:DP_NUMBER" class="js-bound">
</code>```

Expanding the element I can establish that the value is correct. But I can't find any permutation of XPath that locates the element based on its contents.

答:
TextToBePresentInElement checks value in the element using getText method. getText method return empty value for the element which is of type input. To wait until the value in the input text become some value. you can use the following expected conditions.

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElementValue(DpNumber, "Town of Oakura"));
</code>```

Also, the text() function will return empty for input box. So we can't use it in xpath.

Body:
I have a Selenium Webdriver test where I want to wait for a text input field to contain a specific value before moving to the next step. I know what the value will be ("Town of Oakura") and it is set by JavaScript. I tried using the following c# code:

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElement(DpNumber, "Town of Oakura"));

This just timed out every time. So I thought I would try XPath to wait for the field to be updated:

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER'
                                                        and text()='Town of Oakura']")));

Which also didn't work. Using the console in Chrome I can use XPath to identify the element, defined as:

<input id="DP_NUMBER" type="text" name="DP_NUMBER"
     data-bind="textInput:DP_NUMBER" class="js-bound">

Expanding the element I can establish that the value is correct. But I can't find any permutation of XPath that locates the element based on its contents.

Body:
TextToBePresentInElement checks value in the element using getText method. getText method return empty value for the element which is of type input. To wait until the value in the input text become some value. you can use the following expected conditions.

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElementValue(DpNumber, "Town of Oakura"));

Also, the text() function will return empty for input box. So we can't use it in xpath.


问:
New SQLContext: Spark 1.6 backward-compatibility with Spark 2.1
On IBM DSX I have the following problem.

For the Spark 1.6 kernels on DSX it was/is necessary to create new SQLContext objects in order to avoid issues with the metastore_db and HiveContext : http://stackoverflow.com/questions/38117849/you-must-build-spark-with-hive-export-spark-hive-true/38118112#38118112

The following code snippets were implemented using Spark 1.6 and both run for Spark 2.0.2, but not for Spark 2.1:

```<code>from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

df = sqlContext.createDataFrame([(1, "a"), (2, "b"), (3, "c"), (4, "d")], ("k", "v"))
df.count()
</code>```

and

```<code>from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

properties= {
    'jdbcurl': 'JDBCURL',
    'user': 'USER',
    'password': 'PASSWORD!'
}

data_df_1 = sqlContext.read.jdbc(properties['jdbcurl'], table='GOSALES.BRANCH', properties=properties)
data_df_1.head()
</code>```

I get this error:

```<code>IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"
</code>```

However, when I execute the same code a second time it works again.

答: IIRC, creating a new SQLContext was only necessary for the legacy Spark services (bluemix_ipythonspark_16) in Bluemix. DSX supports only the newer services (bluemix_jupyter_bundle), where creating a new SQLContext is more likely to create problems with Hive than to solve them. Please try without.

Body:
On IBM DSX I have the following problem.

For the Spark 1.6 kernels on DSX it was/is necessary to create new SQLContext objects in order to avoid issues with the metastore_db and HiveContext : http://stackoverflow.com/questions/38117849/you-must-build-spark-with-hive-export-spark-hive-true/38118112#38118112

The following code snippets were implemented using Spark 1.6 and both run for Spark 2.0.2, but not for Spark 2.1:

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

df = sqlContext.createDataFrame([(1, "a"), (2, "b"), (3, "c"), (4, "d")], ("k", "v"))
df.count()

and

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

properties= {
    'jdbcurl': 'JDBCURL',
    'user': 'USER',
    'password': 'PASSWORD!'
}

data_df_1 = sqlContext.read.jdbc(properties['jdbcurl'], table='GOSALES.BRANCH', properties=properties)
data_df_1.head()

I get this error:

IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"

However, when I execute the same code a second time it works again.


问:
How to implement a small popup with some images on a button click

I want a popup like this when user click on the three blue dot button. how to achieve this type of popup view in android . any library is available .?

答:
Use PopupWindow:</p>

```<code>  View popupView =LayoutInflater.from(context).inflate(R.layout.urxml,null);
//Design layout of popup view and inflate it here

popupView.findViewById(R.id.whatsapp).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //Handle onClicks here
            }});
// Other onClickListeners

    PopupWindow popupWindow = new PopupWindow(
                    popupView,
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            popupWindow.setAnimationStyle(R.style.UrAnimation);
            popupWindow.showAtLocation(threeDotsView, Gravity.CENTER, x, y); //Position of view on the screen
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
</code>```

Body:
Use PopupWindow:

  View popupView =LayoutInflater.from(context).inflate(R.layout.urxml,null);
//Design layout of popup view and inflate it here

popupView.findViewById(R.id.whatsapp).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //Handle onClicks here
            }});
// Other onClickListeners

    PopupWindow popupWindow = new PopupWindow(
                    popupView,
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            popupWindow.setAnimationStyle(R.style.UrAnimation);
            popupWindow.showAtLocation(threeDotsView, Gravity.CENTER, x, y); //Position of view on the screen
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());


问:
Arbitrary filters for conv2d (as opposed to rectangular)
I using convolutional layers on data samples that consist of 2d images. One option for the shape of the filter is 1x2, which acts on a 1x2 contiguous block of two neighbor pixels. What if I want to have a filter which also acts on 2 pixels, but the pixels are separated by another one between them? Is it possible to encode such a filter for convolutions in the neural network?</p>

答:
Arbitrary filters (with weights placed anywhere) are not available, but there exists a limited by useful version called atrous convolution that places weights on a spare grid, which can handle your specific example.

For example, in your case, you could try

W = tf.Variable(tf.random_uniform((1, 2, n_in, n_out))
tf.nn.atrous_conv2d(value, W, (1, 2), 'SAME')
```


问:
How to remove elements from an array using filter() in JavaScript?
I need to remove all the elements from an array , and all the elements that are to be removed are being passed as arguments.
I am trying to use the filter method to remove them but it is not working properly.
The code is  :

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
   var arr1 = arr.filter(function(v){
    for(var i= 0;i < args.length;i++){
        if(arr.indexOf(args[i]) !== -1)
            return false;

    }
  });
    console.log(arr1);
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);```

I am using args array to store all the arguments into array.The first argument is the array from which elements are to be removed and the following arguments are the ones that are to deleted(It is sure they are present in the array) but somehow the filter function is not working properly and also for more info see,
FreeCodeCamp challenge

答:
You need to return arr1 instead of arr.

The filter() method creates a new array instead of modifying the source array, so you need to return the newly created array from your method.

As to your filtering logic, I believe it should look something like this:

function destroyer(arr) {
  let args = Array.from(arguments);
  args.shift();

  return arr.filter(v => args.indexOf(v) === -1);
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));```
</div>
</div>
</p>

<p>Or if you're only targeting browsers that already support rest parameters:</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>function destroyer(arr, ...args) {
  return arr.filter(v => args.indexOf(v) === -1);
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));</code>```

Body:
I need to remove all the elements from an array , and all the elements that are to be removed are being passed as arguments.
I am trying to use the filter method to remove them but it is not working properly.
The code is  :

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
   var arr1 = arr.filter(function(v){
    for(var i= 0;i < args.length;i++){
        if(arr.indexOf(args[i]) !== -1)
            return false;

    }
  });
    console.log(arr1);
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

I am using args array to store all the arguments into array.The first argument is the array from which elements are to be removed and the following arguments are the ones that are to deleted(It is sure they are present in the array) but somehow the filter function is not working properly and also for more info see,
FreeCodeCamp challenge

Body:
You need to return arr1 instead of arr.

The filter() method creates a new array instead of modifying the source array, so you need to return the newly created array from your method.

As to your filtering logic, I believe it should look something like this:

function destroyer(arr) {
  let args = Array.from(arguments);
  args.shift();

  return arr.filter(v => args.indexOf(v) === -1);
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

Or if you're only targeting browsers that already support rest parameters:

function destroyer(arr, ...args) {
  return arr.filter(v => args.indexOf(v) === -1);
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));


问:
Customizing the AppCompat Actionbar
This question has sort of been asked but not really, what I'm looking to do is have a highly customized toolbar for our app, I recently implemented a drawer menu with the AppCompat Actionbar and it works great, except this is what it gives me by default:

What I'd like to have is something like this (excuse the rushed drawing):

I'm prefectly capable of doing this in a normal layout, so I'm not looking for advice on how to make the toolbar look like this, what my question is, is how do I start customizing the layout of the toolbar at all? For example, I don't see a way to position the home button (I believe that's what the hambuger menu is called in this case), it seems like a lot of this stuff is built into the appcompat actionbar and I don't see a way of getting around it, basically to summarize, I just want to have multiple rows of controls in the toolbar, and customize the default built in controls of the toolbar, including positioning. Is there a way I can just insert my own layout file into the actionbar and just have a control set to be the button that activates the drawer layouts drawers? That would be the most ideal solution to this problem for my circumstances.

答:
what my question is, is how do I start customizing the layout of the toolbar at all?

You can customize the view of your SupportActionbar like this:

Create a ToolbarView.axml view file for your Actionbar(It's just an example, you can define anything inside):

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="300dp">

  <TextView
    android:id="@+id/tvShow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Please Click Me"/>

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>
</code>```

In your activity's onCreate method, set the custom view of the SupportActionbar:

```<code>protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "main" layout resource
    SetContentView (Resource.Layout.Main);
    SupportActionBar.SetDisplayShowCustomEnabled(true);
    SupportActionBar.SetCustomView(Resource.Layout.ToolbarView);
    ...
 }
</code>```

The height of the ActionBar won't change by the content inside, you have to set the height manually in Style.xml:

```<code><resources>
  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">#5A8622</item>
    <!--Set the ActionBar Size-->
    <item name="actionBarSize">200dp</item>
  </style>
</resources>
</code>```

Title: Customizing the AppCompat Actionbar

Body:
what my question is, is how do I start customizing the layout of the toolbar at all?

You can customize the view of your SupportActionbar like this:

Create a ToolbarView.axml view file for your Actionbar(It's just an example, you can define anything inside):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="300dp">

  <TextView
    android:id="@+id/tvShow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Please Click Me"/>

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

In your activity's onCreate method, set the custom view of the SupportActionbar:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "main" layout resource
    SetContentView (Resource.Layout.Main);
    SupportActionBar.SetDisplayShowCustomEnabled(true);
    SupportActionBar.SetCustomView(Resource.Layout.ToolbarView);
    ...
 }

The height of the ActionBar won't change by the content inside, you have to set the height manually in Style.xml:

<resources>
  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">#5A8622</item>
    <!--Set the ActionBar Size-->
    <item name="actionBarSize">200dp</item>
  </style>
</resources>


问:
How to CLONE a fieldset element and append it inside a form, correctly?
Jsfiddle here.

This is a simple example to reproduce my problem. Basically, I have a form (to read in data about multiple candidates), in which I have a fieldset (which takes input of data for one candidate), and then I have a button labelled ADD CANDIDATE. When it is clicked, the above fieldset should be cloned and copied below the above fieldset, so that the data about another candidate can be entered.

For the first candidate, each data field in the form is of the form allCandidatesArray[candidateNumber][fieldName], e.g. allCandidatesArray[0][nameInput] to facilitate the reading and further analysis of data submitted when the form is submitted. So in the Click handler/listener of ADD CANDIDATE button, I also do some programming to increment the candidateNumber in allCandidatesArray[candidateNumber][fieldName] when a new candidate is added.

But the main idea is to clone the previous fieldset and append the cloned fieldset below the previous fieldset. The problem is that the new thing which is appended is Not a fieldset. It is just three input elements. No labels, no nothing! What was cloned was a fieldset containing inputs and labels.

The question is WHY? And how do I fix this?

$(document).on("click", ".addMobileButton", function() {

 //alert(".addMobileButton clicked.");//check

 var parentRow = $(this).closest(".row");

 var idOfThis = $(this).attr('id');
 //alert(idOfThis);//check
 //alert(idOfThis.length);//check
 var candidateNumber = idOfThis.slice(idOfThis.length-2, idOfThis.length-1);
 //alert("candidateNumber: " + candidateNumber);//check

 var nthMobileNumberOfThisCandidate = idOfThis.slice(-1);
 //alert("nthMobileNumberOfThiscandidate: " + nthMobileNumberOfThiscandidate);//check
 var newNthMobileOfThiscandidate = ++nthMobileNumberOfThisCandidate;
 //alert("newNthMobileNumberOfThisCandidate: " + newNthMobileOfThisCandidate);//check

 parentRow.after('

<input type="text" id="mobileInput'+candidateNumber+'" class="validate" name="allCandidatesArray['+candidateNumber+'][mobileInput][]"/>Mobile

add

');

});

$(document).ready(function() {

 /*
 *
 */
 $("a#addNewCandidateButton").on("click", function() {

  alert("#addNewCandidateButton clicked.");//check

  var previousFieldset = $(this).parent(".row").prevAll("fieldset.wrapper:first");
  //alert(previousFieldset[0].outerHTML);//check

  var fieldsetToClone = previousFieldset.clone();
  //alert(fieldsetToClone[0].outerHTML);//check

  var idOfAddMobileButton = fieldsetToClone.find(".addMobileButton").attr('id');
  //alert('idOfAddMobileButton: ' + idOfAddMobileButton);

  var candidateNumber = idOfAddMobileButton.slice(idOfAddMobileButton.length-2, idOfAddMobileButton.length-1);
  //alert("candidateNumber: " + candidateNumber);//check
  var candidateNumberIncremented = ++candidateNumber;
  //alert('candidateNumberIncremented: ' + candidateNumberIncremented);//check

  fieldsetToClone.find('input[type=text]').each(function(index) {
   var inputNameAttribute = $(this).attr('name');
   //alert('inputNameAttribute: ' + inputNameAttribute);//check

   var indexOfFirstOpeningBracket = inputNameAttribute.indexOf('[');
   //alert('indexOfFirstOpeningBracket: ' + indexOfFirstOpeningBracket);//check

   var indexOfFirstClosingBracket = inputNameAttribute.indexOf(']');
   //alert('indexOfFirstClosingBracket') + indexOfFirstClosingBracket;//check

   var inputNameAttributeArray = inputNameAttribute.split('');
   //alert('inputNameAttributeArray: ' + inputNameAttributeArray);//check

   //inputNameAttributeArray.splice(indexOfFirstOpeningBracket, indexOfFirstClosingBracket, candidateNumberIncremented);
   var lengthOfCandidate = (indexOfFirstClosingBracket - indexOfFirstOpeningBracket) -1;
   //alert('lengthOfCandidate: ' + lengthOfCandidate);//check
   inputNameAttributeArray.splice((indexOfFirstOpeningBracket+1), lengthOfCandidate, candidateNumberIncremented);
   //alert('inputNameAttributeArray after SPLICING:' + inputNameAttributeArray);//check

   inputNameAttributeModified = inputNameAttributeArray.join('');
   //alert('inputNameAttributeModified: ' + inputNameAttributeModified);//check

   $(this).attr('name', inputNameAttributeModified);

  });

  fieldsetToClone = fieldsetToClone.prepend('

');

  fieldsetToClone = fieldsetToClone.find("input[type=text]").val('');

  previousFieldset.after(fieldsetToClone);

 });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css" rel="stylesheet"/>

<form id="credentialsForm" action="" method="get">

 <fieldset class="container wrapper">
  <div class="row valign-wrapper">

   <div class="input-field col l3 offset-l1">
    <input type="text" id="nameInput0" class="validate" name="allCandidatesArray[0][nameInput]"/>
    <label class="blue-text" for="nameInput0">Name</label>
   </div>

   <div class="input-field col l3 offset-l1">
    <input type="text" id="ssnValueInput0" class="validate" name="allCandidatesArray[0][ssnValueInput]"/>
    <label class="blue-text" for="ssnValueInput0">SSN</label>
   </div>

  </div><!--.row-->

  <div class="row valign-wrapper">

   <div class="input-field col l3">
    <input type="text" id="mobileInput0" class="validate" name="allCandidatesArray[0][mobileInput][]"/>
    <label class="blue-text" for="mobileInput0">Mobile</label>
   </div>

   <div class="col l1 offset-l1 addMobileButtonWrapper">
    <i class="material-icons">add</i>
   </div>

  </div><!--.row-->

  <!--<div class="container"><div class="divider"></div></div>-->

  </fieldset><!--#wrapper-->

  <div class="row valign-wrapper">
   Add Candidate
  </div><!--.row-->

  <div class="row" id="submitFormRow">
   <div class="col l4 offset-l4">
    <button type="submit" class="btn waves-light waves-effect">Add Candidates</button>
   </div>
  </div><!--.row #s -->

</form></code>```

答:
You are overwriting cloned object in the following statements thus only inputs are appended.

```<code>fieldsetToClone = fieldsetToClone.prepend('<div class="container"><div class="divider"></div></div>');
fieldsetToClone = fieldsetToClone.find("input[type=text]").val('');
</code>```

Use

```<code>fieldsetToClone.prepend('<div class="container"><div class="divider"></div></div>');
fieldsetToClone.find("input[type=text]").val('');
</code>```

$(document).on("click", ".addMobileButton", function() {
  var parentRow = $(this).closest(".row");
  var idOfThis = $(this).attr('id');
  var candidateNumber = idOfThis.slice(idOfThis.length - 2, idOfThis.length - 1);
  var nthMobileNumberOfThisCandidate = idOfThis.slice(-1);
  var newNthMobileOfThiscandidate = ++nthMobileNumberOfThisCandidate;
  parentRow.after('

<input type="text" id="mobileInput' + candidateNumber + '" class="validate" name="allCandidatesArray[' + candidateNumber + '][mobileInput][]"/>Mobile

add

');
});

$("a#addNewCandidateButton").on("click", function() {

  var previousFieldset = $(this).parent(".row").prevAll("fieldset.wrapper:first");
  var fieldsetToClone = previousFieldset.clone();
  var idOfAddMobileButton = fieldsetToClone.find(".addMobileButton").attr('id');
  var candidateNumber = idOfAddMobileButton.slice(idOfAddMobileButton.length - 2, idOfAddMobileButton.length - 1);

  var candidateNumberIncremented = ++candidateNumber;
  fieldsetToClone.find('input[type=text]').each(function(index) {
    var inputNameAttribute = $(this).attr('name');

    var indexOfFirstOpeningBracket = inputNameAttribute.indexOf('[');

    var indexOfFirstClosingBracket = inputNameAttribute.indexOf(']');

    var inputNameAttributeArray = inputNameAttribute.split('');
    var lengthOfCandidate = (indexOfFirstClosingBracket - indexOfFirstOpeningBracket) - 1;

    inputNameAttributeArray.splice((indexOfFirstOpeningBracket + 1), lengthOfCandidate, candidateNumberIncremented);

    inputNameAttributeModified = inputNameAttributeArray.join('');
    $(this).attr('name', inputNameAttributeModified);
  });

  fieldsetToClone.prepend('

');

  fieldsetToClone.find("input[type=text]").val('');
  previousFieldset.after(fieldsetToClone);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css" rel="stylesheet" />

<form id="credentialsForm" action="" method="get">

  <fieldset class="container wrapper">
    <div class="row valign-wrapper">

      <div class="input-field col l3 offset-l1">
        <input type="text" id="nameInput0" class="validate" name="allCandidatesArray[0][nameInput]" />
        <label class="blue-text" for="nameInput0">Name</label>
      </div>

      <div class="input-field col l3 offset-l1">
        <input type="text" id="ssnValueInput0" class="validate" name="allCandidatesArray[0][ssnValueInput]" />
        <label class="blue-text" for="ssnValueInput0">SSN</label>
      </div>

    </div>
    <!--.row-->

    <div class="row valign-wrapper">

      <div class="input-field col l3">
        <input type="text" id="mobileInput0" class="validate" name="allCandidatesArray[0][mobileInput][]" />
        <label class="blue-text" for="mobileInput0">Mobile</label>
      </div>

      <div class="col l1 offset-l1 addMobileButtonWrapper">
        <i class="material-icons">add</i>
      </div>

    </div>
    <!--.row-->

    <!--<div class="container"><div class="divider"></div></div>-->

  </fieldset>
  <!--#wrapper-->

  <div class="row valign-wrapper">
    Add Candidate
  </div>
  <!--.row-->

  <div class="row" id="submitFormRow">
    <div class="col l4 offset-l4">
      <button type="submit" class="btn waves-light waves-effect">Add Candidates</button>
    </div>
  </div>
  <!--.row #s -->

</form></code>```

Body:
Jsfiddle here.

This is a simple example to reproduce my problem. Basically, I have a form (to read in data about multiple candidates), in which I have a fieldset (which takes input of data for one candidate), and then I have a button labelled ADD CANDIDATE. When it is clicked, the above fieldset should be cloned and copied below the above fieldset, so that the data about another candidate can be entered.

For the first candidate, each data field in the form is of the form allCandidatesArray[candidateNumber][fieldName], e.g. allCandidatesArray[0][nameInput] to facilitate the reading and further analysis of data submitted when the form is submitted. So in the Click handler/listener of ADD CANDIDATE button, I also do some programming to increment the candidateNumber in allCandidatesArray[candidateNumber][fieldName] when a new candidate is added.

But the main idea is to clone the previous fieldset and append the cloned fieldset below the previous fieldset. The problem is that the new thing which is appended is Not a fieldset. It is just three input elements. No labels, no nothing! What was cloned was a fieldset containing inputs and labels.

The question is WHY? And how do I fix this?

$(document).on("click", ".addMobileButton", function() {

 //alert(".addMobileButton clicked.");//check

 var parentRow = $(this).closest(".row");

 var idOfThis = $(this).attr('id');
 //alert(idOfThis);//check
 //alert(idOfThis.length);//check
 var candidateNumber = idOfThis.slice(idOfThis.length-2, idOfThis.length-1);
 //alert("candidateNumber: " + candidateNumber);//check

 var nthMobileNumberOfThisCandidate = idOfThis.slice(-1);
 //alert("nthMobileNumberOfThiscandidate: " + nthMobileNumberOfThiscandidate);//check
 var newNthMobileOfThiscandidate = ++nthMobileNumberOfThisCandidate;
 //alert("newNthMobileNumberOfThisCandidate: " + newNthMobileOfThisCandidate);//check

 parentRow.after('

<input type="text" id="mobileInput'+candidateNumber+'" class="validate" name="allCandidatesArray['+candidateNumber+'][mobileInput][]"/>Mobile

add

');

});

$(document).ready(function() {

 /*
 *
 */
 $("a#addNewCandidateButton").on("click", function() {

  alert("#addNewCandidateButton clicked.");//check

  var previousFieldset = $(this).parent(".row").prevAll("fieldset.wrapper:first");
  //alert(previousFieldset[0].outerHTML);//check

  var fieldsetToClone = previousFieldset.clone();
  //alert(fieldsetToClone[0].outerHTML);//check

  var idOfAddMobileButton = fieldsetToClone.find(".addMobileButton").attr('id');
  //alert('idOfAddMobileButton: ' + idOfAddMobileButton);

  var candidateNumber = idOfAddMobileButton.slice(idOfAddMobileButton.length-2, idOfAddMobileButton.length-1);
  //alert("candidateNumber: " + candidateNumber);//check
  var candidateNumberIncremented = ++candidateNumber;
  //alert('candidateNumberIncremented: ' + candidateNumberIncremented);//check

  fieldsetToClone.find('input[type=text]').each(function(index) {
   var inputNameAttribute = $(this).attr('name');
   //alert('inputNameAttribute: ' + inputNameAttribute);//check

   var indexOfFirstOpeningBracket = inputNameAttribute.indexOf('[');
   //alert('indexOfFirstOpeningBracket: ' + indexOfFirstOpeningBracket);//check

   var indexOfFirstClosingBracket = inputNameAttribute.indexOf(']');
   //alert('indexOfFirstClosingBracket') + indexOfFirstClosingBracket;//check

   var inputNameAttributeArray = inputNameAttribute.split('');
   //alert('inputNameAttributeArray: ' + inputNameAttributeArray);//check

   //inputNameAttributeArray.splice(indexOfFirstOpeningBracket, indexOfFirstClosingBracket, candidateNumberIncremented);
   var lengthOfCandidate = (indexOfFirstClosingBracket - indexOfFirstOpeningBracket) -1;
   //alert('lengthOfCandidate: ' + lengthOfCandidate);//check
   inputNameAttributeArray.splice((indexOfFirstOpeningBracket+1), lengthOfCandidate, candidateNumberIncremented);
   //alert('inputNameAttributeArray after SPLICING:' + inputNameAttributeArray);//check

   inputNameAttributeModified = inputNameAttributeArray.join('');
   //alert('inputNameAttributeModified: ' + inputNameAttributeModified);//check

   $(this).attr('name', inputNameAttributeModified);

  });

  fieldsetToClone = fieldsetToClone.prepend('

');

  fieldsetToClone = fieldsetToClone.find("input[type=text]").val('');

  previousFieldset.after(fieldsetToClone);

 });

});

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css" rel="stylesheet"/>

<form id="credentialsForm" action="" method="get">

 <fieldset class="container wrapper">

    <input type="text" id="nameInput0" class="validate" name="allCandidatesArray[0][nameInput]"/>
    Name

    <input type="text" id="ssnValueInput0" class="validate" name="allCandidatesArray[0][ssnValueInput]"/>
    SSN

    <input type="text" id="mobileInput0" class="validate" name="allCandidatesArray[0][mobileInput][]"/>
    Mobile

    add

  </fieldset>

   Add Candidate

    <button type="submit" class="btn waves-light waves-effect">Add Candidates</button>

</form>

Body:
You are overwriting cloned object in the following statements thus only inputs are appended.

fieldsetToClone = fieldsetToClone.prepend('<div class="container"><div class="divider"></div></div>');
fieldsetToClone = fieldsetToClone.find("input[type=text]").val('');

Use

fieldsetToClone.prepend('<div class="container"><div class="divider"></div></div>');
fieldsetToClone.find("input[type=text]").val('');

$(document).on("click", ".addMobileButton", function() {
  var parentRow = $(this).closest(".row");
  var idOfThis = $(this).attr('id');
  var candidateNumber = idOfThis.slice(idOfThis.length - 2, idOfThis.length - 1);
  var nthMobileNumberOfThisCandidate = idOfThis.slice(-1);
  var newNthMobileOfThiscandidate = ++nthMobileNumberOfThisCandidate;
  parentRow.after('<div id="rowAddedForCandidatesMobile" class="row valign-wrapper"><div class="input-field col l3"><input type="text" id="mobileInput' + candidateNumber + '" class="validate" name="allCandidatesArray[' + candidateNumber + '][mobileInput][]"/><label for="mobileInput' + candidateNumber + '">Mobile</label></div><div class="col l1 addMobileButtonWrapper"><a id="addMobileButton' + candidateNumber + '' + newNthMobileOfThisCandidate + '" class="btn-floating btn waves-light waves-effect blue white-text addMobileButton"><i class="material-icons">add</i></a></div></div>');
});

$("a#addNewCandidateButton").on("click", function() {

  var previousFieldset = $(this).parent(".row").prevAll("fieldset.wrapper:first");
  var fieldsetToClone = previousFieldset.clone();
  var idOfAddMobileButton = fieldsetToClone.find(".addMobileButton").attr('id');
  var candidateNumber = idOfAddMobileButton.slice(idOfAddMobileButton.length - 2, idOfAddMobileButton.length - 1);

  var candidateNumberIncremented = ++candidateNumber;
  fieldsetToClone.find('input[type=text]').each(function(index) {
    var inputNameAttribute = $(this).attr('name');

    var indexOfFirstOpeningBracket = inputNameAttribute.indexOf('[');

    var indexOfFirstClosingBracket = inputNameAttribute.indexOf(']');

    var inputNameAttributeArray = inputNameAttribute.split('');
    var lengthOfCandidate = (indexOfFirstClosingBracket - indexOfFirstOpeningBracket) - 1;

    inputNameAttributeArray.splice((indexOfFirstOpeningBracket + 1), lengthOfCandidate, candidateNumberIncremented);

    inputNameAttributeModified = inputNameAttributeArray.join('');
    $(this).attr('name', inputNameAttributeModified);
  });

  fieldsetToClone.prepend('<div class="container"><div class="divider"></div></div>');

  fieldsetToClone.find("input[type=text]").val('');
  previousFieldset.after(fieldsetToClone);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css" rel="stylesheet" />

<form id="credentialsForm" action="" method="get">

  <fieldset class="container wrapper">
    <div class="row valign-wrapper">

      <div class="input-field col l3 offset-l1">
        <input type="text" id="nameInput0" class="validate" name="allCandidatesArray[0][nameInput]" />
        <label class="blue-text" for="nameInput0">Name</label>
      </div>

      <div class="input-field col l3 offset-l1">
        <input type="text" id="ssnValueInput0" class="validate" name="allCandidatesArray[0][ssnValueInput]" />
        <label class="blue-text" for="ssnValueInput0">SSN</label>
      </div>

    </div>
    <!--.row-->

    <div class="row valign-wrapper">

      <div class="input-field col l3">
        <input type="text" id="mobileInput0" class="validate" name="allCandidatesArray[0][mobileInput][]" />
        <label class="blue-text" for="mobileInput0">Mobile</label>
      </div>

      <div class="col l1 offset-l1 addMobileButtonWrapper">
        <a id="addMobileButton00" class="btn-floating btn waves-light waves-effect blue white-text addMobileButton"><i class="material-icons">add</i></a>
      </div>

    </div>
    <!--.row-->

    <!--<div class="container"><div class="divider"></div></div>-->

  </fieldset>
  <!--#wrapper-->

  <div class="row valign-wrapper">
    <a id="addNewCandidateButton" class="btn-flat waves-effect waves-light blue white-text col l2">Add Candidate</a>
  </div>
  <!--.row-->

  <div class="row" id="submitFormRow">
    <div class="col l4 offset-l4">
      <button type="submit" class="btn waves-light waves-effect">Add Candidates</button>
    </div>
  </div>
  <!--.row #s -->

</form>


问:
Excel help - if keyword exists in a column for each row
I need help to check if a user has "Basic" in another column (Doesn't need to be same row) and return true in column D.

It seems I need to do some concatenation with index match but I do not know how to go about it. Can anyone help?

```
Col_A    Col_B    Co_C         Col_D
UserA    Data1    Basic        True
UserB    Data2    Premium      False
UserC    Data1    Basic        True
UserA     Data2   Classic      True
```

答:
Enter following formula in Cell D2

```<code>=IF(COUNTIFS($A$2:$A$5,A2,$C$2:$C$5,"Basic")>0,TRUE,FALSE)
</code>```

or

```<code>=IF(SUMPRODUCT(($A$2:$A$5=A2)*($C$2:$C$5="Basic")),TRUE,FALSE)
</code>```

Drag/Copy down as required. See image for reference.

Body:
I need help to check if a user has "Basic" in another column (Doesn't need to be same row) and return true in column D.

It seems I need to do some concatenation with index match but I do not know how to go about it. Can anyone help?

Col_A    Col_B    Co_C         Col_D
UserA    Data1    Basic        True
UserB    Data2    Premium      False
UserC    Data1    Basic        True
UserA     Data2   Classic      True

Body:
Enter following formula in Cell D2

=IF(COUNTIFS($A$2:$A$5,A2,$C$2:$C$5,"Basic")>0,TRUE,FALSE)

or

=IF(SUMPRODUCT(($A$2:$A$5=A2)*($C$2:$C$5="Basic")),TRUE,FALSE)

Drag/Copy down as required. See image for reference.


答:
you need to change your filter function, check if each value in arr is in args, if yes return false for it otherwise return true.

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
   var arr1 = arr.filter(function(v){
      return (args.indexOf(v) !== -1) ? false : true;
  });
    console.log(arr1);
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);```

Title: How to remove elements from an array using filter() in JavaScript?


问:
Reduce boot time in ionic-2 app
I am new to ionic-2 project.I just want to know how to reduce boot time of  app.Because after 3 sec of splash screen , it shows white screen and takes 9 sec to start.</p>

答:
Even I had the same problem. After revering ionic-team forum, I understand that ionic-team has not yet come up with any solution to this.

I made the following code which minimizes the app instead of closing it, so that when next time the app is opened it opens instantly.

Put the below code in app.component.ts file

```<code>this.platform.registerBackButtonAction(() => {
        if(this.menuCtrl.isOpen()){
           this.menuCtrl.close();
        }
        else if(this.nav.canGoBack()){
          this.nav.pop();
        }else{
          this.appMinimize.minimize();
        }
      });
</code>```

You may need to install @ionic-native/app-minimize

links to refer:

https://ionicframework.com/docs/api/platform/Platform/#registerBackButtonAction
https://ionicframework.com/docs/native/app-minimize/

Title: Reduce boot time in ionic-2 app

Body:
Even I had the same problem. After revering ionic-team forum, I understand that ionic-team has not yet come up with any solution to this.

I made the following code which minimizes the app instead of closing it, so that when next time the app is opened it opens instantly.

Put the below code in app.component.ts file

this.platform.registerBackButtonAction(() => {
        if(this.menuCtrl.isOpen()){
           this.menuCtrl.close();
        }
        else if(this.nav.canGoBack()){
          this.nav.pop();
        }else{
          this.appMinimize.minimize();
        }
      });

You may need to install @ionic-native/app-minimize

links to refer:

https://ionicframework.com/docs/api/platform/Platform/#registerBackButtonAction
https://ionicframework.com/docs/native/app-minimize/


问:
Can the compiler optimize out the empty base if the class contains a member of base class type as first element, followed by other members?
Consider:

```<code>struct empty {};
struct child : empty {
    empty a[sizeof(int) / sizeof(empty)];
    int b;
};
// Assume sizeof(int) >= sizeof(empty)
</code>```

Does the standard mandate that sizeof(child) is more than 2 * sizeof(int)?

The way I see it, nothing prohibits the baseclass-subobject from sharing its address with member b.

If not, are there any common ABIs exploiting that at all?

答:
Is it possible from the specification? Yes. [class.mem]/24 tells us about the relationship between the address of a standard layout class and its first base class subobject. But the standard makes no statement about this relationship for non-standard layout types. And since your type is not standard layout, the standard says nothing about that location.

There are generally two ABI forms for base class assignment: put them before the members or put them after the members (for non-standard layout types). ABIs that assign base classes after the members would be free to assign empty base classes the last valid address with an appropriate alignment in the class's region of storage. If that happens to land in such a way as to avoid violating [intro.object]/8 (unique identity of subobjects), then it can perform that assignment.

The two most common ABIs, Windows and Itanium, both assign base classes before members. While such ABIs could assign base classes more arbitrarily, they don't bother doing that. This would only ever come up in template code anyway, since empty classes are empty. They all behave the same, so there's no reason to deliberately make them both a base class and a member.

So why bother having complex ABI rules for a case that is so rare?

Body:
Consider:

struct empty {};
struct child : empty {
    empty a[sizeof(int) / sizeof(empty)];
    int b;
};
// Assume sizeof(int) >= sizeof(empty)

Does the standard mandate that sizeof(child) is more than 2 * sizeof(int)?

The way I see it, nothing prohibits the baseclass-subobject from sharing its address with member b.

If not, are there any common ABIs exploiting that at all?


问:
JMeter -> http request -> POST parameters don't work in lowercase and changes POST to GET in uppercase
i have a strange issue.
I am testing different group rights of members on a website with JMeter and i have solved the tasks which appeared, for know.

A "http request" which has to "POST" some parameters (4 names, 3 values) doesn't work and has strange behaviors.

I inspect the network dialog of the browser (firefox dev or IE) when i request the new page with the selected parameters and get the following information:
i have 4 parameters, the first has no value and the other 3 have always the same values.
The parameter names are in uppercase.
The Status is 302 Moved Temporarily and not 200.
And i get the expected site.

When i insert these parameters in JMeter (or by value of regex extractor) and set the "http request" to "POST", "Follow Redirects", "Use Keep Alive",
JMeter is send to the url where it comes from and the "http request" shows me a "GET" request in the "Result Tree".
The Status is 200.

When i write the parameter names in lowercase, JMeter is also send back to the previous url but the "Result Tree" has "POST" in the request with the lowercase parameters.
The Status is 200.

When i disable "Follow Redirects", the uppercase parameters get no Response (no html code), but now they were "POST" in the "Result Tree" and have the Status 302 Moved Temporarily.

When i disable "Follow Redirects", the lowercase parameters are still redirecting me to the previous site, the Status is 200.

I don't know why this happens and how i have to handle with JMeter to get to the expected site.

答: If you are uncertain about how to simulate this or that action - just record it using JMeter's built-in HTTP(S) Test Script Recorder or JMeter Chrome Extension, both are smart enough to automatically detect the required redirect configuration and will generate the relevant HTTP Request samplers.</p>


问:
How to force the MATLAB output in the simple terms?
From the textbook, I got the answer yp_tb = exp(x)*(tan(x)-x)/2;

From Matlab, I got the answer:

```<code>yp_mt = (x*exp(x)*tan(x)^2)/2 - (exp(x)*(2*x - sin(2*x)))/(4*cos(x)^2);
</code>```

I made the following script to check whether they are same or not.

```<code>clear all;
syms x
yp_tb = exp(x)*(tan(x)-x)/2;
yp_mt = (x*exp(x)*tan(x)^2)/2 - (exp(x)*(2*x - sin(2*x)))/(4*cos(x)^2);
%  yp_tb = textbook output; yp_mt = matlab output
Equal = isAlways(yp_tb == yp_mt) % Equal is 1, it means they are equal
</code>```

How to force the MATLAB output to be textbook output?

答:
Adding answer since it worked for the OP.

Use the following code to simplify your equation to the required step:

```<code>syms x
yp_tb = exp(x)*(tan(x)-x)/2;
yp_mt = (x*exp(x)*tan(x)^2)/2 - (exp(x)*(2*x - sin(2*x)))/(4*cos(x)^2);
simplify(yp_mt, 3)
</code>```

Also look at the documentation for simplify

Body:
From the textbook, I got the answer yp_tb = exp(x)*(tan(x)-x)/2;

From Matlab, I got the answer:

yp_mt = (x*exp(x)*tan(x)^2)/2 - (exp(x)*(2*x - sin(2*x)))/(4*cos(x)^2);

I made the following script to check whether they are same or not.

clear all;
syms x
yp_tb = exp(x)*(tan(x)-x)/2;
yp_mt = (x*exp(x)*tan(x)^2)/2 - (exp(x)*(2*x - sin(2*x)))/(4*cos(x)^2);
%  yp_tb = textbook output; yp_mt = matlab output
Equal = isAlways(yp_tb == yp_mt) % Equal is 1, it means they are equal

How to force the MATLAB output to be textbook output?

Body:
Adding answer since it worked for the OP.

Use the following code to simplify your equation to the required step:

syms x
yp_tb = exp(x)*(tan(x)-x)/2;
yp_mt = (x*exp(x)*tan(x)^2)/2 - (exp(x)*(2*x - sin(2*x)))/(4*cos(x)^2);
simplify(yp_mt, 3)

Also look at the documentation for simplify


问:
Hooking up UIButton to closure? (Swift, target-action)
I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, action: Selector, forControlEvents: UIControlEvents) function. This uses the Selector construct presumably for backwards compatibility with Obj-C libraries. I think I understand the reason for @selector in Obj-C – being able to refer to a method since in Obj-C methods are not first-class values.

In Swift though, functions are first-class values. Is there a way to connect a UIButton to a closure, something similar to this:

```<code>// -- Some code here that sets up an object X

let buttonForObjectX = UIButton()

// -- configure properties here of the button in regards to object
// -- for example title

buttonForObjectX.addAction(action: {() in

  // this button is bound to object X, so do stuff relevant to X

}, forControlEvents: UIControlEvents.TouchUpOutside)
</code>```

To my knowledge, the above is currently not possible. Considering that Swift looks like it's aiming to be a quite functional, why is this? The two options could clearly co-exist for backwards compatibility. Why doesn't this work more like onClick() in JS? It seems that the only way to hook up a UIButton to a target-action pair is to use something that exists solely for backwards compatibility reasons (Selector).

My use case is to create UIButtons in a loop for different objects, and then hook each up to a closure. (Setting a tag / looking up in a dictionary / subclassing UIButton are dirty semi-solutions, but I'm interested in how to do this functionally, ie this closure approach)

答:
You can replace target-action with a closure by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained.

This is a similar solution to the one in n13's answer. But I find it simpler and more elegant. The closure is invoked more directly and the wrapper is automatically retained (added as an associated object).

Swift 3 and 4

```<code>class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}
</code>```

Usage:

```<code>button.addAction {
    print("Hello")
}
</code>```

It automatically hooks to the .primaryActionTriggered event which equals to .touchUpInside for UIButton.

Body:
I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, action: Selector, forControlEvents: UIControlEvents) function. This uses the Selector construct presumably for backwards compatibility with Obj-C libraries. I think I understand the reason for @selector in Obj-C – being able to refer to a method since in Obj-C methods are not first-class values.

In Swift though, functions are first-class values. Is there a way to connect a UIButton to a closure, something similar to this:

// -- Some code here that sets up an object X

let buttonForObjectX = UIButton()

// -- configure properties here of the button in regards to object
// -- for example title

buttonForObjectX.addAction(action: {() in

  // this button is bound to object X, so do stuff relevant to X

}, forControlEvents: UIControlEvents.TouchUpOutside)

To my knowledge, the above is currently not possible. Considering that Swift looks like it's aiming to be a quite functional, why is this? The two options could clearly co-exist for backwards compatibility. Why doesn't this work more like onClick() in JS? It seems that the only way to hook up a UIButton to a target-action pair is to use something that exists solely for backwards compatibility reasons (Selector).

My use case is to create UIButtons in a loop for different objects, and then hook each up to a closure. (Setting a tag / looking up in a dictionary / subclassing UIButton are dirty semi-solutions, but I'm interested in how to do this functionally, ie this closure approach)

Body:
You can replace target-action with a closure by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained.

This is a similar solution to the one in n13's answer. But I find it simpler and more elegant. The closure is invoked more directly and the wrapper is automatically retained (added as an associated object).

Swift 3 and 4

class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}

Usage:

button.addAction {
    print("Hello")
}

It automatically hooks to the .primaryActionTriggered event which equals to .touchUpInside for UIButton.

ContentLicense: CC BY-SA 4.0


问:
Building apps using .NET Core 2.0.0 Preview 1 on VSTS
I'm trying to build an app using .NET Core 2.0.0 Preview 1 on VSTS, but I'm getting this error while trying to restore the nuget packages:

```
Unable to resolve 'Microsoft.NETCore.App (>= 2.0.0)' for '.NETCoreApp,Version=v2.0'.
```

Any workaround for this?

答:
It seems you were use Hosted VS2017 agent to queue your build. While Hosted VS2017 agent only has .NET core 1.0.0 installed (you can find installed software here).

The work around to build apps using .NET core 2.0.0, you should use a private agent where the .NET core 2.0.0 and Visual Studio 2017 Preview 15.3 is installed.

Body:
I'm trying to build an app using .NET Core 2.0.0 Preview 1 on VSTS, but I'm getting this error while trying to restore the nuget packages:

Unable to resolve 'Microsoft.NETCore.App (>= 2.0.0)' for '.NETCoreApp,Version=v2.0'.

Any workaround for this?


问:
Create a table in mysql
Here is the mysql code. I can't find the error here. when I execute this bunch of code it shows syntax error.</p>

```<code> CREATE TABLE Movie(
-> title            varchar(100),
-> year             int,
-> length           int,
-> inColor          BIT(1),
-> studioName       varchar(50),
-> producerC#       int,
-> PRIMARY KEY      ('title'));
</code>```

答:
Try this. You have quotes in the primary key!</p>

```<code>CREATE TABLE `movie` (
  `title` VARCHAR(100),
  `year` INT(11),
  `length` INT(11),
  `inColor` BIT(1),
  `studioName` VARCHAR(50),
  `producerC#` INT(11),
  PRIMARY KEY (`title`)
)
</code>```

Title: Create a table in mysql

Body:
Here is the mysql code. I can't find the error here. when I execute this bunch of code it shows syntax error.

 CREATE TABLE Movie(
-> title            varchar(100),
-> year             int,
-> length           int,
-> inColor          BIT(1),
-> studioName       varchar(50),
-> producerC#       int,
-> PRIMARY KEY      ('title'));

Body:
Try this. You have quotes in the primary key!

CREATE TABLE `movie` (
  `title` VARCHAR(100),
  `year` INT(11),
  `length` INT(11),
  `inColor` BIT(1),
  `studioName` VARCHAR(50),
  `producerC#` INT(11),
  PRIMARY KEY (`title`)
)


问:
How to place gradient effect above the image in android?
Here i have attached the screenshot of my requirement.Background color can be changed. Can anyone give some idea to achieve this.

Thanks in advance.

答:
```<code>android:background="@drawable/gradient"
</code>```

<p>Note: Please change color code as per your requirement </p>

<p>****gradient.xml**** </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="14dp"
/>
<gradient
android:angle="45"
android:centerX="35%"
android:centerColor="@color/white"
android:startColor="#6d0d18"
android:endColor="#d50225"
android:type="linear"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="42dp"
/>
<stroke
android:width="3dp"
android:color="#878787"
/>
</shape>
[Output:][1]

  [1]: [https://i.stack.imgur.com/IjSez.png][1]
</code>```

Body:
android:background="@drawable/gradient"

Note: Please change color code as per your requirement

****gradient.xml****

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="14dp"
/>
<gradient
android:angle="45"
android:centerX="35%"
android:centerColor="@color/white"
android:startColor="#6d0d18"
android:endColor="#d50225"
android:type="linear"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="42dp"
/>
<stroke
android:width="3dp"
android:color="#878787"
/>
</shape>
[Output:][1]

  [1]: [https://i.stack.imgur.com/IjSez.png][1]


问:
Is it possible to decode QRCode image to value
I'm looking for code which help me to convert QRCode from image. there is very easy way with AVFoundation to scan QR Code with help of camera. But if I want to get encoded qr string from UIImage is there any way to do so?

答:
Just posting for people who have tried above answers but that doesn't worked for them. This worked for me.</p>

```<code>CIContext *context = [CIContext contextWithOptions:nil];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
CIImage *imageQRCode = [CIImage imageWithCGImage:<YourImageToBeRead>.CGImage];
NSArray *features = [detector featuresInImage:imageQRCode];
        CIQRCodeFeature *feature = [features firstObject];

NSString *result = feature.messageString;
</code>```

Body:
Just posting for people who have tried above answers but that doesn't worked for them. This worked for me.

CIContext *context = [CIContext contextWithOptions:nil];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
CIImage *imageQRCode = [CIImage imageWithCGImage:<YourImageToBeRead>.CGImage];
NSArray *features = [detector featuresInImage:imageQRCode];
        CIQRCodeFeature *feature = [features firstObject];

NSString *result = feature.messageString;


问:
Getting NoClassDefFoundError in AndroidStudio
I am doing an app in YouTube VideoPlayer. I am able to run it suceesfully . But when I integrate this in another android application, getting below error. Iam able to run it in marshmallow, but When I tried to run in Lollipop getting below below exception.

```<code>  07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err: java.lang.NoClassDefFoundError: adamas.selfiereporter.gallery.YouTubePlayerActivity
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.approvedfiles.AllApprovedFilesFragment.callOnlineMediaShowingActivity(AllApprovedFilesFragment.java:144)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.approvedfiles.AllApprovedFilesFragment.validateOnItemClickResponse(AllApprovedFilesFragment.java:106)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.approvedfiles.AllApprovedFilesFragment.onReceiveNotification(AllApprovedFilesFragment.java:91)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.common.FragmentBase$1.onReceive(FragmentBase.java:29)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.os.Looper.loop(Looper.java:135)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
    07-03 15:46:34.192 19813-19813/adamas.selfiereporter W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    07-03 15:46:34.193 19813-19813/adamas.selfiereporter W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    07-03 15:46:34.193 19813-19813/adamas.selfiereporter W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    07-03 15:46:34.193 19813-19813/adamas.selfiereporter W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

Below  is my Code:

Error showing at:-

Intent intent = new Intent(getContext(), YouTubePlayerActivity.class);

```<code> private class MyFragment extends fragment
    {

---------
--------
     private void callOnlineMediaShowingActivity(String filePlayUrl) {
            try {
                Intent intent = new Intent(getContext(), YouTubePlayerActivity.class);
                intent.putExtra(Constants.BUNDLE_MEDIA_URL, filePlayUrl);
                startActivity(intent);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
</code>```

But I am not getting error if I use other class in place of YouTubePlayerActivity.class.

Please some one give me the solution

答:
This problem is caused when there is a dependent file missing during the Runtime. Try these steps for the fix:

 Go to Build option in menu.Select Clean Build

Again Click on Build from Menu  and select Build APK from the menu.

Now take the apk file and run it.Your problem will be fixed.

Body:
I am doing an app in YouTube VideoPlayer. I am able to run it suceesfully . But when I integrate this in another android application, getting below error. Iam able to run it in marshmallow, but When I tried to run in Lollipop getting below below exception.

  07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err: java.lang.NoClassDefFoundError: adamas.selfiereporter.gallery.YouTubePlayerActivity
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.approvedfiles.AllApprovedFilesFragment.callOnlineMediaShowingActivity(AllApprovedFilesFragment.java:144)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.approvedfiles.AllApprovedFilesFragment.validateOnItemClickResponse(AllApprovedFilesFragment.java:106)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.approvedfiles.AllApprovedFilesFragment.onReceiveNotification(AllApprovedFilesFragment.java:91)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at adamas.selfiereporter.common.FragmentBase$1.onReceive(FragmentBase.java:29)
    07-03 15:46:34.188 19813-19813/adamas.selfiereporter W/System.err:     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.os.Looper.loop(Looper.java:135)
    07-03 15:46:34.191 19813-19813/adamas.selfiereporter W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
    07-03 15:46:34.192 19813-19813/adamas.selfiereporter W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    07-03 15:46:34.193 19813-19813/adamas.selfiereporter W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    07-03 15:46:34.193 19813-19813/adamas.selfiereporter W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    07-03 15:46:34.193 19813-19813/adamas.selfiereporter W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Below  is my Code:

Error showing at:-

Intent intent = new Intent(getContext(), YouTubePlayerActivity.class);

 private class MyFragment extends fragment
    {

---------
--------
     private void callOnlineMediaShowingActivity(String filePlayUrl) {
            try {
                Intent intent = new Intent(getContext(), YouTubePlayerActivity.class);
                intent.putExtra(Constants.BUNDLE_MEDIA_URL, filePlayUrl);
                startActivity(intent);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

But I am not getting error if I use other class in place of YouTubePlayerActivity.class.

Please some one give me the solution


问:
Dapper. Paging
I am trying Dapper ORM and I am querying a a Posts table.

But I would like to get paged results ...

1 - How can I do this? Isn't there a helper for this?

2 - Can Dapper Query return an IQueryable?

Thank You,
Miguel

答:
I created a sample project to demo the Dapper custom paging, support sorting, criteria and filter:

https://github.com/jinweijie/Dapper.PagingSample

Basically, the method looks like this:

```<code> Tuple<IEnumerable<Log>, int> Find(LogSearchCriteria criteria
        , int pageIndex
        , int pageSize
        , string[] asc
        , string[] desc);
</code>```

The first return value is the item list. The second return value is the total count.

Hope it helps.

Thanks.

Title: Dapper. Paging

Body:
I created a sample project to demo the Dapper custom paging, support sorting, criteria and filter:

https://github.com/jinweijie/Dapper.PagingSample

Basically, the method looks like this:

 Tuple<IEnumerable<Log>, int> Find(LogSearchCriteria criteria
        , int pageIndex
        , int pageSize
        , string[] asc
        , string[] desc);

The first return value is the item list. The second return value is the total count.

Hope it helps.

Thanks.


问:
How do I merge multiple excel files to a single excel file
So I was trying to make an excel sheet aggregator. In my line of work we get people who send us a bunch of individual excel files that are all related each with only 1 sheet used.

I was following to some degree this previous post's ideas. But upon doing so, some of the excel sheets I copied were coming up blank. Only certain ones. I have no idea why some are blank and others are fine.

Here is the code I use to open and copy the excel files

```<code>         OpenFileDialog browse = new OpenFileDialog();
            browse.Multiselect = true;
            DialogResult result = browse.ShowDialog();

            if (result == DialogResult.OK)

                try //try to open it. If its a proper excel file
                {
                    excel = new Excel.Application();
                    excel.Workbooks.Add("");
                    finalized = excel.Workbooks[1];
                    excel.SheetsInNewWorkbook = 1;
                    for(int i=0; i< browse.FileNames.Length; i++)
                    {
                        excel.Workbooks.Add(browse.FileNames[i]);
                    }
                    //skip the first workbook as it is the finalized one
                    //also note everything in excel starts at 1 and not 0
                    for(int i=2; i<excel.Workbooks.Count; i++)
                    {
                        int count = excel.Workbooks[i].Worksheets.Count;
                        excel.Workbooks[i].Activate();
                        for (int j = 1; j < count; j++)
                        {

                            Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
                            Excel._Worksheet sheet = (Excel._Worksheet)finalized.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                            //Excel._Worksheet sheet = finalized.Sheets[1];
                            pastee.Copy(Before: sheet);

                        }//end of for j
                    }//end of for i
                }//end of try
</code>```

Here is the code I use to save the excel file

```<code>            SaveFileDialog browse = new SaveFileDialog();
            browse.Title = "Save as Excel";
            browse.Filter = "Excel workbook | *.xlsx";
            DialogResult result = browse.ShowDialog();

            finalized.SaveAs(browse.FileName, Excel.XlFileFormat.xlWorkbookDefault);

            MessageBox.Show("Success", "Message");
            //unlock the file
            Global.releaseComObjects(finalized, excel);
</code>```

答:
The simplest way to merge worksheets into one is through a third part component called Spire.Xls. It’s a standalone .NET component. </p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Xls;
using System.Data;

namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
    {

        Workbook workbook = new Workbook();
        //load the first workbook
        workbook.LoadFromFile(@"merge1.xlsx");
        //load the second workbook
        Workbook workbook2 = new Workbook();
        workbook2.LoadFromFile(@"merge2.xlsx");

        //import the second workbook's worksheet into the first workbook using a datatable
        Worksheet sheet2 = workbook2.Worksheets[0];
        DataTable dataTable = sheet2.ExportDataTable();
        Worksheet sheet1 = workbook.Worksheets[0];
        sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);

        //save the workbook
        workbook.SaveToFile("result.xlsx");
    }
    }
}
</code>```

Body:
So I was trying to make an excel sheet aggregator. In my line of work we get people who send us a bunch of individual excel files that are all related each with only 1 sheet used.

I was following to some degree this previous post's ideas. But upon doing so, some of the excel sheets I copied were coming up blank. Only certain ones. I have no idea why some are blank and others are fine.

Here is the code I use to open and copy the excel files

         OpenFileDialog browse = new OpenFileDialog();
            browse.Multiselect = true;
            DialogResult result = browse.ShowDialog();

            if (result == DialogResult.OK)

                try //try to open it. If its a proper excel file
                {
                    excel = new Excel.Application();
                    excel.Workbooks.Add("");
                    finalized = excel.Workbooks[1];
                    excel.SheetsInNewWorkbook = 1;
                    for(int i=0; i< browse.FileNames.Length; i++)
                    {
                        excel.Workbooks.Add(browse.FileNames[i]);
                    }
                    //skip the first workbook as it is the finalized one
                    //also note everything in excel starts at 1 and not 0
                    for(int i=2; i<excel.Workbooks.Count; i++)
                    {
                        int count = excel.Workbooks[i].Worksheets.Count;
                        excel.Workbooks[i].Activate();
                        for (int j = 1; j < count; j++)
                        {

                            Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
                            Excel._Worksheet sheet = (Excel._Worksheet)finalized.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                            //Excel._Worksheet sheet = finalized.Sheets[1];
                            pastee.Copy(Before: sheet);

                        }//end of for j
                    }//end of for i
                }//end of try

Here is the code I use to save the excel file

            SaveFileDialog browse = new SaveFileDialog();
            browse.Title = "Save as Excel";
            browse.Filter = "Excel workbook | *.xlsx";
            DialogResult result = browse.ShowDialog();

            finalized.SaveAs(browse.FileName, Excel.XlFileFormat.xlWorkbookDefault);

            MessageBox.Show("Success", "Message");
            //unlock the file
            Global.releaseComObjects(finalized, excel);

Body:
The simplest way to merge worksheets into one is through a third part component called Spire.Xls. It’s a standalone .NET component.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Xls;
using System.Data;

namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
    {

        Workbook workbook = new Workbook();
        //load the first workbook
        workbook.LoadFromFile(@"merge1.xlsx");
        //load the second workbook
        Workbook workbook2 = new Workbook();
        workbook2.LoadFromFile(@"merge2.xlsx");

        //import the second workbook's worksheet into the first workbook using a datatable
        Worksheet sheet2 = workbook2.Worksheets[0];
        DataTable dataTable = sheet2.ExportDataTable();
        Worksheet sheet1 = workbook.Worksheets[0];
        sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);

        //save the workbook
        workbook.SaveToFile("result.xlsx");
    }
    }
}


问:
Difference between now and birthdate in years, months, days, mintues
```<code>import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)
</code>```

Now i want to convert precisely the timedelta object in years, months, days and seconds..
I know i can do like difference.days // 365 to get years and so on..
Is there any other way or methods to convert this timedelta objects in
Year, months, days and minutes precisely and easily?

答:
Adding with the question comment timedeltagives you days and seconds. So if you want to calculate the year than you should perform some simple arithmetic calculation. Here Is simple way to calculate the year. some code adding your given code.

```<code>import datetime
import math
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
year = differnce.days//(365.25)
month = (differnce.days-year*365.25)//(365.25/12)
day = ((differnce.days-year*365.25) - month*(365.25/12))
print('Years=',int(year),' Months=',int(month), ' Days=',int(math.ceil(day)))
</code>```

here the 365.25 is used for almost correctly for leap year calculation. For more details check here and here.

Body:
import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)

Now i want to convert precisely the timedelta object in years, months, days and seconds..
I know i can do like difference.days // 365 to get years and so on..
Is there any other way or methods to convert this timedelta objects in
Year, months, days and minutes precisely and easily?

Body:
Adding with the question comment timedeltagives you days and seconds. So if you want to calculate the year than you should perform some simple arithmetic calculation. Here Is simple way to calculate the year. some code adding your given code.

import datetime
import math
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
year = differnce.days//(365.25)
month = (differnce.days-year*365.25)//(365.25/12)
day = ((differnce.days-year*365.25) - month*(365.25/12))
print('Years=',int(year),' Months=',int(month), ' Days=',int(math.ceil(day)))

here the 365.25 is used for almost correctly for leap year calculation. For more details check here and here.


问:
Changing legend location seaborn factorplot
```<code>g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
</code>```

In seaborn, is there a way to plot the legend in the first sub-plot instead of second? This example is from here: https://seaborn.pydata.org/generated/seaborn.factorplot.html?highlight=factor#seaborn.factorplot

答:
The following should work.

```<code>g = sns.factorplot(x="time", y="pulse", hue="kind",
              col="diet", data=exercise, legend=False)
g.axes[0][0].legend()
</code>```

PS:

How to put the legend on first subplot of seaborn.FacetGrid?

Body:
g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)

In seaborn, is there a way to plot the legend in the first sub-plot instead of second? This example is from here: https://seaborn.pydata.org/generated/seaborn.factorplot.html?highlight=factor#seaborn.factorplot

Body:
The following should work.

g = sns.factorplot(x="time", y="pulse", hue="kind",
              col="diet", data=exercise, legend=False)
g.axes[0][0].legend()

PS:

How to put the legend on first subplot of seaborn.FacetGrid?


问:
Does it safe to save important keys on gradle?
I have some important keys in my application and I want to know where its the best place to put them. I also have enabled my proguard but when I decompile the app the keys steel visible, I was thinking put them on gradle.</p>

答:
Create a folder jni(inside main) and create two files.

hide_key.c.

CMakeLists.txt

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.4.1)

add_library(hide_key SHARED
            hide_key.c)

# Include libraries needed for hide_key lib
target_link_libraries(hide_key
                      android
                      log)
</code>```

Copy above and paste in CMakeLists.txt.

```<code>#include <string.h>
#include <jni.h>

JNIEXPORT jstring JNICALL
Java_/*replace with package*/_stringFromJNI(JNIEnv *env,
                                                                              jobject instance) {
        return (*env)->NewStringUTF(env, "key here");
}
</code>```

This in hide_key.c.

Then in build.gradle

```<code>android{
externalNativeBuild {
        cmake {
            path "src/main/jni/CMakeLists.txt"
        }
    }
}
</code>```

Then in your code do this to get the key.

```<code>static {
        System.loadLibrary("hide_key");
    }

    public native String stringFromJNI();
</code>```

Body:
Create a folder jni(inside main) and create two files.

hide_key.c.

CMakeLists.txt

CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)

add_library(hide_key SHARED
            hide_key.c)

# Include libraries needed for hide_key lib
target_link_libraries(hide_key
                      android
                      log)

Copy above and paste in CMakeLists.txt.

#include <string.h>
#include <jni.h>

JNIEXPORT jstring JNICALL
Java_/*replace with package*/_stringFromJNI(JNIEnv *env,
                                                                              jobject instance) {
        return (*env)->NewStringUTF(env, "key here");
}

This in hide_key.c.

Then in build.gradle

android{
externalNativeBuild {
        cmake {
            path "src/main/jni/CMakeLists.txt"
        }
    }
}

Then in your code do this to get the key.

static {
        System.loadLibrary("hide_key");
    }

    public native String stringFromJNI();