问:
Cannot resubmit job to ml-engine because "A job with this id already exists"
I am trying to submit a job to gcloud ml-engine. For reference the job is using this sample provided by Google

It went through the first time, but with errors unrelated to this question, and now I am trying reissue the command after having corrected my errors:

```<code>gcloud ml-engine jobs submit training $JOB_NAME \
                                    --stream-logs \
                                    --runtime-version 1.0 \
                                    --job-dir $GCS_JOB_DIR \
                                    --module-name trainer.task \
                                    --package-path trainer/ \
                                    --region us-east1 \
                                    -- \
                                    --train-files $TRAIN_GCS_FILE \
                                    --eval-files $EVAL_GCS_FILE \
                                    --train-steps $TRAIN_STEPS
</code>```

, where $JOB_NAME = census. Unfortunately, it seems that I cannot proceed with resubmitting the job unless I change $JOB_NAME to be something like census2, then census3, etc. for every new job.

The following is the error I receive:

```<code>ERROR: (gcloud.ml-engine.jobs.submit.training) Project [my-project-name]
is the subject of a conflict: Field: job.job_id Error: A job with this
id already exists.
</code>```

Is this part of the design to not be able to resubmit using the same job name or I am missing something?

答:
Not sure if this will help but in Google's sample code for flowers, the error is avoided by appending the date and time to the job id as shown on line 22, e.g.,</p>

```<code>declare -r JOB_ID="flowers_${USER}_$(date +%Y%m%d_%H%M%S)"
</code>```

Body:
I am trying to submit a job to gcloud ml-engine. For reference the job is using this sample provided by Google

It went through the first time, but with errors unrelated to this question, and now I am trying reissue the command after having corrected my errors:

gcloud ml-engine jobs submit training $JOB_NAME \
                                    --stream-logs \
                                    --runtime-version 1.0 \
                                    --job-dir $GCS_JOB_DIR \
                                    --module-name trainer.task \
                                    --package-path trainer/ \
                                    --region us-east1 \
                                    -- \
                                    --train-files $TRAIN_GCS_FILE \
                                    --eval-files $EVAL_GCS_FILE \
                                    --train-steps $TRAIN_STEPS

, where $JOB_NAME = census. Unfortunately, it seems that I cannot proceed with resubmitting the job unless I change $JOB_NAME to be something like census2, then census3, etc. for every new job.

The following is the error I receive:

ERROR: (gcloud.ml-engine.jobs.submit.training) Project [my-project-name]
is the subject of a conflict: Field: job.job_id Error: A job with this
id already exists.

Is this part of the design to not be able to resubmit using the same job name or I am missing something?

Body:
Not sure if this will help but in Google's sample code for flowers, the error is avoided by appending the date and time to the job id as shown on line 22, e.g.,

declare -r JOB_ID="flowers_${USER}_$(date +%Y%m%d_%H%M%S)"


来源: stackexchange

问:
How to check the amount of time between two NSDates?
I'm making a kind of challenge based app that requires that the user comes back every day. If he misses one day, he has to start all over again.
My problem is my dateChanged()-function; the first thing is, that it doesn't work very reliable, the second is that I just check if the date changed, I accordingly don't know if there were one or two days between using the app.
Here's my current function:

```<code>public func changeDays()
{
    myFormatter.dateStyle = .short
    myFormatter.locale = Locale(identifier: "de_DE")

    oldDate = defaults.string(forKey: "oldDate")!
    let newDate = Date()
    let newDateString = myFormatter.string(from: newDate)

    if newDateString == oldDate
    {
        NumberOfDaysInARow.text = "\(days) / 30"
    }
    else if newDateString != oldDate
    {
        days += 1
        NumberOfDaysInARow.text = "\(days) / 30"
        defaults.set(days, forKey: "days")
    }

    oldDate = newDateString
    defaults.set(oldDate, forKey: "oldDate")

}
</code>```

Just today it started giving me a fatal error when starting the app on my iPhone, did not happen in the simulator though... weird.
How do I have to change my function to make it a 100% reliable (and working) while also being able to check the amount of time between the two dates?

Thank you for having a look! Have a great day

答:
You could extend Date with the function below that returns the amount of days from another date.

```<code>extension Date {

  // Returns the amount of days from another date
  func days(from date: Date) -> Int {
    return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
  }
}
</code>```

Instead of saving oldDate as a string you can set it to defaults as a date:

```<code>defaults.set(Date(), forKey: "oldDate")
</code>```

You can get the old date from defaults using:

```<code>let oldDate = defaults.object(forKey:"oldDate") as! Date
</code>```

Once you have your old date

```<code>let dateNow = Date()

let timeDifference = dateNow.days(from: oldDate!)

If timeDifference > 1 {
 // older than 1 day
  } else {
  // Streak still alive
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm making a kind of challenge based app that requires that the user comes back every day. If he misses one day, he has to start all over again.
My problem is my dateChanged()-function; the first thing is, that it doesn't work very reliable, the second is that I just check if the date changed, I accordingly don't know if there were one or two days between using the app.
Here's my current function:

public func changeDays()
{
    myFormatter.dateStyle = .short
    myFormatter.locale = Locale(identifier: "de_DE")

    oldDate = defaults.string(forKey: "oldDate")!
    let newDate = Date()
    let newDateString = myFormatter.string(from: newDate)

    if newDateString == oldDate
    {
        NumberOfDaysInARow.text = "\(days) / 30"
    }
    else if newDateString != oldDate
    {
        days += 1
        NumberOfDaysInARow.text = "\(days) / 30"
        defaults.set(days, forKey: "days")
    }

    oldDate = newDateString
    defaults.set(oldDate, forKey: "oldDate")

}

Just today it started giving me a fatal error when starting the app on my iPhone, did not happen in the simulator though... weird.
How do I have to change my function to make it a 100% reliable (and working) while also being able to check the amount of time between the two dates?

Thank you for having a look! Have a great day

Body:
You could extend Date with the function below that returns the amount of days from another date.

extension Date {

  // Returns the amount of days from another date
  func days(from date: Date) -> Int {
    return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
  }
}

Instead of saving oldDate as a string you can set it to defaults as a date:

defaults.set(Date(), forKey: "oldDate")

You can get the old date from defaults using:

let oldDate = defaults.object(forKey:"oldDate") as! Date

Once you have your old date

let dateNow = Date()

let timeDifference = dateNow.days(from: oldDate!)

If timeDifference > 1 {
 // older than 1 day
  } else {
  // Streak still alive
  }
}


问:
Scala: map just first element in tuple
I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.

This is naive version for Tuple2:

```<code>def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
     |   case (x, y) => f(x) -> y
     | }

mapFirst((1, 2))(_ * 5) // returns (5, 2)
</code>```

Though, it doesn't feel native, what I want is to write it this way:

```<code>(1, 2).mapFirst(_ * 5)
</code>```

I wrote implicit conversion then:

```<code>class RichTuple[T, U](tuple: (T, U)) {
  def mapFirst[R](f: T => R): (R, U) = tuple match {
    case (x, y) => f(x) -> y
  }
}

implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)

(1, 2).mapFirst(_ * 5)
</code>```

Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?

答:
You can  use shapeless tuple functions:</p>

```<code>import shapeless._
import syntax.std.tuple._
val x=(1,2,3)
val y=x.updatedAt(0,x.head*5)
// y= (5,2,3)
</code>```

Title: Scala: map just first element in tuple

Body:
I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.

This is naive version for Tuple2:

def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
     |   case (x, y) => f(x) -> y
     | }

mapFirst((1, 2))(_ * 5) // returns (5, 2)

Though, it doesn't feel native, what I want is to write it this way:

(1, 2).mapFirst(_ * 5)

I wrote implicit conversion then:

class RichTuple[T, U](tuple: (T, U)) {
  def mapFirst[R](f: T => R): (R, U) = tuple match {
    case (x, y) => f(x) -> y
  }
}

implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)

(1, 2).mapFirst(_ * 5)

Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?

Body:
You can  use shapeless tuple functions:

import shapeless._
import syntax.std.tuple._
val x=(1,2,3)
val y=x.updatedAt(0,x.head*5)
// y= (5,2,3)


问:
Can you have more than one transport client in Spring Boot?
So I have a Spring Boot application. I've been using it with ElasticSearch. Now I have added an HBase connection. They use transport protocols, I believe TCP clients to connect and communicate.

However, I am now getting some sort of lifecycle error in Spring Boot. I'm wondering if this means that having more than one connection like this (kinda like a socket) means that they need to be in their own threads somehow? I thought Spring Boot would automatically handle that in a way.

```<code>@PostConstruct
</code>```

Do I need them in their own threads? Should I separate them into different Java Apps?

If I separate them, wouldn't I need to find a way to record things in both? How would they communicate?

答: Yes, turns out the problems I face are when there are netty conflicts. Once netty conflicts in POM.xml are resolved, it can multi-thread connect using Spring Boot to different servers.</p>

Body:
So I have a Spring Boot application. I've been using it with ElasticSearch. Now I have added an HBase connection. They use transport protocols, I believe TCP clients to connect and communicate.

However, I am now getting some sort of lifecycle error in Spring Boot. I'm wondering if this means that having more than one connection like this (kinda like a socket) means that they need to be in their own threads somehow? I thought Spring Boot would automatically handle that in a way.

@PostConstruct

Do I need them in their own threads? Should I separate them into different Java Apps?

If I separate them, wouldn't I need to find a way to record things in both? How would they communicate?


问:
How to unit test a "disk full" scenario with Ruby RSpec?
I need to unit test scenarios like the following:

The disk has 1MB free space. I try to copy 2MB of file(s) to the disk.

What's the best way to do this with Ruby RSpec?

For further information, I need to unit test the following file cache method, since it appears to have some issue:

```<code>def set first_key, second_key='', files=[]
  # If cache exists already, overwrite it.
  content_dir = get first_key, second_key
  second_key_file = nil

  begin
    if (content_dir.nil?)

      # Check the size of cache, and evict entries if too large
      check_cache_size if (rand(100) < check_size_percent)

      # Make sure cache dir doesn't exist already
      first_cache_dir = File.join(dir, first_key)
      if (File.exist?first_cache_dir)
        raise "BuildCache directory #{first_cache_dir} should be a directory" unless File.directory?(first_cache_dir)
      else
        FileUtils.mkpath(first_cache_dir)
      end
      num_second_dirs = Dir[first_cache_dir + '/*'].length
      cache_dir = File.join(first_cache_dir, num_second_dirs.to_s)
      # If cache directory already exists, then a directory must have been evicted here, so we pick another name
      while File.directory?cache_dir
        cache_dir = File.join(first_cache_dir, rand(num_second_dirs).to_s)
      end
      content_dir = File.join(cache_dir, '/content')
      FileUtils.mkpath(content_dir)

      # Create 'last_used' file
      last_used_filename = File.join(cache_dir, 'last_used')
      FileUtils.touch last_used_filename
      FileUtils.chmod(permissions, last_used_filename)

      # Copy second key
      second_key_file = File.open(cache_dir + '/second_key', 'w+')
      second_key_file.flock(File::LOCK_EX)
      second_key_file.write(second_key)

    else
      log "overwriting cache #{content_dir}"

      FileUtils.touch content_dir + '/../last_used'
      second_key_file = File.open(content_dir + '/../second_key', 'r')
      second_key_file.flock(File::LOCK_EX)
      # Clear any existing files out of cache directory
      FileUtils.rm_rf(content_dir + '/.')
    end

    # Copy files into content_dir
    files.each do |filename|
      FileUtils.cp(filename, content_dir)
    end
    FileUtils.chmod(permissions, Dir[content_dir + '/*'])

    # Release the lock
    second_key_file.close
    return content_dir
  rescue => e
    # Something went wrong, like a full disk or some other error.
    # Delete any work so we don't leave cache in corrupted state
    unless content_dir.nil?
      # Delete parent of content directory
      FileUtils.rm_rf(File.expand_path('..', content_dir))
    end
    log "ERROR: Could not set cache entry. #{e.to_s}"
    return 'ERROR: !NOT CACHED!'
  end

end
</code>```

答:
One solution is to stub out methods that write to disk to raise an error. For example, for the specs that test disk space errors, you could try:

```<code>before do
  allow_any_instance_of(File).to receive(:open) { raise Errno::ENOSPC }
  # or maybe # allow(File).to receive(:write) { raise Errno::ENOSPC }
  # or       # allow(FileUtils).to receive(:cp) { raise Errno::ENOSPC }
  # or some combination of these 3...
end

it 'handles an out of disk space error' do
  expect{ my_disk_cache.set('key1', 'key2', [...]) }.to # your logic for how BuildCache::DiskCache should handle the error here.
end
</code>```

There are two problems with this however:

1) Errno::ENOSPC may not be the error you actually see getting raised. That error fits the description in your question, but depending on the peculiarities of your lib and the systems it runs on, you might not really be getting an Errno::ENOSPC error. Maybe you run out of RAM first and are getting Errno::ENOMEM, or maybe you have too many file descriptors open and are getting Errno::EMFILE. Of course if you want to be rigorous you could handle all of these, but this is time consuming and you'll get diminishing returns for handling the more obscure errors.

See this for more information on Errno errors.

2) This solution involves stubbing a specific method on a specific class. (File.open) This isn't ideal because it couples the setup for your test to the implementation in your code. That is to say, if you refactor BuildCache::DiskCache#set to not use File.open, then this test might start failing even though the method might be correct.

That said, File.open is fairly low level. I know that some FileUtils methods use File.open, (Notably, FileUtils.cp) so I would suggest just using that first allow_any_instance_of line. I'd expect that to handle most of your use cases.

Alternatively, there is a tool called fakefs that may be able to help you with this. I am not familiar with it, but it may well have functionality that helps with testing such errors. You may want to look into it.

Body:
I need to unit test scenarios like the following:

The disk has 1MB free space. I try to copy 2MB of file(s) to the disk.

What's the best way to do this with Ruby RSpec?

For further information, I need to unit test the following file cache method, since it appears to have some issue:

def set first_key, second_key='', files=[]
  # If cache exists already, overwrite it.
  content_dir = get first_key, second_key
  second_key_file = nil

  begin
    if (content_dir.nil?)

      # Check the size of cache, and evict entries if too large
      check_cache_size if (rand(100) < check_size_percent)

      # Make sure cache dir doesn't exist already
      first_cache_dir = File.join(dir, first_key)
      if (File.exist?first_cache_dir)
        raise "BuildCache directory #{first_cache_dir} should be a directory" unless File.directory?(first_cache_dir)
      else
        FileUtils.mkpath(first_cache_dir)
      end
      num_second_dirs = Dir[first_cache_dir + '/*'].length
      cache_dir = File.join(first_cache_dir, num_second_dirs.to_s)
      # If cache directory already exists, then a directory must have been evicted here, so we pick another name
      while File.directory?cache_dir
        cache_dir = File.join(first_cache_dir, rand(num_second_dirs).to_s)
      end
      content_dir = File.join(cache_dir, '/content')
      FileUtils.mkpath(content_dir)

      # Create 'last_used' file
      last_used_filename = File.join(cache_dir, 'last_used')
      FileUtils.touch last_used_filename
      FileUtils.chmod(permissions, last_used_filename)

      # Copy second key
      second_key_file = File.open(cache_dir + '/second_key', 'w+')
      second_key_file.flock(File::LOCK_EX)
      second_key_file.write(second_key)

    else
      log "overwriting cache #{content_dir}"

      FileUtils.touch content_dir + '/../last_used'
      second_key_file = File.open(content_dir + '/../second_key', 'r')
      second_key_file.flock(File::LOCK_EX)
      # Clear any existing files out of cache directory
      FileUtils.rm_rf(content_dir + '/.')
    end

    # Copy files into content_dir
    files.each do |filename|
      FileUtils.cp(filename, content_dir)
    end
    FileUtils.chmod(permissions, Dir[content_dir + '/*'])

    # Release the lock
    second_key_file.close
    return content_dir
  rescue => e
    # Something went wrong, like a full disk or some other error.
    # Delete any work so we don't leave cache in corrupted state
    unless content_dir.nil?
      # Delete parent of content directory
      FileUtils.rm_rf(File.expand_path('..', content_dir))
    end
    log "ERROR: Could not set cache entry. #{e.to_s}"
    return 'ERROR: !NOT CACHED!'
  end

end

Body:
One solution is to stub out methods that write to disk to raise an error. For example, for the specs that test disk space errors, you could try:

before do
  allow_any_instance_of(File).to receive(:open) { raise Errno::ENOSPC }
  # or maybe # allow(File).to receive(:write) { raise Errno::ENOSPC }
  # or       # allow(FileUtils).to receive(:cp) { raise Errno::ENOSPC }
  # or some combination of these 3...
end

it 'handles an out of disk space error' do
  expect{ my_disk_cache.set('key1', 'key2', [...]) }.to # your logic for how BuildCache::DiskCache should handle the error here.
end

There are two problems with this however:

1) Errno::ENOSPC may not be the error you actually see getting raised. That error fits the description in your question, but depending on the peculiarities of your lib and the systems it runs on, you might not really be getting an Errno::ENOSPC error. Maybe you run out of RAM first and are getting Errno::ENOMEM, or maybe you have too many file descriptors open and are getting Errno::EMFILE. Of course if you want to be rigorous you could handle all of these, but this is time consuming and you'll get diminishing returns for handling the more obscure errors.

See this for more information on Errno errors.

2) This solution involves stubbing a specific method on a specific class. (File.open) This isn't ideal because it couples the setup for your test to the implementation in your code. That is to say, if you refactor BuildCache::DiskCache#set to not use File.open, then this test might start failing even though the method might be correct.

That said, File.open is fairly low level. I know that some FileUtils methods use File.open, (Notably, FileUtils.cp) so I would suggest just using that first allow_any_instance_of line. I'd expect that to handle most of your use cases.

Alternatively, there is a tool called fakefs that may be able to help you with this. I am not familiar with it, but it may well have functionality that helps with testing such errors. You may want to look into it.


问:
Machine Learning on web, PHP connection with python
I'm currently working on a ML project with geo data...

In my web I let the models parameters of the machine learning algorithm to the user, then I send those to an Apache server where PHP gets the parameters... In js I use Ajax to make the POST request.

My ML algorithm is made with Python, right now is working with the library argparse to read the parameters that PHP sends (after of a verification) as command trough the function exec()

I have 2 problems with this:

If the ML model takes time to calculate the results, the exec function does't wait for them and returns null after some time, but if it's fast everything is ok. I already have the function set_limit_time(0); in my PHP file.

In my local machine it doesn't take so much time to calculate results like on the server, but the server has better hardware, so I don't know what is going on there.

PHP 7.0.15

Python 2.7

Server Apache/2.4.18 (Ubuntu 16.04.1 LTS)

Also, is there a better way to do this?.

答: I ended up opening a Python Socket and connecting PHP trough it, now the process it's still slower than my local machine but the timeout is not longer a problem.</p>

ContentLicense: CC BY-SA 4.0


问:
Two apps share one Redis. How to prevent cache collisions?
Two different versions of the application (debug and release) share same instance of Redis.
Both Debug and Release have identical source code and therefore identical caching keys for being stored in Redis.

Thus when Debug does redis.StringSet(key1, value1) Release could easily overwrite key1 or read incorrect value (since it should have its own key1).

Is there a way to avoid such interference?

答: Do not do that - sharing is bad. Spin a Redis instance per environment, each server has negligible overhead.</p>


问:
what is the equivalent component in android like uiindicator in iphone
can anybody tell what is the equivalent component in android like uiindicator in iphone give example

Thanks

答:
In activity java class:

```<code>protected void startProgress() {
    ProgressBar pbSpinner = (ProgressBar)findViewById(R.id.activity_progress_bar);
    pbSpinner.setVisibility(View.VISIBLE);
}

protected void stopProgress() {
    ProgressBar pbSpinner = (ProgressBar)findViewById(R.id.activity_progress_bar);
    pbSpinner.setVisibility(View.INVISIBLE);
}
</code>```

And in layout xml file you can add progress bar:

```<code><ProgressBar android:id="@+id/activity_progress_bar"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:layout_centerVertical="true">
</ProgressBar>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In activity java class:

protected void startProgress() {
    ProgressBar pbSpinner = (ProgressBar)findViewById(R.id.activity_progress_bar);
    pbSpinner.setVisibility(View.VISIBLE);
}

protected void stopProgress() {
    ProgressBar pbSpinner = (ProgressBar)findViewById(R.id.activity_progress_bar);
    pbSpinner.setVisibility(View.INVISIBLE);
}

And in layout xml file you can add progress bar:

<ProgressBar android:id="@+id/activity_progress_bar"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:layout_centerVertical="true">
</ProgressBar>


问:
Wordpress search form 2 input text field
I have a Wordpress site. I want to search with 2 input text field in one search form. One for searching title and one for custom-field.</p>

答:
First, you'll need to create a searchform.php file in your theme with the new field. It's best to create a child theme for any custom work.

Once you've modified the search form, you'll need to hook into the search query. I don't know off hand what filter you'll need to use, probably the pre_get_posts hook. There's some good documentation about how to use pre_get_posts on wp's codex.


问:
How to use a DocumentDB(MongoDB) connection string as an Environment variable in an Azure Resource Management Template
I want to use a DocumentDB(MongoDB) connection string as an environment variable in an Azure Resource Management Template. Forexample i have a resource group which has a wep app and a DocumentDB(MongoDB) database.

```<code>"siteConfig": {
          "appSettings": [
            {
              "name": "db",
              "value": "connection string"
            }
          ]
        }
</code>```

How can i assign an environment variable to a connection string in template?

答:
After a bit of a struggle:</p>

```<code>"appSettings": [{
                    "Name": "DOCUMENTDB_ENDPOINT",
                    "Value": "[reference(concat('Microsoft.DocumentDb/databaseAccounts/', parameters('databaseAccountName'))).documentEndpoint]"
                }, {
                    "Name": "DOCUMENTDB_PRIMARY_KEY",
                    "Value": "[listKeys(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('databaseAccountName')), '2015-04-08').primaryMasterKey]"
                }]
</code>```

Body:
I want to use a DocumentDB(MongoDB) connection string as an environment variable in an Azure Resource Management Template. Forexample i have a resource group which has a wep app and a DocumentDB(MongoDB) database.

"siteConfig": {
          "appSettings": [
            {
              "name": "db",
              "value": "connection string"
            }
          ]
        }

How can i assign an environment variable to a connection string in template?

Body:
After a bit of a struggle:

"appSettings": [{
                    "Name": "DOCUMENTDB_ENDPOINT",
                    "Value": "[reference(concat('Microsoft.DocumentDb/databaseAccounts/', parameters('databaseAccountName'))).documentEndpoint]"
                }, {
                    "Name": "DOCUMENTDB_PRIMARY_KEY",
                    "Value": "[listKeys(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('databaseAccountName')), '2015-04-08').primaryMasterKey]"
                }]


问:
Multiple select in wagtail admin
When using Django ModelAdmin, I can use:

```<code>filter_horizontal = ('some_many_to_many_field',)
</code>```

So that, instead of showing the default multiple select widget, it shows a nice interface with two blocks for selecting some values.

Is there a similar option for using the same widget as in django ModelAdmin for my many-to-many fields in wagtail's ModelAdmin?

Thank you!

答:
In answer to your question: No, there is no equivalent of filter_horizontal in Wagtail's contrib.modeladmin app.

However, there are ways to override the widget used for fields on your model. The easiest of which is to use FieldPanel's widget argument in your model's panel definitions. For example:

```<code>from django import forms
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel

class TestModel(models.Model):
    manytomany = models.ManyToManyField('someapp.SomeModel', blank=True)

    panels = [
        FieldPanel('manytomany', widget=forms.CheckboxSelectMultiple)
    ]
</code>```

Or, if the model you're registering is a subclass of wagtail.core.models.Page, the following example is more appropriate:

```<code>from django import forms
from django.db import models
from modelcluster.fields import ParentalManyToManyField
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel

class TestPageModel(Page):
    manytomany = ParentalManyToManyField('someapp.SomeModel', blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('manytomany', widget=forms.CheckboxSelectMultiple)
    ]
</code>```

There is no equivalent of Django's filter_horizontal widget that can easily be used in this way though, unfortunately. That particular widget is dependant on various styles and scripts that are loaded as part of Django's admin UI. Wagtail's admin UI is completely custom and doesn't include any such styles or scripts.

Title: Multiple select in wagtail admin

Body:
When using Django ModelAdmin, I can use:

filter_horizontal = ('some_many_to_many_field',)

So that, instead of showing the default multiple select widget, it shows a nice interface with two blocks for selecting some values.

Is there a similar option for using the same widget as in django ModelAdmin for my many-to-many fields in wagtail's ModelAdmin?

Thank you!

Body:
In answer to your question: No, there is no equivalent of filter_horizontal in Wagtail's contrib.modeladmin app.

However, there are ways to override the widget used for fields on your model. The easiest of which is to use FieldPanel's widget argument in your model's panel definitions. For example:

from django import forms
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel

class TestModel(models.Model):
    manytomany = models.ManyToManyField('someapp.SomeModel', blank=True)

    panels = [
        FieldPanel('manytomany', widget=forms.CheckboxSelectMultiple)
    ]

Or, if the model you're registering is a subclass of wagtail.core.models.Page, the following example is more appropriate:

from django import forms
from django.db import models
from modelcluster.fields import ParentalManyToManyField
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel

class TestPageModel(Page):
    manytomany = ParentalManyToManyField('someapp.SomeModel', blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('manytomany', widget=forms.CheckboxSelectMultiple)
    ]

There is no equivalent of Django's filter_horizontal widget that can easily be used in this way though, unfortunately. That particular widget is dependant on various styles and scripts that are loaded as part of Django's admin UI. Wagtail's admin UI is completely custom and doesn't include any such styles or scripts.


问:
Drupal Views taxonomy hierarchy
I´ve got a problem with how to display taxonomy terms of node with which I need some help.

I´ve got 2 taxonomy vocabularies: categories and featured article. The first is a hierarchical vocabulary in which terms can be nested on multiple levels. The featured article vocabulary only has a YES term.

Now in my View I want to display my nodes which have featured article set to YES in random fashion. This I have managed to do.

Now besides the teaser and title, I would also like to display every category of the node, nested like this:

Parent > Child > ChildOfChild

Can anybody tell me how to do this?

Thanks in advance.

答: Selecting the Taxonomy: All terms fields with the limit the terms by vocabulary option did the job. It didn´t work before cause I only selected the child category for the node. I have to selecte both the parent and child categories.</p>

Title: Drupal Views taxonomy hierarchy


问:
Add directive from directive
I have a directive deciding if an input must be required, masked, etc... I ran into a situation that I need to add a new directive to it: basically this new directive adds the mask feature to the input.

```<code><input type="text" formInput [rules]="rules"  [(ngModel)]="value" />
</code>```

This is the formInput directive:

```<code>export class DefaultFormInputDirective {

@Input() private rules;
private el: ElementRef;

constructor(el: ElementRef) {
    this.el = el;
}

ngOnInit() {
    this.defineRules();
}

defineRules() {

    if(this.rules == undefined) {
        return;
    }

    if(this.rules.indexOf('required') != -1) {
        this.el.nativeElement.required = true;
    }

    if(this.rules.indexOf('numeric') != -1) {
        // Here is where I need to add currencyMask directive
    }

}

}
</code>```

This is the package I am using: https://www.npmjs.com/package/ng2-currency-mask

答: Adding directives dynamically is not supported. You can only add/remove components dynamically.</p>

Title: Add directive from directive

Body:
I have a directive deciding if an input must be required, masked, etc... I ran into a situation that I need to add a new directive to it: basically this new directive adds the mask feature to the input.

<input type="text" formInput [rules]="rules"  [(ngModel)]="value" />

This is the formInput directive:

export class DefaultFormInputDirective {

@Input() private rules;
private el: ElementRef;

constructor(el: ElementRef) {
    this.el = el;
}

ngOnInit() {
    this.defineRules();
}

defineRules() {

    if(this.rules == undefined) {
        return;
    }

    if(this.rules.indexOf('required') != -1) {
        this.el.nativeElement.required = true;
    }

    if(this.rules.indexOf('numeric') != -1) {
        // Here is where I need to add currencyMask directive
    }

}

}

This is the package I am using: https://www.npmjs.com/package/ng2-currency-mask


问:
TSLint throwing warning
My tslint.json looks like the following

```<code>{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}
</code>```

My gulp file has a task named tslint which looks like:

```<code>gulp.task('tslint', function() {
    return gulp.src(lintFiles)
        .pipe(tslint({
            formatter: "verbose"
        }))
        .pipe(tslint.report());
});
</code>```

When I run gulp tslint, it throws me the following warning

Following rules specified in configuration couldn't be applied to .js or .jsx files:

no-reference-import

Make sure to exclude them from "jsRules" section of your tslint.json.

In order to exclude I changed "jsRules": {}, to "jsRules": {"no-reference-import": false }, still no change and I got the same warning. I googled about it and could not find anything. Can you please help me?

答: This is an issue with the current version of tslint 5.0.0. The issue has been referenced here. You can go back to a previous version of tslint as a workaround until the issue is fixed.

Title: TSLint throwing warning

Body:
My tslint.json looks like the following

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}

My gulp file has a task named tslint which looks like:

gulp.task('tslint', function() {
    return gulp.src(lintFiles)
        .pipe(tslint({
            formatter: "verbose"
        }))
        .pipe(tslint.report());
});

When I run gulp tslint, it throws me the following warning

Following rules specified in configuration couldn't be applied to .js or .jsx files:

no-reference-import

Make sure to exclude them from "jsRules" section of your tslint.json.

In order to exclude I changed "jsRules": {}, to "jsRules": {"no-reference-import": false }, still no change and I got the same warning. I googled about it and could not find anything. Can you please help me?


问:
what does PHP substr do on utf-8 string?
Reminded by Sammitch, I double checked my input with Hexinator binary editor and found my input was wrong. So this question is closed.

_______Original Question:_______

I have a UTF-8 string as:

```<code><?php $str = '收听'; ?>
</code>```

In binary, $str is:
E694B6E590AC

```<code><?php $a = $str[1]; ?>
</code>```

or

```<code><?php $a = substr($str,1,1); ?>
</code>```

I got $a as binary 90, NOT 94.

Walk through $str[0] to $str[5], I got new binary:
E590ACE8AFB4

They are identical to url encoding of $str:
%E5%90%AC%E8%AF%B4

So what did substr actually do here internally on the UTF-8 $str?

By the way, I don't want to use mb_substr to cut a UTF-8 string.

I don't understand why $str[0] is E5, not E6; $str[1] is 90, Not 94.

I also have a function as below which do substr or index of string on utf-8 string.

```<code><?php
/**
 * urlencodes complete string, including alphanumeric characters and multibyte characters
 * @param string $string the string to encode
 */
function urlencode_all($string){
    $chars = array();
    for($i = 0; $i < strlen($string); $i++){
        $char = (string)dechex(ord($string[$i]));
        if(strlen($char)==1) $char = '0'.$char;
        $chars[] = '%'.$char;
    }
    return implode('', $chars);
}
?>
</code>```

Can someone explain what did substr do here?

答:
By the way, I don't want to use mb_substr to cut a UTF-8 string.

Welcome to hell.

There are two core problems:

1. Any UTF codepoint can be comprised of between 1 and 4 bytes in UTF8.

In the case of your example each symbol is a 3-byte UTF8 sequence, but it's perfectly valid to have a mix of any length byte sequences in a single string. This makes it impractical to use substr() since it operates on numbers of bytes.

Solution: Use mb_substr()

2. Any single symbol you see might be composed of multiple codepoints.

While mb_substr() may be able to slice a UTF8 string into individual codepoints there's a chance you could corrupt the string by breaking a particular codepoint sequence.

Eg: T҉̲̰ọ͕͉n͘y͕̣̹͚͇̗ ͉̺̘̣̟t͍̹̟̙h̬̰̪̭̘͎̥e̛̮ ̨P͕͖̩o͡n̛͕̤̥̼͔̩͎y͍̤͠ is actually:

```<code>00000000  54 d2 89 cc b2 cc b0 6f  cc a3 cd 95 cd 89 6e cd  |T......o......n.|
00000010  98 79 cd 95 cc a3 cc b9  cd 9a cd 87 cc 97 20 cd  |.y............ .|
00000020  89 cc ba cc 98 cc a3 cc  9f 74 cd 8d cc b9 cc 9f  |.........t......|
00000030  cc 99 68 cc ac cc b0 cc  aa cc ad cc 98 cd 8e cc  |..h.............|
00000040  a5 65 cc 9b cc ae 20 cc  a8 50 cd 95 cd 96 cc a9  |.e.... ..P......|
00000050  6f cd a1 6e cc 9b cd 95  cc a4 cc a5 cc bc cd 94  |o..n............|
00000060  cc a9 cd 8e 79 cd a0 cd  8d cc a4                 |....y......|
</code>```

Solution: Uhh... let me know if someone figures this one out.

As far as I know Chinese doesn't do much with multiple codepoints [I'm not an expert, though] so you're probably fine with mb_substr(). [until you're not]

Lastly

The Wikipedia article on UTF8 is really great if you want to understand how UTF8 works and I recommend that everyone that has to deal with UTF8 read it.

https://en.wikipedia.org/wiki/UTF-8

Body:
Reminded by Sammitch, I double checked my input with Hexinator binary editor and found my input was wrong. So this question is closed.

_______Original Question:_______

I have a UTF-8 string as:

<?php $str = '收听'; ?>

In binary, $str is:
E694B6E590AC

<?php $a = $str[1]; ?>

or

<?php $a = substr($str,1,1); ?>

I got $a as binary 90, NOT 94.

Walk through $str[0] to $str[5], I got new binary:
E590ACE8AFB4

They are identical to url encoding of $str:
%E5%90%AC%E8%AF%B4

So what did substr actually do here internally on the UTF-8 $str?

By the way, I don't want to use mb_substr to cut a UTF-8 string.

I don't understand why $str[0] is E5, not E6; $str[1] is 90, Not 94.

I also have a function as below which do substr or index of string on utf-8 string.

<?php
/**
 * urlencodes complete string, including alphanumeric characters and multibyte characters
 * @param string $string the string to encode
 */
function urlencode_all($string){
    $chars = array();
    for($i = 0; $i < strlen($string); $i++){
        $char = (string)dechex(ord($string[$i]));
        if(strlen($char)==1) $char = '0'.$char;
        $chars[] = '%'.$char;
    }
    return implode('', $chars);
}
?>

Can someone explain what did substr do here?

Body:
By the way, I don't want to use mb_substr to cut a UTF-8 string.

Welcome to hell.

There are two core problems:

1. Any UTF codepoint can be comprised of between 1 and 4 bytes in UTF8.

In the case of your example each symbol is a 3-byte UTF8 sequence, but it's perfectly valid to have a mix of any length byte sequences in a single string. This makes it impractical to use substr() since it operates on numbers of bytes.

Solution: Use mb_substr()

2. Any single symbol you see might be composed of multiple codepoints.

While mb_substr() may be able to slice a UTF8 string into individual codepoints there's a chance you could corrupt the string by breaking a particular codepoint sequence.

Eg: T҉̲̰ọ͕͉n͘y͕̣̹͚͇̗ ͉̺̘̣̟t͍̹̟̙h̬̰̪̭̘͎̥e̛̮ ̨P͕͖̩o͡n̛͕̤̥̼͔̩͎y͍̤͠ is actually:

00000000  54 d2 89 cc b2 cc b0 6f  cc a3 cd 95 cd 89 6e cd  |T......o......n.|
00000010  98 79 cd 95 cc a3 cc b9  cd 9a cd 87 cc 97 20 cd  |.y............ .|
00000020  89 cc ba cc 98 cc a3 cc  9f 74 cd 8d cc b9 cc 9f  |.........t......|
00000030  cc 99 68 cc ac cc b0 cc  aa cc ad cc 98 cd 8e cc  |..h.............|
00000040  a5 65 cc 9b cc ae 20 cc  a8 50 cd 95 cd 96 cc a9  |.e.... ..P......|
00000050  6f cd a1 6e cc 9b cd 95  cc a4 cc a5 cc bc cd 94  |o..n............|
00000060  cc a9 cd 8e 79 cd a0 cd  8d cc a4                 |....y......|

Solution: Uhh... let me know if someone figures this one out.

As far as I know Chinese doesn't do much with multiple codepoints [I'm not an expert, though] so you're probably fine with mb_substr(). [until you're not]

Lastly

The Wikipedia article on UTF8 is really great if you want to understand how UTF8 works and I recommend that everyone that has to deal with UTF8 read it.

https://en.wikipedia.org/wiki/UTF-8


问:
Is String str = new String("my string") really less efficient?
I often saw people saying String str = new String("my string") is less efficient than writing String str = "my string", because the former creates a static "my string" object and then new's a String object that gets copied from the static one.

However, given that the language here is so simple and unambiguous, I can hardly imagine that Java optimizer won't take any effort to simply convert the former to the latter. Why would it really choose to do it the more laborious way? What can any negative side effects be if Java does optimize it?

答:
Have a look into the generated bytecode for String s1 = "1":

```<code>LDC "1"
ASTORE 1
</code>```

And for String s2 = new String("2"):

```<code>NEW java/lang/String
DUP
LDC "2"
INVOKESPECIAL java/lang/String.<init> (Ljava/lang/String;)V
ASTORE 2
</code>```

The latter example is redundant and more complicated. Compiler won't make any optimizations in this case. It is guaranteed that a new instance of a String class will be created.

With a String str = "my string" the JVM can reuse instance of a String instead of creating a new one. Consider next examples:

```<code>String s1 = "1";
String s2 = "1";
System.out.println(s1 == s2); // true  => same reference, s1 & s2 point to the same object

String s3 = "1";
String s4 = new String("1");
System.out.println(s3 == s4); // false => s3 & s4 point to different objects
</code>```

Body:
Have a look into the generated bytecode for String s1 = "1":

LDC "1"
ASTORE 1

And for String s2 = new String("2"):

NEW java/lang/String
DUP
LDC "2"
INVOKESPECIAL java/lang/String.<init> (Ljava/lang/String;)V
ASTORE 2

The latter example is redundant and more complicated. Compiler won't make any optimizations in this case. It is guaranteed that a new instance of a String class will be created.

With a String str = "my string" the JVM can reuse instance of a String instead of creating a new one. Consider next examples:

String s1 = "1";
String s2 = "1";
System.out.println(s1 == s2); // true  => same reference, s1 & s2 point to the same object

String s3 = "1";
String s4 = new String("1");
System.out.println(s3 == s4); // false => s3 & s4 point to different objects


问:
Racket type annotations in for/list using in-query (DB calls)
I'm trying to read data from a database in typed Racket and convert it to a list of structures. The code below is the untyped version that works perfectly. This is the smallest bit I can make that demonstrates the problem.

```<code>#lang racket

(require db)

(define dbc (sqlite3-connect #:database "dmdb.sqlite3" #:mode 'read/write))

(struct player (name size str dex con base-hp current-hp base-ac attack) #:mutable)

(define get-players
  (lambda (c)
    (for/list
        ([(n s str dex con bhp chp bac attack)
            (in-query c "select * from players")])
      (player n s str dex con bhp chp bac attack))))
</code>```

The typed version of the procedure is as shown below:

```<code>#lang type/racket
(require typed/db)

(: get-players (-> Connection (Listof player)))
(define get-players
  (lambda (c)
    (for/list
        ([(n s str dex con bhp chp bac attack)
            (in-query c "select * from players")])
      (player n s str dex con bhp chp bac attack))))
</code>```

When I try to compile it in typed Racket I receive some strange error messages:

```<code>Type Checker: Expression should produce 9 values, but produces 1 values of
types SQL-Datum in: (for/list (((n s str dex con bhp chp bac attack
(in-query c "select * from players"))) (player n s str dex con bhp chp bac
attack))
</code>```

Again, the code works perfectly as long as it is not typed.

答:
It looks like even though the syntax of for in typed racket supports multiple values, you cannot actually type check a sequence of multiple values in typed/racket. You can, however, convert a sequence of values into a list with the in-values-sequence. From there, you can use define-values to split out the list back into values, or just use the list inline. For the function you gave, this would look like:

```<code>(: get-players (-> Connection (Listof player)))
(define (get-players c)
  (for/list ([a (in-values-sequence (in-query c "select * from players"))])
    (player (list-ref a 0)
            (list-ref a 1)
            (list-ref a 2)
            (list-ref a 3)
            (list-ref a 4)
            (list-ref a 5)
            (list-ref a 6)
            (list-ref a 7)
            (list-ref a 8))))
</code>```

I suspect this might have an effect on your program's performance, but I can't say for sure what. If you want to create a sequence of multiple values, you could ask the people on the racket mailing list for help, as they likely know something I don't.

Body:
I'm trying to read data from a database in typed Racket and convert it to a list of structures. The code below is the untyped version that works perfectly. This is the smallest bit I can make that demonstrates the problem.

#lang racket

(require db)

(define dbc (sqlite3-connect #:database "dmdb.sqlite3" #:mode 'read/write))

(struct player (name size str dex con base-hp current-hp base-ac attack) #:mutable)

(define get-players
  (lambda (c)
    (for/list
        ([(n s str dex con bhp chp bac attack)
            (in-query c "select * from players")])
      (player n s str dex con bhp chp bac attack))))

The typed version of the procedure is as shown below:

#lang type/racket
(require typed/db)

(: get-players (-> Connection (Listof player)))
(define get-players
  (lambda (c)
    (for/list
        ([(n s str dex con bhp chp bac attack)
            (in-query c "select * from players")])
      (player n s str dex con bhp chp bac attack))))

When I try to compile it in typed Racket I receive some strange error messages:

Type Checker: Expression should produce 9 values, but produces 1 values of
types SQL-Datum in: (for/list (((n s str dex con bhp chp bac attack
(in-query c "select * from players"))) (player n s str dex con bhp chp bac
attack))

Again, the code works perfectly as long as it is not typed.

Body:
It looks like even though the syntax of for in typed racket supports multiple values, you cannot actually type check a sequence of multiple values in typed/racket. You can, however, convert a sequence of values into a list with the in-values-sequence. From there, you can use define-values to split out the list back into values, or just use the list inline. For the function you gave, this would look like:

(: get-players (-> Connection (Listof player)))
(define (get-players c)
  (for/list ([a (in-values-sequence (in-query c "select * from players"))])
    (player (list-ref a 0)
            (list-ref a 1)
            (list-ref a 2)
            (list-ref a 3)
            (list-ref a 4)
            (list-ref a 5)
            (list-ref a 6)
            (list-ref a 7)
            (list-ref a 8))))

I suspect this might have an effect on your program's performance, but I can't say for sure what. If you want to create a sequence of multiple values, you could ask the people on the racket mailing list for help, as they likely know something I don't.


答:
Use two databases in the same Redis instance.
The SELECT instruction allows you to chose the instance to be used.
The number of the database may be given to your app by an environnement variable, so the code of the app remains the same for both application instances.</p>

Title: Two apps share one Redis. How to prevent cache collisions?

Body:
Two different versions of the application (debug and release) share same instance of Redis.
Both Debug and Release have identical source code and therefore identical caching keys for being stored in Redis.

Thus when Debug does redis.StringSet(key1, value1) Release could easily overwrite key1 or read incorrect value (since it should have its own key1).

Is there a way to avoid such interference?


问:
How to undo git checkout file for uncommitted changes?
I did a git status and noticed a bunch of files that were staged that should have been ignored by git ignore, such as .gitignore, .htaccess, and settings files for my Drupal site.

I mistakenly used git checkout <file> instead of git rm <file> to remove them from the staging area. While it looked like it worked, I broke the website. I think I now understand that git checkout reverts any changes I've made to those files, correct? The changes weren't committed because they weren't supposed to be tracked in the first place.

How is git checkout <file> supposed to be used and what is the opposite of it? Most importantly, how can I undo the undo or where do I go from here?

答:
According to the documentation of git here:

It’s important to understand that git checkout -- <file> is a
  dangerous command. Any changes you made to that file are gone – Git
  just copied another file over it. Don’t ever use this command unless
  you absolutely know that you don’t want the file.

So you can't undo this command.


问:
Run a PHP function every X minutes
I'm currently writting a forum software to learn PHP. I made some sitewide stats section that I cache in my RAM so the SQL won't get called on every pageload.

I plan to update these stats every ten or so minutes.

Is there a way to implement this without cron? It's fine if I need it but without would be better.

Is there some way with the time so that after every X minutes a visitor would be fine to trigger the re-caching?

答:
Php scripts can run indefinitelly. You should not want to do this but you can.

```<code>set_time_limit(0); // make it run forever
while(true) {
    doSomethingSpecial();
    sleep(300);
}
</code>```

Use cron instead.

Title: Run a PHP function every X minutes

Body:
Php scripts can run indefinitelly. You should not want to do this but you can.

set_time_limit(0); // make it run forever
while(true) {
    doSomethingSpecial();
    sleep(300);
}

Use cron instead.


问:
Cannot change app.message = 'something' in console
I was trying out vue.js through https://v2.vuejs.org/v2/guide/, I have included https://cdn.jsdelivr.net/vue/latest/vue.min.js file in my view.
The First App example I am able to load "Hello Vue!" when the app loads, But when from console I try to change app.message it does not change the title. I have tried viewing the dataset as app.dataset it returns empty object.

Js.coffee Code

```<code>$(document).ready ->
  # initialization of Vue JS
  app = new Vue(
    el: '#app'
    data: message: 'Hello Vue!')
  app2 = new Vue(
    el: '#app2'
    data: message: 'You loaded this page on ' + new Date)
  app3 = new Vue(
    el: '#app3'
    data: seen: true)
</code>```

View Code

```<code>.mapWrap
  .latLong
    #app
      {{ message }}
    #app2
      %span{"v-bind:title" => "message"}
        Hover your mouse over me for a few seconds
        to see my dynamically bound title!
    #app3
      %p{"v-if"=> "seen"} Now you see me
  - content_for :js do
    = javascript_include_tag 'https://cdn.jsdelivr.net/vue/latest/vue.min.js'
</code>```

答:
Your problem is that coffeescript is scoping your app variable inside the $(document).ready function. Try this.

```<code>$(document).ready ->
  window.app = new Vue(
    el: '#app'
    data: {message: 'Hello Vue!'})
  window.app2 = new Vue(
    el: '#app2'
    data: message: 'You loaded this page on ' + new Date)
  window.app3 = new Vue(
    el: '#app3'
    data: seen: true)
</code>```

Example.

Body:
I was trying out vue.js through https://v2.vuejs.org/v2/guide/, I have included https://cdn.jsdelivr.net/vue/latest/vue.min.js file in my view.
The First App example I am able to load "Hello Vue!" when the app loads, But when from console I try to change app.message it does not change the title. I have tried viewing the dataset as app.dataset it returns empty object.

Js.coffee Code

$(document).ready ->
  # initialization of Vue JS
  app = new Vue(
    el: '#app'
    data: message: 'Hello Vue!')
  app2 = new Vue(
    el: '#app2'
    data: message: 'You loaded this page on ' + new Date)
  app3 = new Vue(
    el: '#app3'
    data: seen: true)

View Code

.mapWrap
  .latLong
    #app
      {{ message }}
    #app2
      %span{"v-bind:title" => "message"}
        Hover your mouse over me for a few seconds
        to see my dynamically bound title!
    #app3
      %p{"v-if"=> "seen"} Now you see me
  - content_for :js do
    = javascript_include_tag 'https://cdn.jsdelivr.net/vue/latest/vue.min.js'

Body:
Your problem is that coffeescript is scoping your app variable inside the $(document).ready function. Try this.

$(document).ready ->
  window.app = new Vue(
    el: '#app'
    data: {message: 'Hello Vue!'})
  window.app2 = new Vue(
    el: '#app2'
    data: message: 'You loaded this page on ' + new Date)
  window.app3 = new Vue(
    el: '#app3'
    data: seen: true)

Example.


问:
When is a factory appropriate?
Taken from wikipedia:

In object-oriented computer
  programming, a factory is an object
  for creating other objects. It is an
  abstraction of a constructor, and can
  be used to implement various
  allocation schemes.

Could anyone please explain when a factory class is required or beneficial?

I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?

答:
My opinion on the Factory pattern has always been somewhat different, but I'll give it anyway.

A Factory is for creating a set of related types. Related does not mean that they necessarily implement the same interface(s) exactly. Related means that if you have one type you need to instantiate, and then you need to create another object and the concrete (implementation) type of the second object depends on the concrete type of the first object, you need a Factory.

A Factory that only creates one type of object (there is no "relatedness") is not a Factory but more like a Strategy.

My above definitions imply that Factory isn't used or needed as much as you would think.

And for objects that fail to initialize, I recommend the fail-fast approach by throwing an exception instead of relying on a status field.

Title: When is a factory appropriate?


问:
Values error: Boolean types not allowed (at 'android:windowBackground' with value 'true')
I modified the values.xml files, and I accidentally put "true" in this part of code:

```<code> <item name="android:windowBackground"> true </item>
</code>```

I tried to change "true" to other variables, but always returns "true"

and this error:

Error:(2002, 47) Boolean types not allowed (at 'android:windowBackground' with value 'true').

Error:Execution failed for task ':app:processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute aapt

And the values.xml file is on ( /app/build/intermediates/res/merged/debug/values ) folder.

Sorry fo my bad Englih.

答:
Go to your styles.xml file located in app/src/main/res/values folder.

For item android:windowBackground, use a color code instead of value true. For example:

```<code><item name="android:windowBackground">#FF0000</item>
</code>```

If android:windowBackground value true used in multiple style.xml then change their value to color code

Finally, clean and build your project again and RUN on your device

Body:
I modified the values.xml files, and I accidentally put "true" in this part of code:

 <item name="android:windowBackground"> true </item>

I tried to change "true" to other variables, but always returns "true"

and this error:

Error:(2002, 47) Boolean types not allowed (at 'android:windowBackground' with value 'true').

Error:Execution failed for task ':app:processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute aapt

And the values.xml file is on ( /app/build/intermediates/res/merged/debug/values ) folder.

Sorry fo my bad Englih.

Body:
Go to your styles.xml file located in app/src/main/res/values folder.

For item android:windowBackground, use a color code instead of value true. For example:

<item name="android:windowBackground">#FF0000</item>

If android:windowBackground value true used in multiple style.xml then change their value to color code

Finally, clean and build your project again and RUN on your device


问:
R Y-axis with two main labels
I want to make a scatter plot in R where Y-values are in [-3,-2,-1,1,2,3].
I want to change the Y-axis labels to reflect the binary nature of my data (all positive values are of category A and all negative value of category B), and the numbers themselves specify the subcategories (X,Y,Z for when abs(Y) = 1,2,3).

How can I plot this?

What I want is a Y-axis from -3 to +3 with a main label of "A" when Y>0 and "B" when Y<0 and the normal ticks for the subcategories. Normally I would use Ylab for this, but this only allows ONE main label which is centered, but I want two: each centered at the positive/negative axis.

This is my code so far:

```<code>X = c(1.5,2.3,2.5,2.1,0.2)
Y = c(1,-3,2,-2,1)

plot(x = X,y=Y,ylab = "Categories",axes=F,ylim = c(-3,3))
axis(2, at=-3:3, labels=c("x","y","z","","x","y","z"))
abline(v = seq(min(X), max(X), 0.2), h = seq(-3,3,1), col = "lightgray", lty = 3)
abline(h=0)
box()
</code>```

which looks like this:

So I want "A" to be stated on the left side above the X-axis and "B" on the left side below the X-axis.

答:
Use mtext() e.g.:

```<code>mtext('A', side=2, line=2, at=2)
mtext('B', side=2, line=2, at=-2)
</code>```

and add las=2 if you want it horizontally.

Title: R Y-axis with two main labels

Body:
I want to make a scatter plot in R where Y-values are in [-3,-2,-1,1,2,3].
I want to change the Y-axis labels to reflect the binary nature of my data (all positive values are of category A and all negative value of category B), and the numbers themselves specify the subcategories (X,Y,Z for when abs(Y) = 1,2,3).

How can I plot this?

What I want is a Y-axis from -3 to +3 with a main label of "A" when Y>0 and "B" when Y<0 and the normal ticks for the subcategories. Normally I would use Ylab for this, but this only allows ONE main label which is centered, but I want two: each centered at the positive/negative axis.

This is my code so far:

X = c(1.5,2.3,2.5,2.1,0.2)
Y = c(1,-3,2,-2,1)

plot(x = X,y=Y,ylab = "Categories",axes=F,ylim = c(-3,3))
axis(2, at=-3:3, labels=c("x","y","z","","x","y","z"))
abline(v = seq(min(X), max(X), 0.2), h = seq(-3,3,1), col = "lightgray", lty = 3)
abline(h=0)
box()

which looks like this:

So I want "A" to be stated on the left side above the X-axis and "B" on the left side below the X-axis.

Body:
Use mtext() e.g.:

mtext('A', side=2, line=2, at=2)
mtext('B', side=2, line=2, at=-2)

and add las=2 if you want it horizontally.


问:
Python Pandas GroupBy returns blank rows
I am trying to group a dataframe that has

```<code>date
month_year
business_id
sales
cost
</code>```

by:

```<code>df.groupby(['month_year', 'business_id'])[['sales','cost']].sum()
</code>```

Which returns:

```<code>month_year  business_id  sales  cost
2016/01     1             44     43
            2             55     43
            3             55     34
</code>```

But I need to insert this df into an sql table and need the format to be in a flat table with the month_year in every row:

```<code>month_year  business_id  sales  cost
2016/01     1             44     43
2016/01     2             55     43
2016/01     3             55     34
</code>```

How would I achieve this? (Note there are different months in the real data)

答:
Add .reset_index() to the end of your groupby:</p>
```<code>df.groupby(['month_year', 'business_id'])[['sales','cost']].sum().reset_index()
</code>```

Body:
I am trying to group a dataframe that has

date
month_year
business_id
sales
cost

by:

df.groupby(['month_year', 'business_id'])[['sales','cost']].sum()

Which returns:

month_year  business_id  sales  cost
2016/01     1             44     43
            2             55     43
            3             55     34

But I need to insert this df into an sql table and need the format to be in a flat table with the month_year in every row:

month_year  business_id  sales  cost
2016/01     1             44     43
2016/01     2             55     43
2016/01     3             55     34

How would I achieve this? (Note there are different months in the real data)

Body:
Add .reset_index() to the end of your groupby:

df.groupby(['month_year', 'business_id'])[['sales','cost']].sum().reset_index()


问:
Firebase StartAt Query With Deletions
If I have a query that looks like:

```<code>orderByChild("updated_at").startAt(mostRecentUpdatedAt + 1)
</code>```

to implement caching without having to download the whole data set every time I connect, is there a way that I can get child remove events if the child is removed without updating the updated_at field?

答: You can create a addChildEventListener and implement the public void onChildRemoved(DataSnapshot dataSnapshot) method.

Title: Firebase StartAt Query With Deletions

Body:
If I have a query that looks like:

orderByChild("updated_at").startAt(mostRecentUpdatedAt + 1)

to implement caching without having to download the whole data set every time I connect, is there a way that I can get child remove events if the child is removed without updating the updated_at field?


问:
How to configure on-behalf-of authentication in multi-tenant environment?
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

```<code>result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);
</code>```

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?

答:
Here's my client manifest...

Client Manifest

...and my service manifest...

Service Manifest

Body:
I have a native client that calls a service I wrote-- that in turn calls the Graph API (using the original caller's credentials).

This is exactly like the 'onbehalfof' sample found here (my code fails the same way as the sample):

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

When logging in as a user from the same tenant as the service (tenant A), everything works fine (just like the onbehalf of sample).  When logging in as a user from a different tenant (tenant B), I get an exception on this line in the service:

result = await authContext.AcquireTokenAsync(GraphResourceId, clientCred, userAssertion);

(this is line 153 from TodoListController.cs in the onbehalfof sample).

The exception is this:

AADSTS65001: The user or administrator has not consented to use the
  application with ID 'de2fb28b-83f8-419d-9b00-3fbce0a60bf4'. Send an
  interactive authorization request for this user and resource.\r\nTrace
  ID: 6865c420-674a-4adf-a070-3d9b9c500200\r\nCorrelation ID:
  7e088563-d7fe-4131-a05c-cbe04dbb2bbd\r\nTimestamp: 2017-03-29
  22:56:58Z

The application id above refers to the service I wrote (which is the same line in the TodoListService in the onbehalfofsample).

I configured everything for multi-tenant authentication. But it's the additional call that my service is making to another service (Graph API) that's causing the problem.  What additional configuration do I need to do in the Azure portal to make this work?


问:
How do I construct a regex string in Javascript using variables
I've found similar questions and, thanks to those question, I think I've come close, but this still isn't doing what I want. (JQuery is already in use on this project, so I'm using it too.)

The snippet, as saved, works. If I comment out the current replace line and un-comment the one that's currently a comment, It seems to do nothing. It's supposed to find the first maxWordschars characters from the text, and any characters up to the next space and replace the string with what has been found.

  $('.practice').each(function(){
      var maxWordschars = 34;
      var strippedString = $(this).text().trim();
      var regexpattern = new RegExp("/^(.{" + maxWordschars + "}[^\s]*).*/");
      var newString = strippedString.replace(/^(.{34}[^\s]*).*/, "$1");
      //var newString = strippedString.replace(regexpattern, "$1");
      if (newString != strippedString){
        newString += "...";
      }
      $(this).text(newString);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="practice">
  Let this be a long string of text that my script has to deal with to make it fit.
</div>
<br>
<div class="practice">
  Allow this considerably longer paragraph of text with multisylable enunciations to further quantify the effectiveness of my script
</div></code>```

答:
```<code>var regexpattern = new RegExp("^(.{" + maxWordschars + "}\\S*).*");
</code>```

  $('.practice').each(function(){
      var maxWordschars = 34;
      var strippedString = $(this).text().trim();
      var regexpattern = new RegExp("^(.{" + maxWordschars + "}\\S*).*");
      //var newString = strippedString.replace(/^(.{34}[^\s]*).*/, "$1");
      var newString = strippedString.replace(regexpattern, "$1");
      if (newString != strippedString){
        newString += "...";
      }
      $(this).text(newString);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="practice">
  Let this be a long string of text that my script has to deal with to make it fit.
</div>
<br>
<div class="practice">
  Allow this considerably longer paragraph of text with multisylable enunciations to further quantify the effectiveness of my script
</div></code>```

Body:
I've found similar questions and, thanks to those question, I think I've come close, but this still isn't doing what I want. (JQuery is already in use on this project, so I'm using it too.)

The snippet, as saved, works. If I comment out the current replace line and un-comment the one that's currently a comment, It seems to do nothing. It's supposed to find the first maxWordschars characters from the text, and any characters up to the next space and replace the string with what has been found.

  $('.practice').each(function(){
      var maxWordschars = 34;
      var strippedString = $(this).text().trim();
      var regexpattern = new RegExp("/^(.{" + maxWordschars + "}[^\s]*).*/");
      var newString = strippedString.replace(/^(.{34}[^\s]*).*/, "$1");
      //var newString = strippedString.replace(regexpattern, "$1");
      if (newString != strippedString){
        newString += "...";
      }
      $(this).text(newString);
  });

  Let this be a long string of text that my script has to deal with to make it fit.

  Allow this considerably longer paragraph of text with multisylable enunciations to further quantify the effectiveness of my script

Body:
var regexpattern = new RegExp("^(.{" + maxWordschars + "}\\S*).*");

  $('.practice').each(function(){
      var maxWordschars = 34;
      var strippedString = $(this).text().trim();
      var regexpattern = new RegExp("^(.{" + maxWordschars + "}\\S*).*");
      //var newString = strippedString.replace(/^(.{34}[^\s]*).*/, "$1");
      var newString = strippedString.replace(regexpattern, "$1");
      if (newString != strippedString){
        newString += "...";
      }
      $(this).text(newString);
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="practice">
  Let this be a long string of text that my script has to deal with to make it fit.
</div>
<br>
<div class="practice">
  Allow this considerably longer paragraph of text with multisylable enunciations to further quantify the effectiveness of my script
</div>


问:
Fog::Compute::AWS::Error: AuthFailure => AWS was not able to validate the provided access credentials
chef and aws

I installed knife-ec2 gem in chef. when i try to ping knife ec2 server list getting below error.

I have provided access key and secrete key in knife.rb configuration file.

knife[:aws_access_key_id] = ""
knife[:aws_secret_access_key] = ""

but still getting this error.

ERROR: Fog::Compute::AWS::Error: AuthFailure => AWS was not able to validate the provided access credentials.

how to resolve this error.

答:
You need to add your credentials to the ~/.aws/credentials

AWS Credential File

```<code>[default]
AWSAccessKeyId=YourAWSAccessKeyID
AWSSecretKey=YourAWSSecretAccessKey
</code>```

The preferred method is to specify them in Knife.rb

Knife.rb Configuration

```<code>knife[:aws_access_key_id] = "Your AWS Access Key ID"
knife[:aws_secret_access_key] = "Your AWS Secret Access Key"
</code>```

Body:
You need to add your credentials to the ~/.aws/credentials

AWS Credential File

[default]
AWSAccessKeyId=YourAWSAccessKeyID
AWSSecretKey=YourAWSSecretAccessKey

The preferred method is to specify them in Knife.rb

Knife.rb Configuration

knife[:aws_access_key_id] = "Your AWS Access Key ID"
knife[:aws_secret_access_key] = "Your AWS Secret Access Key"


问:
Javascript Google Maps API icon
For the last week and a half I have been tinkering with a script for my website. I slightly altered it but have hit a skills wall. It works perfectly at the moment but I would love to add a custom marker icon. I have tried loads using lots of example code but am getting knowhere. I have saved an image on my google drive at

"https://drive.google.com/open?id=0B8DJ6pJV3E9FWmFiUlFTWGl5RjA"

Please can anyone show me how to incorporate it into the code below which I know works.

```

答:
You ran into same problem as I did once, you just need to host your image image locally(localhost) or anywhere on web and then use it's url to set marker url path.

If you are using chrome, use app 'Web Server' from App Store to host your project folder that includes the image as well.

Title: Javascript Google Maps API icon


问:
stacked bar chart want to pair mismatched data python
I have two lists that I want to combine into one stacked bar chart with labels.

```<code>Males = [('Surfing', 832), ('Swimming', 653), ('Fishing', 314),
         ('Spearfishing', 299), ('Bathing', 132), ('Diving', 102),
         ('Wading', 89), ('Standing', 70), ('Scuba diving', 65)]

Females = [('Swimming', 141), ('Wading', 53), ('Surfing', 45),
           ('Snorkeling', 33), ('Standing', 27), ('Bathing', 16),
           ('Scuba diving', 9), ('Boogie boarding', 8), ('Walking', 8)]
</code>```

I want it so that the graph will display the total number of people in each activity, while showing the gender breakdown in different colours. However as the order of the lists do not match and neither do all the activities i.e only women were 'walking' and there was no male equivalent. This bar then should appear on its own.

The code  I have written cannot do this. Please just give me general guidelines. Can I use a for loop to go over each element and and an if statement to see if it's also present in the the other gender data? And if so add them together.

I really don't understand how this could be done with an unknown number of bars possible.

答:
As I mentioned in a comment there is a fairly simple solution for this using pandas. Basically you would put each set of data into a dataframe and then do an outer merge on the activities. I'm not including code because you specifically asked for just guidelines.

The result of that:

If you can't use pandas for whatever reason you can make an ordered dictionary and populate that with your female and male data in a list for example. So the keys to the ordered dictionary would be the activities and the values would be a regular dictionary containing a mapping of activity to count. Then it would be simple to plot each of those. Again I'm not including code because you specifically asked for just guidelines.

Here's the result:

Body:
I have two lists that I want to combine into one stacked bar chart with labels.

Males = [('Surfing', 832), ('Swimming', 653), ('Fishing', 314),
         ('Spearfishing', 299), ('Bathing', 132), ('Diving', 102),
         ('Wading', 89), ('Standing', 70), ('Scuba diving', 65)]

Females = [('Swimming', 141), ('Wading', 53), ('Surfing', 45),
           ('Snorkeling', 33), ('Standing', 27), ('Bathing', 16),
           ('Scuba diving', 9), ('Boogie boarding', 8), ('Walking', 8)]

I want it so that the graph will display the total number of people in each activity, while showing the gender breakdown in different colours. However as the order of the lists do not match and neither do all the activities i.e only women were 'walking' and there was no male equivalent. This bar then should appear on its own.

The code  I have written cannot do this. Please just give me general guidelines. Can I use a for loop to go over each element and and an if statement to see if it's also present in the the other gender data? And if so add them together.

I really don't understand how this could be done with an unknown number of bars possible.


问:
Django - Return none object if record not found given the queried list
I've a list of ids [1,2,3,4,5,6,7,8,9,10]

Now I want to query a model with the above list of ids. This is how I perform the operation.

```<code>ModelA.objects.filter(id__in=ids)
</code>```

This returns objects of ModelA which match the given id list. Now consider ids [2,3,5] were not present. Can I get a queryset of same length as that of the input list, including all the non-found objects as well.??

For eg:-

if [2,3,5] are not found, it should return

```<code>[1,None,None,4,None,6,7,8,9,10]
</code>```

How can I achieve it?

答:
You can do something like...</p>

```<code>ids = [1,2,3,4,5,6,7,8,9,10]
results = ModelA.objects.filter(id__in=ids)
result_ids = [result.id for result in results]
return [id if id in result_ids else None for id in ids]
</code>```

Body:
I've a list of ids [1,2,3,4,5,6,7,8,9,10]

Now I want to query a model with the above list of ids. This is how I perform the operation.

ModelA.objects.filter(id__in=ids)

This returns objects of ModelA which match the given id list. Now consider ids [2,3,5] were not present. Can I get a queryset of same length as that of the input list, including all the non-found objects as well.??

For eg:-

if [2,3,5] are not found, it should return

[1,None,None,4,None,6,7,8,9,10]

How can I achieve it?

Body:
You can do something like...

ids = [1,2,3,4,5,6,7,8,9,10]
results = ModelA.objects.filter(id__in=ids)
result_ids = [result.id for result in results]
return [id if id in result_ids else None for id in ids]


问:
How to link Eigen and BLIS
I looked that Eigen can use with BLAS.

And BLIS is the BLAS-like dense linear algebra libraries.

Can Eigen link BLIS?  How to do it?

THX

答: Simply link to the BLAS compatibility layer of BLIS using the instructions you referenced: http://eigen.tuxfamily.org/dox-devel/TopicUsingBlasLapack.html, that is compile your application with -DEIGEN_USE_BLAS -lblis

Title: How to link Eigen and BLIS


问:
Why is my Silex autoloader (composer) not loading a class?
I'm using composer to load classes. It does work for a provider, but it does not load my classes folder. This is my composer.json :

```<code>{
    "require": {
        "silex/silex": "~1.3",
        "twig/twig": "^1.33",
        "doctrine/dbal": "^2.5",
        "uploadcare/uploadcare-php": "^1.5",
        "symfony/twig-bridge": "^2.8",
        "symfony/form": "^2.8",
        "symfony/security-csrf": "^2.8",
        "symfony/validator": "^2.8",
        "symfony/config": "^2.8",
        "symfony/translation": "^2.8"
    },
    "autoload": {
        "psr-4": {
            "Models\\": "app/Models/",
            "Providers\\": "app/Providers/"
        }
    }
}
</code>```

And this is my folder structure:

Webshop
--app
----Config
----Models
---->>Session.php
----Providers
--public
----index.php
--vendor
--views
--composer.jason
--composer.lock

This line is in index.php:

```<code>require_once __DIR__.'/../vendor/autoload.php';
</code>```

But I get this error for some reason:

```<code>Fatal error: Class 'Session' not found in E:\Software\XAMPP\htdocs\Webshop\public\index.php on line 32
</code>```

And in case you might need it, I can give you the session class of course. If anything needs to be added. Please ask and I'll add it within a minute.

Edit

This is my Session top:

```<code><?php

namespace Models;

class Session
    {
        public static function exists($name)
        {
</code>```

答: Kyoya solved it! I've forgot to put 'use Models\Session;' in the top of index.html</p>

Body:
I'm using composer to load classes. It does work for a provider, but it does not load my classes folder. This is my composer.json :

{
    "require": {
        "silex/silex": "~1.3",
        "twig/twig": "^1.33",
        "doctrine/dbal": "^2.5",
        "uploadcare/uploadcare-php": "^1.5",
        "symfony/twig-bridge": "^2.8",
        "symfony/form": "^2.8",
        "symfony/security-csrf": "^2.8",
        "symfony/validator": "^2.8",
        "symfony/config": "^2.8",
        "symfony/translation": "^2.8"
    },
    "autoload": {
        "psr-4": {
            "Models\\": "app/Models/",
            "Providers\\": "app/Providers/"
        }
    }
}

And this is my folder structure:

Webshop
--app
----Config
----Models
---->>Session.php
----Providers
--public
----index.php
--vendor
--views
--composer.jason
--composer.lock

This line is in index.php:

require_once __DIR__.'/../vendor/autoload.php';

But I get this error for some reason:

Fatal error: Class 'Session' not found in E:\Software\XAMPP\htdocs\Webshop\public\index.php on line 32

And in case you might need it, I can give you the session class of course. If anything needs to be added. Please ask and I'll add it within a minute.

Edit

This is my Session top:

<?php

namespace Models;

class Session
    {
        public static function exists($name)
        {


问:
Read NetCDF file from Azure file storage
I have uploaded a file to my Azure file storage account and created a SAS (shared access signature). Let's pretend the file in question is called fileA.nc

Now, with Python3, I am attempting to read fileA.nc:

```<code>from netCDF4 import Dataset

url ='https://<my-azure-resource-group>.file.core.windows.net/<some-file-share>/fileA.nc<SAS-token>';
dataset = Dataset(url)

print(dataset.variables.keys())
</code>```

The above code does not work, instead giving me the following error:

Traceback (most recent call last):   File "yadaYadaYada/test.py", line
  8, in
      dataset = Dataset(url)   File "netCDF4/_netCDF4.pyx", line 1848, in netCDF4._netCDF4.Dataset.init (netCDF4/_netCDF4.c:13983)
  OSError: NetCDF: Malformed or unexpected Constraint

This is line 8:

```<code> dataset = Dataset(url)
</code>```

I know the URL provided works. If I paste it into the browser, the file downloads...

I have checked the netCDF4 documentation, which says this:

Remote OPeNDAP-hosted datasets can be accessed for reading over
  http
      if a URL is provided to the Dataset constructor instead of a filename.
      However, this requires that the netCDF library be built with OPenDAP
      support, via the --enable-dap configure option (added in version
      4.0.1).

However, I have no idea how to tell if when Pycharms installed netcdf4, it used the --enable-dap argument, but I cannot imagine why it would not. Besides, if I stick in a url which points to some HTML, I get the HTML in the error dump and so from that I would think netcdf4 is actually trying to load a remote dataset and so the problem is somewhere else.

I'd really appreciate some help here. Maybe someone knows of another Python 3 netCDF library that will allow me to load my datasets from Azure?

UPDATE

Okay, I can now confirm that the python netcdf4 library does come with --OPenDAP enabled:

Hello again, netCDF4 1.0.4 with OpenDAP support is now available in
  the conda respoitory on Unix. To install: $ conda install netcdf4

Ilan

答:
I have found a solution. It turns out that you cannot read directly from an Azure File share, even though when you  paste the link to a file in the browser, the file begins to download.

What I needed to do was to mount the File Share on my OS. In my case, I was using Windows but this can be done with Linux, too. The following code should be modified accordingly and then put into Command Prompt:

```<code>net use <drive-letter>: \\<storage-account-name>.file.core.windows.net\<share-name>

example :
net use z: \\samples.file.core.windows.net\logs
</code>```

Once the File Share is mounted, you can read from it as if it were an external HDD. You may need to add permission, but I didn't.

Here is the link to the documentation for mounting the File Share: Documentation

Body:
I have uploaded a file to my Azure file storage account and created a SAS (shared access signature). Let's pretend the file in question is called fileA.nc

Now, with Python3, I am attempting to read fileA.nc:

from netCDF4 import Dataset

url ='https://<my-azure-resource-group>.file.core.windows.net/<some-file-share>/fileA.nc<SAS-token>';
dataset = Dataset(url)

print(dataset.variables.keys())

The above code does not work, instead giving me the following error:

Traceback (most recent call last):   File "yadaYadaYada/test.py", line
  8, in
      dataset = Dataset(url)   File "netCDF4/_netCDF4.pyx", line 1848, in netCDF4._netCDF4.Dataset.init (netCDF4/_netCDF4.c:13983)
  OSError: NetCDF: Malformed or unexpected Constraint

This is line 8:

 dataset = Dataset(url)

I know the URL provided works. If I paste it into the browser, the file downloads...

I have checked the netCDF4 documentation, which says this:

Remote OPeNDAP-hosted datasets can be accessed for reading over
  http
      if a URL is provided to the Dataset constructor instead of a filename.
      However, this requires that the netCDF library be built with OPenDAP
      support, via the --enable-dap configure option (added in version
      4.0.1).

However, I have no idea how to tell if when Pycharms installed netcdf4, it used the --enable-dap argument, but I cannot imagine why it would not. Besides, if I stick in a url which points to some HTML, I get the HTML in the error dump and so from that I would think netcdf4 is actually trying to load a remote dataset and so the problem is somewhere else.

I'd really appreciate some help here. Maybe someone knows of another Python 3 netCDF library that will allow me to load my datasets from Azure?

UPDATE

Okay, I can now confirm that the python netcdf4 library does come with --OPenDAP enabled:

Hello again, netCDF4 1.0.4 with OpenDAP support is now available in
  the conda respoitory on Unix. To install: $ conda install netcdf4

Ilan

Body:
I have found a solution. It turns out that you cannot read directly from an Azure File share, even though when you  paste the link to a file in the browser, the file begins to download.

What I needed to do was to mount the File Share on my OS. In my case, I was using Windows but this can be done with Linux, too. The following code should be modified accordingly and then put into Command Prompt:

net use <drive-letter>: \\<storage-account-name>.file.core.windows.net\<share-name>

example :
net use z: \\samples.file.core.windows.net\logs

Once the File Share is mounted, you can read from it as if it were an external HDD. You may need to add permission, but I didn't.

Here is the link to the documentation for mounting the File Share: Documentation


问:
Is this method of calculating Bitmap size in kb destructive to the Bitmap?
I have seen the following code elsewhere for calculating the size in kb of an Android Bitmap, and was wondering if this is actually destructive to the Bitmap?

```<code>ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
long sizeInKB = bytes.length;
</code>```

Specifically the line:

```<code>bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
</code>```

Does this actually mutate the Bitmap? Ideally I am looking for a totally non-destructive way of recording the image size in kb before continuing to use it.

NOTE: It is not practical in this case to use something like:

```<code>File file = new File(filepath);
long length = file.length();
</code>```

Because I don't have the Bitmap on file at that point.

EDIT: I decided to solve my problem by getting the bytes downloaded value a different way: I extended InputStream and overrode the read(byte b[], int off, int len) method to include a counter, which can be returned at completion of the download - or indeed if the download was interrupted at all.

答:
That's a horrible way of doing it.  You're compressing the file in memory, writing that entire memory to a byte array, and getting the size of that-  a total memory usage of 2-3x what the bitmap should take, with the side negative of being very slow.

Do you want the size of the bitmap loaded into memory or saved to disk?  If you want it on disk, save it to disk then use the File api.  Because if you aren't going to write it to disk anyway, why would you care what its size on disk is?  If you want it in memory use bitmap.getByteCount()-  which will always be higher than what your code returns, as its the size of the uncompressed bitmap.

Body:
I have seen the following code elsewhere for calculating the size in kb of an Android Bitmap, and was wondering if this is actually destructive to the Bitmap?

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
long sizeInKB = bytes.length;

Specifically the line:

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

Does this actually mutate the Bitmap? Ideally I am looking for a totally non-destructive way of recording the image size in kb before continuing to use it.

NOTE: It is not practical in this case to use something like:

File file = new File(filepath);
long length = file.length();

Because I don't have the Bitmap on file at that point.

EDIT: I decided to solve my problem by getting the bytes downloaded value a different way: I extended InputStream and overrode the read(byte b[], int off, int len) method to include a counter, which can be returned at completion of the download - or indeed if the download was interrupted at all.


问:
How to display contact us form echo result
code is working and I'm getting when I try to send mail from website contact us form but when I click Send button on website it redirects me and getting echo result that message have successfully sent but I want to display that echo in same page.

PHP code:

```<code> <?php
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");

if(isset($_POST['btn-send']))
echo "Thank you for your message"; ?>
</code>```

HTML code:

```<code><div class="second_third">
  <h6 class="title" style="padding-left: 45px;">Contact Us</h6>
  <ul class="nospace linklist">
   <form class="form1" method="post" action="send.php">
    Mail<br />
    <input type="email" id="input-email" class="input1" name="email">
    <br />
    Message
   <textarea name="message" class="textarea1" id="input-message"></textarea>
  <br />
   <input type="submit" value="Send" id="input-submit" class="input1" name="btn-send">
  </form>
</code>```

What I have to add or how to do it ?

Thank you.

答:
You can also use a small jquery code to do an ajax call to the php code. It will not reload the page, rather display an alert or a message box with your message on the same page. Please find the below code

index.html

```<code><body>
<div class="second_third">
  <h6 class="title" style="padding-left: 45px;">Contact Us</h6>
  <ul class="nospace linklist">
   <form class="form1" >
    Mail<br />
    <input type="email" id="input-email" class="input1" name="email">
    <br />
    Message
   <textarea name="message" class="textarea1" id="input-message"></textarea>
  <br />
   <input type="submit" value="Send" id="input-submit" class="input1" name="btn-send" onclick="mail();">
  </form>
  </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script>
    function mail(){
    var email=$('#input-email').val();
    var message=$('#input-message').val();
    $.ajax({
       url:'mail.php',
       method:'post',
       data:{email:email, message:message},
       success:function(data){
          alert(data);
      }
     })
   }
  </script>
  </body>
</code>```

Mail.php

```<code><?php
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");
echo "Thank you for your message"; ?>
</code>```

Body:
code is working and I'm getting when I try to send mail from website contact us form but when I click Send button on website it redirects me and getting echo result that message have successfully sent but I want to display that echo in same page.

PHP code:

 <?php
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");

if(isset($_POST['btn-send']))
echo "Thank you for your message"; ?>

HTML code:

Contact Us

   <form class="form1" method="post" action="send.php">
    Mail

    <input type="email" id="input-email" class="input1" name="email">

    Message
   <textarea name="message" class="textarea1" id="input-message"></textarea>

   <input type="submit" value="Send" id="input-submit" class="input1" name="btn-send">
  </form>

What I have to add or how to do it ?

Thank you.

Body:
You can also use a small jquery code to do an ajax call to the php code. It will not reload the page, rather display an alert or a message box with your message on the same page. Please find the below code

index.html

<body>
<div class="second_third">
  <h6 class="title" style="padding-left: 45px;">Contact Us</h6>
  <ul class="nospace linklist">
   <form class="form1" >
    Mail<br />
    <input type="email" id="input-email" class="input1" name="email">
    <br />
    Message
   <textarea name="message" class="textarea1" id="input-message"></textarea>
  <br />
   <input type="submit" value="Send" id="input-submit" class="input1" name="btn-send" onclick="mail();">
  </form>
  </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script>
    function mail(){
    var email=$('#input-email').val();
    var message=$('#input-message').val();
    $.ajax({
       url:'mail.php',
       method:'post',
       data:{email:email, message:message},
       success:function(data){
          alert(data);
      }
     })
   }
  </script>
  </body>

Mail.php

<?php
 $email = $_POST['email'];
 $message = $_POST['message'];

mail("info@info.info", "From info.info", $message, "From: $email\r\n");
echo "Thank you for your message"; ?>


问:
Add directive from directive
I have a directive deciding if an input must be required, masked, etc... I ran into a situation that I need to add a new directive to it: basically this new directive adds the mask feature to the input.

```<code><input type="text" formInput [rules]="rules"  [(ngModel)]="value" />
</code>```

This is the formInput directive:

```<code>export class DefaultFormInputDirective {

@Input() private rules;
private el: ElementRef;

constructor(el: ElementRef) {
    this.el = el;
}

ngOnInit() {
    this.defineRules();
}

defineRules() {

    if(this.rules == undefined) {
        return;
    }

    if(this.rules.indexOf('required') != -1) {
        this.el.nativeElement.required = true;
    }

    if(this.rules.indexOf('numeric') != -1) {
        // Here is where I need to add currencyMask directive
    }

}

}
</code>```

This is the package I am using: https://www.npmjs.com/package/ng2-currency-mask

答:
In most cases I would recommend to add attributes directly to the input as it seem much more approrpriate approach to me.

Anyway to achieve this you can create some kind of input abstraction component that will accept such inputs like type, will work with ngModel (you can find more about this here or here for instance) and will contain whatever input you need with any attributes and directives.

So it may look like this in the end:

<custom-input type="text" formInput [rules]="rules"  [(ngModel)]="value"></custom-input>

Then you can hide your logic on what actual input has to be like in this component: assign needed attributes, directives and many other things you'll need.

Title: Add directive from directive

Body:
I have a directive deciding if an input must be required, masked, etc... I ran into a situation that I need to add a new directive to it: basically this new directive adds the mask feature to the input.

<input type="text" formInput [rules]="rules"  [(ngModel)]="value" />

This is the formInput directive:

export class DefaultFormInputDirective {

@Input() private rules;
private el: ElementRef;

constructor(el: ElementRef) {
    this.el = el;
}

ngOnInit() {
    this.defineRules();
}

defineRules() {

    if(this.rules == undefined) {
        return;
    }

    if(this.rules.indexOf('required') != -1) {
        this.el.nativeElement.required = true;
    }

    if(this.rules.indexOf('numeric') != -1) {
        // Here is where I need to add currencyMask directive
    }

}

}

This is the package I am using: https://www.npmjs.com/package/ng2-currency-mask


问:
Div page-breaking css
I need to print an HTML page where all divs are't "pagebroken", without page-break-after:always, in order to show different short divs in the same page especially to avoid blank spaces

答:
I would think this would do the trick.

@media print {
    div {page-break-after: avoid;}
}

Title: Div page-breaking css