问:
amazon elastic transcode with shrine
I am working on an app that require to upload videos. I added Shrine and s3 storage.

Till here everything is working. Now I need to transcode the videos and I added the following code to the video_uploader file

```<code>class VideoUploader < Shrine

  plugin :processing
  plugin :versions

  process(:store) do |io|

    transcoder = Aws::ElasticTranscoder::Client.new(
      access_key_id:     ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
      region:            'us-east-1',
    )

    pipeline = transcoder.create_pipeline(options = {
        :name => "name",
        :input_bucket => "bucket",
        :output_bucket => "bucket",
        :role => "arn:aws:iam::XXXXX:role/Elastic_Transcoder_Default_Role",
    })

    PIPELINE_ID =  pipeline[:pipeline][:id]

    transcode_hd = transcoder.create_job({
      :pipeline_id=>PIPELINE_ID,
      :input=> {
        :key=> "cache/"+io.id,
        :frame_rate=> "auto",
        :resolution => "auto",
        :aspect_ratio => "auto",
        :container => 'auto'
      },
      :outputs=>[{
        :key=>"store/"+io.id,
        :preset_id=>"1351620000001-000010",
      }]
    })

  end

end
</code>```

The transcoding is working and basically is transcoding the new file uploaded to cache folder and put in the store folder with the same name.

The issue now is to attach this file to the record in the database. As of now the record is updated with a different name it creates a new file in the store folder of 0mb.

How can I  attach the results of processing into Shrine's uploaded file for storage?

答:
The process(:store) block expects you to return a file for Shrine to upload to permanent storage, so this flow won't work Amazon Elastic Transcoder, because Amazon Elastic Transcoder is now the one that will upload the cached file to permanent storage.

You can delay the transcoding request into a background job, poll the transcoding job every N seconds, and create a Shrine::UploadedFile from the results and update the record. Something like the following should work:

```<code># superclass for all uploaders that use Amazon Elastic Transcoder
class TranscoderUploader < Shrine
  plugin :backgrounding
  Attacher.promote { |data| TranscodeJob.perform_async(data) }
end

class VideoUploader < TranscoderUploader
  plugin :versions
end

class TranscodeJob
  include Sidekiq::Worker

  def perform(data)
    attacher = TranscoderUploader::Attacher.load(data)
    cached_file = attacher.get #=> #<Shrine::UploadedFile>

    # create transcoding job, use `cached_file.id`

    transcoder.wait_until(:job_complete, id: job.id)
    response = transcoder.read_job(id: job.id)
    output = response.output

    versions = {
      video: attacher.shrine_class::UploadedFile.new(
        "id" => cached_file.id,
        "storage" => "store",
        "metadata" => {
          "width" => output.width,
          "height" => output.height,
          # ...
        }
      ),
      ...
    }

    attacher.swap(versions)
  end
end
</code>```

If you'll by any chance be interested in making a Shrine plugin for Amazon Elastic Transcoder, take a look at shrine-transloadit which provides integration for Transloadit, which uses practically the same flow as the Amazon Elastic Transcoder, and it works with webhooks rather than polling for the response.

Title: amazon elastic transcode with shrine

Body:
I am working on an app that require to upload videos. I added Shrine and s3 storage.

Till here everything is working. Now I need to transcode the videos and I added the following code to the video_uploader file

class VideoUploader < Shrine

  plugin :processing
  plugin :versions

  process(:store) do |io|

    transcoder = Aws::ElasticTranscoder::Client.new(
      access_key_id:     ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
      region:            'us-east-1',
    )

    pipeline = transcoder.create_pipeline(options = {
        :name => "name",
        :input_bucket => "bucket",
        :output_bucket => "bucket",
        :role => "arn:aws:iam::XXXXX:role/Elastic_Transcoder_Default_Role",
    })

    PIPELINE_ID =  pipeline[:pipeline][:id]

    transcode_hd = transcoder.create_job({
      :pipeline_id=>PIPELINE_ID,
      :input=> {
        :key=> "cache/"+io.id,
        :frame_rate=> "auto",
        :resolution => "auto",
        :aspect_ratio => "auto",
        :container => 'auto'
      },
      :outputs=>[{
        :key=>"store/"+io.id,
        :preset_id=>"1351620000001-000010",
      }]
    })

  end

end

The transcoding is working and basically is transcoding the new file uploaded to cache folder and put in the store folder with the same name.

The issue now is to attach this file to the record in the database. As of now the record is updated with a different name it creates a new file in the store folder of 0mb.

How can I  attach the results of processing into Shrine's uploaded file for storage?

Body:
The process(:store) block expects you to return a file for Shrine to upload to permanent storage, so this flow won't work Amazon Elastic Transcoder, because Amazon Elastic Transcoder is now the one that will upload the cached file to permanent storage.

You can delay the transcoding request into a background job, poll the transcoding job every N seconds, and create a Shrine::UploadedFile from the results and update the record. Something like the following should work:

# superclass for all uploaders that use Amazon Elastic Transcoder
class TranscoderUploader < Shrine
  plugin :backgrounding
  Attacher.promote { |data| TranscodeJob.perform_async(data) }
end

class VideoUploader < TranscoderUploader
  plugin :versions
end

class TranscodeJob
  include Sidekiq::Worker

  def perform(data)
    attacher = TranscoderUploader::Attacher.load(data)
    cached_file = attacher.get #=> #<Shrine::UploadedFile>

    # create transcoding job, use `cached_file.id`

    transcoder.wait_until(:job_complete, id: job.id)
    response = transcoder.read_job(id: job.id)
    output = response.output

    versions = {
      video: attacher.shrine_class::UploadedFile.new(
        "id" => cached_file.id,
        "storage" => "store",
        "metadata" => {
          "width" => output.width,
          "height" => output.height,
          # ...
        }
      ),
      ...
    }

    attacher.swap(versions)
  end
end

If you'll by any chance be interested in making a Shrine plugin for Amazon Elastic Transcoder, take a look at shrine-transloadit which provides integration for Transloadit, which uses practically the same flow as the Amazon Elastic Transcoder, and it works with webhooks rather than polling for the response.


来源: stackexchange

问:
Strange strings behaviour when const reference
I encountered a strange behaviour with const reference strings when it goes over 15 characters. It simply replaces the beginning of the string by null bytes.

```<code>Class A
{
public:
  A(const std::string& str) : str_(str)
  {
    std::cout << str_ << std::endl;
  }
  void test()
  {
    std::cout << str_ << std::endl;
  }
private:
  const std::string& str;
};

int main()
{
  //printing the full string "01234567890123456789"
  A a("01234567890123456789");
  //replacing first bytes by '\0', printing "890123456789"
  a.test();
}
</code>```

This is happening only with strings exceeding 15 characters. If a remove the const & in the attribute of the class, I don't have this problem anymore I've experienced in an other project memory leaks in my code when strings were exceeding 15 characters, so I wonder :

What is really happening when a string goes over 15 characters?

答:
str_ is a reference to a temporary object. When you use str_ in the body of the constructor, the temporary is still alive. When you use str_ in test, the temporary is not alive any longer.

Your program has undefined behavior.

ContentLicense: CC BY-SA 3.0

Body:
I encountered a strange behaviour with const reference strings when it goes over 15 characters. It simply replaces the beginning of the string by null bytes.

Class A
{
public:
  A(const std::string& str) : str_(str)
  {
    std::cout << str_ << std::endl;
  }
  void test()
  {
    std::cout << str_ << std::endl;
  }
private:
  const std::string& str;
};

int main()
{
  //printing the full string "01234567890123456789"
  A a("01234567890123456789");
  //replacing first bytes by '\0', printing "890123456789"
  a.test();
}

This is happening only with strings exceeding 15 characters. If a remove the const & in the attribute of the class, I don't have this problem anymore I've experienced in an other project memory leaks in my code when strings were exceeding 15 characters, so I wonder :

What is really happening when a string goes over 15 characters?


问:
UI is not updating the backing bean
This is my UI code in JSF. The app is a small currency conversion from Singaporean dollar to Japanese Yen.

```<code><h:form>
            <h:inputText id="conversion" value="#{conversor.sgd}"></h:inputText>
         <h:commandButton value = "Convertir a yen">
            <f:ajax execute = "@all" render = "conversion_lista" event="click"/>
         </h:commandButton>
         <h2><h:outputText id = "conversion_lista" value = "Conversion: #{conversor.jpy}"/></h2>
      </h:form>
</code>```

And this is my backing bean:

```<code>@Named("conversor")
@Dependent
public class Conversor {

    private int sgd;

    public Conversor() {
        sgd = 1; //initial value
    }

    public int getSgd(){
        return sgd;
    }

    public void setSgd(int sgd){
        this.sgd = sgd;
    }

    public int getJpy(){
        return sgd * 2; //fake
    }
}
</code>```

I want to click on the commandButton, execute the first inputText, make the sgd property in the backing bean change, then render the outputText by previously calculating the converstion from Singaporean dollar to Japanese yen.

However the input isn't passed to the backing bean.

I did try some things like, making getJpy() return a random number everytime it's called, and it did render a random number everytime I clicked the button. So that means that call works. But I can't pass the text input (sgd/singaporean dollar) to the backing bean and make the right conversion.

What's going on in here?

答:
Ok, I fixed it.

I used @RequestScoped instead of @Dependent.

I have no idea what I'm doing, but it works.

Now the outcome is what I wanted, the conversion takes place on the UI when I click the button.

Title: UI is not updating the backing bean

Body:
This is my UI code in JSF. The app is a small currency conversion from Singaporean dollar to Japanese Yen.

<h:form>
            <h:inputText id="conversion" value="#{conversor.sgd}"></h:inputText>
         <h:commandButton value = "Convertir a yen">
            <f:ajax execute = "@all" render = "conversion_lista" event="click"/>
         </h:commandButton>

<h:outputText id = "conversion_lista" value = "Conversion: #{conversor.jpy}"/>

      </h:form>

And this is my backing bean:

@Named("conversor")
@Dependent
public class Conversor {

    private int sgd;

    public Conversor() {
        sgd = 1; //initial value
    }

    public int getSgd(){
        return sgd;
    }

    public void setSgd(int sgd){
        this.sgd = sgd;
    }

    public int getJpy(){
        return sgd * 2; //fake
    }
}

I want to click on the commandButton, execute the first inputText, make the sgd property in the backing bean change, then render the outputText by previously calculating the converstion from Singaporean dollar to Japanese yen.

However the input isn't passed to the backing bean.

I did try some things like, making getJpy() return a random number everytime it's called, and it did render a random number everytime I clicked the button. So that means that call works. But I can't pass the text input (sgd/singaporean dollar) to the backing bean and make the right conversion.

What's going on in here?


问:
Filling the whole screen with Gridview items
I have a GridView (with 2 columns and 2 rows) and want to stretch the rows to fill the whole screen. It should look the same on all devices.

That means I don't want some empty space under the last row. So I searched a little bit and found a solution to set the minimum height of the GridView dynamically with following code:

```<code>DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int width = metrics.widthPixels;
int height = metrics.heightPixels;
</code>```

In addition I added these lines of code in my Adapter:

```<code>gridView = inflater.inflate(R.layout.act_main_menu_sub, null);
gridView.setMinimumHeight(ActMainMenu.height/2);
</code>```

But now it looks like this:

The View is scrollable now and the items have the same size. But it doesn't fit on the screen.

Here is the code of my layout including the GridView:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:id="@+id/layout_main_menu"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="#b2b2b2"
          android:orientation="vertical">

<!-- android:layout_height="wrap_content" -->
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    android:padding="2dp"
    app:titleMarginStart="20dp"
    app:titleTextAppearance="@style/MyMaterialTheme.Base.TitleTextStyle"
    app:titleTextColor="@color/textColorPrimary">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="MASTERFITNESS TRAINERSCHULUNG"
        android:textColor="@android:color/white"
        android:textStyle="bold|italic"/>

</android.support.v7.widget.Toolbar>

<!--android:columnWidth="160dp"-->
<GridView
    android:id="@+id/grid_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:gravity="center"
    android:horizontalSpacing="20dp"
    android:numColumns="2"
    android:stretchMode="columnWidth"
    android:verticalSpacing="20dp"></GridView>

</LinearLayout>
</code>```

What is the problem here?

答:
The problem with your 2nd screen shots in the height calculation.  metrics.heightPixels gives you the full height of the screen, including the toolbar and any margins you have.  These should 1st be subtracted out, then divide the screen in half.

```<code>    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    // your layout has 10dp margin (top & bottom) + 20 dp between grid items, 10+10+20=40
    int marginSizeDp = 40;
    float scale = metrics.density;
    int marginSizePx = Math.round (marginSizeDp * scale);

    int appBarHeight = getAppBarHeight();

    int height = metrics.heightPixels;
    int minHt = Math.round((height - marginSizePx - appBarHeight)/2);
    gridView.setMinimumHeight(minHt);
</code>```

Get the toolbar height thanks to AZ13 at https://stackoverflow.com/a/7167086/7292819

```<code>    // returns height of app bar in pixels
    private int getAppBarHeight() {
        final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.actionBarSize });
        int appBarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return appBarHeight;
    }
</code>```

Truthfully, if this layout is static (there's only 4 items, no scrolling, little or no changing of the content of each item), I probably wouldn't bother with a GridView & adapter.  A RelativeLayout or GridLayout might be better.

Body:
I have a GridView (with 2 columns and 2 rows) and want to stretch the rows to fill the whole screen. It should look the same on all devices.

That means I don't want some empty space under the last row. So I searched a little bit and found a solution to set the minimum height of the GridView dynamically with following code:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int width = metrics.widthPixels;
int height = metrics.heightPixels;

In addition I added these lines of code in my Adapter:

gridView = inflater.inflate(R.layout.act_main_menu_sub, null);
gridView.setMinimumHeight(ActMainMenu.height/2);

But now it looks like this:

The View is scrollable now and the items have the same size. But it doesn't fit on the screen.

Here is the code of my layout including the GridView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:id="@+id/layout_main_menu"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="#b2b2b2"
          android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    android:padding="2dp"
    app:titleMarginStart="20dp"
    app:titleTextAppearance="@style/MyMaterialTheme.Base.TitleTextStyle"
    app:titleTextColor="@color/textColorPrimary">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="MASTERFITNESS TRAINERSCHULUNG"
        android:textColor="@android:color/white"
        android:textStyle="bold|italic"/>

</android.support.v7.widget.Toolbar>

<GridView
    android:id="@+id/grid_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:gravity="center"
    android:horizontalSpacing="20dp"
    android:numColumns="2"
    android:stretchMode="columnWidth"
    android:verticalSpacing="20dp"></GridView>

</LinearLayout>

What is the problem here?

Body:
The problem with your 2nd screen shots in the height calculation.  metrics.heightPixels gives you the full height of the screen, including the toolbar and any margins you have.  These should 1st be subtracted out, then divide the screen in half.

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    // your layout has 10dp margin (top & bottom) + 20 dp between grid items, 10+10+20=40
    int marginSizeDp = 40;
    float scale = metrics.density;
    int marginSizePx = Math.round (marginSizeDp * scale);

    int appBarHeight = getAppBarHeight();

    int height = metrics.heightPixels;
    int minHt = Math.round((height - marginSizePx - appBarHeight)/2);
    gridView.setMinimumHeight(minHt);

Get the toolbar height thanks to AZ13 at https://stackoverflow.com/a/7167086/7292819

    // returns height of app bar in pixels
    private int getAppBarHeight() {
        final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.actionBarSize });
        int appBarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return appBarHeight;
    }

Truthfully, if this layout is static (there's only 4 items, no scrolling, little or no changing of the content of each item), I probably wouldn't bother with a GridView & adapter.  A RelativeLayout or GridLayout might be better.


问:
h2o.performance predictions differ from h2o.predict?
Apologies if this has been answered elsewhere but i couldn't find anything.

I'm using h2o (latest release) in R. I've created a random forest model using h2o.grid (for parameter tuning) and called this 'my_rf'

My steps are as follows:

train grid of `randomForests with parameter tuning & cross validation (nfolds = 5)

get the sorted grid of models (by AUC) and set my_rf = best model

use h2o performance(my_rf, test) to assess auc, accuracy etc on a test set

predict on test set using h2o.predict and export results

The exact line I've used for h2o.performance is:

```<code>h2o.performance(my_rf, newdata = as.h2o(test))
</code>```

.... which gives me a confusion matrix, from which I can calculate accuracy (as well as giving me AUC, max F1 score etc)

I would have thought that using

```<code>h2o.predict(my_rf, newdata = as.h2o(test))
</code>```

I would be able to replicate the confusion matrix from h2o.performance. But the accuracy is different - 3% worse in fact.

Is anyone able to explain why this is so?

Also, is there any way to return the predictions that make up the confusion matrix in h2o.performance?

Edit: here is the relevant code:

```<code>library(mlbench)
data(Sonar)
head(Sonar)

mainset <- Sonar
mainset$Class <- ifelse(mainset$Class == "M", 0,1)          #binarize
mainset$Class <- as.factor(mainset$Class)

response <- "Class"
predictors <- setdiff(names(mainset), c(response, "name"))

# split into training and test set

library(caTools)
set.seed(123)
split = sample.split(mainset[,61], SplitRatio = 0.75)
train = subset(mainset, split == TRUE)
test =  subset(mainset, split == FALSE)

# connect to h2o

Sys.unsetenv("http_proxy")
Sys.setenv(JAVA_HOME='C:\\Program Files (x86)\\Java\\jre7')                #set JAVA home for 32 bit
library(h2o)
h2o.init(nthread = -1)

# stacked ensembles

nfolds <- 5
ntrees_opts <- c(20:500)
max_depth_opts <- c(4,8,12,16,20)
sample_rate_opts <- seq(0.3,1,0.05)
col_sample_rate_opts <- seq(0.3,1,0.05)

rf_hypers <- list(ntrees = ntrees_opts, max_depth = max_depth_opts,
                  sample_rate = sample_rate_opts,
                  col_sample_rate_per_tree = col_sample_rate_opts)

search_criteria <- list(strategy = 'RandomDiscrete', max_runtime_secs = 240, max_models = 15,
stopping_metric = "AUTO", stopping_tolerance = 0.00001, stopping_rounds = 5,seed = 1)

my_rf <- h2o.grid("randomForest", grid_id = "rf_grid", x = predictors, y = response,
                                                                training_frame = as.h2o(train),
                                                                nfolds = 5,
                                                                fold_assignment = "Modulo",
                                                                keep_cross_validation_predictions = TRUE,
                                                                hyper_params = rf_hypers,
                                                                search_criteria = search_criteria)

get_grid_rf <- h2o.getGrid(grid_id = "rf_grid", sort_by = "auc", decreasing = TRUE)                         # get grid of models built
my_rf <- h2o.getModel(get_grid_rf@model_ids[[1]])
perf_rf <- h2o.performance(my_rf, newdata = as.h2o(test))

pred <- h2o.predict(my_rf, newdata = as.h2o(test))
pred <- as.vectpr(pred$predict)

cm <- table(test[,61], pred)
print(cm)
</code>```

答: Mostly likely, function h2o.performance is using F1 threshold to set yes and no. If you take the predict results and instrument the table to separate yes/no based based on models "F1 threshold" value you will see the number is almost match. I believe this is the main reason you see discrepancy in the results between h2o.performance and h2o.predict. </p>

Body:
Apologies if this has been answered elsewhere but i couldn't find anything.

I'm using h2o (latest release) in R. I've created a random forest model using h2o.grid (for parameter tuning) and called this 'my_rf'

My steps are as follows:

train grid of `randomForests with parameter tuning & cross validation (nfolds = 5)

get the sorted grid of models (by AUC) and set my_rf = best model

use h2o performance(my_rf, test) to assess auc, accuracy etc on a test set

predict on test set using h2o.predict and export results

The exact line I've used for h2o.performance is:

h2o.performance(my_rf, newdata = as.h2o(test))

.... which gives me a confusion matrix, from which I can calculate accuracy (as well as giving me AUC, max F1 score etc)

I would have thought that using

h2o.predict(my_rf, newdata = as.h2o(test))

I would be able to replicate the confusion matrix from h2o.performance. But the accuracy is different - 3% worse in fact.

Is anyone able to explain why this is so?

Also, is there any way to return the predictions that make up the confusion matrix in h2o.performance?

Edit: here is the relevant code:

library(mlbench)
data(Sonar)
head(Sonar)

mainset <- Sonar
mainset$Class <- ifelse(mainset$Class == "M", 0,1)          #binarize
mainset$Class <- as.factor(mainset$Class)

response <- "Class"
predictors <- setdiff(names(mainset), c(response, "name"))

# split into training and test set

library(caTools)
set.seed(123)
split = sample.split(mainset[,61], SplitRatio = 0.75)
train = subset(mainset, split == TRUE)
test =  subset(mainset, split == FALSE)

# connect to h2o

Sys.unsetenv("http_proxy")
Sys.setenv(JAVA_HOME='C:\\Program Files (x86)\\Java\\jre7')                #set JAVA home for 32 bit
library(h2o)
h2o.init(nthread = -1)

# stacked ensembles

nfolds <- 5
ntrees_opts <- c(20:500)
max_depth_opts <- c(4,8,12,16,20)
sample_rate_opts <- seq(0.3,1,0.05)
col_sample_rate_opts <- seq(0.3,1,0.05)

rf_hypers <- list(ntrees = ntrees_opts, max_depth = max_depth_opts,
                  sample_rate = sample_rate_opts,
                  col_sample_rate_per_tree = col_sample_rate_opts)

search_criteria <- list(strategy = 'RandomDiscrete', max_runtime_secs = 240, max_models = 15,
stopping_metric = "AUTO", stopping_tolerance = 0.00001, stopping_rounds = 5,seed = 1)

my_rf <- h2o.grid("randomForest", grid_id = "rf_grid", x = predictors, y = response,
                                                                training_frame = as.h2o(train),
                                                                nfolds = 5,
                                                                fold_assignment = "Modulo",
                                                                keep_cross_validation_predictions = TRUE,
                                                                hyper_params = rf_hypers,
                                                                search_criteria = search_criteria)

get_grid_rf <- h2o.getGrid(grid_id = "rf_grid", sort_by = "auc", decreasing = TRUE)                         # get grid of models built
my_rf <- h2o.getModel(get_grid_rf@model_ids[[1]])
perf_rf <- h2o.performance(my_rf, newdata = as.h2o(test))

pred <- h2o.predict(my_rf, newdata = as.h2o(test))
pred <- as.vectpr(pred$predict)

cm <- table(test[,61], pred)
print(cm)


问:
How to convert ":" colonized names from XML to XSD schema?
I want to generate POJOS using xjc from JAXB from a XSD schema. I am having trouble converting elements with names like "media:title" to schema.

```<code><media:title>Sink or Swim - Trailer</media:title>
<media:credit role="Director" scheme="urn:ebu">Jon Bowermaster</media:credit>
<media:credit role="Writer" scheme="urn:ebu">Jon Bowermaster</media:credit>
<media:credit role="Editor" scheme="urn:ebu">Devin Pickering</media:credit>
<media:thumbnail type="landscape" url="http://snagfilms-a.akamaihd.net/bf/f6/41421f834ff49b86e36beae9f47e/sinkorswim-video.jpg"/>
<media:thumbnail type="thumbnail" url="http://snagfilms-a.akamaihd.net/11/50/68399aa743ffa9fa9f9a155ba1c1/sinkorswim-thumbnail.jpg"/>
<media:thumbnail type="widget" url="http://snagfilms-a.akamaihd.net/ce/f7/5a967d1042288b53fecdf100393a/sinkorswim-widget.jpg"/>
<media:thumbnail type="poster" url="http://snagfilms-a.akamaihd.net/30/40/0875f149490a853057bebf69dac0/sinkorswim-poster.jpg"/>
<media:content duration="117" height="323" type="text/html" url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-affd-b32ce8700000" width="500"/>
<media:keywords>
snagfilms,Trailers,Climate Change,Documentary,Inspiring,Maldives,Swimming,Trailers
</media:keywords>
<media:restriction relationship="allow" type="sharing"/>
<media:community>
  <media:starRating average="0" count="0"/>
  <media:statistics favorites="5" views="5"/>
  <media:tags>
  snagfilms,Trailers,Climate Change,Documentary,Inspiring,Maldives,Swimming,Trailers
  </media:tags>
</media:community>
<media:rights status="official"/>
<media:player height="323" url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-affd-b32ce8700000" width="500"/>
</code>```

What will the above look like in XSD schema

答:
To ask how to convert colonized names from XML to XSD indicates a misunderstanding of XML namespaces.  Colonized names are a way to place an XML component into a namespace via a namespace prefix.  You don't want to convert XML to XSD; you want to write an XSD that describes the XML.

In your example markup, there should be

a single root element

a declaration of the media namespace prefix (eg: xmlns:media="http://www.example.com/media")

Lacking these items, your markup isn't even XML because it doesn't meet the requirements for being well-formed.

After making these corrections, you can write an XSD that has a target namespace that matches the namespace of the root element of your XML.  You can import additional XSD to cover an additional namespaces used in your XML.  Only then will you be ready to generate Java classes via JAXB and xjc.

Body:
I want to generate POJOS using xjc from JAXB from a XSD schema. I am having trouble converting elements with names like "media:title" to schema.

<media:title>Sink or Swim - Trailer</media:title>
<media:credit role="Director" scheme="urn:ebu">Jon Bowermaster</media:credit>
<media:credit role="Writer" scheme="urn:ebu">Jon Bowermaster</media:credit>
<media:credit role="Editor" scheme="urn:ebu">Devin Pickering</media:credit>
<media:thumbnail type="landscape" url="http://snagfilms-a.akamaihd.net/bf/f6/41421f834ff49b86e36beae9f47e/sinkorswim-video.jpg"/>
<media:thumbnail type="thumbnail" url="http://snagfilms-a.akamaihd.net/11/50/68399aa743ffa9fa9f9a155ba1c1/sinkorswim-thumbnail.jpg"/>
<media:thumbnail type="widget" url="http://snagfilms-a.akamaihd.net/ce/f7/5a967d1042288b53fecdf100393a/sinkorswim-widget.jpg"/>
<media:thumbnail type="poster" url="http://snagfilms-a.akamaihd.net/30/40/0875f149490a853057bebf69dac0/sinkorswim-poster.jpg"/>
<media:content duration="117" height="323" type="text/html" url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-affd-b32ce8700000" width="500"/>
<media:keywords>
snagfilms,Trailers,Climate Change,Documentary,Inspiring,Maldives,Swimming,Trailers
</media:keywords>
<media:restriction relationship="allow" type="sharing"/>
<media:community>
  <media:starRating average="0" count="0"/>
  <media:statistics favorites="5" views="5"/>
  <media:tags>
  snagfilms,Trailers,Climate Change,Documentary,Inspiring,Maldives,Swimming,Trailers
  </media:tags>
</media:community>
<media:rights status="official"/>
<media:player height="323" url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-affd-b32ce8700000" width="500"/>

What will the above look like in XSD schema


问:
How to interpolate variables that are within a file on remote machine via Ansible?
I have a config file on the remote machine in the format:

```<code>key1={{key1}}
key2={{key2}}
</code>```

I want to use Ansible to populate the values of the keys with values from group_vars.

How can I read this file in, interpolate the contents, and write the file back out?

I don't want to use templates since different config files will have different keys, and my understanding of templates is that i'd have to know in advance which keys I need.

答:
Here you are (but I don't think this is how you should manage systems):

```<code>---
- hosts: target
  vars:
    key1: "value1"
    key2: "value2"
  tasks:
    - command: cat /path/to/file
      register: cat_file
    - copy:
        content: "{{ cat_file.stdout }}\n"
        dest: /path/to/file
</code>```

There is a problem with the trailing newline character, which is not reflected in the stdout from cat. I assumed it should be added.

Alternatively:

```<code>---
- hosts: target
  vars:
    key1: "value1"
    key2: "value2"
  tasks:
    - fetch:
        src: /path/to/file
        dest: ./tmp/file
    - template:
        src: ./tmp/file
        dest: /path/to/file
</code>```

Body:
I have a config file on the remote machine in the format:

key1={{key1}}
key2={{key2}}

I want to use Ansible to populate the values of the keys with values from group_vars.

How can I read this file in, interpolate the contents, and write the file back out?

I don't want to use templates since different config files will have different keys, and my understanding of templates is that i'd have to know in advance which keys I need.

Body:
Here you are (but I don't think this is how you should manage systems):

---
- hosts: target
  vars:
    key1: "value1"
    key2: "value2"
  tasks:
    - command: cat /path/to/file
      register: cat_file
    - copy:
        content: "{{ cat_file.stdout }}\n"
        dest: /path/to/file

There is a problem with the trailing newline character, which is not reflected in the stdout from cat. I assumed it should be added.

Alternatively:

---
- hosts: target
  vars:
    key1: "value1"
    key2: "value2"
  tasks:
    - fetch:
        src: /path/to/file
        dest: ./tmp/file
    - template:
        src: ./tmp/file
        dest: /path/to/file


问:
How can I perfect the logic of lock-screen?
When you need to temporarily leave your web application and computer unattended, there’s a safe way to put it to screen-lock status and unlock it by input your unique password again. Shows our login screen without logging you out in our web applications seems easy to add a lock screen page like this.

Lock screen Demo from Metronic

But how can I perfect the logic of lock-screen.
For example can i let the other people can not use the forward or backward tools change the current url?

答:
By definition, you can't.

The backwards and forwards buttons are browser's capability so there's no way you can alter it with Javascript.

What you can do though is whenever a user is locked there's no way for him to leave the lock page (if locked every page redirect to lock page)


问:
How can I get my Child Theme's Stylesheet to load after Parent Theme's 'Colour Theme' Stylesheets?
I have created a Child Theme, whereby I have enqueued the stylesheets as follows:

```<code><?php
function child_theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/css/custom-stylesheet.css', array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_styles', 10 );
?>
</code>```

The above code, ensures that the Child Theme Custom Stylesheet loads after the Parent Theme Stylesheets.  That said, the Parent Theme also has the following CSS Files within the following directories, which load after the Child Theme Stylesheets:

```<code><link rel='stylesheet' id='responsive-css'  href='http://www.example.com/wp-content/themes/theme/assets/css/responsive.css?ver=4.7.3' type='text/css' media='all' />
<link rel='stylesheet' id='theme-skin-color8-css'  href='http://www.example.com/wp-content/themes/theme/assets/css/theme-skin/color8.css?ver=4.7.3'
</code>```

I have checked the priority settings for the above files and none have been set.  I have also changed the priorities of the Child Theme stylesheets, yet this has no affect.

Does anyone have any other possible suggestions, that I can try, in order to ensure that the Child Theme Stylesheet loads last?

答:
If no priority has been set on the wp_enqueue_scripts function calling those other stylesheets, then their priority is at 10 and setting your call to a higher priority will work:

```<code>function child_theme_enqueue_styles() {
  wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
  wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/css/custom-stylesheet.css', array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_styles', 11 );
</code>```

If this isn't working, then the parent theme is poorly coded and not properly enqueuing those other stylesheets.

Body:
I have created a Child Theme, whereby I have enqueued the stylesheets as follows:

<?php
function child_theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/css/custom-stylesheet.css', array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_styles', 10 );
?>

The above code, ensures that the Child Theme Custom Stylesheet loads after the Parent Theme Stylesheets.  That said, the Parent Theme also has the following CSS Files within the following directories, which load after the Child Theme Stylesheets:

<link rel='stylesheet' id='responsive-css'  href='http://www.example.com/wp-content/themes/theme/assets/css/responsive.css?ver=4.7.3' type='text/css' media='all' />
<link rel='stylesheet' id='theme-skin-color8-css'  href='http://www.example.com/wp-content/themes/theme/assets/css/theme-skin/color8.css?ver=4.7.3'

I have checked the priority settings for the above files and none have been set.  I have also changed the priorities of the Child Theme stylesheets, yet this has no affect.

Does anyone have any other possible suggestions, that I can try, in order to ensure that the Child Theme Stylesheet loads last?

Body:
If no priority has been set on the wp_enqueue_scripts function calling those other stylesheets, then their priority is at 10 and setting your call to a higher priority will work:

function child_theme_enqueue_styles() {
  wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
  wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/css/custom-stylesheet.css', array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_styles', 11 );

If this isn't working, then the parent theme is poorly coded and not properly enqueuing those other stylesheets.


问:
ReactJS: On scroll, debounce - test scroll distance - if true - load more components
So, essentially, my own lazy loader... I want to fire a class method every time a scroll takes place and check to see if the user has scrolled to the bottom. If so, then load more components. I know there are packages for this (infinity-scroll / infinity-scroller), but I feel like I'm pretty close with my own code.

```<code>export default class Gallery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      photos: [ // data from mongodb ],
      numberToLoad: 0,
    };

    this.handleScroll = _.debounce(() => this.loadMore(), 200);
  }

  handleScroll() {
    var hT = $('#contentBottom').offset().top,
    hH = $('#contentBottom').outerHeight(),
    wH = $(window).height(),
    wS = $(this).scrollTop();
    if (wS > (hT + hH - wH) && (hT > wS) && (wS+wH > hT + hH)) {
      // essentially, I want to call the class method to load more photos
      this.loadMore(); // doesn't work, wrong 'this' context
    }
  }

  loadMore() {
    this.setState({
      // increase photos returned with this.state.photos.slice(0, this.state.numberToLoad);
      // so, the user gets to the bottom, trigger the load more, to increase the slice
      numberToLoad: this.state.numberToLoad + 4,
    });
  }

  render() {
    return (
    // I have tried <InfiniteScroll /> from 'react-infinite-scroller' but I'm not
// sure how to use it properly with pageStart, as I'm using array.slice()...
      <Component onScroll={this.handleScroll}>
        {this.renderPhotos()}
      </Component>
    )
  }
}
</code>```

Okay, so that is the general code, I'm using debounce so that the scroll isn't triggering hundreds of checks.

Thoughts?

Errors I get:

```<code>Uncaught TypeError: this.loadMore is not a function
</code>```

答:
You need to bind your methods

```<code>this.handleScroll = _.debounce(this.loadMore.bind(this), 200);
</code>```

Also, this line will immediately overwrite your definition of handleScroll, making it (the definition) redundant.  Perhaps you meant:

```<code>this.handleScroll = _.debounce(this.handleScroll.bind(this), 200);
</code>```

Also, as functions are first-class objects in Javascript, these 2 statements are essentially identical:

```<code>_.debounce(() => this.loadMore(), 200)
_.debounce(this.loadMore, 200)
</code>```

Body:
So, essentially, my own lazy loader... I want to fire a class method every time a scroll takes place and check to see if the user has scrolled to the bottom. If so, then load more components. I know there are packages for this (infinity-scroll / infinity-scroller), but I feel like I'm pretty close with my own code.

export default class Gallery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      photos: [ // data from mongodb ],
      numberToLoad: 0,
    };

    this.handleScroll = _.debounce(() => this.loadMore(), 200);
  }

  handleScroll() {
    var hT = $('#contentBottom').offset().top,
    hH = $('#contentBottom').outerHeight(),
    wH = $(window).height(),
    wS = $(this).scrollTop();
    if (wS > (hT + hH - wH) && (hT > wS) && (wS+wH > hT + hH)) {
      // essentially, I want to call the class method to load more photos
      this.loadMore(); // doesn't work, wrong 'this' context
    }
  }

  loadMore() {
    this.setState({
      // increase photos returned with this.state.photos.slice(0, this.state.numberToLoad);
      // so, the user gets to the bottom, trigger the load more, to increase the slice
      numberToLoad: this.state.numberToLoad + 4,
    });
  }

  render() {
    return (
    // I have tried <InfiniteScroll /> from 'react-infinite-scroller' but I'm not
// sure how to use it properly with pageStart, as I'm using array.slice()...
      <Component onScroll={this.handleScroll}>
        {this.renderPhotos()}
      </Component>
    )
  }
}

Okay, so that is the general code, I'm using debounce so that the scroll isn't triggering hundreds of checks.

Thoughts?

Errors I get:

Uncaught TypeError: this.loadMore is not a function

Body:
You need to bind your methods

this.handleScroll = _.debounce(this.loadMore.bind(this), 200);

Also, this line will immediately overwrite your definition of handleScroll, making it (the definition) redundant.  Perhaps you meant:

this.handleScroll = _.debounce(this.handleScroll.bind(this), 200);

Also, as functions are first-class objects in Javascript, these 2 statements are essentially identical:

_.debounce(() => this.loadMore(), 200)
_.debounce(this.loadMore, 200)


问:
How to Open Menu from Activity w/o toolbar or menu button
I want to open the menu, the problem is my game uses full screen so there is no toolbar, no room for a FAB and no menu button. I have tried to use

```<code>openOptionsMenu();
</code>```

in an onClickListener from a button on the screen but it does nothing. If you have any suggestions please reply here.

答:
The answer I found was to use the PopupMenu, see the example and comments below.</p>

```<code>import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.new_game_button:
            //start new game
            break;

        case R.id.menu_button:
            /** Instantiating PopupMenu class */
            PopupMenu popup = new PopupMenu(getBaseContext(), view);
            /** Adding menu items to the popumenu */
            popup.getMenuInflater().inflate(R.menu.game_menu, popup.getMenu());
            /** Defining menu item click listener for the popup menu */
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {

                        case R.id.menu_more_apps:
                            //do something
                            return true;

                        case R.id.menu_about:
                            // do something
                            return true;

                        case R.id.menu_like_us:
                            //do something
                            return true;
            break;
</code>```

Body:
I want to open the menu, the problem is my game uses full screen so there is no toolbar, no room for a FAB and no menu button. I have tried to use

openOptionsMenu();

in an onClickListener from a button on the screen but it does nothing. If you have any suggestions please reply here.

Body:
The answer I found was to use the PopupMenu, see the example and comments below.

import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.new_game_button:
            //start new game
            break;

        case R.id.menu_button:
            /** Instantiating PopupMenu class */
            PopupMenu popup = new PopupMenu(getBaseContext(), view);
            /** Adding menu items to the popumenu */
            popup.getMenuInflater().inflate(R.menu.game_menu, popup.getMenu());
            /** Defining menu item click listener for the popup menu */
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {

                        case R.id.menu_more_apps:
                            //do something
                            return true;

                        case R.id.menu_about:
                            // do something
                            return true;

                        case R.id.menu_like_us:
                            //do something
                            return true;
            break;


问:
How to add a new line in textarea element?
I want to add a newline in a textarea. I tried with \n and
 tag but are not working. You can see above the HTML code. Can you help me to insert a newline in a textarea?

```<code><textarea cols='60' rows='8'>This is my statement one.\n This is my statement2</textarea>

<textarea cols='60' rows='8'>This is my statement one.<br/> This is my statement2</textarea>
</code>```

答:
I think you are confusing the syntax of different languages.

 is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

\n is the linefeed character literal (ASCII 10) in a Javascript string.

 is a line break in HTML. Many other elements, eg
,
, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

T.innerText = "Position of LF: " + t.value.indexOf("\n");

p1.innerHTML = t.value;
p2.innerHTML = t.value.replace("\n", "
");
p3.innerText = t.value.replace("\n", "
");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="t">Line 1
Line 2</textarea>

<p id='T'></p>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p></code>```

A few points to note about Html:

The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A link.</textarea> to see.

The P element renders all contiguous white spaces (including new lines) as one space.

The LF character does not render to a new line or line break in HTML.

The TEXTAREA renders LF as a new line inside the text area box.

ContentLicense: CC BY-SA 4.0

Body:
I want to add a newline in a textarea. I tried with \n and
 tag but are not working. You can see above the HTML code. Can you help me to insert a newline in a textarea?

<textarea cols='60' rows='8'>This is my statement one.\n This is my statement2</textarea>

<textarea cols='60' rows='8'>This is my statement one.
 This is my statement2</textarea>

Body:
I think you are confusing the syntax of different languages.

&#10; is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

\n is the linefeed character literal (ASCII 10) in a Javascript string.

<br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

T.innerText = "Position of LF: " + t.value.indexOf("\n");

p1.innerHTML = t.value;
p2.innerHTML = t.value.replace("\n", "<br/>");
p3.innerText = t.value.replace("\n", "<br/>");

<textarea id="t">Line 1&#10;Line 2</textarea>

<p id='T'></p>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p>

A few points to note about Html:

The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.

The P element renders all contiguous white spaces (including new lines) as one space.

The LF character does not render to a new line or line break in HTML.

The TEXTAREA renders LF as a new line inside the text area box.


问:
Why did my SQL Server database fill up so fast, and how can I get back my space?
Have a SQL Server environment in which we are using Microsoft SQL Server Management Studio to perform data analysis. The server capacity is 50GB and we loaded in about 8GB worth of '.csv' datasets using the Import Wizard. The 8GB worth of '.csv' files are no longer stored on the server environment.

However, after a few days of querying and creating three new tables, the full 50GB is taken up.

I tried to delete all interim tables, restart the server multiple times, turn off backup, and limit log autogrowth--all to no avail.

How can I get back my storage space? Or at least figure out what is using it all up?

答:
In Simple mode, the log files should cycle on themselves and cause few issues unless you have really big transactions.

In Full mode, the log will grow until you backup the database. Indeed, SQL Server wants to keep all the logs until the datas are safely stored somewhere else. So, rule of the thumb, in Full mode, you MUST backup your database.

Now, when you delete a record or a table, it is not physically deleted from the storage until you clean the database. Use the command DBCC SHRINKDATABASE to do that. You can also shrink a specific file, just lookup the various commands offered.

For more informations:

https://learn.microsoft.com/en-us/sql/relational-databases/databases/shrink-a-database

https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-shrinkdatabase-transact-sql

https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-shrinkfile-transact-sql


问:
How to get a count of the total number of lines in almost all files in git repository?
I have a problem where I have files in a directory with extensions .doc, .js, .pdf, .md, .txt

I want to ignore all files except .txt and get a count of the total number of lines in those files.

Using this command, I can ignore ones with .md, but how do I include other extensions?

```<code>git ls-files *[^.md] | xargs cat | wc -l
</code>```

I tried:

```<code>git ls-files *[^.md|^.pdf||^.doc] | xargs cat | wc -l
</code>```

but that does not work.

答:
You don't need git ls-files to do the work of limiting the files for you, you can just insert a grep into your pipeline for that.  This variant is affirmative, selecting only the extensions you list:

```<code>git ls-files | egrep '\.(doc|js|pdf|md)$' | xargs cat | wc -l
</code>```

This variant is negative, excluding .txt and keeping anything else:

```<code>git ls-files | egrep -v '\.txt$' | xargs cat | wc -l
</code>```

Note, however, that wc -l doesn't really give any meaningful output for binary files like Word docs and PDFs.

Body:
I have a problem where I have files in a directory with extensions .doc, .js, .pdf, .md, .txt

I want to ignore all files except .txt and get a count of the total number of lines in those files.

Using this command, I can ignore ones with .md, but how do I include other extensions?

git ls-files *[^.md] | xargs cat | wc -l

I tried:

git ls-files *[^.md|^.pdf||^.doc] | xargs cat | wc -l

but that does not work.

Body:
You don't need git ls-files to do the work of limiting the files for you, you can just insert a grep into your pipeline for that.  This variant is affirmative, selecting only the extensions you list:

git ls-files | egrep '\.(doc|js|pdf|md)$' | xargs cat | wc -l

This variant is negative, excluding .txt and keeping anything else:

git ls-files | egrep -v '\.txt$' | xargs cat | wc -l

Note, however, that wc -l doesn't really give any meaningful output for binary files like Word docs and PDFs.


问:
How to catch ESC key press with WndProc?
How to catch an ESC KeyPress using WndProc?</p>

答:
Another option (for forms):</p>

```<code>protected override bool ProcessKeyPreview(ref System.Windows.Forms.Message m)
{
  int VK_ESCAPE = 27;
  if (m.Msg == Win32Constants.WM_KEYDOWN && (int)m.WParam == VK_ESCAPE)
  {
    // ...
  }
  return base.ProcessKeyPreview(ref m);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Another option (for forms):

protected override bool ProcessKeyPreview(ref System.Windows.Forms.Message m)
{
  int VK_ESCAPE = 27;
  if (m.Msg == Win32Constants.WM_KEYDOWN && (int)m.WParam == VK_ESCAPE)
  {
    // ...
  }
  return base.ProcessKeyPreview(ref m);
}


问:
Outlook 365 EAS to Exchange 2013 server issue
Can anyone please help me if Outlook 365 is able to connect to Exchange 2013 server using EAS? When i try to configure Outlook 365, i am getting the below error.
"Log onto Exchange ActiveSync mail server (EAS): The server cannot be found"

Please note that AutoDiscover is configured in DNS. Please Help.
Thanks in advance.

答: Thanks for your support. I have figured out the issue. This particular domain name was not resolving from this particular users PC which is because of client side network issues. To resolve this issue we changed the DNS client IP and reconfigured outlook</p>


问:
cannot find symbol method findAndHookMethod(String,ClassLoader,String,<anonymous XC_MethodHook>)
I am very confused right now. Android Studio is recognizing everything from the Xposed API library, except the method findAndHookMethod().

This is my code:

```<code>package com.tylerr147.xposed.red.clock;

import android.graphics.Color;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;

public class XposedHook implements IXposedHookLoadPackage {
    public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
        if (!lpparam.packageName.equals("com.android.systemui"))
            return;

        findAndHookMethod("com.android.systemui.statusbar.policy.Clock", lpparam.classLoader, "updateClock", new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                TextView tv = (TextView) param.thisObject;
                String text = tv.getText().toString();
                tv.setText(text + " :)");
                tv.setTextColor(Color.RED);
            }
        });
    }
}
</code>```

The only error is the method findAndHookMethod(), Android Studio is not finding it in the Xposed API library.

My build.gradle is here:

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

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.tylerr147.xposed.red.clock"
        minSdkVersion 23
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:24.2.1'
    provided 'de.robv.android.xposed:api:82'
    provided 'de.robv.android.xposed:api:82:sources'
}
</code>```

Here is a screenshot of Android Studio with the error:
Image of error

I am just getting started with developing Xposed Modules (This app is literally rovo89's Red Clock tutorial), so if this is some stupid mistake, please pardon me.

Any help is extremely appreciated. If you need any more information all you need to do is ask!

答:
You're missing this line from the tutorial:

```<code>import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
</code>```

My guess is that your IDE removed it by accident. Alternatively, you can just change your use of findAndHookMethod to XposedHelpers.findAndHookMethod.

Body:
I am very confused right now. Android Studio is recognizing everything from the Xposed API library, except the method findAndHookMethod().

This is my code:

package com.tylerr147.xposed.red.clock;

import android.graphics.Color;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;

public class XposedHook implements IXposedHookLoadPackage {
    public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
        if (!lpparam.packageName.equals("com.android.systemui"))
            return;

        findAndHookMethod("com.android.systemui.statusbar.policy.Clock", lpparam.classLoader, "updateClock", new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                TextView tv = (TextView) param.thisObject;
                String text = tv.getText().toString();
                tv.setText(text + " :)");
                tv.setTextColor(Color.RED);
            }
        });
    }
}

The only error is the method findAndHookMethod(), Android Studio is not finding it in the Xposed API library.

My build.gradle is here:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.tylerr147.xposed.red.clock"
        minSdkVersion 23
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:24.2.1'
    provided 'de.robv.android.xposed:api:82'
    provided 'de.robv.android.xposed:api:82:sources'
}

Here is a screenshot of Android Studio with the error:
Image of error

I am just getting started with developing Xposed Modules (This app is literally rovo89's Red Clock tutorial), so if this is some stupid mistake, please pardon me.

Any help is extremely appreciated. If you need any more information all you need to do is ask!

Body:
You're missing this line from the tutorial:

import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;

My guess is that your IDE removed it by accident. Alternatively, you can just change your use of findAndHookMethod to XposedHelpers.findAndHookMethod.


问:
Perl - remove double quotes from file name in a directory
I'm trying to find the best way to remove double quotes from all files in directory with perl. I know I can do this through 'rename \" "" *'. However when I have that in perl script, perl always complain the double quote is not closed. How can I work around it?

I've tried to call it with backtick inside my perl script rename \" "" * but this gave me bash error: 'unexpected EOF while looking for matching `"'

THe situation I have. I have files in directory with this name 123."ABC".xyz. I want to rename them with perl scripts ideally with rename command.

Thanks,

答:
How can I work around it?

No work around is needed; you simply have to fix your bug. To remove remove double-quotes (") from a string, you can use the following:

```<code>$string =~ s/"//g;
</code>```

I've tried to call it with backtick inside my perl script rename \" "" *

You did

```<code>`rename \" "" *`    # Produces the string <<rename " "" *>> and executes it.
</code>```

when you should have used

```<code>`rename \\" "" *`   # Produces the string <<rename \" "" *>> and executes it.
</code>```

Body:
How can I work around it?

No work around is needed; you simply have to fix your bug. To remove remove double-quotes (") from a string, you can use the following:

$string =~ s/"//g;

I've tried to call it with backtick inside my perl script rename \" "" *

You did

`rename \" "" *`    # Produces the string <<rename " "" *>> and executes it.

when you should have used

`rename \\" "" *`   # Produces the string <<rename \" "" *>> and executes it.


问:
SQL - Constraint on insert value to be less than existed value in other rows
I do have a table that looks like:

```<code>CategoryID | GameNO | Name         | Price
-----------+--------+--------------+-------
     1     |    1   | Zelda        |   10
     1     |    2   | Sonic        |   12
     2     |    1   | Metal Gear   |   21
     2     |    2   | Street Fight |   15
</code>```

Where both CategoryID & GameNo are a primary key, and GameNo is a foreign key to another relation.

I want to alter the table and add constraint that each category game price to not be greater than the double price of any other from the same category?

For instance if I want to do:

```<code>insert into tableName
values (1, 3, 'Super Mario', 21);
</code>```

The inserted price for Super Mario 21 is greater than the double price of Zelda which is 10. I want to constraint this to be not accepted?

答: You should use a trigger after update or after insert.</p>

Body:
I do have a table that looks like:

CategoryID | GameNO | Name         | Price
-----------+--------+--------------+-------
     1     |    1   | Zelda        |   10
     1     |    2   | Sonic        |   12
     2     |    1   | Metal Gear   |   21
     2     |    2   | Street Fight |   15

Where both CategoryID & GameNo are a primary key, and GameNo is a foreign key to another relation.

I want to alter the table and add constraint that each category game price to not be greater than the double price of any other from the same category?

For instance if I want to do:

insert into tableName
values (1, 3, 'Super Mario', 21);

The inserted price for Super Mario 21 is greater than the double price of Zelda which is 10. I want to constraint this to be not accepted?


问:
How to stop execve from exiting original program
I have written my own shell and wrote a function that handles triple piping but I have an issue with my shell exiting after execve. I believe the issue is that I need to fork an extra time? but I am not entirely sure where, since this executes the piped programs perfectly. Also there is no use of wait(2) in this implementation, not sure if that has something to do with it too. Thanks</p>

```<code>int fd[2];
int fd2[2];

if (pipe(fd) == -1)
{
    perror("ERROR CREATING PIPE");
    return;
}

pid_t pid = fork();

if (args4[0] != NULL)
{
    switch(pid)
    {
        case -1:
            printf("%s\n", "fail to fork");
            return;
        case 0:
            if (pipe(fd2) == -1)
            {
                perror("ERROR CREATING PIPE");
                return;
            }
            switch(pid = fork())
            {
                case -1:
                    printf("%s\n", "fail to fork");
                    return;
                    break;
                case 0:
                    if ( dup2(fd2[1], STDOUT_FILENO) == -1 )
                    {
                        printf("%s\n", "fail to dup");
                        return;
                    }
                    close(fd2[0]);
                    close(fd2[1]);
                    execve(args2[0], args2, environ);
                    exit(1);
                default:
                    if ( dup2(fd2[0], STDIN_FILENO) == -1 )
                    {
                        printf("%s\n", "fail to dup");
                        return;
                    }
                    if ( dup2(fd[1], STDOUT_FILENO) == -1 )
                    {
                        printf("%s\n", "fail to dup");
                        return;
                    }
                    close(fd2[0]);
                    close(fd2[1]);
                    execve(args3[0], args3, environ);
                    exit(2);
            }
            exit(3);

        default:
            if ( dup2(fd[0], STDIN_FILENO) == -1)
            {
                printf("%s\n", "fail to dup");
                return;
            }
            close(fd[0]);
            close(fd[1]);
            printf("%s\n", "4");
            execve(args4[0], args4, environ);
            exit(4);
    }
}
</code>```

答:
You have forked twice so you have 3 processes. Each of them is replaced by the respective process created by execve. You will never get to the exit() statements since execve() does not return (on success). Here is your code rewritten without the pipes (you clearly understand how to set up the pipes) and without the unnecessary statements:

```<code>pid_t pid = fork();
if (pid) {
    execve(args4[0], args4, environ);
}
else {
    pid = fork();
    if (pid) {
        execve(args3[0], args3, environ);
    }
    else {
        execve(args2[0], args2, environ);
    }
}
</code>```

With the rewritten code above you can more easily see that you will get three processes like this:

args2[0] | args3[0] | arg4[0]

Body:
I have written my own shell and wrote a function that handles triple piping but I have an issue with my shell exiting after execve. I believe the issue is that I need to fork an extra time? but I am not entirely sure where, since this executes the piped programs perfectly. Also there is no use of wait(2) in this implementation, not sure if that has something to do with it too. Thanks

int fd[2];
int fd2[2];

if (pipe(fd) == -1)
{
    perror("ERROR CREATING PIPE");
    return;
}

pid_t pid = fork();

if (args4[0] != NULL)
{
    switch(pid)
    {
        case -1:
            printf("%s\n", "fail to fork");
            return;
        case 0:
            if (pipe(fd2) == -1)
            {
                perror("ERROR CREATING PIPE");
                return;
            }
            switch(pid = fork())
            {
                case -1:
                    printf("%s\n", "fail to fork");
                    return;
                    break;
                case 0:
                    if ( dup2(fd2[1], STDOUT_FILENO) == -1 )
                    {
                        printf("%s\n", "fail to dup");
                        return;
                    }
                    close(fd2[0]);
                    close(fd2[1]);
                    execve(args2[0], args2, environ);
                    exit(1);
                default:
                    if ( dup2(fd2[0], STDIN_FILENO) == -1 )
                    {
                        printf("%s\n", "fail to dup");
                        return;
                    }
                    if ( dup2(fd[1], STDOUT_FILENO) == -1 )
                    {
                        printf("%s\n", "fail to dup");
                        return;
                    }
                    close(fd2[0]);
                    close(fd2[1]);
                    execve(args3[0], args3, environ);
                    exit(2);
            }
            exit(3);

        default:
            if ( dup2(fd[0], STDIN_FILENO) == -1)
            {
                printf("%s\n", "fail to dup");
                return;
            }
            close(fd[0]);
            close(fd[1]);
            printf("%s\n", "4");
            execve(args4[0], args4, environ);
            exit(4);
    }
}

Body:
You have forked twice so you have 3 processes. Each of them is replaced by the respective process created by execve. You will never get to the exit() statements since execve() does not return (on success). Here is your code rewritten without the pipes (you clearly understand how to set up the pipes) and without the unnecessary statements:

pid_t pid = fork();
if (pid) {
    execve(args4[0], args4, environ);
}
else {
    pid = fork();
    if (pid) {
        execve(args3[0], args3, environ);
    }
    else {
        execve(args2[0], args2, environ);
    }
}

With the rewritten code above you can more easily see that you will get three processes like this:

args2[0] | args3[0] | arg4[0]


问:
Table CSS Issue
I have this in HTML:

```<code><div class="dataBurst" title="What is the Matrix?">
    <table align="center" height="100%">
        <tr>
            <td id="matrixTD">
                <span onclick="alert('Not Yet Online');" class="coredump"
                    title="How Would You Know the Difference Between the Dream World And the Real World?">
                    Click for System Core Dump
                </span>
            </td>
        </tr>
    </table>
</div>
</code>```

The CSS I'm using:

```<code>div.dataBurst
{
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

td#matrixTD
{
    text-align:justify;
    cursor:default;
}
</code>```

The issue is when I try to create a class/id using:
, it does not work; how can I implement this?

my site is at: http://guygar.com

答:
After think about it for a while I think I slowly get what you are after: You want to vertically align the text "Click for System Core Dump" inside the div #dataBurst

I think you are thinking too complicate here. There is no real need to actually vertical align anything here, just give the div big top and bottom paddings:

```<code><div class="dataBurst" title="What is the Matrix?" onclick="alert('Not Yet Online');">
     Click for System Core Dump
</div>

div.dataBurst {
    /* vertical-align:middle; -- not needed  */
    width:500px;
    padding: 150px 5px; /* First value is top/bottom, second is left/right. Adjust as neeeded. Replaces height:321px; */
    background-color:#FFF;
    text-align: center; /* replaces margin-left:auto; margin-right:auto; because you are centering inline text here. */
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    /*
       Remove following, since there is not overflow happening here anyway,
       so the scrollbar properties also become unnecessary - and wont work
       like this in newer IE's anyway, as they require the -ms- prefix.

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
    */
}
</code>```

Also you need to decide which title you really want. I've removed the inner one, because it's probably overridden by the outer one anyway.

Title: Table CSS Issue

Body:
I have this in HTML:

                    Click for System Core Dump

The CSS I'm using:

div.dataBurst
{
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

td#matrixTD
{
    text-align:justify;
    cursor:default;
}

The issue is when I try to create a class/id using:
, it does not work; how can I implement this?

my site is at: http://guygar.com

Body:
After think about it for a while I think I slowly get what you are after: You want to vertically align the text "Click for System Core Dump" inside the div #dataBurst

I think you are thinking too complicate here. There is no real need to actually vertical align anything here, just give the div big top and bottom paddings:

<div class="dataBurst" title="What is the Matrix?" onclick="alert('Not Yet Online');">
     Click for System Core Dump
</div>

div.dataBurst {
    /* vertical-align:middle; -- not needed  */
    width:500px;
    padding: 150px 5px; /* First value is top/bottom, second is left/right. Adjust as neeeded. Replaces height:321px; */
    background-color:#FFF;
    text-align: center; /* replaces margin-left:auto; margin-right:auto; because you are centering inline text here. */
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    /*
       Remove following, since there is not overflow happening here anyway,
       so the scrollbar properties also become unnecessary - and wont work
       like this in newer IE's anyway, as they require the -ms- prefix.

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
    */
}

Also you need to decide which title you really want. I've removed the inner one, because it's probably overridden by the outer one anyway.


问:
Building a timetable in Windows API with C
Making a simple program where the user inputs different classes, times and dates, and a timetable is generated (like a timetable with university classes). I've worked with Windows API for basic applications however I cannot find a way to display all the information in a timetable chart.

Something like this:

Is there a function that can be used in Windows API for displaying a timetable, or will I have to work with graphics to generate an image of a timetable (using OpenGL for instance)?

答:
If you are programming in Win32 mode, to use ListView control is a better choice. You could get references from msdn: ListView Control
You can also use the TextOut api to print information onto your Window form.</p>


问:
Calling a shell command from Applescript with quotes
This seems like it should be simple, but I'm pulling out my remaining hair trying to get it to work. In a shell script I want to run some Applescript code that defines a string, then pass that string (containing a single quote) to a shell command that calls PHP's addslashes function, to return a string with that single quote escaped properly.

Here's the code I have so far - it's returning a syntax error.

```<code>STRING=$(osascript -- - <<'EOF'
set s to "It's me"
return "['test'=>'" & (do shell script "php -r 'echo addslashes(\"" & s & "\");") & "']"
EOF)
echo -e $STRING
</code>```

It's supposed to return this:

```<code>['test'=>'It\'s me']
</code>```

答:
To complement Gordon Davisson's helpful answer with a pragmatic solution:

Shell strings cannot contain \0 (NUL) characters, but the following sed command emulates all other escaping that PHP's (oddly named) addslashes PHP function performs (\-escaping ', " and \ instances):

string=$(osascript <<'EOF'
  set s to "It's me\\you and we got 3\" of rain."
  return "['test'=>'" & (do shell script "sed 's/[\"\\\\'\\'']/\\\\&/g' <<<" & quoted form of s) & "']"
EOF
)
printf '%s\n' "$string"
```

<p>yields</p>

```['test'=>'It\'s me\\you and we got 3\" of rain.']
```

Note the use of quoted form of, which is crucial for passing a string from AppleScript to a do shell script shell command with proper quoting.

Also note how the closing here-doc delimiter, EOF, is on its own line to ensure that it is properly recognized (in Bash 3.2.57, as used on macOS 10.12, (also when called as /bin/sh, which is what do shell script does), this isn't strictly necessary, but Bash 4.x would rightfully complain about EOF) with warning: here-document at line <n> delimited by end-of-file (wanted 'EOF')

Body:
This seems like it should be simple, but I'm pulling out my remaining hair trying to get it to work. In a shell script I want to run some Applescript code that defines a string, then pass that string (containing a single quote) to a shell command that calls PHP's addslashes function, to return a string with that single quote escaped properly.

Here's the code I have so far - it's returning a syntax error.

STRING=$(osascript -- - <<'EOF'
set s to "It's me"
return "['test'=>'" & (do shell script "php -r 'echo addslashes(\"" & s & "\");") & "']"
EOF)
echo -e $STRING

It's supposed to return this:

['test'=>'It\'s me']

Body:
To complement Gordon Davisson's helpful answer with a pragmatic solution:

Shell strings cannot contain \0 (NUL) characters, but the following sed command emulates all other escaping that PHP's (oddly named) addslashes PHP function performs (\-escaping ', " and \ instances):

string=$(osascript <<'EOF'
  set s to "It's me\\you and we got 3\" of rain."
  return "['test'=>'" & (do shell script "sed 's/[\"\\\\'\\'']/\\\\&/g' <<<" & quoted form of s) & "']"
EOF
)
printf '%s\n' "$string"

yields

['test'=>'It\'s me\\you and we got 3\" of rain.']

Note the use of quoted form of, which is crucial for passing a string from AppleScript to a do shell script shell command with proper quoting.

Also note how the closing here-doc delimiter, EOF, is on its own line to ensure that it is properly recognized (in Bash 3.2.57, as used on macOS 10.12, (also when called as /bin/sh, which is what do shell script does), this isn't strictly necessary, but Bash 4.x would rightfully complain about EOF) with warning: here-document at line <n> delimited by end-of-file (wanted 'EOF')


问:
Java Class with multiple methods that can be executed in a thread
I am new to Java multithreaded programming. I have a use case where I have a runnable class called Diner and based on the state of different variables in the program, I want to execute different methods of the Diner Class in parallel.
One way to do that would be to have a single run() method containing multiple if conditions corresponding to different code blocks you want to execute as shown below.

```<code>    public class Diner implements Runnable  {
        Order order;
        int arrivalTime;

        public void run () {
            if(!isSeated){
                //do something to get a seat
            }
            if(!notEatenYet){
                //place order
            }
            if(!orderHasArrived){
                //start eating
            }
            if(finishedEating){
                //pay bill and leave
            }
        }
    }
</code>```

However, is there a more elegant way to do this? Like rather than having a single run() method that can be parallelized, have different methods in the class that could be parallelized (overloading run() ?).

I believe I can use Akka Actors to accomplish something like this, but I am looking for a native solution.

答:
If you are new to multi-threading consider easing into it gradually. Start with a single worker thread and post all your diner's tasks to this one thread.  This provides some concurrency - submitting tasks to the thread does not block - but eliminates many of the complexities of having multiple threads accessing the same Diner at the same time (synchronization, risk of deadlock, risk of race conditions etc)

Here is an example using a single thread scheduled executor.  It schedules some events to happen at 2, 4 and 6 seconds, but the calling thread does not block waiting for each event (although I do add an artificial block at the end with the countdown latch, so we can shutdown the executor cleanly)

```<code>public class Diner {

    public void findSeat() {
        System.out.println("findSeat");
    }
    public void placeOrder() {
        System.out.println("placeOrder");
    }

    public static void main(String[] args) throws InterruptedException {
        final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        final CountDownLatch done = new CountDownLatch(1);

        final Diner diner = new Diner();

        exec.schedule(new Runnable() {
            public void run() {
                diner.findSeat();
            }
        }, 2, TimeUnit.SECONDS);

        exec.schedule(new Runnable() {
            public void run() {
                diner.placeOrder();
            }
        }, 4, TimeUnit.SECONDS);

        exec.schedule(new Runnable() {
            public void run() {
                done.countDown();
            }
        }, 6, TimeUnit.SECONDS);

        done.await();
        exec.shutdown();
        System.out.println("done");
    }
}
</code>```

Also there is no need for your Diner to implement Runnable.  Just create temporary
 runnables as necessary for each task.

When you need additional concurrency add a second, third executor service.  If you
 have tasks which are "stateless" - such as a database query - you could add a new
 executor service with multiple threads to get better parallelism.  Just make sure that
 when you update your diner your db threads do so by scheduling a task to the Diner
 executor, instead of modifying diner directly.

This would give you an Akka-esque style, but just using native Java utilities.

Body:
I am new to Java multithreaded programming. I have a use case where I have a runnable class called Diner and based on the state of different variables in the program, I want to execute different methods of the Diner Class in parallel.
One way to do that would be to have a single run() method containing multiple if conditions corresponding to different code blocks you want to execute as shown below.

    public class Diner implements Runnable  {
        Order order;
        int arrivalTime;

        public void run () {
            if(!isSeated){
                //do something to get a seat
            }
            if(!notEatenYet){
                //place order
            }
            if(!orderHasArrived){
                //start eating
            }
            if(finishedEating){
                //pay bill and leave
            }
        }
    }

However, is there a more elegant way to do this? Like rather than having a single run() method that can be parallelized, have different methods in the class that could be parallelized (overloading run() ?).

I believe I can use Akka Actors to accomplish something like this, but I am looking for a native solution.

Body:
If you are new to multi-threading consider easing into it gradually. Start with a single worker thread and post all your diner's tasks to this one thread.  This provides some concurrency - submitting tasks to the thread does not block - but eliminates many of the complexities of having multiple threads accessing the same Diner at the same time (synchronization, risk of deadlock, risk of race conditions etc)

Here is an example using a single thread scheduled executor.  It schedules some events to happen at 2, 4 and 6 seconds, but the calling thread does not block waiting for each event (although I do add an artificial block at the end with the countdown latch, so we can shutdown the executor cleanly)

public class Diner {

    public void findSeat() {
        System.out.println("findSeat");
    }
    public void placeOrder() {
        System.out.println("placeOrder");
    }

    public static void main(String[] args) throws InterruptedException {
        final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        final CountDownLatch done = new CountDownLatch(1);

        final Diner diner = new Diner();

        exec.schedule(new Runnable() {
            public void run() {
                diner.findSeat();
            }
        }, 2, TimeUnit.SECONDS);

        exec.schedule(new Runnable() {
            public void run() {
                diner.placeOrder();
            }
        }, 4, TimeUnit.SECONDS);

        exec.schedule(new Runnable() {
            public void run() {
                done.countDown();
            }
        }, 6, TimeUnit.SECONDS);

        done.await();
        exec.shutdown();
        System.out.println("done");
    }
}

Also there is no need for your Diner to implement Runnable.  Just create temporary
 runnables as necessary for each task.

When you need additional concurrency add a second, third executor service.  If you
 have tasks which are "stateless" - such as a database query - you could add a new
 executor service with multiple threads to get better parallelism.  Just make sure that
 when you update your diner your db threads do so by scheduling a task to the Diner
 executor, instead of modifying diner directly.

This would give you an Akka-esque style, but just using native Java utilities.


问:
React included script data not recognized
I have a React setup with an index.html page which includes a JavaScript file defining a simple variable:

```<code>var pData = {};
</code>```

Inside my index.js file I tried to access this variable in a simple way:

```<code>ReactDOM.render(
  <App presData={ pData }/>,
  document.getElementById('root')
);
</code>```

But after running npm start this does not compile because it says 'pData' is not defined.

When I add some debug I get something really strange to me:

```<code>var testData;
if (typeof pData === "object") {
    testData = pData; // Fails on this line because pData is not defined!
} else {
    alert("Typeof pData inside index.js: " + (typeof pData));
}
</code>```

The above code fails because the variable is not defined inside a code block that is only executed when the variable is defined as an object.

How is this possible, and how do I get access to this variable inside the React file?

Thanks in advance for any help.

Paul

答:
You can use window.pData = {}; it will be available but it's not a good practice. If you're using ES6 with babel you can import your variable with import.

myData.js

```<code>var pData = {};
export default pData;
</code>```

index.js :

```<code>import pData from './myData.js';

ReactDOM.render(
  <App presData={ pData }/>,
  document.getElementById('root')
);
</code>```

Body:
I have a React setup with an index.html page which includes a JavaScript file defining a simple variable:

var pData = {};

Inside my index.js file I tried to access this variable in a simple way:

ReactDOM.render(
  <App presData={ pData }/>,
  document.getElementById('root')
);

But after running npm start this does not compile because it says 'pData' is not defined.

When I add some debug I get something really strange to me:

var testData;
if (typeof pData === "object") {
    testData = pData; // Fails on this line because pData is not defined!
} else {
    alert("Typeof pData inside index.js: " + (typeof pData));
}

The above code fails because the variable is not defined inside a code block that is only executed when the variable is defined as an object.

How is this possible, and how do I get access to this variable inside the React file?

Thanks in advance for any help.

Paul

Body:
You can use window.pData = {}; it will be available but it's not a good practice. If you're using ES6 with babel you can import your variable with import.

myData.js

var pData = {};
export default pData;

index.js :

import pData from './myData.js';

ReactDOM.render(
  <App presData={ pData }/>,
  document.getElementById('root')
);


答:
This is because your js file is include in html, so When staring compile, index.js doesn't know where pData defined.

Let's say the code var pData = {}; is in a file named data.js, and it's in the same folder with index.js, try

```<code>import './data.js';
</code>```

at first line in  index.js file;

Title: React included script data not recognized

Body:
This is because your js file is include in html, so When staring compile, index.js doesn't know where pData defined.

Let's say the code var pData = {}; is in a file named data.js, and it's in the same folder with index.js, try

import './data.js';

at first line in  index.js file;


问:
window border width and height in Win32 - how do I get it?
```
      ::GetSystemMetrics (SM_CYBORDER)
```

...comes back with 1 and I know the title bar is taller than ONE pixel :/

I also tried:

```
     RECT r;
      r.left = r.top = 0;   r.right = r.bottom = 400;
      ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
      _bdW = (uword)(r.right - r.left - 400);
      _bdH = (uword)(r.bottom - r.top - 400);
```

But border w,h came back as 0.

In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.

But ::MoveWindow needs the dimensions WITH the border space added in.

SOMEbody must have done this before...
Thanks for any help :)

答: Head Geek gives the detailed answer: use GetSystemMetrics to add up the caption and border bits.  You can also do a difference on width/height between the GetWindowRect and GetClientRect.  This will give you the total of all captions/borders/etc.</p>

OwnerDisplayName: Stephen Hazel

Body:
      ::GetSystemMetrics (SM_CYBORDER)

...comes back with 1 and I know the title bar is taller than ONE pixel :/

I also tried:

     RECT r;
      r.left = r.top = 0;   r.right = r.bottom = 400;
      ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
      _bdW = (uword)(r.right - r.left - 400);
      _bdH = (uword)(r.bottom - r.top - 400);

But border w,h came back as 0.

In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.

But ::MoveWindow needs the dimensions WITH the border space added in.

SOMEbody must have done this before...
Thanks for any help :)

OwnerDisplayName: CodeGuy


问:
check for the option label string
I'm using the option Label string for my Html.DropDownList but my datasource is a SelectList. How I would check for the option label back on the server? The backing type for the variable is an EnumType. I inspected the value and it says 0 but it won't let me check for 0.

Thanks,
rod.

答: You can't.  Labels aren't posted with the form.  You'll need to place the value in a <input type="hidden"> if you want the value.

Title: check for the option label string


问:
list.retainAll() on empty list returns true
In some experiments, I found out that list.retainAll(list2) returns true if list2 is an empty list even if no changes have been made on the initial list.

Why is that so?

Project code:

```<code>private static boolean isUpToDate(Map<Long, List<Operation>> writeSet, List<Operation> localWriteSet,
        List<NodeStorage> readSetNode,
        List<RelationshipStorage> readSetRelationship, long snapshotId)
{
    return !writeSet.keySet().stream().filter(id -> id > snapshotId).anyMatch(id -> new ArrayList<>(writeSet.get(id)).retainAll(readSetNode));
}
</code>```

Code it also happened to me:

```<code>new ArrayList(writeSet.get(id)).retainAll(new ArrayList<>());
</code>```

答:
Did you actually read the documentation on retainAll()?

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

Returns:

true if this list changed as a result of the call

Therefore, what you are describing is exactly what you should be seeing:

If you pass an empty list to list.retainAll(), all elements will be removed from list. Therefore, list has been changed and the call will return true.

Body:
In some experiments, I found out that list.retainAll(list2) returns true if list2 is an empty list even if no changes have been made on the initial list.

Why is that so?

Project code:

private static boolean isUpToDate(Map<Long, List<Operation>> writeSet, List<Operation> localWriteSet,
        List<NodeStorage> readSetNode,
        List<RelationshipStorage> readSetRelationship, long snapshotId)
{
    return !writeSet.keySet().stream().filter(id -> id > snapshotId).anyMatch(id -> new ArrayList<>(writeSet.get(id)).retainAll(readSetNode));
}

Code it also happened to me:

new ArrayList(writeSet.get(id)).retainAll(new ArrayList<>());


问:
How do I create a custom button/action in a Chromecast expanded controller?
I'm developing an Android application using the Chromecast SDK v3.

I need to create custom button with a custom action in a Chromecast expanded controller.

I'm aware of the custom button type "@id/cast_button_type_custom," but I'm not sure how to create it. How can I create a button of this type with a custom action? Is this even possible?

答: You can read about what type of customization you can make to the ExpandedController here. As for buttons, there is a fixed set of button/actions that it supports, same set as what the Mini Controller supports. To see an example of how this can be used, checkout the official v3 sample: CastVideos-android.</p>


问:
AWS EC2 - browser can't connect to server
I'm trying to point my static portfolio url, laurenleague.io to AWS EC2 so I can build a site there.

I've followed a tutorial on setting AWS EC2 up and installing Apache on it. It seems like I've done everything right, including enabling HTTP on port 80 in the inbound rules of the security groups. I can ssh into the machine, so my key pair is fine. I can also ping the public dns, public ip, and my new url and get a response.

However, my browser can't connect to the server.

In my security groups on AWS, it says port 80 is open and accepting traffic from anywhere. But when I run nmap from my shell, it says port 80 is closed! Why??

Please help, this is driving me crazy.

答:
GOT IT!

Thanks to @stdunbar, I logged into my machine and found out that Apache server on my EC2 had stopped! I found this out by ssh-ing into it and running:

```<code>sudo ps -efww | grep httpd
</code>```

which returned nothing. So I rebooted Apache with:

```<code>sudo service httpd start
</code>```

And now it works!

Body:
GOT IT!

Thanks to @stdunbar, I logged into my machine and found out that Apache server on my EC2 had stopped! I found this out by ssh-ing into it and running:

sudo ps -efww | grep httpd

which returned nothing. So I rebooted Apache with:

sudo service httpd start

And now it works!


问:
Anaconda is not creating full environment

I'm trying to create a conda environment using git-bash and win10. I ran:

```<code>$ conda create --name my_env
</code>```

The result looks like the screenshot above.

Looking at other environments , I can see they normally look like:

How can I fix this?

答:
To create the environment with the Python executable, use one of:

```<code>conda create --name my_env python  # latest available python version
conda create --name my_env python=3.7  # specific python version
</code>```

Without specifying packages, i.e. python as above, conda just doesn't install anything at all in my_env environment.

You can alternatively install the Python interpreter after environment creation. For a list of installable Python versions, run conda search "^python$".

```<code>conda install python  # latest available python version
conda install python=3.7  # specific python version
</code>```

Body:
I'm trying to create a conda environment using git-bash and win10. I ran:

$ conda create --name my_env

The result looks like the screenshot above.

Looking at other environments , I can see they normally look like:

How can I fix this?

Body:
To create the environment with the Python executable, use one of:

conda create --name my_env python  # latest available python version
conda create --name my_env python=3.7  # specific python version

Without specifying packages, i.e. python as above, conda just doesn't install anything at all in my_env environment.

You can alternatively install the Python interpreter after environment creation. For a list of installable Python versions, run conda search "^python$".

conda install python  # latest available python version
conda install python=3.7  # specific python version