问:
Can you install drivers in a VM which will be used when the WIM is captured?
I am using Hyper-v and have configured my VM (installed company specific software etc) and I am now ready to create a WIM from it.

What I noticed after creating the WIM file and deploying it was that the drivers were not available for the hardware I was deploying the WIM on. For example the windows resolution was wrong and when I check device manager, the intel graphics driver was missing.

So, is it possible to install drivers for the hardware I will be deploying to on the VM and then capture the image? That way I do not have to do a windows update to get the drivers (they are already on the VM and in my WIM).

答:
From your target system you can do the powershell command

```<code>Export-WindowsDriver -Online -Destination d:\drivers
</code>```

This will export all drivers from that machine to the d:\drivers folder. Once you have that folder mount your image some place and you can do the command

```<code>Add-WindowsDriver –Path "c:\offline" –Driver "c:\someHardware\drivers" –Recurse
</code>```

Where the image is mounted to c:\offline and the d:\drivers from the source machine was coped to c:\someHardware\drivers

NOTE: if you are using the Microsoft Deployment Toolkit to capture the image you can import the drivers in to the "Out-of-Box drivers" so images you build will automatically have the needed drivers added to them.

Body:
From your target system you can do the powershell command

Export-WindowsDriver -Online -Destination d:\drivers

This will export all drivers from that machine to the d:\drivers folder. Once you have that folder mount your image some place and you can do the command

Add-WindowsDriver –Path "c:\offline" –Driver "c:\someHardware\drivers" –Recurse

Where the image is mounted to c:\offline and the d:\drivers from the source machine was coped to c:\someHardware\drivers

NOTE: if you are using the Microsoft Deployment Toolkit to capture the image you can import the drivers in to the "Out-of-Box drivers" so images you build will automatically have the needed drivers added to them.


来源: stackexchange

问:
Ionic: close/hide modal on Android back button not working
According to the documentation (http://ionicframework.com/docs/api/controller/ionicModal/), the default behaviour is to close the current modal on back button. But it's not closing anything, instead, it performs the action of the main view, go back.

{boolean=} hardwareBackButtonClose: Whether the modal can be closed using the hardware back button on Android and similar devices. Default: true.

Here is my code when I initialize the modal:

```<code>$ionicModal.fromTemplateUrl('app/components/contacts/views/contacts.selectModal.html', {
    scope: $scope,
    animation: 'slide-in-up',
    hardwareBackButtonClose: true
}).then(function(modal) {
    $scope.contactSelect = modal;
});
</code>```

I'm using Android 5.1, Ionic 1.2.1

答:
Use $ionicModal option isShown() for recognize modal is open and close on tap  hardwareBackButton

Work for me in Android Api 16

$ionicPlatform.registerBackButtonAction(function (event) {
    if(vm.modal.isShown()) {
      backModal();
    } else {
      window.history.back();
    }

 }, 999);  ```

ContentLicense: CC BY-SA 3.0

Body:
According to the documentation (http://ionicframework.com/docs/api/controller/ionicModal/), the default behaviour is to close the current modal on back button. But it's not closing anything, instead, it performs the action of the main view, go back.

{boolean=} hardwareBackButtonClose: Whether the modal can be closed using the hardware back button on Android and similar devices. Default: true.

Here is my code when I initialize the modal:

$ionicModal.fromTemplateUrl('app/components/contacts/views/contacts.selectModal.html', {
    scope: $scope,
    animation: 'slide-in-up',
    hardwareBackButtonClose: true
}).then(function(modal) {
    $scope.contactSelect = modal;
});

I'm using Android 5.1, Ionic 1.2.1


问:
Simple count date with month by month
I want to ask a formula that can automatically create the number of days from a date line. Then can be categorized based on the number of days in a month. I created a sample table like in the picture. And date data beside it. anyone can help??

答:
Here's the formula to count Mondays:

```<code>=NETWORKDAYS.INTL(DATE(2017,MONTH(1&T8),1),EOMONTH(DATE(2017,MONTH(1&T8),1),0),"0111111")
</code>```

For Tuesdays change last param to  "1011111" and so on. I guess "July" in your table is in T8. If not, change both T8 to the cell where "July" is. After filling first row, you can drag or copy it to the remaining rows.

There is a way to take days' names from your table instead of typing "0111111", but it will make formula look much more complicated.

Title: Simple count date with month by month

Body:
Here's the formula to count Mondays:

=NETWORKDAYS.INTL(DATE(2017,MONTH(1&T8),1),EOMONTH(DATE(2017,MONTH(1&T8),1),0),"0111111")

For Tuesdays change last param to  "1011111" and so on. I guess "July" in your table is in T8. If not, change both T8 to the cell where "July" is. After filling first row, you can drag or copy it to the remaining rows.

There is a way to take days' names from your table instead of typing "0111111", but it will make formula look much more complicated.


问:
How to remove GitHub commit along with it's history?
My friend made a config file, holding our apikey/token/secrets, and a .gitignore to ignore said file. Someone accidentally pushed to the master branch with the config file saved as another name and is now showing.

I was wondering if there was a way to delete that commit and the history of that commit.

I have seen this (below) and I understand this will delete the commit and re-push everything. But it still shows the config info via history/changes:

```<code>git reset --hard hash#

git push -f origin branch
</code>```

答:
git-filter-branch can help you in your case, as follows:

Replace PATH-TO-YOUR-CONFIG-FILE with the path to your config file you want to remove, not just its filename.

```<code>git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch PATH-TO-YOUR-CONFIG-FILE' \
--prune-empty --tag-name-filter cat -- --all
</code>```

Add your config file to .gitignore to ensure that you don't accidentally commit it again, commit and push it, following below commands:

```<code>echo "YOUR-CONFIG-FILE" >> .gitignore
git add .gitignore
git commit -m "Add YOUR-CONFIG-FILE to .gitignore"
git push origin --force --all
</code>```

Body:
My friend made a config file, holding our apikey/token/secrets, and a .gitignore to ignore said file. Someone accidentally pushed to the master branch with the config file saved as another name and is now showing.

I was wondering if there was a way to delete that commit and the history of that commit.

I have seen this (below) and I understand this will delete the commit and re-push everything. But it still shows the config info via history/changes:

git reset --hard hash#

git push -f origin branch

Body:
git-filter-branch can help you in your case, as follows:

Replace PATH-TO-YOUR-CONFIG-FILE with the path to your config file you want to remove, not just its filename.

git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch PATH-TO-YOUR-CONFIG-FILE' \
--prune-empty --tag-name-filter cat -- --all

Add your config file to .gitignore to ensure that you don't accidentally commit it again, commit and push it, following below commands:

echo "YOUR-CONFIG-FILE" >> .gitignore
git add .gitignore
git commit -m "Add YOUR-CONFIG-FILE to .gitignore"
git push origin --force --all


问:
Android Studio: Boolean function crashes my app
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.

Code:
MainActivity.java

```<code>    package com.leuchtstein.flashlight;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView)   ;

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

 public void triggerlight(View view) {

 if (stat == false) {

    text.setText("ON");
    stat = true;

} else {

    text.setText("OFF");
    stat = false;

  }

  }

 }
</code>```

activity_main.xml

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

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="@string/desc_textview"
          android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
    app:layout_constraintHorizontal_bias="0.95"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="triggerlight"
    android:text="Turn on/off"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.387" />
</code>```

Well, thanks in advance.

答:
Try this :    </p>

```<code>public class MainActivity extends AppCompatActivity {
    public boolean stat = false;
    TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.textView)
}
</code>```

Body:
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.

Code:
MainActivity.java

    package com.leuchtstein.flashlight;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView)   ;

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

 public void triggerlight(View view) {

 if (stat == false) {

    text.setText("ON");
    stat = true;

} else {

    text.setText("OFF");
    stat = false;

  }

  }

 }

activity_main.xml

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

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="@string/desc_textview"
          android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
    app:layout_constraintHorizontal_bias="0.95"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="triggerlight"
    android:text="Turn on/off"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.387" />

Well, thanks in advance.

Body:
Try this :

public class MainActivity extends AppCompatActivity {
    public boolean stat = false;
    TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.textView)
}


问:
angularjs multi level editable tree
I'm building my first angularjs app, and still struggling with the scopes and stuff.

I'm trying to build a multi level tree, where I can edit nodes to become sub-nodes, or get them one level up (from sub node to parent), but I'm kind of stuck.

So far, I managed to set a root node as a sub-node. But set a sub-node as a root node is a whole different story, because I have to access the parent node, which right now I don't know how to do.

Plnkr

Any idea of how I can change a sub-node to a root node? Thanks

Edit:

Imagine this tree:

Item 1

Sub Item 1.1 [button 1]

Sub Item 1.2 [button 2]

Item 2

Item 3

Item 4

You click the [button 2] and you got this:

Item 1

Sub Item 1.1

Sub Item 1.2

Item 2

Item 3

Item 4

答:
this one is dynamic and drag drop tree.

http://www.jqueryrain.com/?KIVkhqxl

it supports:

Inputs

Custom Templates

Action Mapping

Events

Async Data

Filtering

Drag & Drop

Features:

Dynamically changing the tree

API

Styling

Tri-State Checkboxes

Large Trees & Virtual Scroll

Redux / Immutable Data

Title: angularjs multi level editable tree


问:
Replacing first part of string by another
I need to replace multiple file names in a folder. Here is one of the files:

Abc.CDE.EFG

I need to replace the first part of the string before the dot ("ABC") and replace it with: "zef".

Any ideas? I found this but it takes out the dot and not sure how to add the "zef".

```<code>var input = _FileInfo.ToString();
var output = input.Substring(input.IndexOf(".").Trim())
</code>```

答:
Try this:</p>

```<code>    var input = _FileInfo.ToString();
    var output = "zef" + input.Substring(input.IndexOf("."));
</code>```

Body:
I need to replace multiple file names in a folder. Here is one of the files:

Abc.CDE.EFG

I need to replace the first part of the string before the dot ("ABC") and replace it with: "zef".

Any ideas? I found this but it takes out the dot and not sure how to add the "zef".

var input = _FileInfo.ToString();
var output = input.Substring(input.IndexOf(".").Trim())

Body:
Try this:

    var input = _FileInfo.ToString();
    var output = "zef" + input.Substring(input.IndexOf("."));


问:
Read records dbf foxpro 2.6 have been deleted on excel
How to read records that have been deleted. Can the record be read on excel or another software? If so, how? </p>

答:
Lets start by talking about Excel...

The newer versions of Excel (2007 & 2010) cannot open Foxpro DBF files.  Microsoft, in its infinite wisdom (??), decided to eliminate Excel's Read or Write capability of DBF files.

If, however you have an older version of Excel, then OK.

Should you happen to have Foxpro/Visual Foxpro and use it to 'export' DBF file contents into a CSV file, then Excel can open the CSV file (regardless of Excel version).

Now everything Alan B said above holds true.  If the file is PACK'ed, the Deleted records are GONE!!

However if you have a backup, you can always do a comparison of the backup data table records and those in the current file to identify those records which were Deleted.

Again if you should happen to have a copy of Foxpro/Visual Foxpro and you have not PACK'ed the data table (DBF file), then you could always run a SQL Query of the table and pull the Deleted records into a separate memory cursor or data table and then do whatever you need to do with it.

Good Luck


答:
You are almost there, try:

```<code>string myString = "Abc.CDE.EFG";

//This splits your string into an array with 3 items
//"Abc", "CDE" and "EFG"
var stringArray = myString.Split('.');

//Now modify the first item by changing it to "zef"
stringArray[0] = "zef";

//Then we rebuild the string by joining the array together
//delimiting each group by a period
string newString = string.Join(".", stringArray);
</code>```

With this solution you can independently access any of the "blocks" just by referencing the array by index.

Fiddle here

Title: Replacing first part of string by another

Body:
You are almost there, try:

string myString = "Abc.CDE.EFG";

//This splits your string into an array with 3 items
//"Abc", "CDE" and "EFG"
var stringArray = myString.Split('.');

//Now modify the first item by changing it to "zef"
stringArray[0] = "zef";

//Then we rebuild the string by joining the array together
//delimiting each group by a period
string newString = string.Join(".", stringArray);

With this solution you can independently access any of the "blocks" just by referencing the array by index.

Fiddle here


问:
How to delete the first 2 lines from string in C#?
I have a string like the following:

```<code>string myString = @"This is the first line

This is the third line as the 2nd is empty
The string continues

Anso so on ...
...
..
.";
</code>```

I know that I can split this into an array, delete the first 2 elements and then rebuild my string from that array but I'm looking for something much more simple.

答:
If you do want to micro-optimize (or your strings are large, or you're calling this in a loop), here is a more performant way to do it:

```<code>private static string RemoveFirstTwoLines(string myString) {
    int ix = myString.IndexOf('\n');
    ix = myString.IndexOf('\n', ix + 1);
    return myString.Substring(ix + 1);
}
</code>```

Body:
I have a string like the following:

string myString = @"This is the first line

This is the third line as the 2nd is empty
The string continues

Anso so on ...
...
..
.";

I know that I can split this into an array, delete the first 2 elements and then rebuild my string from that array but I'm looking for something much more simple.

Body:
If you do want to micro-optimize (or your strings are large, or you're calling this in a loop), here is a more performant way to do it:

private static string RemoveFirstTwoLines(string myString) {
    int ix = myString.IndexOf('\n');
    ix = myString.IndexOf('\n', ix + 1);
    return myString.Substring(ix + 1);
}


问:
Springs XmlBeanFactory is deprecated
I try to learn Spring. I am following this site http://www.roseindia.net/spring/spring3/spring-3-hello-world.shtml

I tried one example in that. I am using some what like below, but here it shows:

The type XmlBeanFactory is deprecated

What do I have to use as an alternative to this?

```<code>public class SpringHelloWorldTest {
    public static void main(String[] args) {

        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringHelloWorld.xml"));

        Spring3HelloWorld myBean = (Spring3HelloWorld)beanFactory.getBean("Spring3HelloWorldBean");
        myBean.sayHello();
    }
}
</code>```

答:
Alternative to XMLBeanFactory found on Spring documentation</p>

```<code>GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new
ClassPathResource("applicationContext.xml"));
PropertiesBeanDefinitionReader propReader = new
PropertiesBeanDefinitionReader(ctx);
propReader.loadBeanDefinitions(new
ClassPathResource("otherBeans.properties"));
ctx.refresh();

MyBean myBean = (MyBean) ctx.getBean("myBean");
</code>```

Title: Springs XmlBeanFactory is deprecated

Body:
I try to learn Spring. I am following this site http://www.roseindia.net/spring/spring3/spring-3-hello-world.shtml

I tried one example in that. I am using some what like below, but here it shows:

The type XmlBeanFactory is deprecated

What do I have to use as an alternative to this?

public class SpringHelloWorldTest {
    public static void main(String[] args) {

        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringHelloWorld.xml"));

        Spring3HelloWorld myBean = (Spring3HelloWorld)beanFactory.getBean("Spring3HelloWorldBean");
        myBean.sayHello();
    }
}

Body:
Alternative to XMLBeanFactory found on Spring documentation

GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new
ClassPathResource("applicationContext.xml"));
PropertiesBeanDefinitionReader propReader = new
PropertiesBeanDefinitionReader(ctx);
propReader.loadBeanDefinitions(new
ClassPathResource("otherBeans.properties"));
ctx.refresh();

MyBean myBean = (MyBean) ctx.getBean("myBean");


问:
open file in different directory to read lines - ruby
I've been using ARGV to open files but i feel like its clunky i want to have them in a different folder.

i want to open input.txt within my talk_parser.rb, I don't want to hardcode the file name either.

My directory (pwd is bin)

```<code>├── bin
│ └── talk_parser.rb
└── data
  └── input.txt
</code>```

tried

```<code>x = Dir.glob('../data/*.txt').to_s
file = File.open(File.expand_path(x))
</code>```

but i get this error

```<code>talk_parser.rb:34:in `initialize':
No such file or directory @ rb_sysopen - /home/huvi/Desktop/test/bin/["../data/input.txt"] (Errno::ENOENT)
from talk_parser.rb:34:in `open'
from talk_parser.rb:34:in `<main>'
</code>```

not sure what to do

答:
Dir.glob returns an Array.
You can get the first element and open it:

```<code>  path = Dir.glob('../data/*.txt').first
  file = File.open(path)
</code>```

Body:
I've been using ARGV to open files but i feel like its clunky i want to have them in a different folder.

i want to open input.txt within my talk_parser.rb, I don't want to hardcode the file name either.

My directory (pwd is bin)

├── bin
│ └── talk_parser.rb
└── data
  └── input.txt

tried

x = Dir.glob('../data/*.txt').to_s
file = File.open(File.expand_path(x))

but i get this error

talk_parser.rb:34:in `initialize':
No such file or directory @ rb_sysopen - /home/huvi/Desktop/test/bin/["../data/input.txt"] (Errno::ENOENT)
from talk_parser.rb:34:in `open'
from talk_parser.rb:34:in `'

not sure what to do

Body:
Dir.glob returns an Array.
You can get the first element and open it:

  path = Dir.glob('../data/*.txt').first
  file = File.open(path)


问:
Location of Scala: MatchError
```<code>ERROR Executor: Exception in task 0.0 in stage 10.0 (TID 20)
scala.MatchError: [0.0,(20,[0,5,9,17],[0.6931471805599453,0.6931471805599453,0.28768207245178085,1.3862943611198906])] (of class org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema)
</code>```

I am seeing this error with my scala program where I am trying to classify movie reviews using a NaiveBayes Classifier. I am seeing this error on the line at which I attempt to train the NaiveBayes Classifer. I am unable to correct this error as I am unaware of the datatype that the classifier is expecting. The documentation for NaiveBayes says it expects a RDD entry which is what I have. Any help would be greatly appreciated. Please find my full SCALA code for this movie review classification program.

PS: Please ignore the possible mistakes in indenting in the code. Its right in my program file. Thanks in advance.

```<code>    import  org.apache.spark.sql.{Dataset, DataFrame, SparkSession}
    import org.apache.spark.{SparkConf, SparkContext}
    import org.apache.spark.sql.functions._
    import org.apache.spark.sql._
    import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer, PCA}
    import org.apache.spark.mllib.classification.{NaiveBayes,NaiveBayesModel}
    import org.apache.spark.mllib.util.MLUtils
    import org.apache.spark.mllib.regression.LabeledPoint
    import org.apache.spark.mllib.linalg._

    //Reading the file from csv into dataframe object
    val sqlContext = new SQLContext(sc)
    val df = sqlContext.read.option("header", "true").option("delimiter",",").option("inferSchema", "true").csv("movie-pang02.csv")

     //Tokenizing the data by splitting the text into words
     val tokenizer = new Tokenizer().setInputCol("text").setOutputCol("words")
     val wordsData = tokenizer.transform(df)

     //Hashing the data by converting the words into rawFeatures
     val hashingTF = new HashingTF().setInputCol("words").setOutputCol("rawFeatures").setNumFeatures(200)
     val featurizedData = hashingTF.transform(wordsData)

      //Applying Estimator on the data which converts the raw features into features by scaling each column
      val idf  = new IDF().setInputCol("rawFeatures").setOutputCol("features")
      val idfModel = idf.fit(featurizedData)
      val rescaledData = idfModel.transform(featurizedData)

      val coder: (String => Int) = (arg: String) => {if (arg == "Pos") 1 else 0}
      val sqlfunc = udf(coder)
      val new_set = rescaledData.withColumn("label", sqlfunc(col("class")))

      val EntireDataRdd = new_set.select("label","features").map{case Row(label: Int, features: Vector) =>  LabeledPoint(label.toDouble, Vectors.dense(features.toArray))}

    //Converted the data into RDD<LabeledPoint> format so as to input it into the inbuilt Naive Bayes classifier
    val labeled = EntireDataRdd.rdd
    val Array(trainingData, testData) = labeled.randomSplit(Array(0.7, 0.3), seed = 1234L)
    //Error in the following statement
    val model = NaiveBayes.train(trainingData, lambda = 1.0, modelType = "multinomial")

    val predictionAndLabel = testData.map(p => (model.predict(p.features), p.label))
    val accuracy = 1.0 * predictionAndLabel.filter(x => x._1 == x._2).count() / testData.count()
    val testErr = predictionAndLabel.filter(r => r._1 != r._2).count.toDouble / testData.count()
</code>```

答:
This is a painful (and not uncommon) pitfall - you're matching the contents of your Row to the wrong Vector class - it should be org.apache.spark.ml.linalg.Vector and not org.apache.spark.mllib.linalg.Vector... (yes - frustrating!)

Adding the right import before the mapping solves this issue:

```<code>import org.apache.spark.ml.linalg.Vector // and not org.apache.spark.mllib.linalg.Vector!
import org.apache.spark.mllib.linalg.Vectors // and not org.apache.spark.ml.linalg.Vectors!

val EntireDataRdd = new_set.select("label","features").map {
  case Row(label: Int, features: Vector) =>  LabeledPoint(label.toDouble, Vectors.dense(features.toArray))
}
</code>```

Title: Location of Scala: MatchError

Body:
ERROR Executor: Exception in task 0.0 in stage 10.0 (TID 20)
scala.MatchError: [0.0,(20,[0,5,9,17],[0.6931471805599453,0.6931471805599453,0.28768207245178085,1.3862943611198906])] (of class org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema)

I am seeing this error with my scala program where I am trying to classify movie reviews using a NaiveBayes Classifier. I am seeing this error on the line at which I attempt to train the NaiveBayes Classifer. I am unable to correct this error as I am unaware of the datatype that the classifier is expecting. The documentation for NaiveBayes says it expects a RDD entry which is what I have. Any help would be greatly appreciated. Please find my full SCALA code for this movie review classification program.

PS: Please ignore the possible mistakes in indenting in the code. Its right in my program file. Thanks in advance.

    import  org.apache.spark.sql.{Dataset, DataFrame, SparkSession}
    import org.apache.spark.{SparkConf, SparkContext}
    import org.apache.spark.sql.functions._
    import org.apache.spark.sql._
    import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer, PCA}
    import org.apache.spark.mllib.classification.{NaiveBayes,NaiveBayesModel}
    import org.apache.spark.mllib.util.MLUtils
    import org.apache.spark.mllib.regression.LabeledPoint
    import org.apache.spark.mllib.linalg._

    //Reading the file from csv into dataframe object
    val sqlContext = new SQLContext(sc)
    val df = sqlContext.read.option("header", "true").option("delimiter",",").option("inferSchema", "true").csv("movie-pang02.csv")

     //Tokenizing the data by splitting the text into words
     val tokenizer = new Tokenizer().setInputCol("text").setOutputCol("words")
     val wordsData = tokenizer.transform(df)

     //Hashing the data by converting the words into rawFeatures
     val hashingTF = new HashingTF().setInputCol("words").setOutputCol("rawFeatures").setNumFeatures(200)
     val featurizedData = hashingTF.transform(wordsData)

      //Applying Estimator on the data which converts the raw features into features by scaling each column
      val idf  = new IDF().setInputCol("rawFeatures").setOutputCol("features")
      val idfModel = idf.fit(featurizedData)
      val rescaledData = idfModel.transform(featurizedData)

      val coder: (String => Int) = (arg: String) => {if (arg == "Pos") 1 else 0}
      val sqlfunc = udf(coder)
      val new_set = rescaledData.withColumn("label", sqlfunc(col("class")))

      val EntireDataRdd = new_set.select("label","features").map{case Row(label: Int, features: Vector) =>  LabeledPoint(label.toDouble, Vectors.dense(features.toArray))}

    //Converted the data into RDD<LabeledPoint> format so as to input it into the inbuilt Naive Bayes classifier
    val labeled = EntireDataRdd.rdd
    val Array(trainingData, testData) = labeled.randomSplit(Array(0.7, 0.3), seed = 1234L)
    //Error in the following statement
    val model = NaiveBayes.train(trainingData, lambda = 1.0, modelType = "multinomial")

    val predictionAndLabel = testData.map(p => (model.predict(p.features), p.label))
    val accuracy = 1.0 * predictionAndLabel.filter(x => x._1 == x._2).count() / testData.count()
    val testErr = predictionAndLabel.filter(r => r._1 != r._2).count.toDouble / testData.count()

Body:
This is a painful (and not uncommon) pitfall - you're matching the contents of your Row to the wrong Vector class - it should be org.apache.spark.ml.linalg.Vector and not org.apache.spark.mllib.linalg.Vector... (yes - frustrating!)

Adding the right import before the mapping solves this issue:

import org.apache.spark.ml.linalg.Vector // and not org.apache.spark.mllib.linalg.Vector!
import org.apache.spark.mllib.linalg.Vectors // and not org.apache.spark.ml.linalg.Vectors!

val EntireDataRdd = new_set.select("label","features").map {
  case Row(label: Int, features: Vector) =>  LabeledPoint(label.toDouble, Vectors.dense(features.toArray))
}


答:
If you know the length of the first string , you can replace mentioning number of characters starting from position until the length you want to replace else.    </p>

```<code>string s = "Abc.CDE.EFG";
                string [] n = s.Split('.');
                n[0] = "ZEF";
                string p = string.Join(".",n);
                Console.WriteLine(p);
            }
</code>```

Body:
If you know the length of the first string , you can replace mentioning number of characters starting from position until the length you want to replace else.

string s = "Abc.CDE.EFG";
                string [] n = s.Split('.');
                n[0] = "ZEF";
                string p = string.Join(".",n);
                Console.WriteLine(p);
            }


问:
SQLite3::query(): Unable to prepare statement: 1, unrecognized token ""
I am trying to create a PHP search query that searches by each word from the database. But i get this error when search query is submitted.

Warning: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'%export%" in C:\xampp\htdocs\xport\searchresult.php on line 107

Below is my code.

For the search page

```<code>if (isset($_POST['mainSearch']))
{

if (!empty($_POST['mainSearch']))
{
    $searchquery = $_POST['mainSearch'];

    $query = str_replace(" ", "+", $_POST['mainSearch']);
    header("Location: searchresult.php?mainSearch=" . $query);

}

}
</code>```

Page to display search result.

```<code>if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET['mainSearch']);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%'";
  }
  $condition = substr($condition, 0, -4);

  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $result = $db->query($sql_query);

  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_2">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  else
  {

  }
  }
</code>```

What is the reason for this error. I think its because the string is not properly escaped, if this is the reason how do i mysqli_real_escape_string() in SQLite3 (this is the database i am using). If not, Please how do i fix this.

答:
Try it this way if you are trying to search by each word</p>

```<code><?php
if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      //change condition query
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition;
  $result = $db->query($sql_query);

  //count query result to display something else if no records where found.
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_3">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}
?>
</code>```

Body:
I am trying to create a PHP search query that searches by each word from the database. But i get this error when search query is submitted.

Warning: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'%export%" in C:\xampp\htdocs\xport\searchresult.php on line 107

Below is my code.

For the search page

if (isset($_POST['mainSearch']))
{

if (!empty($_POST['mainSearch']))
{
    $searchquery = $_POST['mainSearch'];

    $query = str_replace(" ", "+", $_POST['mainSearch']);
    header("Location: searchresult.php?mainSearch=" . $query);

}

}

Page to display search result.

if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET['mainSearch']);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%'";
  }
  $condition = substr($condition, 0, -4);

  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $result = $db->query($sql_query);

  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '

'.$row["question"].'

'.$row["answer"].'

';
      }
  }
  else
  {

  }
  }

What is the reason for this error. I think its because the string is not properly escaped, if this is the reason how do i mysqli_real_escape_string() in SQLite3 (this is the database i am using). If not, Please how do i fix this.

Body:
Try it this way if you are trying to search by each word

<?php
if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      //change condition query
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition;
  $result = $db->query($sql_query);

  //count query result to display something else if no records where found.
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_3">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}
?>


问:
Searching Xml Document with linq doesn't return anything
I'm trying to learn how to save and extract data with XML in C#, and even though I've read various answers to similar questions on here, I cannot get a hold of why my statement isn't returning anything.
The program I'm writing is just a test, in which I've saved data about a couple movies in the xml document and now I'm trying to retrieve some of them based on their cost.

This is the class that I've written for searching:

```<code> class ExtractData
{
    private XDocument _xdoc;
    public List<string> SearchByCost(double cost)
    {
        _xdoc = XDocument.Load(FileLocation.XmlFileLocation);
        List<string> list = new List<string>();

        var movies = from movie in _xdoc.Root.Elements("Name")
                where Convert.ToDouble(movie.Element("Cost").Value) < cost
                select movie;

        foreach (var item in movies)
        {
            list.Add(item.Value);
        }

        return list;
    }

}
</code>```

This is how I'm trying to make it print it in the console:

```<code>        eData = new ExtractData();
        foreach (var movie in eData.SearchByCost(9))
        {
            Console.WriteLine(movie);
        }
</code>```

And this is the content of the XML document:

```<code><?xml version="1.0" encoding="utf-8"?>
<Movies>
  <Movie>
    <Id>1</Id>
    <Name>Shawshank Redemption</Name>
    <Director>Frank Darabont</Director>
    <Year>1994</Year>
    <Cost>9.95</Cost>
  </Movie>
  <Movie>
    <Id>2</Id>
    <Name>Pulp Fiction</Name>
    <Director>Quentin Tarantino</Director>
    <Year>1995</Year>
    <Cost>8.95</Cost>
  </Movie>
  <Movie>
    <Id>3</Id>
    <Name>Sharknado</Name>
    <Director>Anthony Ferrante</Director>
    <Year>2013</Year>
    <Cost>5.95</Cost>
  </Movie>
</Movies>
</code>```

I hope this is enough information to try and help me out, and thanks in advance! :)

答:
Root element contains Movie elements:

```<code>var movies = from movie in _xdoc.Root.Elements("Movie")  // here instead of "Name"
             where (double)movie.Element("Cost") < cost
             select movie;
</code>```

Also, XElement supports explicit casting to double. And you can replace the second loop with LINQ query (assume you want to select names of movies):

```<code>List<string> list = movies.Select(m => (string)m.Element("Name")).ToList();
</code>```

Body:
I'm trying to learn how to save and extract data with XML in C#, and even though I've read various answers to similar questions on here, I cannot get a hold of why my statement isn't returning anything.
The program I'm writing is just a test, in which I've saved data about a couple movies in the xml document and now I'm trying to retrieve some of them based on their cost.

This is the class that I've written for searching:

 class ExtractData
{
    private XDocument _xdoc;
    public List<string> SearchByCost(double cost)
    {
        _xdoc = XDocument.Load(FileLocation.XmlFileLocation);
        List<string> list = new List<string>();

        var movies = from movie in _xdoc.Root.Elements("Name")
                where Convert.ToDouble(movie.Element("Cost").Value) < cost
                select movie;

        foreach (var item in movies)
        {
            list.Add(item.Value);
        }

        return list;
    }

}

This is how I'm trying to make it print it in the console:

        eData = new ExtractData();
        foreach (var movie in eData.SearchByCost(9))
        {
            Console.WriteLine(movie);
        }

And this is the content of the XML document:

<?xml version="1.0" encoding="utf-8"?>
<Movies>
  <Movie>
    <Id>1</Id>
    <Name>Shawshank Redemption</Name>
    <Director>Frank Darabont</Director>
    <Year>1994</Year>
    <Cost>9.95</Cost>
  </Movie>
  <Movie>
    <Id>2</Id>
    <Name>Pulp Fiction</Name>
    <Director>Quentin Tarantino</Director>
    <Year>1995</Year>
    <Cost>8.95</Cost>
  </Movie>
  <Movie>
    <Id>3</Id>
    <Name>Sharknado</Name>
    <Director>Anthony Ferrante</Director>
    <Year>2013</Year>
    <Cost>5.95</Cost>
  </Movie>
</Movies>

I hope this is enough information to try and help me out, and thanks in advance! :)

Body:
Root element contains Movie elements:

var movies = from movie in _xdoc.Root.Elements("Movie")  // here instead of "Name"
             where (double)movie.Element("Cost") < cost
             select movie;

Also, XElement supports explicit casting to double. And you can replace the second loop with LINQ query (assume you want to select names of movies):

List<string> list = movies.Select(m => (string)m.Element("Name")).ToList();


问:
How can I make these headers inside bootstrap columns fixed to top this way?
I have exhausted everything I can think of. I have a page with a menu and 2 bootstrap columns with content inside. I want the menu to scroll out of view, but once you scroll past the first divs in each column (the titles of the sections), then I want them to stay fixed to the top...but I want them still to look the same way (right aligned over the column and as wide as the column).

I have the code set to only work when the screen is wide enough for both columns to fit side by side (you'll want to view the snippet in full screen mode). You'll see that when you scroll, the fixed divs will be on the left of each container and not full width. I want it to look just as it did before it was fixed.

Anyone have any ideas? See code below:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Menu - Not fixed, let user scroll past it

Fixed Header 1

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

Fixed Header 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

```

答:
Try to replace this css.

```<code>.fixedHeader {
    position: fixed;
    top: 0;
    background: white;
    width: 100%;
  }
</code>```

EDIT

Change this 2 things in your code

CSS

```<code><style>
    .NotfixedHeader {
      text-align: right;
      border-bottom: 2px solid black;
    }
    .no-pad {padding: 0;} //new added
    @media screen and (min-width: 300px) {
      .fixedHeader {
        position: fixed;
        top: 0;
        background: white;
        width: 100%;
      }
    }
</style>
</code>```

jQuery

```<code>$(document).ready(function() {
  $(window).scroll(function() {
    //console.log($(window).scrollTop())
    if ($(window).scrollTop() > 99) {
      $('.NotfixedHeader').addClass('fixedHeader');
      $('.fixedHeader').parent().addClass("no-pad");
    }
    if ($(window).scrollTop() < 100) {
      $('.NotfixedHeader').removeClass('fixedHeader');
      $('.fixedHeader').parent().removeClass("no-pad");
    }
  });
});
</code>```

It was not proper because position:fixed element was taking padding of his parent class.

Try with this code. Hope this will helps you

Body:
Try to replace this css.

.fixedHeader {
    position: fixed;
    top: 0;
    background: white;
    width: 100%;
  }

EDIT

Change this 2 things in your code

CSS

<style>
    .NotfixedHeader {
      text-align: right;
      border-bottom: 2px solid black;
    }
    .no-pad {padding: 0;} //new added
    @media screen and (min-width: 300px) {
      .fixedHeader {
        position: fixed;
        top: 0;
        background: white;
        width: 100%;
      }
    }
</style>

jQuery

$(document).ready(function() {
  $(window).scroll(function() {
    //console.log($(window).scrollTop())
    if ($(window).scrollTop() > 99) {
      $('.NotfixedHeader').addClass('fixedHeader');
      $('.fixedHeader').parent().addClass("no-pad");
    }
    if ($(window).scrollTop() < 100) {
      $('.NotfixedHeader').removeClass('fixedHeader');
      $('.fixedHeader').parent().removeClass("no-pad");
    }
  });
});

It was not proper because position:fixed element was taking padding of his parent class.

Try with this code. Hope this will helps you


问:
How to produce a formatted date string in Q/KDB?
How can one produce an ISO date string "yyyy-MM-dd" from a Q date type? I looked at concatenating the various parts but am not even able to get the day/month, e.g. d:2015.12.01;d.month prints 2015.12, i.e. more than just the month.

Body:
Please change the separator like - or / in the update statement.

update s:{ssr[string x;".";y]}'[d;"-"] from ([]a:5#1;5?.z.d)
a d          s
-------------------------
1 2010.12.31 "2010-12-31"
1 2012.08.24 "2012-08-24"
1 2004.12.05 "2004-12-05"
1 2000.10.02 "2000-10-02"
1 2006.09.10 "2006-09-10"


问:
Allow single quote in sql query
I want to update my sql table , but in my case I am getting error look like this

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ivision '' at line 1

```<code>$name = "A'nme";

$this->db->update("users",["name" => $name]);
</code>```

My project based  on Codeigniter

How can I solve this problem ?

答:
Double up and use single quotes to see it better:
How to insert a value that contains an apostrophe (single quote)?</p>

```<code>$name = 'A''nme';
</code>```

Title: Allow single quote in sql query

Body:
I want to update my sql table , but in my case I am getting error look like this

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ivision '' at line 1

$name = "A'nme";

$this->db->update("users",["name" => $name]);

My project based  on Codeigniter

How can I solve this problem ?

Body:
Double up and use single quotes to see it better:
How to insert a value that contains an apostrophe (single quote)?

$name = 'A''nme';


问:
DELETE_FAILED_INTERNAL_ERROR Error while Installing APK
I am using Android Studio 2.2 Preview. I am facing the issue

Failure: Install failed invalid apk

Error: While installing apk,

I have made changes in build.gradle but could not retrack it, please suggest me solution???

答:
Even after following all the suggestions, if it shows error then check your buildType in Gradle.

Make sure
signingConfig signingConfigs.config

is in release scope, not in debug.


答:
Since the question is tagged with regex, you can use a regular expression like so:

```<code>var input = "abc.def.efg";
var pattern = "^[^\\.]+";
var replacement = "zef";
var rgx = new Regex(pattern);
var output = rgx.Replace(input, replacement);
</code>```

Source: https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx

Body:
I need to replace multiple file names in a folder. Here is one of the files:

Abc.CDE.EFG

I need to replace the first part of the string before the dot ("ABC") and replace it with: "zef".

Any ideas? I found this but it takes out the dot and not sure how to add the "zef".

var input = _FileInfo.ToString();
var output = input.Substring(input.IndexOf(".").Trim())

Body:
Since the question is tagged with regex, you can use a regular expression like so:

var input = "abc.def.efg";
var pattern = "^[^\\.]+";
var replacement = "zef";
var rgx = new Regex(pattern);
var output = rgx.Replace(input, replacement);

Source: https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx


问:
SQL - Source Control and Schema/Script management
My company has just gone though its annual review process, and I have finally convinced them that it is time to find a better solution to manage our SQL schema/scripts.  Currently, we only have a few scripts to manually update.

I've worked with VS2008 Database Edition at a different company and that is an awesome product. My boss has asked me to take a look at SQL Compare by Redgate and to look for any other products that may be better.  SQL Compare appears to be a great product also.  However, it does not look like they have support for Perforce.

Have you used a variety of products for this?

What tools do you use to manage SQL?

What should be included in the requirements before my company makes a purchase?

答:
We use LiquiBase to keep control of database changes:</p>

```<code>Liquibase is an open source (Apache 2.0 Licensed), database-independent library for tracking, managing and applying database changes.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
We use LiquiBase to keep control of database changes:

Liquibase is an open source (Apache 2.0 Licensed), database-independent library for tracking, managing and applying database changes.


问:
connect points during multiple Matlab plot calls
I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

```<code>function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return

function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber);
    if ~ishold
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return
</code>```

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.

答:
Here is some code that works. However, I am open to suggestions or other code that may be simpler and/or faster :)</p>

```<code>function calculateErrorAndPlot(figureNumber,x,y,time)

figure(figureNumber);
if ~ishold
    hold on
end

error = x-y;

h = findobj(figure(figureNumber),'Type','line');
if isempty(h)
    xx = time;
    yy = error;
else
    xx = [h(1).XData(end) time];
    yy = [h(1).YData(end) error];
end
plot(xx,yy,'.-black');
return
</code>```

Body:
I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return

function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber);
    if ~ishold
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.

Body:
Here is some code that works. However, I am open to suggestions or other code that may be simpler and/or faster :)

function calculateErrorAndPlot(figureNumber,x,y,time)

figure(figureNumber);
if ~ishold
    hold on
end

error = x-y;

h = findobj(figure(figureNumber),'Type','line');
if isempty(h)
    xx = time;
    yy = error;
else
    xx = [h(1).XData(end) time];
    yy = [h(1).YData(end) error];
end
plot(xx,yy,'.-black');
return


问:
Selenium driver - wait on page reload
Is there a way, how to wait on page reload? For example, when I'm on page localhost:9000/web and I instruct the webdriver again to navigate to the localhost:9000/web. I don't want or can't indicate the reloading by waiting on some elements.

答:
We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.</p>

```<code>        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }
</code>```

Title: Selenium driver - wait on page reload

Body:
We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.

        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }


问:
rules-based grouping of near-identical individuals (NOT clustering?)
I have datasets with roughly 100s of thousands of rows (or roughly 100s of thousands of RDF triples.)  From a tabular standpoint, each row represents a person's participation in some process.  The data are noisy, and what appear to be separate individuals may in reality be the same person.  I need to authoritatively assign new identifiers to each unique person that is modeled in the data, according to rules, but I don't even know if there is a name for this practice.

I am familiar with may kinds of clustering methods, but this seems different to me.  I have no idea of the true number unique individuals, and I don't want to find individuals with a minimal distance between them.  I want to find individuals that satisfy some rules provided by my collaborators.

For example, if I have these data:

```<code>+-------------+-----+------------+--------+
| Transaction | ID  |    DOB     | Gender |
+-------------+-----+------------+--------+
|           1 | 111 | 5/5/1969   | M      |
|           2 | 112 | 6/6/1966   | F      |
|           3 | 113 | 7/7/1970   | F      |
|           4 | 113 | 9/9/1970   | F      |
|           5 | 114 | 2/3/2000   | M      |
|           6 | 114 | 2/4/2000   | F      |
|           7 | 115 | 9/10/2001  | M      |
|           8 | 115 | 11/11/2001 | F      |
+-------------+-----+------------+--------+
</code>```

And these exhaustive rules

people that have the same identifier and the same gender are the same
person

people who have the same identifier and have birth dates
within one day of another are the same person

Then the solution would be

```<code>+-------------+-----+------------+--------+-----------------+-----------------------------------------------------+
| Transaction | ID  |    DOB     | Gender | UniqueIdByRules |                        Notes                        |
+-------------+-----+------------+--------+-----------------+-----------------------------------------------------+
|           1 | 111 | 5/5/1969   | M      | A               |                                                     |
|           2 | 112 | 6/6/1966   | F      | B               |                                                     |
|           3 | 113 | 7/7/1970   | F      | C               |                                                     |
|           4 | 113 | 9/9/1970   | F      | C               | IDs identical, genders identical                    |
|           5 | 114 | 2/3/2000   | M      | D               |                                                     |
|           6 | 114 | 2/4/2000   | F      | D               | IDs identical, birthdates within one day of another |
|           7 | 115 | 9/10/2001  | M      | E               |                                                     |
|           8 | 115 | 11/11/2001 | F      | F               |                                                     |
+-------------+-----+------------+--------+-----------------+-----------------------------------------------------+
</code>```

My "best language" is R, but my project's core language is Scala.  So I'm especially interested in solutions that could be reasonably implemented in R, Scala, or Java.  The original data come as tables but are transformed to RDF triples fairly early in my process, so maybe SWRL is relevant?  One of my collaborators has casually suggested PyCLIPS for this kind of problem, so maybe Jess or Drools are relevant?

What is my problem/task called?

Are there existing solutions for this, other than exhaustive pairwise comparison?

Am I going to have problems with transitivity because I have two (or more) rules, and one of them doesn't require identity?

答:
This is called a "for loop" with "if statements".

Sort the data by ID, iterate over all IDs. if there is more than one, check your conditions with if statements.

Body:
I have datasets with roughly 100s of thousands of rows (or roughly 100s of thousands of RDF triples.)  From a tabular standpoint, each row represents a person's participation in some process.  The data are noisy, and what appear to be separate individuals may in reality be the same person.  I need to authoritatively assign new identifiers to each unique person that is modeled in the data, according to rules, but I don't even know if there is a name for this practice.

I am familiar with may kinds of clustering methods, but this seems different to me.  I have no idea of the true number unique individuals, and I don't want to find individuals with a minimal distance between them.  I want to find individuals that satisfy some rules provided by my collaborators.

For example, if I have these data:

+-------------+-----+------------+--------+
| Transaction | ID  |    DOB     | Gender |
+-------------+-----+------------+--------+
|           1 | 111 | 5/5/1969   | M      |
|           2 | 112 | 6/6/1966   | F      |
|           3 | 113 | 7/7/1970   | F      |
|           4 | 113 | 9/9/1970   | F      |
|           5 | 114 | 2/3/2000   | M      |
|           6 | 114 | 2/4/2000   | F      |
|           7 | 115 | 9/10/2001  | M      |
|           8 | 115 | 11/11/2001 | F      |
+-------------+-----+------------+--------+

And these exhaustive rules

people that have the same identifier and the same gender are the same
person

people who have the same identifier and have birth dates
within one day of another are the same person

Then the solution would be

+-------------+-----+------------+--------+-----------------+-----------------------------------------------------+
| Transaction | ID  |    DOB     | Gender | UniqueIdByRules |                        Notes                        |
+-------------+-----+------------+--------+-----------------+-----------------------------------------------------+
|           1 | 111 | 5/5/1969   | M      | A               |                                                     |
|           2 | 112 | 6/6/1966   | F      | B               |                                                     |
|           3 | 113 | 7/7/1970   | F      | C               |                                                     |
|           4 | 113 | 9/9/1970   | F      | C               | IDs identical, genders identical                    |
|           5 | 114 | 2/3/2000   | M      | D               |                                                     |
|           6 | 114 | 2/4/2000   | F      | D               | IDs identical, birthdates within one day of another |
|           7 | 115 | 9/10/2001  | M      | E               |                                                     |
|           8 | 115 | 11/11/2001 | F      | F               |                                                     |
+-------------+-----+------------+--------+-----------------+-----------------------------------------------------+

My "best language" is R, but my project's core language is Scala.  So I'm especially interested in solutions that could be reasonably implemented in R, Scala, or Java.  The original data come as tables but are transformed to RDF triples fairly early in my process, so maybe SWRL is relevant?  One of my collaborators has casually suggested PyCLIPS for this kind of problem, so maybe Jess or Drools are relevant?

What is my problem/task called?

Are there existing solutions for this, other than exhaustive pairwise comparison?

Am I going to have problems with transitivity because I have two (or more) rules, and one of them doesn't require identity?


问:
Android Studio: Boolean function crashes my app
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.

Code:
MainActivity.java

```<code>    package com.leuchtstein.flashlight;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView)   ;

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

 public void triggerlight(View view) {

 if (stat == false) {

    text.setText("ON");
    stat = true;

} else {

    text.setText("OFF");
    stat = false;

  }

  }

 }
</code>```

activity_main.xml

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

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="@string/desc_textview"
          android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
    app:layout_constraintHorizontal_bias="0.95"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="triggerlight"
    android:text="Turn on/off"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.387" />
</code>```

Well, thanks in advance.

答:
You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :

TextView text = (TextView) findViewById(R.id.textView);

Change your code to look like this :

```<code>public class MainActivity extends AppCompatActivity {

TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.textView)
}
</code>```

So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.

Body:
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.

Code:
MainActivity.java

    package com.leuchtstein.flashlight;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView)   ;

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

 public void triggerlight(View view) {

 if (stat == false) {

    text.setText("ON");
    stat = true;

} else {

    text.setText("OFF");
    stat = false;

  }

  }

 }

activity_main.xml

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

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="@string/desc_textview"
          android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
    app:layout_constraintHorizontal_bias="0.95"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="triggerlight"
    android:text="Turn on/off"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.387" />

Well, thanks in advance.

Body:
You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :

TextView text = (TextView) findViewById(R.id.textView);

Change your code to look like this :

public class MainActivity extends AppCompatActivity {

TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.textView)
}

So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.


问:
How to do music streaming
I want to develop a web application which gets media files from a streaming server and plays it on my website. How can I do this using ASP.NET?</p>

答:
Windows Media Services should be able to help you.

If it is just for hobby then make your music directory as Virtual Directory in your IIS and then enable permission for Directory Browsing. When user clicks on any song or playlist then Windows Media Player/Default Player of your machine should be able to play it automatically.

But if it is for some commercial reason then it would be better to look out for some sophisticated solution.

Title: How to do music streaming


问:
react native link using expo?
How can I use react-native link or How can I link a third party library manually in IOS and Android using exponent.

I was trying to link react-native-image-crop-picker but unable to use in exponent.

答:
You can't. It states this very clearly in the docs:

But no native modules…

The most limiting thing about Expo is that you can’t add in your own native modules without detaching and using ExpoKit. Continue reading the next question for a full explanation.

If you want to use anything that requires react-native link, then you need to detach your project and then develop it with or without ExpoKit. You will lose certain features and integrations (off the top of my head, I think Push Notifications via Expo is one of them) when doing so, but that is the trade-off Expo provides as an all-in-one package. When detaching, you lose those features.

Title: react native link using expo?

ContentLicense: CC BY-SA 4.0


问:
Target double quotes using regular expressions in Swift
I have been trying to extract a piece of text inside an string using regular expressions in Swift. The text I want to extract is inside double quotes so I'm trying to target those double quotes and get the piece of text inside.

This is the RegExp that I'm using: (?<=")(?:\\.|[^"\\])*(?=")

It work pretty well with any kind of text and it could be even simpler since I'm looking for anything that could be inside those double quotes.

When I try to use this RegExp with Swift I have to scape the double quotes in it, but for some reason the RegExp doesn't work with escaped double quotes e.g. (?<=\")(?:\\.|[^\"\\])*(?=\").

Even if I try some as simple as this \" the RegExp doesn't match any double quote in the string.

Code Example

```<code>func extractText(sentence: String?) -> String {
    let pattern = "(?<=\")(?:\\.|[^\"\\])*(?=\")"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "Text: \(source[range])"
    }

    return ""
}

extractText("Hello \"this is\" a test") -> "this is"
</code>```

To have in mind:

All these RegExps must be inside double quotes to create the string literal that is going to be used as a pattern.

I'm using the String's range method with the .regularExpression option to match the content.

I'm using Swift 4 with an Xcode 9 Playground

How can I scape double quotes in Swift to successfully match these in a string?

Solution

Thanks to @Atlas_Gondal and @vadian I noticed the problem "in part" is not the RegExp but the string I'm getting which is using a different type of double quotes “ ... ” so I have to change my pattern to something like this "(?<=“).*(?=”)" in order to use it.

The resulted code looks like this:

```<code>func extractText(sentence: String?) -> String {
    let pattern = "(?<=“).*(?=”)"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "\(source[range])"
    }

    return ""
}
</code>```

答:
range(of with regularExpression option can't do that because it's not able to capture groups.

You need real NSRegularExpression

```<code>func extractText(sentence: String) -> String {
    let pattern = "\"([^\"]+)\""
    let regex = try! NSRegularExpression(pattern: pattern)

    if let match = regex.firstMatch(in: sentence, range: NSRange(sentence.startIndex..., in: sentence)) {
        let range = Range(match.range(at: 1), in: sentence)!
        return String(sentence[range])
    }

    return ""
}

extractText(sentence:"Hello \"this is\" a test")
</code>```

The pattern is much simpler: Search for a double quote followed by one or more non-double-quote characters followed by a closing double quote. Capture the characters between the double quotes.

Note that escaped double quotes in a literal string are only virtually escaped.

PS: Your code doesn't compile without the parameter label in Swift 3 nor 4.

Body:
I have been trying to extract a piece of text inside an string using regular expressions in Swift. The text I want to extract is inside double quotes so I'm trying to target those double quotes and get the piece of text inside.

This is the RegExp that I'm using: (?<=")(?:\\.|[^"\\])*(?=")

It work pretty well with any kind of text and it could be even simpler since I'm looking for anything that could be inside those double quotes.

When I try to use this RegExp with Swift I have to scape the double quotes in it, but for some reason the RegExp doesn't work with escaped double quotes e.g. (?<=\")(?:\\.|[^\"\\])*(?=\").

Even if I try some as simple as this \" the RegExp doesn't match any double quote in the string.

Code Example

func extractText(sentence: String?) -> String {
    let pattern = "(?<=\")(?:\\.|[^\"\\])*(?=\")"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "Text: \(source[range])"
    }

    return ""
}

extractText("Hello \"this is\" a test") -> "this is"

To have in mind:

All these RegExps must be inside double quotes to create the string literal that is going to be used as a pattern.

I'm using the String's range method with the .regularExpression option to match the content.

I'm using Swift 4 with an Xcode 9 Playground

How can I scape double quotes in Swift to successfully match these in a string?

Solution

Thanks to @Atlas_Gondal and @vadian I noticed the problem "in part" is not the RegExp but the string I'm getting which is using a different type of double quotes “ ... ” so I have to change my pattern to something like this "(?<=“).*(?=”)" in order to use it.

The resulted code looks like this:

func extractText(sentence: String?) -> String {
    let pattern = "(?<=“).*(?=”)"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "\(source[range])"
    }

    return ""
}

Body:
range(of with regularExpression option can't do that because it's not able to capture groups.

You need real NSRegularExpression

func extractText(sentence: String) -> String {
    let pattern = "\"([^\"]+)\""
    let regex = try! NSRegularExpression(pattern: pattern)

    if let match = regex.firstMatch(in: sentence, range: NSRange(sentence.startIndex..., in: sentence)) {
        let range = Range(match.range(at: 1), in: sentence)!
        return String(sentence[range])
    }

    return ""
}

extractText(sentence:"Hello \"this is\" a test")

The pattern is much simpler: Search for a double quote followed by one or more non-double-quote characters followed by a closing double quote. Capture the characters between the double quotes.

Note that escaped double quotes in a literal string are only virtually escaped.

PS: Your code doesn't compile without the parameter label in Swift 3 nor 4.


问:
Oracle SQL WITH clause correct use case and performance
I have to perform relatively complicated query involving multiple deep joins and complex predicates, where the result (and criteria) depends of suitable entries available meeting the criteria. There are kinda primary and secondary criteria involved, primary is applied always, and secondary strikes in if the the result is not satisfying. In a nutshell

Return N (pseudo) random  distinct customers and their newest document

The result should contain equal amount of documents of two different type

But if there's not enough different document types or different customers with a document, try to still satisfy the amount of N documents

Compensate the lack of other document type by choosing more another

Compensate the lack of overall document count by using multiple documents of the same customers, when necessary

I choose declarative (query) approach over imperative (cursors and counters). And this is where the WITH clause comes in. Roughly, by using multiple WITH blocks (CTE's) I declare queries (I like to think them as ad-hoc views) to declare two distinct target set for both document types. In the end, I UNION subsets of different CTE's for the final result, performing some COUNT checks to limit the amount.

Multiple CTE's are referencing each other and are referenced from multiple places in the context of COUNT and NOT EXISTS for example. I'm novice with SQL and happened to encounter WITH by a coincidence, and chose to use it intuitively. Is this the correct use case for WITH, or an anti pattern? How does this solution compares in performance to implementing the same functionality with cursors and counters in an imperative style? Have I chosen the wrong approach? We are talking about tables with million entries.

Here is the the query as a whole. Pardon me, I had to obscure the fields due confidentiality.

```<code>    WITH target_documents AS (
        SELECT
            <Necessary fields>
        FROM documents l
        WHERE
            <Suitable document criteria>
    ),
    target_documents_type_1 AS (
        SELECT * FROM target_documents WHERE type = 1
    ),
    target_documents_type_2 AS (
        SELECT * FROM target_documents WHERE type = 2
    ),
    target_customers AS (
        SELECT
            <Necessary fields>
        FROM customers a
        WHERE
            <Suitable customer criteria>
            AND
            EXISTS(
                SELECT 1 FROM target_documents l WHERE l.customer_id = a.customer_id
            )
    ),
    target_customers_type_1 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_1 l WHERE l.customer_id = a.customer_id
        )
        AND ROWNUM <= (<N> / 2)
    ),
    target_customers_type_2 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_2 l WHERE l.customer_id = a.customer_id
        )
        AND a.customer_id NOT IN (
            SELECT customer_id FROM target_customers_type_1
        )
        AND ROWNUM <= <N>
    ),
    -- This is the set, which meets the the primary criteria:
    -- Contains only distinct customers
    -- The amount of different document types is balanced as much as possible
    different_customers_set AS (
        SELECT
            <Necessary fields>
        FROM target_customers_type_1 a -- rows 0--(<N>/2) amount
        JOIN target_documents_type_1 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_1 WHERE customer_id = l.customer_id)
        UNION ALL
        SELECT
            <Necessary fields>
        FROM target_customers_type_2 a -- rows 0--<N> amount
        JOIN target_documents_type_2 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_2 WHERE customer_id = l.customer_id) AND
            ROWNUM <= <N> - (SELECT COUNT(*) FROM target_customers_type_1) -- Limit the total to max N rows
    )

    -- Final result: primary criteria result filled with the result of secondary criteria
    SELECT * FROM different_customers_set
    UNION ALL
    SELECT
        <Necessary fields>
    FROM target_customers a
    JOIN target_documents l ON (l.customer_id = a.customer_id AND l.document_id NOT IN (SELECT document_id FROM different_customers_set))
    WHERE
        ROWNUM <= <N> - (SELECT COUNT(1) FROM different_customers_set);
</code>```

Is this the correct usage of WITH clause? Are there some obvious performance issues, where I should refactor? Or should I have done all this imperatively? Also, this query itself defines a cursor, which is used opened repeatedly in a loop (the loop defines certain criteria for customers).

I'm especially concerned, how the optimizer handles those WITH blocks. Is the most efficiently plan always used (so there's not performance penalty compared to using cursors)?

答:
Using multiple CTEs isn't inherently bad, and I do this from time to time to make for cleaner code. Here's my general approach for determining if a query meets my performance standards:

Write out a version of the query that you think will grab the data you want. It seems obvious, but make sure you're actually gathering all the data you meant to, with none of the data you don't want.

Run an Explain plan (F10 if using Oracle SQL Developer) to evaluate the cost before you run. I do this to make sure I haven't missed a critical join or index that would cause my query to run for an entire weekend and not return (speaking from experience; in my environment, cancelling a query in SQL Dev is just a suggestion and the database usually ignores the request).

If everything looks OK in the Explain plan, run the query with an Autotrace to evaluate its actual performance. The Explain is just a guess, and the Autotrace is far more accurate.

Compare execution plans with multiple versions of your query. Are you doing everything you can to extract that last bit of performance? Do you see any full table scans where it should be using an index? Do you have any nested loops that can be eliminated?

I rarely if ever across a situation where I think to myself "wow, this query would be way better off without CTEs", though I think the opposite nearly every day.

Body:
I have to perform relatively complicated query involving multiple deep joins and complex predicates, where the result (and criteria) depends of suitable entries available meeting the criteria. There are kinda primary and secondary criteria involved, primary is applied always, and secondary strikes in if the the result is not satisfying. In a nutshell

Return N (pseudo) random  distinct customers and their newest document

The result should contain equal amount of documents of two different type

But if there's not enough different document types or different customers with a document, try to still satisfy the amount of N documents

Compensate the lack of other document type by choosing more another

Compensate the lack of overall document count by using multiple documents of the same customers, when necessary

I choose declarative (query) approach over imperative (cursors and counters). And this is where the WITH clause comes in. Roughly, by using multiple WITH blocks (CTE's) I declare queries (I like to think them as ad-hoc views) to declare two distinct target set for both document types. In the end, I UNION subsets of different CTE's for the final result, performing some COUNT checks to limit the amount.

Multiple CTE's are referencing each other and are referenced from multiple places in the context of COUNT and NOT EXISTS for example. I'm novice with SQL and happened to encounter WITH by a coincidence, and chose to use it intuitively. Is this the correct use case for WITH, or an anti pattern? How does this solution compares in performance to implementing the same functionality with cursors and counters in an imperative style? Have I chosen the wrong approach? We are talking about tables with million entries.

Here is the the query as a whole. Pardon me, I had to obscure the fields due confidentiality.

    WITH target_documents AS (
        SELECT
            <Necessary fields>
        FROM documents l
        WHERE
            <Suitable document criteria>
    ),
    target_documents_type_1 AS (
        SELECT * FROM target_documents WHERE type = 1
    ),
    target_documents_type_2 AS (
        SELECT * FROM target_documents WHERE type = 2
    ),
    target_customers AS (
        SELECT
            <Necessary fields>
        FROM customers a
        WHERE
            <Suitable customer criteria>
            AND
            EXISTS(
                SELECT 1 FROM target_documents l WHERE l.customer_id = a.customer_id
            )
    ),
    target_customers_type_1 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_1 l WHERE l.customer_id = a.customer_id
        )
        AND ROWNUM <= (<N> / 2)
    ),
    target_customers_type_2 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_2 l WHERE l.customer_id = a.customer_id
        )
        AND a.customer_id NOT IN (
            SELECT customer_id FROM target_customers_type_1
        )
        AND ROWNUM <= <N>
    ),
    -- This is the set, which meets the the primary criteria:
    -- Contains only distinct customers
    -- The amount of different document types is balanced as much as possible
    different_customers_set AS (
        SELECT
            <Necessary fields>
        FROM target_customers_type_1 a -- rows 0--(<N>/2) amount
        JOIN target_documents_type_1 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_1 WHERE customer_id = l.customer_id)
        UNION ALL
        SELECT
            <Necessary fields>
        FROM target_customers_type_2 a -- rows 0--<N> amount
        JOIN target_documents_type_2 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_2 WHERE customer_id = l.customer_id) AND
            ROWNUM <= <N> - (SELECT COUNT(*) FROM target_customers_type_1) -- Limit the total to max N rows
    )

    -- Final result: primary criteria result filled with the result of secondary criteria
    SELECT * FROM different_customers_set
    UNION ALL
    SELECT
        <Necessary fields>
    FROM target_customers a
    JOIN target_documents l ON (l.customer_id = a.customer_id AND l.document_id NOT IN (SELECT document_id FROM different_customers_set))
    WHERE
        ROWNUM <= <N> - (SELECT COUNT(1) FROM different_customers_set);

Is this the correct usage of WITH clause? Are there some obvious performance issues, where I should refactor? Or should I have done all this imperatively? Also, this query itself defines a cursor, which is used opened repeatedly in a loop (the loop defines certain criteria for customers).

I'm especially concerned, how the optimizer handles those WITH blocks. Is the most efficiently plan always used (so there's not performance penalty compared to using cursors)?


问:
How to insert checkbox in excel using openpyxl python ?
How to insert checkbox in excel using openpyxl python ?
By using pywin32 we can do the same using following lines of codes </p>

```<code>cb = sheet.CheckBoxes().Add(Left=sheet.Cells(row,column).Left,
                            Top=sheet.Cells(row,column).Top,
                            Width=sheet.Cells(row,column).Width,
                            Height=sheet.Cells(row,column).Height)
cb.Caption = name_of_checkbox
</code>```

<p>but i want to do using openpyxl ? </p>

答:
To the best of my knowledge it's not possible to create new form controls such as checkboxes with openpyxl.

However openpyxl does allow you to load an existing excel file that already contains form controls, modify the data in the excel file, and then save the excel file with preservation of the form controls. For this to work you must use the method openpyxl.load_workbook() with parameter keep_vba=True to load the existing excel file (see here).

Body:
How to insert checkbox in excel using openpyxl python ?
By using pywin32 we can do the same using following lines of codes

cb = sheet.CheckBoxes().Add(Left=sheet.Cells(row,column).Left,
                            Top=sheet.Cells(row,column).Top,
                            Width=sheet.Cells(row,column).Width,
                            Height=sheet.Cells(row,column).Height)
cb.Caption = name_of_checkbox

but i want to do using openpyxl ?