问:
Build bazel-0.5.0rc9 fails on MIPS
Building bazel-0.5.0rc9 failed for BadExitStatusException: Process exited with status 50. Terminal output error as follow

```
ERROR: /home/xzy/bazel-0.5.0rc9/src/java_tools/singlejar/BUILD:77:1: error executing shell command: 'set -e;rm -rf bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output;mkdir bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/h...' failed: bash failed: error executing command
  (cd /tmp/bazel_Qvcl1sVW/out/execroot/bazel-0.5.0rc9 && \
  exec env - \
    PATH=/opt/j2sdk-image/bin:/usr/local/bin/:/opt/j2sdk-image/bin:/usr/local/bin/:/opt/j2sdk-image/bin:/usr/local/bin/:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/xzy/.local/bin:/home/xzy/bin \
  /bin/bash -c 'set -e;rm -rf bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output;mkdir bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/src/java_tools/singlejar/libbootstrap.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/src/java_tools/singlejar/libskylark-deps.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/auto/auto-common-0.3.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_annotation-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_annotations-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_check_api-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_core-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/guava/guava-21.0.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/jcip_annotations/jcip-annotations-1.0-1.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/jsr305/jsr-305.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/pcollections/pcollections-2.1.2.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/third_party/checker_framework_dataflow/libbootstrap.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/third_party/jformatstring/libbootstrap.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/src/main/java/com/google/devtools/build/lib/libshell-skylark.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
external/local_jdk/bin/jar cmf bazel-out/host/bin/src/java_tools/singlejar/bootstrap_MANIFEST.MF bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar -C bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output .
touch bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
'): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 50.
???????
ERROR: I/O error while writing action log: ???????.
Target //src:bazel failed to build
INFO: Elapsed time: 118.800s, Critical Path: 36.91s

$ java -version
openjdk version "1.8.0_25"
OpenJDK Runtime Environment (build 1.8.0_25-rc21-b17)
OpenJDK 64-Bit Server VM (build 25.25-b02, mixed mode)
$ uname -a
Linux localhost.localdomain 3.10.84 #1 SMP PREEMPT Wed Feb 8 16:03:10 CST 2017 mips64 mips64 mips64 GNU/Linux
```

答:
I get upwards error, because i add some print info at CrosstoolConfigurationLoader.java file for debug. Removing it can fix it.

```<code>...
String selectedIdentifier = null;
String desiredCpu = cpuTransformer.apply(config.getCpu());
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("desiredCpu="+desiredCpu);
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
for (CrosstoolConfig.DefaultCpuToolchain selector :
release.getDefaultToolchainList()) {
System.out.println("#########selector.getCpu()="+selector.getCpu());
if (selector.getCpu().equals(desiredCpu)) {
selectedIdentifier = selector.getToolchainIdentifier();
break;
}
...
</code>```

Error details see bazel#3017 and bazel#3068 , links see upwards comment

Build success patch infers build-bazel-mips64.patch

Title: Build bazel-0.5.0rc9 fails on MIPS

Body:
Building bazel-0.5.0rc9 failed for BadExitStatusException: Process exited with status 50. Terminal output error as follow

ERROR: /home/xzy/bazel-0.5.0rc9/src/java_tools/singlejar/BUILD:77:1: error executing shell command: 'set -e;rm -rf bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output;mkdir bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/h...' failed: bash failed: error executing command
  (cd /tmp/bazel_Qvcl1sVW/out/execroot/bazel-0.5.0rc9 && \
  exec env - \
    PATH=/opt/j2sdk-image/bin:/usr/local/bin/:/opt/j2sdk-image/bin:/usr/local/bin/:/opt/j2sdk-image/bin:/usr/local/bin/:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/xzy/.local/bin:/home/xzy/bin \
  /bin/bash -c 'set -e;rm -rf bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output;mkdir bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/src/java_tools/singlejar/libbootstrap.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/src/java_tools/singlejar/libskylark-deps.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/auto/auto-common-0.3.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_annotation-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_annotations-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_check_api-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/error_prone/error_prone_core-2.0.20-SNAPSHOT.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/guava/guava-21.0.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/jcip_annotations/jcip-annotations-1.0-1.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/jsr305/jsr-305.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn third_party/pcollections/pcollections-2.1.2.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/third_party/checker_framework_dataflow/libbootstrap.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/third_party/jformatstring/libbootstrap.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
unzip -qn bazel-out/host/bin/src/main/java/com/google/devtools/build/lib/libshell-skylark.jar -d bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
external/local_jdk/bin/jar cmf bazel-out/host/bin/src/java_tools/singlejar/bootstrap_MANIFEST.MF bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar -C bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output .
touch bazel-out/host/bin/src/java_tools/singlejar/bootstrap_deploy.jar.build_output
'): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 50.
???????
ERROR: I/O error while writing action log: ???????.
Target //src:bazel failed to build
INFO: Elapsed time: 118.800s, Critical Path: 36.91s

$ java -version
openjdk version "1.8.0_25"
OpenJDK Runtime Environment (build 1.8.0_25-rc21-b17)
OpenJDK 64-Bit Server VM (build 25.25-b02, mixed mode)
$ uname -a
Linux localhost.localdomain 3.10.84 #1 SMP PREEMPT Wed Feb 8 16:03:10 CST 2017 mips64 mips64 mips64 GNU/Linux

Body:
I get upwards error, because i add some print info at CrosstoolConfigurationLoader.java file for debug. Removing it can fix it.

...
String selectedIdentifier = null;
String desiredCpu = cpuTransformer.apply(config.getCpu());
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println("desiredCpu="+desiredCpu);
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
for (CrosstoolConfig.DefaultCpuToolchain selector :
release.getDefaultToolchainList()) {
System.out.println("#########selector.getCpu()="+selector.getCpu());
if (selector.getCpu().equals(desiredCpu)) {
selectedIdentifier = selector.getToolchainIdentifier();
break;
}
...

Error details see bazel#3017 and bazel#3068 , links see upwards comment

Build success patch infers build-bazel-mips64.patch


来源: stackexchange

问:
why Isn't my form working
I'm trying to use a listbox form to query the database but it's not showing anything. The idea is that I've queried the database to fill the form with the names of suburbs and then, selecting a suburb will query the database again to return the names of parks in that suburb. When I use the search form it doesn't return anything.

this is the form:

```<code><p>Select Suburb to search</p>
    <form method="post" action="suburb_search.php" id="search">
    <select>
    <?php while ($row = $result->fetch_assoc()) { ?>
    <option value="suburb"> <?php echo $row['suburb']?></option>
    <?php }
     } ?>
    </select>
    <input type="submit" name="search" value="Search" />
    </form>
    </div>
</code>```

This is where it should use the results of the form to query the database but its not working:

```<code> <?php
 $searchRequest = False;
if (isset($_GET['suburb'])){
    $search = $_GET['suburb'];
    $sql2 = "SELECT * FROM park_list WHERE suburb=$search";
    $result2 = $db->query($sql2);
if($message){
    echo "<p>$message</>";
} else {
    ?>
    <div class="form">
    <?php
        while ($row2 = $result2->fetch_assoc()){
    ?>
    <div class="results">
    <h2><?php echo $row2['park_name'];?></h2>
        <?php
    }
    }
   } ?>
</code>```

答:
give a name for your select element as

```<code><select name="suburb">
    <?php while ($row = $result->fetch_assoc()) { ?>
        <option value="suburb"> <?php echo $row['suburb']?></option>
    <?php }
    } ?>
</select>
</code>```

and you are giving form method as POST but accepting data in GET in your php code, change this

```<code>if (isset($_GET['suburb'])){
</code>```

to

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

ContentLicense: CC BY-SA 3.0

Title: why Isn't my form working

Body:
I'm trying to use a listbox form to query the database but it's not showing anything. The idea is that I've queried the database to fill the form with the names of suburbs and then, selecting a suburb will query the database again to return the names of parks in that suburb. When I use the search form it doesn't return anything.

this is the form:

Select Suburb to search

    <form method="post" action="suburb_search.php" id="search">
    <select>
    <?php while ($row = $result->fetch_assoc()) { ?>
    <option value="suburb"> <?php echo $row['suburb']?></option>
    <?php }
     } ?>
    </select>
    <input type="submit" name="search" value="Search" />
    </form>

This is where it should use the results of the form to query the database but its not working:

 <?php
 $searchRequest = False;
if (isset($_GET['suburb'])){
    $search = $_GET['suburb'];
    $sql2 = "SELECT * FROM park_list WHERE suburb=$search";
    $result2 = $db->query($sql2);
if($message){
    echo "
$message</>";
} else {
    ?>

    <?php
        while ($row2 = $result2->fetch_assoc()){
    ?>

<?php echo $row2['park_name'];?>

        <?php
    }
    }
   } ?>

Body:
give a name for your select element as

<select name="suburb">
    <?php while ($row = $result->fetch_assoc()) { ?>
        <option value="suburb"> <?php echo $row['suburb']?></option>
    <?php }
    } ?>
</select>

and you are giving form method as POST but accepting data in GET in your php code, change this

if (isset($_GET['suburb'])){

to

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


问:
How to get the selected row item in XamDatagrid
Below is my xaml

```<code><Grid>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<ListBox x:Name="movieList" ItemsSource="{Binding Path=MovieMain.Movies}" Margin="10">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<StackPanel Grid.Column="1" Margin="10">
<StackPanel Orientation="Horizontal">
<Label Content="Selected movie: " Margin="2" />
<Label Content="{Binding Path=SelectedItem.Name, ElementName=movieList}" />
</StackPanel>

<igDP:XamDataGrid x:Name="dataGrid" DataSource="{Binding Path=SelectedItem.Artists, ElementName=movieList}">

<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>

<igDP:ComboBoxField Name="Name">
<igDP:ComboBoxField.EditorStyle>
<Style TargetType="igEditors:XamComboEditor">
<Setter Property="ItemsSource"
Value="{Binding Path=DataContext.ComboItems, RelativeSource={RelativeSource AncestorType={x:Type igDP:XamDataGrid}}}" />
</Style>
</igDP:ComboBoxField.EditorStyle>
</igDP:ComboBoxField>

<igDP:NumericField Name="Age" />

</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>

</igDP:XamDataGrid>
</StackPanel>

<Button Grid.Row="1" Grid.Column="0" Width="55" Height="25" Command="{Binding ClickCommand}"/>

</Grid>
</code>```

In above I bind Listbox with one model and based on selected item I am binding datagrid.

Now I am doing delete operation on datagrid. So how can I achieve the delete functionality?

I created a button for deleteing records. Can we pass command parameter for sleeted row?

答:
Try this:</p>

```<code><Button ... Command="{Binding ClickCommand}"
            CommandParameter="{Binding SelectedDataItems[0], ElementName=dataGrid}" />
</code>```

Body:
Below is my xaml

<Grid>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<ListBox x:Name="movieList" ItemsSource="{Binding Path=MovieMain.Movies}" Margin="10">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<StackPanel Grid.Column="1" Margin="10">
<StackPanel Orientation="Horizontal">

</StackPanel>

<igDP:XamDataGrid x:Name="dataGrid" DataSource="{Binding Path=SelectedItem.Artists, ElementName=movieList}">

<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>

<igDP:ComboBoxField Name="Name">
<igDP:ComboBoxField.EditorStyle>

</igDP:ComboBoxField.EditorStyle>
</igDP:ComboBoxField>

<igDP:NumericField Name="Age" />

</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>

</igDP:XamDataGrid>
</StackPanel>

<Button Grid.Row="1" Grid.Column="0" Width="55" Height="25" Command="{Binding ClickCommand}"/>

</Grid>

In above I bind Listbox with one model and based on selected item I am binding datagrid.

Now I am doing delete operation on datagrid. So how can I achieve the delete functionality?

I created a button for deleteing records. Can we pass command parameter for sleeted row?

Body:
Try this:

<Button ... Command="{Binding ClickCommand}"
            CommandParameter="{Binding SelectedDataItems[0], ElementName=dataGrid}" />


问:
Android new Intent with back button
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

```<code>void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}
</code>```

The ServiceActivity is just an Empty Activity

```<code>    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>
</code>```

答:
In the second activity ..make your activity extend AppCompactActivity

and in onCreate add

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
</code>```

and override the onOptionsItemSelected in activity as

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
    }
    return super.onOptionsItemSelected(item);
}
</code>```

Title: Android new Intent with back button

Body:
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}

The ServiceActivity is just an Empty Activity

    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>

Body:
In the second activity ..make your activity extend AppCompactActivity

and in onCreate add

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

and override the onOptionsItemSelected in activity as

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
    }
    return super.onOptionsItemSelected(item);
}

ContentLicense: CC BY-SA 4.0


问:
Memory error using cv.fit_transform(corpus).toarray()
I would be grateful if anyone can help with cv.fit_transform(corpus).toarray() for handling a corpus of size approx 732066 x <140 (tweets). The text has been cleaned to reduce the features and dimensionality but I keep getting the error below

Here's how I started

```<code># Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
cols = ["text","geocoordinates0","geocoordinates1","grid"]
dataset = pd.read_csv('tweets.tsv', delimiter = '\t', usecols=cols, quoting = 3, error_bad_lines=False, low_memory=False)

# Removing Non-ASCII characters
def remove_non_ascii_1(dataset):
    return ''.join([i if ord(i) < 128 else ' ' for i in dataset])

# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 732066):
    review = re.sub('[^a-zA-Z]', ' ', str(dataset['text'][i]))
    review = review.lower()
    review = review.split()
    ps = PorterStemmer()
    review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
    review = ' '.join(review)
    corpus.append(review)

# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()
</code>```

And here's the output error gotten below:

X = cv.fit_transform(corpus).toarray() Traceback (most recent call
  last):

File "", line 1, in
      X = cv.fit_transform(corpus).toarray()

File
  "C:\Anaconda3\envs\py35\lib\site-packages\scipy\sparse\compressed.py",
  line 920, in toarray
      return self.tocoo(copy=False).toarray(order=order, out=out)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\scipy\sparse\coo.py",
  line 252, in toarray
      B = self._process_toarray_args(order, out)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\scipy\sparse\base.py",
  line 1009, in _process_toarray_args
      return np.zeros(self.shape, dtype=self.dtype, order=order)

MemoryError

Many Thanks ahead!

PS: After removing the arraylist and using MultinomiaNB as advised by @Kumar I now have the following error:

```<code>from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)
</code>```

Traceback (most recent call last):

File "", line 1, in
      classifier.fit(X_train, y_train)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\naive_bayes.py",
  line 566, in fit
      Y = labelbin.fit_transform(y)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\base.py",
  line 494, in fit_transform
      return self.fit(X, **fit_params).transform(X)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\preprocessing\label.py",
  line 296, in fit
      self.y_type_ = type_of_target(y)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\utils\multiclass.py",
  line 275, in type_of_target
      if (len(np.unique(y)) > 2) or (y.ndim >= 2 and len(y[0]) > 1):

File
  "C:\Anaconda3\envs\py35\lib\site-packages\numpy\lib\arraysetops.py",
  line 198, in unique
      ar.sort()

TypeError: unorderable types: str() > float()

答:
All I was saying was, remove .toarray() and replace GaussianNB with MultinomialNB.

```<code>....
....
# Other code
....
....

X = cv.fit_transform(corpus)
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

....
....
# Other code
</code>```

Body:
I would be grateful if anyone can help with cv.fit_transform(corpus).toarray() for handling a corpus of size approx 732066 x <140 (tweets). The text has been cleaned to reduce the features and dimensionality but I keep getting the error below

Here's how I started

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
cols = ["text","geocoordinates0","geocoordinates1","grid"]
dataset = pd.read_csv('tweets.tsv', delimiter = '\t', usecols=cols, quoting = 3, error_bad_lines=False, low_memory=False)

# Removing Non-ASCII characters
def remove_non_ascii_1(dataset):
    return ''.join([i if ord(i) < 128 else ' ' for i in dataset])

# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 732066):
    review = re.sub('[^a-zA-Z]', ' ', str(dataset['text'][i]))
    review = review.lower()
    review = review.split()
    ps = PorterStemmer()
    review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
    review = ' '.join(review)
    corpus.append(review)

# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()

And here's the output error gotten below:

X = cv.fit_transform(corpus).toarray() Traceback (most recent call
  last):

File "", line 1, in
      X = cv.fit_transform(corpus).toarray()

File
  "C:\Anaconda3\envs\py35\lib\site-packages\scipy\sparse\compressed.py",
  line 920, in toarray
      return self.tocoo(copy=False).toarray(order=order, out=out)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\scipy\sparse\coo.py",
  line 252, in toarray
      B = self._process_toarray_args(order, out)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\scipy\sparse\base.py",
  line 1009, in _process_toarray_args
      return np.zeros(self.shape, dtype=self.dtype, order=order)

MemoryError

Many Thanks ahead!

PS: After removing the arraylist and using MultinomiaNB as advised by @Kumar I now have the following error:

from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)

Traceback (most recent call last):

File "", line 1, in
      classifier.fit(X_train, y_train)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\naive_bayes.py",
  line 566, in fit
      Y = labelbin.fit_transform(y)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\base.py",
  line 494, in fit_transform
      return self.fit(X, **fit_params).transform(X)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\preprocessing\label.py",
  line 296, in fit
      self.y_type_ = type_of_target(y)

File
  "C:\Anaconda3\envs\py35\lib\site-packages\sklearn\utils\multiclass.py",
  line 275, in type_of_target
      if (len(np.unique(y)) > 2) or (y.ndim >= 2 and len(y[0]) > 1):

File
  "C:\Anaconda3\envs\py35\lib\site-packages\numpy\lib\arraysetops.py",
  line 198, in unique
      ar.sort()

TypeError: unorderable types: str() > float()

Body:
All I was saying was, remove .toarray() and replace GaussianNB with MultinomialNB.

....
....
# Other code
....
....

X = cv.fit_transform(corpus)
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

....
....
# Other code


问:
C# - Insert XML Element from String template
I have a xml with the given structure:

```<code><ArrayOfElement>
    <Element>
        <ID>1</ID>
        <Value>Value1</Value>
    </Element>
    <Element>
        <ID>2</ID>
        <Value>Value2</Value>
    </Element>
    <Element>
        <ID>3</ID>
        <Value>Value3</Value>
    </Element>
    ...
</ArrayOfElement>
</code>```

And I want to insert another Element with this template (but only if no element with the given ID exists):

```<code><Element>
    <ID>$ID$</ID>
    <Value>$VALUE$</Value>
</Element>
</code>```

So my idea was to load the template as string and replace $ID$ and $VALUE$ by whatever is given. Then I parse this string as a XmlDocumentFragment. And then I need to see if an element with this ID is already present and only if none is there I want to insert the new one.

But I don't know how to find if one exists.

My current approach is:

```<code>// Load the XML with the ArrayOfElement
var allElements = new XmlDocument();
allElements.Load("file.xml");

// Load the template and insert id and value
var xmlTemplate = File.ReadAllText("template.xml");
var fragment = allElements.CreateDocumentFragment();
fragment.InnerXml = xmlTemplate.Replace("$ID$", _id).Replace("$VALUE$", _value);

// This does not work since it will throw an exception if none is found:
if (allElements.SelectNodes("ArrayOfElement/Element/ID/text() = '" + _id + "'").Count == 0)
{
    allElements.appendChild(fragment);
}
</code>```

Also I really want to use a template file because I actually have more complex scenarios where adding these XML-Tags in C# without a template string would be way to much work.

答:
you can achieve this with the help of XMLSerialization and Deserialization,

```<code>public class SerializeDeserialize
    {
        [XmlRoot(ElementName = "ArraofElements")]
        public class ArraofElements
        {
            private List<Element> elm = new List<Element>();

            [XmlElement("Module")]
            public List<Element> Elm
            {
                get { return elm; }
                set { elm = value; }
            }
        }

        public class Element
        {
            [XmlElement("ID")]
            public int id { get; set; }

            [XmlElement("Value")]
            public string value { get; set; }
        }

        ArraofElements dnl = new ArraofElements();

        public void Serialize(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                var temp = dnl.Elm.FirstOrDefault(x => x.id == i);
                if (temp == null)
                    temp = new Element();

                temp.id = i;
                temp.value = "Element " + i;

                dnl.Elm.Add(temp);
            }

            try
            {
                // to Save columnorders to the file
                var serializer = new XmlSerializer(typeof(ArraofElements));
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                using (TextWriter writer = new StreamWriter(@"your path"))
                {
                    serializer.Serialize(writer, dnl, ns);
                }

            }
            catch { }
        }

        public void Deserialize(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(@"your path"))
                {

                    var deserializer = new XmlSerializer(typeof(ArraofElements));
                    using (TextReader reader = new StreamReader(@"your path"))
                    {
                        dnl = (ArraofElements)deserializer.Deserialize(reader);
                    }

                }
            }
            catch
            {
            }
        }
    }
</code>```

this will work as you expected, try this

Body:
I have a xml with the given structure:

<ArrayOfElement>
    <Element>
        <ID>1</ID>
        <Value>Value1</Value>
    </Element>
    <Element>
        <ID>2</ID>
        <Value>Value2</Value>
    </Element>
    <Element>
        <ID>3</ID>
        <Value>Value3</Value>
    </Element>
    ...
</ArrayOfElement>

And I want to insert another Element with this template (but only if no element with the given ID exists):

<Element>
    <ID>$ID$</ID>
    <Value>$VALUE$</Value>
</Element>

So my idea was to load the template as string and replace $ID$ and $VALUE$ by whatever is given. Then I parse this string as a XmlDocumentFragment. And then I need to see if an element with this ID is already present and only if none is there I want to insert the new one.

But I don't know how to find if one exists.

My current approach is:

// Load the XML with the ArrayOfElement
var allElements = new XmlDocument();
allElements.Load("file.xml");

// Load the template and insert id and value
var xmlTemplate = File.ReadAllText("template.xml");
var fragment = allElements.CreateDocumentFragment();
fragment.InnerXml = xmlTemplate.Replace("$ID$", _id).Replace("$VALUE$", _value);

// This does not work since it will throw an exception if none is found:
if (allElements.SelectNodes("ArrayOfElement/Element/ID/text() = '" + _id + "'").Count == 0)
{
    allElements.appendChild(fragment);
}

Also I really want to use a template file because I actually have more complex scenarios where adding these XML-Tags in C# without a template string would be way to much work.

Body:
you can achieve this with the help of XMLSerialization and Deserialization,

public class SerializeDeserialize
    {
        [XmlRoot(ElementName = "ArraofElements")]
        public class ArraofElements
        {
            private List<Element> elm = new List<Element>();

            [XmlElement("Module")]
            public List<Element> Elm
            {
                get { return elm; }
                set { elm = value; }
            }
        }

        public class Element
        {
            [XmlElement("ID")]
            public int id { get; set; }

            [XmlElement("Value")]
            public string value { get; set; }
        }

        ArraofElements dnl = new ArraofElements();

        public void Serialize(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                var temp = dnl.Elm.FirstOrDefault(x => x.id == i);
                if (temp == null)
                    temp = new Element();

                temp.id = i;
                temp.value = "Element " + i;

                dnl.Elm.Add(temp);
            }

            try
            {
                // to Save columnorders to the file
                var serializer = new XmlSerializer(typeof(ArraofElements));
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                using (TextWriter writer = new StreamWriter(@"your path"))
                {
                    serializer.Serialize(writer, dnl, ns);
                }

            }
            catch { }
        }

        public void Deserialize(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(@"your path"))
                {

                    var deserializer = new XmlSerializer(typeof(ArraofElements));
                    using (TextReader reader = new StreamReader(@"your path"))
                    {
                        dnl = (ArraofElements)deserializer.Deserialize(reader);
                    }

                }
            }
            catch
            {
            }
        }
    }

this will work as you expected, try this


问:
Completely copying a postgres table with SQL
DISCLAIMER: This question is similar to the stack overflow question here, but none of those answers work for my problem, as I will explain later.

I'm trying to copy a large table (~40M rows, 100+ columns) in postgres where a lot of the columns are indexed. Currently I use this bit of SQL:

```<code>CREATE TABLE <tablename>_copy (LIKE <tablename> INCLUDING ALL);
INSERT INTO <tablename>_copy SELECT * FROM <tablename>;
</code>```

This method has two issues:

It adds the indices before data ingest, so it will take much longer than creating the table without indices and then indexing after copying all of the data.

This doesn't copy `SERIAL' style columns properly. Instead of setting up a new 'counter' on the the new table, it sets the default value of the column in the new table to the counter of the past table, meaning it won't increment as rows are added.

The table size makes indexing a real time issue. It also makes it infeasible to dump to a file to then re-ingest. I also don't have the advantage of a command line. I need to do this in SQL.

What I'd like to do is either straight make an exact copy with some miracle command, or if that's not possible, to copy the table with all contraints but without indices, and make sure they're the constraints 'in spirit' (aka a new counter for a SERIAL column). Then copy all of the data with a SELECT * and then copy over all of the indices.

Sources

Stack Overflow question about database copying: This isn't what I'm asking for for three reasons

It uses the command line option pg_dump -t x2 | sed 's/x2/x3/g' | psql and in this setting I don't have access to the command line

It creates the indices pre data ingest, which is slow

It doesn't update the serial columns correctly as evidence by default nextval('x1_id_seq'::regclass)

Method to reset the sequence value for a postgres table: This is great, but unfortunately it is very manual.

答:
```<code>create table newTableName (like   oldTableName including indexes);
insert into newTableName  select * from oldTableName
</code>```

This worked for me 9.3

Body:
DISCLAIMER: This question is similar to the stack overflow question here, but none of those answers work for my problem, as I will explain later.

I'm trying to copy a large table (~40M rows, 100+ columns) in postgres where a lot of the columns are indexed. Currently I use this bit of SQL:

CREATE TABLE <tablename>_copy (LIKE <tablename> INCLUDING ALL);
INSERT INTO <tablename>_copy SELECT * FROM <tablename>;

This method has two issues:

It adds the indices before data ingest, so it will take much longer than creating the table without indices and then indexing after copying all of the data.

This doesn't copy `SERIAL' style columns properly. Instead of setting up a new 'counter' on the the new table, it sets the default value of the column in the new table to the counter of the past table, meaning it won't increment as rows are added.

The table size makes indexing a real time issue. It also makes it infeasible to dump to a file to then re-ingest. I also don't have the advantage of a command line. I need to do this in SQL.

What I'd like to do is either straight make an exact copy with some miracle command, or if that's not possible, to copy the table with all contraints but without indices, and make sure they're the constraints 'in spirit' (aka a new counter for a SERIAL column). Then copy all of the data with a SELECT * and then copy over all of the indices.

Sources

Stack Overflow question about database copying: This isn't what I'm asking for for three reasons

It uses the command line option pg_dump -t x2 | sed 's/x2/x3/g' | psql and in this setting I don't have access to the command line

It creates the indices pre data ingest, which is slow

It doesn't update the serial columns correctly as evidence by default nextval('x1_id_seq'::regclass)

Method to reset the sequence value for a postgres table: This is great, but unfortunately it is very manual.

Body:
create table newTableName (like   oldTableName including indexes);
insert into newTableName  select * from oldTableName

This worked for me 9.3


问:
"[ERROR] Sorry! The --v1 and --v2 flags have been removed."
Having this error and have not been able to resolve it after so many trials
i have reinstalled the ionic cordova but still get this error when i want to use angular 2 (ionic start boxapp tabs --v2) [ERROR] Sorry! The --v1 and --v2 flags have been removed.
but it works when i use --v but not --v2</p>

答:
On the console (cmd):

npm install -g cordova ionic

ionic start myApp tabs

For v1 projects, use the --type ionic1 flag:

```<code>ionic start myApp tabs --type ionic1
</code>```

Body:
On the console (cmd):

npm install -g cordova ionic

ionic start myApp tabs

For v1 projects, use the --type ionic1 flag:

ionic start myApp tabs --type ionic1


问:
Sharepoint 2013 Permissions: Everyone cannot read jquery lib?
I have a site where I use jquery and custom scripts (stored in Site Assets).
For me as a member of the "Designer" and "Owner" group, everything works perfectly.

However, other ("normal") users get errors like "$" is undefined. I guess, the jquery library is not being loaded?

I tried to add Everyone and also NT AUTHORITY\authenticated users to the Visitors group. But this doesn't help.

The inheritance is not broken, all the site uses the same permissions for all pages/libraries etc.

How can I set the permisssions so that everyone can "see" the pages including the scripts as I do?

edit:
I have no option to "publish" the jquery file. When I check-out and check-in again, there is no effect.
Also, the script path is correct.

答:
I found the cause:

All the permissions were correct. Also Check Permissions for Everyone was showing the correct entries.

The solution was that the Master Page had been customized and had to be published as a Major Version!
Otherwise, "normal" users were shown an older version of the customized master page where jquery was not included yet.


问:
Is it a good idea to use static variables in Asp.Net MVC?
I have Asp.net mvc application and I need global counter for some purpose for all users(and guests). I mean any user can change it(sometimes from different threads), but this counter is common for all of them.
So,

1. is it good idea to create just static variable somewhere in my code for this ?

2. Are there possible problems?

Any other suggestions? Thanks a lot!

答:
Its tricky to say anything here. Static in itself do not have problem. It depends on how you are using it. As you said you are putting some global counter in variable. So multiple threads will modify it; right? Make sure this call is thread-safe. Otherwise the counters will be wrong.

If this was some rarely written and mostly read-only value, it was not an issue at all.

If this is a value known to you at design time, better you use const.

You should also consider IIS recycles application pool. In that case, new Application instance will be created and two copies of your static variable will exist.

If this all does not create problem for you then static is ok.


问:
adding List of objects to Context in ef
Is it possible to add list of object to Context in entity framework without using foreach addObject ?

thanks for help

答:
Generally you can't do that - you have to do it in a loop. In some cases, however, you can avoid adding every object - specifically, if you have an entity graph and you add the parent node. E.g. if you have a Company object that has a collection of Employees:

```<code>context.AddToCompanies(company);

/* The following loop is not necessary */
/* The employees will be saved together with the company */
/*
foreach (var employee in company.Employees)
{
    context.AddToEmployees(employee);
}*/

context.SaveChanges();
</code>```

ContentLicense: CC BY-SA 2.5

Title: adding List of objects to Context in ef

Body:
Generally you can't do that - you have to do it in a loop. In some cases, however, you can avoid adding every object - specifically, if you have an entity graph and you add the parent node. E.g. if you have a Company object that has a collection of Employees:

context.AddToCompanies(company);

/* The following loop is not necessary */
/* The employees will be saved together with the company */
/*
foreach (var employee in company.Employees)
{
    context.AddToEmployees(employee);
}*/

context.SaveChanges();


问:
Cordova speech recognition plugin "Invalid action"
I'm trying to use this plugin: https://github.com/pbakondy/cordova-plugin-speechrecognition

All set-up ok, but when I call isRecognitionAvailable(), I'm getting a promise rejection with the error msg: 'Invalid action'.

I've checked all the permissions and minSDKVersion are correct in the generated AndroidManifest.xml and all that stuff.

Note: I'm on Wifi.

Here's my code:

```<code>let options = {
  language: 'en-US',
  matches: 1,
  prompt: '',
  showPopup: false,
  showPartial: false
}
this.speechRecognition.startListening(options).subscribe(
    (matches: Array<string>) => {
      // matches arrive here....
    },
    (onerror) => {
      alert(JSON.stringify(onerror));
    }
);
</code>```

Manifest:

```<code><?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="cordova.plugins.Diagnostic$LocationProviderChangedReceiver">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />
            </intent-filter>
        </receiver>
        <receiver android:name="cordova.plugins.Diagnostic$NFCStateChangedReceiver">
            <intent-filter>
                <action android:name="android.nfc.action.ADAPTER_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="25" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
</code>```

Thanks.

答: Removing and re-adding the android platform fixed this issue, now I have another which is different.</p>

Body:
I'm trying to use this plugin: https://github.com/pbakondy/cordova-plugin-speechrecognition

All set-up ok, but when I call isRecognitionAvailable(), I'm getting a promise rejection with the error msg: 'Invalid action'.

I've checked all the permissions and minSDKVersion are correct in the generated AndroidManifest.xml and all that stuff.

Note: I'm on Wifi.

Here's my code:

let options = {
  language: 'en-US',
  matches: 1,
  prompt: '',
  showPopup: false,
  showPartial: false
}
this.speechRecognition.startListening(options).subscribe(
    (matches: Array<string>) => {
      // matches arrive here....
    },
    (onerror) => {
      alert(JSON.stringify(onerror));
    }
);

Manifest:

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="cordova.plugins.Diagnostic$LocationProviderChangedReceiver">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />
            </intent-filter>
        </receiver>
        <receiver android:name="cordova.plugins.Diagnostic$NFCStateChangedReceiver">
            <intent-filter>
                <action android:name="android.nfc.action.ADAPTER_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="25" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

Thanks.


问:
How can I declare an empty variable?
Here's my code:

```<code>private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }
</code>```

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

答:
try something like this: </p>

```<code>var game = (Object)null;
</code>```

Title: How can I declare an empty variable?

Body:
Here's my code:

private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

Body:
try something like this:

var game = (Object)null;


问:
angular js ui grid memory leak issue
I am working on an application that uses angular js UI grid. But as and when I keep using my application, it keeps adding up to the memory without releasing the dom objects.

I have created a sample application where I am able to recreate the same issue of memory leak. I have kept a button("Open slider") in one div, on click of which I am dynamically loading another div that contains UI grid with some data. There is another button("Close Slider") in the other div, on click of which I am able to hide the UI grid.

Following are the screen shots which we observed while investigating the issue on IE browser:

Screen shot showing memory usage when I click on Open slider button to show up the UI grid

Screen show showing no memory released when I click on Close slider button to hide UI grid

So, as you can see in image 2, that when I close the UI grid div, memory is not being released (as shown in developer options > memory tab). So, Is there any way to release the memory once I unload the UI grid or any other way to remove the de-attached dom objects?

You can find the plunker of above application in the comments section.

答:
The best way to handle memory management in angular js is to make use of  “Controller as” syntax.

Using alias for controllers releases DOM elements from the memory once the controller is unloaded.

Title: angular js ui grid memory leak issue


问:
How do I make a different icon name for the home screen and the App Store?
How do I make a different icon name for the home screen and the App Store in iPhone?</p>

答: I guess then that the answer your are looking for is that the icon shown in the app store is uploaded at the time you submit the app in iTunes Connect. It can then obviously be a different file but we recommend you to pass on a picture very close to what th app icon is otherwise your app could be rejected.</p>


问:
How to design a model to allow apply or cancel updates?
Is there a design or development pattern where we deal with making updates to a copy of the actual data and applying the diff to the original reference if needed?

If not, what is the best way of designing such models?

What I think I should do:

I should probably use an enum mode to indicate whether the model is being used in 'Update direct reference mode' OR 'Update only a copy mode'

Update the setters and getters of data to reference the actualState or the temporaryState as per what mode is the model being used in.

Have the setter method for mode to create a copy of the actual data and store it in a temporary state. If the mode is updated to update direct reference, clear out the temporaryState

Create a method for applying the changes from temporaryState to the actualState. This method shall also clear out the temporary state from memory.

In code:

```<code>enum InsertionMode {
    UPDATE_DIRECT, UPDATE_COPY
}

class Store {
  private Data actualState;
  private Data temporaryState;
  private InsertionMode mode;

  private void resetTemporaryState() {
    ....
  }

  private void initTemporaryState() {
    this.temporaryState = copy(actualState);
  }

  private commitTemporaryState() {
    this.actualState = this.temporaryState;
    this.resetTemporaryState();
  }

  public Data setInsertionMode(InsertionMode mode) {
    if (this.mode != mode) {
        InsertionMode previousMode = this.mode;
        this.mode = mode;

        if (previousMode == InsertionMode.UPDATE_COPY) {
            this.resetTemporaryState();
        }
        if (this.mode == InsertionMode.UPDATE_COPY) {
            this.initTemporaryState();
        }
    }
  }

  public void commit() {
    if (this.mode == InsertionMode.UPDATE_COPY) {
        this.commitTemporaryState();
    }
  }

  public void abort() {
    if (this.mode == InsertionMode.UPDATE_COPY) {
        this.resetTemporaryState();
        this.setInsertionMode(InsertionMode.UPDATE_DIRECT);
    }
  }
  ...
}
</code>```

答:
The given code is "okay", as it will support your requirements.

But: updating objects is a simple approach, and is easy to implement. But depending on your context, you do things really differently in 2017.

Instead of having one mutable object that changes state, you could instead go for immutable objects. State becomes a sequence of such objects.

Reaching a new state means adding a newly created object at the end of the sequence, cancel means to go with the old, unchanged sequence. This approach is the base for blockchain applications; but it can be scaled down to a smaller context as well - just by looking at its core aspect: you never change state by changing existing objects, but by creating new objects. Of course, this needs a lot of thought; you don't want to blindly duplicate everything; you might more be looking having "delta" objects (that represent individual changes) and "views" that show aggregations of deltas.

Beyond that: you might want to read about CQRS versus CRUD (for example this).

Body:
Is there a design or development pattern where we deal with making updates to a copy of the actual data and applying the diff to the original reference if needed?

If not, what is the best way of designing such models?

What I think I should do:

I should probably use an enum mode to indicate whether the model is being used in 'Update direct reference mode' OR 'Update only a copy mode'

Update the setters and getters of data to reference the actualState or the temporaryState as per what mode is the model being used in.

Have the setter method for mode to create a copy of the actual data and store it in a temporary state. If the mode is updated to update direct reference, clear out the temporaryState

Create a method for applying the changes from temporaryState to the actualState. This method shall also clear out the temporary state from memory.

In code:

enum InsertionMode {
    UPDATE_DIRECT, UPDATE_COPY
}

class Store {
  private Data actualState;
  private Data temporaryState;
  private InsertionMode mode;

  private void resetTemporaryState() {
    ....
  }

  private void initTemporaryState() {
    this.temporaryState = copy(actualState);
  }

  private commitTemporaryState() {
    this.actualState = this.temporaryState;
    this.resetTemporaryState();
  }

  public Data setInsertionMode(InsertionMode mode) {
    if (this.mode != mode) {
        InsertionMode previousMode = this.mode;
        this.mode = mode;

        if (previousMode == InsertionMode.UPDATE_COPY) {
            this.resetTemporaryState();
        }
        if (this.mode == InsertionMode.UPDATE_COPY) {
            this.initTemporaryState();
        }
    }
  }

  public void commit() {
    if (this.mode == InsertionMode.UPDATE_COPY) {
        this.commitTemporaryState();
    }
  }

  public void abort() {
    if (this.mode == InsertionMode.UPDATE_COPY) {
        this.resetTemporaryState();
        this.setInsertionMode(InsertionMode.UPDATE_DIRECT);
    }
  }
  ...
}


答:
You should declare variable before try-catch block, otherwise it will not be visible outside the try-catch block:

```<code>TypeOfGame game = null; // declare local variable here
// note that you should provide initial value as well

try
{
   // assigne it here
   game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
}
catch (RiotSharpException ex)
{
    // I hope you have some real code here
    throw;
}

// now you can use it
foreach(var player in game.Participants)
{

}
</code>```

Note that your current try-catch block don't catch anything except RiotSharpException and even for that type of exceptions you simply rethrow it. So nothing will change if you'll remove try-catch completely here

```<code>var api = RiotApi.GetInstance("KEY");
// if api can be null, then you can use null-propagation operation ?.
var game = api?.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
if (game == null) // consider to add null-check
   return;

foreach(var player in game.Participants)
   // ...
</code>```

Further reading: 3.7 Scopes from C# specification

The scope of a name is the region of program text within which it is
  possible to refer to the entity declared by the name without
  qualification of the name. Scopes can be nested

And especially

• The scope of a local variable declared in a
  local-variable-declaration (§8.5.1) is the block in which the
  declaration occurs.

So when you declare local variable within try-catch block, it can be referred only within try-catch block. If you declare local variable within method body block, it can be referred within method body scope and within nested scopes.

Title: How can I declare an empty variable?

Body:
You should declare variable before try-catch block, otherwise it will not be visible outside the try-catch block:

TypeOfGame game = null; // declare local variable here
// note that you should provide initial value as well

try
{
   // assigne it here
   game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
}
catch (RiotSharpException ex)
{
    // I hope you have some real code here
    throw;
}

// now you can use it
foreach(var player in game.Participants)
{

}

Note that your current try-catch block don't catch anything except RiotSharpException and even for that type of exceptions you simply rethrow it. So nothing will change if you'll remove try-catch completely here

var api = RiotApi.GetInstance("KEY");
// if api can be null, then you can use null-propagation operation ?.
var game = api?.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
if (game == null) // consider to add null-check
   return;

foreach(var player in game.Participants)
   // ...

Further reading: 3.7 Scopes from C# specification

The scope of a name is the region of program text within which it is
  possible to refer to the entity declared by the name without
  qualification of the name. Scopes can be nested

And especially

• The scope of a local variable declared in a
  local-variable-declaration (§8.5.1) is the block in which the
  declaration occurs.

So when you declare local variable within try-catch block, it can be referred only within try-catch block. If you declare local variable within method body block, it can be referred within method body scope and within nested scopes.


问:
Performing a bitwise sum
As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):

```<code>select SUM(y.test)
from (
    select x.test
    from ( -- garbage test data
        select 1 as [test]
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8) x
group by x.test) y
</code>```

but is there a clean way to perform a bitwise sum in [T]SQL?

答:
If all of your test values are single bits as in your example (1, 2, 8) - simply use SUM(DISTINCT col) in your query.

Hope that helps.

(For reference: http://msdn.microsoft.com/en-us/library/ms187810.aspx)

Title: Performing a bitwise sum

Body:
As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):

select SUM(y.test)
from (
    select x.test
    from ( -- garbage test data
        select 1 as [test]
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8) x
group by x.test) y

but is there a clean way to perform a bitwise sum in [T]SQL?


问:
Css images on the right side of the footer
I am trying to create a footer with 2 Images who link to a page.

The two links / Images shall stay on the right side of the footer.

The Images shall stand next to each other with a Little margin.

How to I manage this with css?

```<code><footer>
    <a href="http://www.google.de/" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
    <a href="http://www.google.de" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
</footer>
</code>```

答:
hi if you are using bootstrap framework try this code

html

```<code><footer class="clearfix">
  <ul class="links pull-right">
   <li> <a href="http://www.google.de/" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
     </li>
    <li>
    <a href="http://www.google.de" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
      </li>
    </ul>
</footer>
</code>```

css

```<code>.links
{
  list-style-type:none;
  padding:0;
}
.links li
{
  display:inline-block;
}
</code>```

Body:
hi if you are using bootstrap framework try this code

html

<footer class="clearfix">
  <ul class="links pull-right">
   <li> <a href="http://www.google.de/" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
     </li>
    <li>
    <a href="http://www.google.de" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
      </li>
    </ul>
</footer>

css

.links
{
  list-style-type:none;
  padding:0;
}
.links li
{
  display:inline-block;
}


问:
Failed to Refresh data in RecyclerViewAdapter
I'm using the RecyclerViewAdapter. It's perfectly working.

My problem comes in when I am trying to populate the list from the server.

My DataHandaling class, I am trying to get the array to refresh the ListView from here...

```<code>void getEvents() {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(enviroClass.url() + "/api/events/" + 7)
            .build();

    client.newCall(request)
            .enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject eventObject = new JSONObject(response.body().string());
                        JSONArray eventJsonArray = eventObject.getJSONArray("events");
                        System.out.println(eventJsonArray.length());
                        for (int i = 0; i<2; i++) {
                            eventObject = eventJsonArray.getJSONObject(i);
                            eventObject = eventObject.getJSONObject("event");
                            eventArray.add(new Object_Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100" ,eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
                        }
                        System.out.println("This is from the http request in the datahandeling class" + "\n" + eventArray.get(0).getName());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
}
</code>```

Adapter Class I do have a method here to refresh the view

(NOTE: I have no idea if the swap method will work because I can't try it.)

```<code>import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.EventListFragment.OnListFragmentInteractionListener;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 * specified {@link OnListFragmentInteractionListener}.
 * TODO: Replace the implementation with code for your data type.
 */
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {

    private final List<Object_Event> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyItemRecyclerViewAdapter(List<Object_Event> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    public void swap(String hello){
//        mValues.clear();
//        DataHandaling dh = new DataHandaling();
//        System.out.println("This is the name of the event from the adapter" + "\n" + dh.getEventArray().get(0).getName());
//        mValues.addAll(eventArray);
//        notifyDataSetChanged();

        System.out.println(hello);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mItem = mValues.get(position);
        holder.mIdView.setText(mValues.get(position).getId() + "");
        holder.mContentView.setText(mValues.get(position).getName());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;
        public Object_Event mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.id);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}
</code>```

Fragment class

(NOTE: This should be done right because it does initially populate the ListView)

```<code>import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.dummy.DummyContent;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import org.w3c.dom.Text;

import java.util.ArrayList;

import static android.R.attr.data;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class EventListFragment extends Fragment {

    DataHandaling dh = new DataHandaling();

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public EventListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static EventListFragment newInstance(int columnCount) {
        EventListFragment fragment = new EventListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(dh.getEventArray(), mListener));
        }
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(int item);
    }
</code>```

I try to (refresh list) refresh data which i fetch from server.where I am failing miserably.

Can anyone help me? Thanks.

答:
Ok, So I found out what I was doing wrong...

I changed the constructor of MyItemRecyclerViewAdapter (Which I should rename) so that it checked the values to check if they are null.

```<code>public MyItemRecyclerViewAdapter(List<Object_Event> items, OnListFragmentInteractionListener listener) {
    if (items != null) {
        mValues = items;
    }
    if (listener != null ) {
        mListener = listener;
    }
}
</code>```

Then I called the swap method without any difficulty

```<code>MyItemRecyclerViewAdapter adapter = new MyItemRecyclerViewAdapter(null, null);
adapter.swap(eventArray);
</code>```

Body:
I'm using the RecyclerViewAdapter. It's perfectly working.

My problem comes in when I am trying to populate the list from the server.

My DataHandaling class, I am trying to get the array to refresh the ListView from here...

void getEvents() {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(enviroClass.url() + "/api/events/" + 7)
            .build();

    client.newCall(request)
            .enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject eventObject = new JSONObject(response.body().string());
                        JSONArray eventJsonArray = eventObject.getJSONArray("events");
                        System.out.println(eventJsonArray.length());
                        for (int i = 0; i<2; i++) {
                            eventObject = eventJsonArray.getJSONObject(i);
                            eventObject = eventObject.getJSONObject("event");
                            eventArray.add(new Object_Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100" ,eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
                        }
                        System.out.println("This is from the http request in the datahandeling class" + "\n" + eventArray.get(0).getName());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
}

Adapter Class I do have a method here to refresh the view

(NOTE: I have no idea if the swap method will work because I can't try it.)

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.EventListFragment.OnListFragmentInteractionListener;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 * specified {@link OnListFragmentInteractionListener}.
 * TODO: Replace the implementation with code for your data type.
 */
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {

    private final List<Object_Event> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyItemRecyclerViewAdapter(List<Object_Event> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    public void swap(String hello){
//        mValues.clear();
//        DataHandaling dh = new DataHandaling();
//        System.out.println("This is the name of the event from the adapter" + "\n" + dh.getEventArray().get(0).getName());
//        mValues.addAll(eventArray);
//        notifyDataSetChanged();

        System.out.println(hello);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mItem = mValues.get(position);
        holder.mIdView.setText(mValues.get(position).getId() + "");
        holder.mContentView.setText(mValues.get(position).getName());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;
        public Object_Event mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.id);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}

Fragment class

(NOTE: This should be done right because it does initially populate the ListView)

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.dummy.DummyContent;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import org.w3c.dom.Text;

import java.util.ArrayList;

import static android.R.attr.data;

/**
 * A fragment representing a list of Items.
 *

 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class EventListFragment extends Fragment {

    DataHandaling dh = new DataHandaling();

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public EventListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static EventListFragment newInstance(int columnCount) {
        EventListFragment fragment = new EventListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(dh.getEventArray(), mListener));
        }
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(int item);
    }

I try to (refresh list) refresh data which i fetch from server.where I am failing miserably.

Can anyone help me? Thanks.

Body:
Ok, So I found out what I was doing wrong...

I changed the constructor of MyItemRecyclerViewAdapter (Which I should rename) so that it checked the values to check if they are null.

public MyItemRecyclerViewAdapter(List<Object_Event> items, OnListFragmentInteractionListener listener) {
    if (items != null) {
        mValues = items;
    }
    if (listener != null ) {
        mListener = listener;
    }
}

Then I called the swap method without any difficulty

MyItemRecyclerViewAdapter adapter = new MyItemRecyclerViewAdapter(null, null);
adapter.swap(eventArray);


问:
Botan pipe failbit exception
When I followed the instructions in Botan document Pipe/Filter Message Processing, I was faced with an unexpected failbit error.

My code is very simple:

```<code>ifstream in("2.txt", ios::binary);
ofstream out("2.enc", ios::binary);
AutoSeeded_RNG rng;
SymmetricKey key(rng, 16); // a random 128-bit key
InitializationVector iv(rng, 16); // a random 128-bit IV

Pipe pipe(get_cipher("AES-128/CBC/CTS", key, iv, ENCRYPTION), new DataSink_Stream(out));
pipe.start_msg();
in >> pipe;
pipe.end_msg();
cout << in.fail() << endl;
</code>```

It would always output 1, since the failbit is always set to 1.

Is this a bug or is there something wrong with my code?

答:
This is how C++ input streams work; when a read is attempted past EOF, failbit and eofbit are set.

We can see from the documented Botan code that operator>> will throw an exception if only failbit is set after extraction is attempted; in short, you have nothing to worry about here. The computer is just telling you that you consumed all the input data1.

1 This is not solely what eofbit means in the strictest sense, but the way that Botan's operator>> works (reading as much as it can) requires an attempted read past EOF; otherwise, it wouldn't know when to stop!

Title: Botan pipe failbit exception

Body:
When I followed the instructions in Botan document Pipe/Filter Message Processing, I was faced with an unexpected failbit error.

My code is very simple:

ifstream in("2.txt", ios::binary);
ofstream out("2.enc", ios::binary);
AutoSeeded_RNG rng;
SymmetricKey key(rng, 16); // a random 128-bit key
InitializationVector iv(rng, 16); // a random 128-bit IV

Pipe pipe(get_cipher("AES-128/CBC/CTS", key, iv, ENCRYPTION), new DataSink_Stream(out));
pipe.start_msg();
in >> pipe;
pipe.end_msg();
cout << in.fail() << endl;

It would always output 1, since the failbit is always set to 1.

Is this a bug or is there something wrong with my code?


问:
Qt - serialize/deserialaize text and picture
I want to use a field (kind of QTextEdit), which is capabale of storing picture and text (like MS Word is doing) and it serializes and deserialaizes picture+text data. Is there any Qt Widget that allows us to manipulate with picture and text simultaniously and it has set/get  functions which operate with serializable type? In othger words, I want to know if there exsists any Qt widget that can store picture+text and has "get" types of function that returns the content of that widgets editable area, which is a Type that could be serialized with QDataStream.</p>

答:
See this:

How to serialize and deserialize rich text in QTextEdit?


问:
Adding Font color and No fill to a sub routine
hopefully a quick fix on this one. I have a sub routine that I am using to amend the column sizes for all the sheets in a workbook which works absolutely fine but I wanted to add to this sub so that it will change the font color black for all cells within my ranges and remove any fill color from them also. I have written the code below but it doesn't seem to perform the way I want. Any ideas as to how I can correct this would be awesome!</p>

```<code>Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Font.Color = vbBlack
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Interior.ColorIndex = xlNone

End With
End Sub
</code>```

答:
I would suggest defining a last row (by working up from the bottom), and you omitted the dots necessary for your With statement</p>

```<code>Sub resizingColumns(ws As Worksheet)

Dim n As Long

With ws
    n = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:BB1").EntireColumn.AutoFit
    .Range("A2:BB" & n).Font.Color = vbBlack
    .Range("A2:BB" & n).Interior.ColorIndex = xlNone
End With

End Sub
</code>```

Body:
hopefully a quick fix on this one. I have a sub routine that I am using to amend the column sizes for all the sheets in a workbook which works absolutely fine but I wanted to add to this sub so that it will change the font color black for all cells within my ranges and remove any fill color from them also. I have written the code below but it doesn't seem to perform the way I want. Any ideas as to how I can correct this would be awesome!

Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Font.Color = vbBlack
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Interior.ColorIndex = xlNone

End With
End Sub

Body:
I would suggest defining a last row (by working up from the bottom), and you omitted the dots necessary for your With statement

Sub resizingColumns(ws As Worksheet)

Dim n As Long

With ws
    n = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:BB1").EntireColumn.AutoFit
    .Range("A2:BB" & n).Font.Color = vbBlack
    .Range("A2:BB" & n).Interior.ColorIndex = xlNone
End With

End Sub


问:
Unable to get access to specific directory to run a site on ec2
Still fairly new to ec2, I made a new directory as /home/user/www. Opened ftp service that allows git commits to be pushed to the server. This works fine as I can see the files come up. The problem being when I run my site, the Apache test page pops up and when I try opening a page in /home/user/www directory, it says Forbidden, you don't have permission to access / on this server.
I have successfully changed the DocumentRoot

```<code>DocumentRoot "/home/user/www"
AllowOverride None
# Allow open access:
Require all granted
</code>```

and Directory in httpd.config to /home/user/www, all but to no result.
Any help is appreciated. Permissions are 777 for test basis but still no success. User is the owner of all the files in www

答:
Solved my own question. Permissions need to be set on the third directory i.e., www. Therefore, I did chmod 755 ~/www.
Worked like a charm</p>

Body:
Still fairly new to ec2, I made a new directory as /home/user/www. Opened ftp service that allows git commits to be pushed to the server. This works fine as I can see the files come up. The problem being when I run my site, the Apache test page pops up and when I try opening a page in /home/user/www directory, it says Forbidden, you don't have permission to access / on this server.
I have successfully changed the DocumentRoot

DocumentRoot "/home/user/www"
AllowOverride None
# Allow open access:
Require all granted

and Directory in httpd.config to /home/user/www, all but to no result.
Any help is appreciated. Permissions are 777 for test basis but still no success. User is the owner of all the files in www