问:
Set permissions to file stored using JCA in OSB
I have a proxy which stores a file (Publish action) in a specific directory using a JCA File Adapter. I need to set permissions over the stored file, 777 for instance.

Does anyone know how/where to set it? Maybe a property in JCA file?

答:
we had a similar issue we had to use a java callout to set the permissions manually.

this is a bit of a dirty workaround and is to do with the permissions of the user who started the weblogic server.

in java there is two methods to try, but we used:

Runtime.getRuntime().exec("chmod 777 file");```
</div>
</div>
</p>

<p>you might like to try, </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>   file.setExecutable(false);
   file.setReadable(false);
   file.setWritable(false);</code>```

Body:
we had a similar issue we had to use a java callout to set the permissions manually.

this is a bit of a dirty workaround and is to do with the permissions of the user who started the weblogic server.

in java there is two methods to try, but we used:

Runtime.getRuntime().exec("chmod 777 file");

you might like to try,

   file.setExecutable(false);
   file.setReadable(false);
   file.setWritable(false);


来源: stackexchange

问:
Map is omitting one curly braces
I have a json array which i am putting in a map.

```<code>  for(int i = 0; i < jsonarr.length(); i++){

                try {
                    JSONObject jsonobj = jsonarr.getJSONObject(i);

                    Iterator<Object> keysItr = jsonobj.keys();
                    while(keysItr.hasNext()) {
                        Object key = keysItr.next();
                        Object value = jsonobj.get((String) key);

                        map.put((String) key, value);

                    }
                System.out.println(map);
</code>```

But when I display the map it gives me a string in which there is one curly brace missing.

Output

```<code>{
  subtype=text,
  maxlength=22,
  values=[
    {
      "label":"Time",
      "value":"two",
      "selected":true
    },{
      "label":"Milk",
      "value":"hot"
    },{
      "label":"sky",
      "value":"blue"
    }
  ],
  (HERE)
  name=text-1496816623336,
  description=sa,
  className=form-control,
  label=Text Field,
  type=text,
  required=true
}
</code>```

I have used jackson and gson also but in that case they weren't even putting the whole json into map.It might be a stupid question but thanks.

EDIT :

Here is the JSON used to create the Map

```<code>[
  {
    "type":"select",
    "label":"Select",
    "className":"form-control",
    "name":"select-1496823185891",
    "values":[
      {
        "label":"Option 1",
        "value":"option-1",
        "selected":true
      },{
        "label":"Option 2",
        "value":"option-2"
      },{
        "label":"Option 3",
        "value":"option-3"
      }
    ]
  },{
    "type":"text",
    "label":"Text Field",
    "className":"form-control",
    "name":"text-1496823186970",
    "subtype":"text"
  }
]
</code>```

答:
Hey nope there is no curly brace missing,.... format the output and you will see:

```<code>{
    subtype=text, maxlength=22, values=[
        {"label":"Time","value":"two","selected":true},
        {"label":"Milk","value":"hot"},
        {"label":"sky","value":"blue"}
    ],(HERE)
    name=text-1496816623336,
    description=sa,
    className=form-control,
    label=Text Field,
    type=text,
    required=true
}
</code>```

Edit (answer to your comment):
This is a valid Json string:

[{"type":"select","label":"select","className":"form-control","name":"select-1496823185891","values":[{"label":"Option 1","value":"option-1","selected":true},{"label":"Option 2","value":"option-2"},{"label":"Option 3","value":"option-3"}]},{"type":"text","label":"Text Field","className":"form-control","name":"text-1496823186970","subtype":"text"}].

Formated:

```<code>[
    {
        "type": "select",
        "label": "select",
        "className": "form-control",
        "name": "select-1496823185891",
        "values": [
            {
                "label": "Option 1",
                "value": "option-1",
                "selected": true
            },
            {
                "label": "Option 2",
                "value": "option-2"
            },
            {
                "label": "Option 3",
                "value": "option-3"
            }
        ]
    },
    {
        "type": "text",
        "label": "Text Field",
        "className": "form-control",
        "name": "text-1496823186970",
        "subtype": "text"
    }
]
</code>```

In your one there is some hidden chars between "values" and the :.

ContentLicense: CC BY-SA 3.0

Title: Map is omitting one curly braces

Body:
I have a json array which i am putting in a map.

  for(int i = 0; i < jsonarr.length(); i++){

                try {
                    JSONObject jsonobj = jsonarr.getJSONObject(i);

                    Iterator<Object> keysItr = jsonobj.keys();
                    while(keysItr.hasNext()) {
                        Object key = keysItr.next();
                        Object value = jsonobj.get((String) key);

                        map.put((String) key, value);

                    }
                System.out.println(map);

But when I display the map it gives me a string in which there is one curly brace missing.

Output

{
  subtype=text,
  maxlength=22,
  values=[
    {
      "label":"Time",
      "value":"two",
      "selected":true
    },{
      "label":"Milk",
      "value":"hot"
    },{
      "label":"sky",
      "value":"blue"
    }
  ],
  (HERE)
  name=text-1496816623336,
  description=sa,
  className=form-control,
  label=Text Field,
  type=text,
  required=true
}

I have used jackson and gson also but in that case they weren't even putting the whole json into map.It might be a stupid question but thanks.

EDIT :

Here is the JSON used to create the Map

[
  {
    "type":"select",
    "label":"Select",
    "className":"form-control",
    "name":"select-1496823185891",
    "values":[
      {
        "label":"Option 1",
        "value":"option-1",
        "selected":true
      },{
        "label":"Option 2",
        "value":"option-2"
      },{
        "label":"Option 3",
        "value":"option-3"
      }
    ]
  },{
    "type":"text",
    "label":"Text Field",
    "className":"form-control",
    "name":"text-1496823186970",
    "subtype":"text"
  }
]

Body:
Hey nope there is no curly brace missing,.... format the output and you will see:

{
    subtype=text, maxlength=22, values=[
        {"label":"Time","value":"two","selected":true},
        {"label":"Milk","value":"hot"},
        {"label":"sky","value":"blue"}
    ],(HERE)
    name=text-1496816623336,
    description=sa,
    className=form-control,
    label=Text Field,
    type=text,
    required=true
}

Edit (answer to your comment):
This is a valid Json string:

[{"type":"select","label":"select","className":"form-control","name":"select-1496823185891","values":[{"label":"Option 1","value":"option-1","selected":true},{"label":"Option 2","value":"option-2"},{"label":"Option 3","value":"option-3"}]},{"type":"text","label":"Text Field","className":"form-control","name":"text-1496823186970","subtype":"text"}].

Formated:

[
    {
        "type": "select",
        "label": "select",
        "className": "form-control",
        "name": "select-1496823185891",
        "values": [
            {
                "label": "Option 1",
                "value": "option-1",
                "selected": true
            },
            {
                "label": "Option 2",
                "value": "option-2"
            },
            {
                "label": "Option 3",
                "value": "option-3"
            }
        ]
    },
    {
        "type": "text",
        "label": "Text Field",
        "className": "form-control",
        "name": "text-1496823186970",
        "subtype": "text"
    }
]

In your one there is some hidden chars between "values" and the :.


问:
How to trigger jQuery script on site by Java parser
I'm trying to parse a vacancies from https://www.epam.com/careers/job-listings?query=java&department=all&city=Kyiv&country=Ukraine

But I dont get anything execept plain text like "Job Listings Global/English Deutschland/Deutsch Россия/Русский"

The problem is when you load a page - browser runs a script that load some vacancies, but how can I undesrstand JSOUP cant "simulate" browser and run a script. I tried HtmlUnit, but it also done nothing.

Question: What should i do? Am I doing something wrong with HtmlUnit?

Jsoup

```<code>Element page = = Jsoup.connect("https://www.epam.com/careers/job-listings?sort=best_match&query=java&department=all&city=all&country=Poland").get();
</code>```

HtmlUnit

```<code>try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52)) {
    page = webClient.getPage("https://www.epam.com/careers/job-listings?query=java&department=all&city=Kyiv&country=Ukraine");
}
</code>```

I think i need manualy run some script with

```<code>result = page.executeJavaScript("function aa()");
</code>```

But which one?

答:
You just need to wait a little as hinted here.

You can use:

```<code>try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
    String url = "https://www.epam.com/careers/job-listings?query=java&department=all&city=Kyiv&country=Ukraine";

    HtmlPage page = webClient.getPage(url);
    Thread.sleep(3_000);
    System.out.println(page.asXml());
}
</code>```

Body:
I'm trying to parse a vacancies from https://www.epam.com/careers/job-listings?query=java&department=all&city=Kyiv&country=Ukraine

But I dont get anything execept plain text like "Job Listings Global/English Deutschland/Deutsch Россия/Русский"

The problem is when you load a page - browser runs a script that load some vacancies, but how can I undesrstand JSOUP cant "simulate" browser and run a script. I tried HtmlUnit, but it also done nothing.

Question: What should i do? Am I doing something wrong with HtmlUnit?

Jsoup

Element page = = Jsoup.connect("https://www.epam.com/careers/job-listings?sort=best_match&query=java&department=all&city=all&country=Poland").get();

HtmlUnit

try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52)) {
    page = webClient.getPage("https://www.epam.com/careers/job-listings?query=java&department=all&city=Kyiv&country=Ukraine");
}

I think i need manualy run some script with

result = page.executeJavaScript("function aa()");

But which one?

Body:
You just need to wait a little as hinted here.

You can use:

try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
    String url = "https://www.epam.com/careers/job-listings?query=java&department=all&city=Kyiv&country=Ukraine";

    HtmlPage page = webClient.getPage(url);
    Thread.sleep(3_000);
    System.out.println(page.asXml());
}


问:
Getting Exception in tread Thread-1 where a try should catch the error
I am using Wifi module and using this helper file I want to connect to wifi with the function Connect() it does work but when there is a problem the function should return False but for some reason, I am getting this error wifi.exceptions.ConnectionError.... as I can tell the helper file should catch that error and then return False to my main program. As stated in line 57 and 69 except wifi.exceptions.ConnectionError: instead it is just crashing my program.

```<code> import WifiHandler

 isConnected = WifiHandler.Connect("wifiNetwork","Password")

 if isConnect == True:
      do Somthing
</code>```

and this is the error

```<code>TraceBack (most recent call last):
 File "test.py". line 11, in <module>
  isConnected = WifiHandler.Connect(ssid,password)
 File "/home/pi/WifiHandler.py", line 43, in Connect
    savedcell.activate()
 File "/usr/local/lib/python3.4/dist-packages/wifi/scheme.py", line 176. in activate
     return self.parse_ifup_output(ifup_output)
 File "/usr/local/lib/python3.4/dist-packages/wifi/scheme.py" line 183, in parse_ifuo_output
     raise ConnectionError("failed to connect to %r" % self)
     wifi.exceptions.ConnectionError: Failed to connect to Scheme(interface='wlan0',name ='SSIDName', options={'wpa-psk':'32nnj3323jej222n4n2n421353535353535353535353535353', 'wpa-ssid': 'SSIDName' , 'wireless-channel':'auto'})
</code>```

答:
Hey guys thank to Morb. I fix the problem.

In the helper file it was not catching the error for savedcells

```<code>      if savedcell:
            savedcell.activate()
            return cell
</code>```

it should be

```<code> if savedcell:
        try:
           savedcell.activate()
        except wifi.exceptions.ConnectionError:

            return False

        return cell
</code>```

Body:
I am using Wifi module and using this helper file I want to connect to wifi with the function Connect() it does work but when there is a problem the function should return False but for some reason, I am getting this error wifi.exceptions.ConnectionError.... as I can tell the helper file should catch that error and then return False to my main program. As stated in line 57 and 69 except wifi.exceptions.ConnectionError: instead it is just crashing my program.

 import WifiHandler

 isConnected = WifiHandler.Connect("wifiNetwork","Password")

 if isConnect == True:
      do Somthing

and this is the error

TraceBack (most recent call last):
 File "test.py". line 11, in <module>
  isConnected = WifiHandler.Connect(ssid,password)
 File "/home/pi/WifiHandler.py", line 43, in Connect
    savedcell.activate()
 File "/usr/local/lib/python3.4/dist-packages/wifi/scheme.py", line 176. in activate
     return self.parse_ifup_output(ifup_output)
 File "/usr/local/lib/python3.4/dist-packages/wifi/scheme.py" line 183, in parse_ifuo_output
     raise ConnectionError("failed to connect to %r" % self)
     wifi.exceptions.ConnectionError: Failed to connect to Scheme(interface='wlan0',name ='SSIDName', options={'wpa-psk':'32nnj3323jej222n4n2n421353535353535353535353535353', 'wpa-ssid': 'SSIDName' , 'wireless-channel':'auto'})

Body:
Hey guys thank to Morb. I fix the problem.

In the helper file it was not catching the error for savedcells

      if savedcell:
            savedcell.activate()
            return cell

it should be

 if savedcell:
        try:
           savedcell.activate()
        except wifi.exceptions.ConnectionError:

            return False

        return cell


问:
Rails 5 - controller spec example - passing params set to nil value gets their value set to blank string
I have this following Controller spec example passing in my API-only application based on Rails 4.2.0 and Ruby 2.2.1

```<code>  let!(:params) { { user_token: user_token } }

  context "- and optional address and contact details params value are received as a nil values -" do
    it "doesn't set the address and contact details and responds with 201 success", check: true do
      params.merge!(
        address_street: nil, address_other: nil, city: nil, state: nil,
        zip_code: nil, phone: nil)

      post :create, params

      expect(response).to have_http_status(201)

      saved_client_id = json_response["id"]
      saved_client = Client.find_by(id: saved_client_id)
      expect(saved_client.address_street).to be_nil
      expect(saved_client.address_other).to be_nil
      expect(saved_client.city).to be_nil
      expect(saved_client.state).to be_nil
      expect(saved_client.zip_code).to be_nil
      expect(saved_client.phone).to be_nil
    end
  end
</code>```

However evaluating my application against Rails 5 (edge version) and Ruby 2.2.3 the same spec fails with following error:

```<code>  1) Api::V1::ClientsController POST #create when receives valid client details - and optional address and contact details params value are received as nil values - doesn't set the address and contact details and responds with 201 success
     Failure/Error: expect(saved_client.address_street).to be_nil
       expected: nil
            got: ""
     # ./spec/controllers/api/v1/clients_controller_spec.rb:352:in `block (5 levels) in <top (required)>'
     # ./spec/rails_helper.rb:61:in `block (3 levels) in <top (required)>'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/generic/base.rb:16:in `cleaning'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/base.rb:92:in `cleaning'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/configuration.rb:87:in `call'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/configuration.rb:87:in `cleaning'
 # ./spec/rails_helper.rb:60:in `block (2 levels) in <top (required)>'
</code>```

I did inspected the Rails source code at few points and found that the nil values are transformed to blank values before reaching the controller's targeted action logic.

This changed behavior is setting attributes to empty strings, when they are expected to be nil.

In my app's Gemfile (for using Rails 5) I have specified Rails using following code:

```<code>gem 'rails', git: 'https://github.com/rails/rails.git'

gem 'rack', :git => 'https://github.com/rack/rack.git'
gem 'arel', :git => 'https://github.com/rails/arel.git'
</code>```

and in Gemfile.lock following can be seen (Gem and Dependencies portions truncated to cut it short):

```<code>GIT
  remote: git://github.com/capistrano/rbenv.git
  revision: 6f1216cfe0a6b4ac23ca4eaf8acf012e8165d247
  specs:
    capistrano-rbenv (2.0.3)
      capistrano (~> 3.1)
      sshkit (~> 1.3)

GIT
  remote: https://github.com/rack/rack.git
  revision: c393176b0edf3e5d06cabbb6eb9d9c7a07b2afa7
  specs:
    rack (2.0.0.alpha)
      json

GIT
  remote: https://github.com/rails/arel.git
  revision: 3c429c5d86e9e2201c2a35d934ca6a8911c18e69
  specs:
    arel (7.0.0.alpha)

GIT
  remote: https://github.com/rails/rails.git
  revision: 58df2f4b4abcce0b698c2540da215a565c24cbc9
  specs:
    actionmailer (5.0.0.alpha)
      actionpack (= 5.0.0.alpha)
      actionview (= 5.0.0.alpha)
      activejob (= 5.0.0.alpha)
      mail (~> 2.5, >= 2.5.4)
      rails-dom-testing (~> 1.0, >= 1.0.5)
    actionpack (5.0.0.alpha)
      actionview (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      rack (~> 2.x)
      rack-test (~> 0.6.3)
      rails-dom-testing (~> 1.0, >= 1.0.5)
      rails-html-sanitizer (~> 1.0, >= 1.0.2)
    actionview (5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      builder (~> 3.1)
      erubis (~> 2.7.0)
      rails-dom-testing (~> 1.0, >= 1.0.5)
      rails-html-sanitizer (~> 1.0, >= 1.0.2)
    activejob (5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      globalid (>= 0.3.0)
    activemodel (5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      builder (~> 3.1)
    activerecord (5.0.0.alpha)
      activemodel (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      arel (= 7.0.0.alpha)
    activesupport (5.0.0.alpha)
      concurrent-ruby (~> 1.0)
      i18n (~> 0.7)
      json (~> 1.7, >= 1.7.7)
      method_source
      minitest (~> 5.1)
      tzinfo (~> 1.1)
    rails (5.0.0.alpha)
      actionmailer (= 5.0.0.alpha)
      actionpack (= 5.0.0.alpha)
      actionview (= 5.0.0.alpha)
      activejob (= 5.0.0.alpha)
      activemodel (= 5.0.0.alpha)
      activerecord (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      bundler (>= 1.3.0, < 2.0)
      railties (= 5.0.0.alpha)
      sprockets-rails (>= 2.0.0)
    railties (5.0.0.alpha)
      actionpack (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      method_source
      rake (>= 0.8.7)
      thor (>= 0.18.1, < 2.0)
...
....
</code>```

Can anybody please let me know what changed caused this? I guess it has something to do with change in Rails 5 or the latest Rack. Is this some-kind of bug which shall be fixed in the final release version or this is deliberate change.

答:
A variant of violetaria's answer is to add as: :json to your requests, e.g.

```<code>post :create, params: {…}, as: :json
</code>```

Body:
I have this following Controller spec example passing in my API-only application based on Rails 4.2.0 and Ruby 2.2.1

  let!(:params) { { user_token: user_token } }

  context "- and optional address and contact details params value are received as a nil values -" do
    it "doesn't set the address and contact details and responds with 201 success", check: true do
      params.merge!(
        address_street: nil, address_other: nil, city: nil, state: nil,
        zip_code: nil, phone: nil)

      post :create, params

      expect(response).to have_http_status(201)

      saved_client_id = json_response["id"]
      saved_client = Client.find_by(id: saved_client_id)
      expect(saved_client.address_street).to be_nil
      expect(saved_client.address_other).to be_nil
      expect(saved_client.city).to be_nil
      expect(saved_client.state).to be_nil
      expect(saved_client.zip_code).to be_nil
      expect(saved_client.phone).to be_nil
    end
  end

However evaluating my application against Rails 5 (edge version) and Ruby 2.2.3 the same spec fails with following error:

  1) Api::V1::ClientsController POST #create when receives valid client details - and optional address and contact details params value are received as nil values - doesn't set the address and contact details and responds with 201 success
     Failure/Error: expect(saved_client.address_street).to be_nil
       expected: nil
            got: ""
     # ./spec/controllers/api/v1/clients_controller_spec.rb:352:in `block (5 levels) in <top (required)>'
     # ./spec/rails_helper.rb:61:in `block (3 levels) in <top (required)>'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/generic/base.rb:16:in `cleaning'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/base.rb:92:in `cleaning'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/configuration.rb:87:in `call'
     # /home/jignesh/.rvm/gems/ruby-2.2.3@myapp-on-rails-5/gems/database_cleaner-1.5.1/lib/database_cleaner/configuration.rb:87:in `cleaning'
 # ./spec/rails_helper.rb:60:in `block (2 levels) in <top (required)>'

I did inspected the Rails source code at few points and found that the nil values are transformed to blank values before reaching the controller's targeted action logic.

This changed behavior is setting attributes to empty strings, when they are expected to be nil.

In my app's Gemfile (for using Rails 5) I have specified Rails using following code:

gem 'rails', git: 'https://github.com/rails/rails.git'

gem 'rack', :git => 'https://github.com/rack/rack.git'
gem 'arel', :git => 'https://github.com/rails/arel.git'

and in Gemfile.lock following can be seen (Gem and Dependencies portions truncated to cut it short):

GIT
  remote: git://github.com/capistrano/rbenv.git
  revision: 6f1216cfe0a6b4ac23ca4eaf8acf012e8165d247
  specs:
    capistrano-rbenv (2.0.3)
      capistrano (~> 3.1)
      sshkit (~> 1.3)

GIT
  remote: https://github.com/rack/rack.git
  revision: c393176b0edf3e5d06cabbb6eb9d9c7a07b2afa7
  specs:
    rack (2.0.0.alpha)
      json

GIT
  remote: https://github.com/rails/arel.git
  revision: 3c429c5d86e9e2201c2a35d934ca6a8911c18e69
  specs:
    arel (7.0.0.alpha)

GIT
  remote: https://github.com/rails/rails.git
  revision: 58df2f4b4abcce0b698c2540da215a565c24cbc9
  specs:
    actionmailer (5.0.0.alpha)
      actionpack (= 5.0.0.alpha)
      actionview (= 5.0.0.alpha)
      activejob (= 5.0.0.alpha)
      mail (~> 2.5, >= 2.5.4)
      rails-dom-testing (~> 1.0, >= 1.0.5)
    actionpack (5.0.0.alpha)
      actionview (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      rack (~> 2.x)
      rack-test (~> 0.6.3)
      rails-dom-testing (~> 1.0, >= 1.0.5)
      rails-html-sanitizer (~> 1.0, >= 1.0.2)
    actionview (5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      builder (~> 3.1)
      erubis (~> 2.7.0)
      rails-dom-testing (~> 1.0, >= 1.0.5)
      rails-html-sanitizer (~> 1.0, >= 1.0.2)
    activejob (5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      globalid (>= 0.3.0)
    activemodel (5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      builder (~> 3.1)
    activerecord (5.0.0.alpha)
      activemodel (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      arel (= 7.0.0.alpha)
    activesupport (5.0.0.alpha)
      concurrent-ruby (~> 1.0)
      i18n (~> 0.7)
      json (~> 1.7, >= 1.7.7)
      method_source
      minitest (~> 5.1)
      tzinfo (~> 1.1)
    rails (5.0.0.alpha)
      actionmailer (= 5.0.0.alpha)
      actionpack (= 5.0.0.alpha)
      actionview (= 5.0.0.alpha)
      activejob (= 5.0.0.alpha)
      activemodel (= 5.0.0.alpha)
      activerecord (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      bundler (>= 1.3.0, < 2.0)
      railties (= 5.0.0.alpha)
      sprockets-rails (>= 2.0.0)
    railties (5.0.0.alpha)
      actionpack (= 5.0.0.alpha)
      activesupport (= 5.0.0.alpha)
      method_source
      rake (>= 0.8.7)
      thor (>= 0.18.1, < 2.0)
...
....

Can anybody please let me know what changed caused this? I guess it has something to do with change in Rails 5 or the latest Rack. Is this some-kind of bug which shall be fixed in the final release version or this is deliberate change.

Body:
A variant of violetaria's answer is to add as: :json to your requests, e.g.

post :create, params: {…}, as: :json


问:
High Availability in CEPH monitor
I have 4 node ceph architecture as shown in the figure.
Ceph Architecture
Ceph.conf contains

```<code>[global]
fsid = 23923667-d7af-4138-a6e5-2e38fb999e2d
max open files = 131072
mon_initial_members = host1, host2
mon host = 10.xx.xx.1,10.xx.xx.2
public_network = 10.xx.xx.xx/27
cluster_network = 10.xx.xx.xx/27
</code>```

The first monitor has been attached using the following command

```<code>ceph-deploy mon create-initial
</code>```

Second monitor has been added to the cluster by the following command

```<code>ceph-deploy mon add 10.xx.xx.2
</code>```

We are testing high availability cases with this setup.

Case 1: I brought down the node 10.xx.xx.2 and tested my connection. Ceph was up and responding with the monitor 10.xx.xx.1

Case 2: I brought down the node 10.xx.xx.1. But I am unable to access the ceph cluster via 10.xx.xx.2.

Is there any other way to create the setup so that the second node becomes master when the first node is down ?

[edit1]

The scenario is

```<code> intial monitor node = mon.a
 additional monitor node =mon.b,mon.c
</code>```

When I bring down mon.b and mon.c ceph is working fine.

But when I bring down mon.a entire ceph cluster gets disturbed and ceph is not responding.

答: If you have two MON, either MON disappear will not have Quorum. Therefore you will not have a running state if one MON disappear. So yes, you always need odd number for MON total. 1,3,5, etc. I'm not sure why you have Quorum without any one for MON. But if you really do, ceph -s show you how does it get Quorum. </p>

Title: High Availability in CEPH monitor

Body:
I have 4 node ceph architecture as shown in the figure.
Ceph Architecture
Ceph.conf contains

[global]
fsid = 23923667-d7af-4138-a6e5-2e38fb999e2d
max open files = 131072
mon_initial_members = host1, host2
mon host = 10.xx.xx.1,10.xx.xx.2
public_network = 10.xx.xx.xx/27
cluster_network = 10.xx.xx.xx/27

The first monitor has been attached using the following command

ceph-deploy mon create-initial

Second monitor has been added to the cluster by the following command

ceph-deploy mon add 10.xx.xx.2

We are testing high availability cases with this setup.

Case 1: I brought down the node 10.xx.xx.2 and tested my connection. Ceph was up and responding with the monitor 10.xx.xx.1

Case 2: I brought down the node 10.xx.xx.1. But I am unable to access the ceph cluster via 10.xx.xx.2.

Is there any other way to create the setup so that the second node becomes master when the first node is down ?

[edit1]

The scenario is

 intial monitor node = mon.a
 additional monitor node =mon.b,mon.c

When I bring down mon.b and mon.c ceph is working fine.

But when I bring down mon.a entire ceph cluster gets disturbed and ceph is not responding.


问:
Can't hide soft keyboard in Android Studio project, why?
I'm trying to hide the soft keyboard in an Android Studio project. The View in the hideKeyboard() method keeps coming up as null... I can't figure out why... Please advise. </p>

```<code>  @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rewashlog_options);

    luxuryCountTextView = (TextView) findViewById(R.id.luxuryCountTextView);
    fullCountTextView = (TextView) findViewById(R.id.fullCountTextView);
    quickCountTextView = (TextView) findViewById(R.id.quickCountTextView);
    totalCountTextView = (TextView) findViewById(R.id.totalCountTextView);
    emailRecipient = (EditText) findViewById(R.id.emailRecipient);

    instantiateMonthSpinner();
    instantiateYearSpinner();
    getEntireRewashList();
    updateListView();
    hideKeyboard();

}

 private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}
</code>```

答:
You can use android:windowSoftInputMode="stateHidden" in your mainfest to hide the keyboard on activity launch like this

```<code>`<activity android:name=".YourActivity"
        android:windowSoftInputMode="stateHidden" />`
</code>```

Body:
I'm trying to hide the soft keyboard in an Android Studio project. The View in the hideKeyboard() method keeps coming up as null... I can't figure out why... Please advise.

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

    luxuryCountTextView = (TextView) findViewById(R.id.luxuryCountTextView);
    fullCountTextView = (TextView) findViewById(R.id.fullCountTextView);
    quickCountTextView = (TextView) findViewById(R.id.quickCountTextView);
    totalCountTextView = (TextView) findViewById(R.id.totalCountTextView);
    emailRecipient = (EditText) findViewById(R.id.emailRecipient);

    instantiateMonthSpinner();
    instantiateYearSpinner();
    getEntireRewashList();
    updateListView();
    hideKeyboard();

}

 private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}

Body:
You can use android:windowSoftInputMode="stateHidden" in your mainfest to hide the keyboard on activity launch like this

`<activity android:name=".YourActivity"
        android:windowSoftInputMode="stateHidden" />`


问:
"File Not Found" while trying to compile an RC file (probably dumb mistake)
Following these steps for adding a UAC manifest to my C# project embedded as a resource.

Step 1 works fine, I create the RC file in my project as a simple text file as described.

```<code>#include <winuser.h>
#define IDR_MANIFEST 1 // 2 for a DLL

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
{
 "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
   <asmv3:trustInfo xmlns:asmv3=""urn:schemas-microsoft-com:asm.v3"">
     <asmv3:security>
       <asmv3:requestedPrivileges>
         <asmv3:requestedExecutionLevel
           level=""asInvoker""
           uiAccess=""false"" />
       </asmv3:requestedPrivileges>
     </asmv3:security>
   </asmv3:trustInfo>
  </assembly>"
}
</code>```

Then using the Visual Studio Command Prompt, I get the following output at step 2:

```<code>  c:\myproject>rc MyResourceFile.rc
  Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
  Copyright (C) Microsoft Corporation.  All rights reserved.

  ConfigurationManager.rc(4) : error RC2135 : file not found: 1
</code>```

I assume this is something quite dumb, right?

答: As Hans Passant said, starting with VS 2008 you can simply directly add the manifest file to the project. Then under the properties of the project, select the "application" tab and choose the manifest file from the ComboBox "Manifest:".</p>

ContentLicense: CC BY-SA 2.5

Body:
Following these steps for adding a UAC manifest to my C# project embedded as a resource.

Step 1 works fine, I create the RC file in my project as a simple text file as described.

#include <winuser.h>
#define IDR_MANIFEST 1 // 2 for a DLL

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
{
 "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
   <asmv3:trustInfo xmlns:asmv3=""urn:schemas-microsoft-com:asm.v3"">
     <asmv3:security>
       <asmv3:requestedPrivileges>
         <asmv3:requestedExecutionLevel
           level=""asInvoker""
           uiAccess=""false"" />
       </asmv3:requestedPrivileges>
     </asmv3:security>
   </asmv3:trustInfo>
  </assembly>"
}

Then using the Visual Studio Command Prompt, I get the following output at step 2:

  c:\myproject>rc MyResourceFile.rc
  Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
  Copyright (C) Microsoft Corporation.  All rights reserved.

  ConfigurationManager.rc(4) : error RC2135 : file not found: 1

I assume this is something quite dumb, right?


问:
how can I detect if singleTap was tapped or annotation on mapView of mapbox?
Requirment on iOS for mapBox map. (I am not talking about MKMapView)
how can we detect if singleTap was tapped or annotation on mapView? I need that singleTap will be handled only on empty area of map (without pins), and didSelectAnnotation called when i tap on pin.

But I found on android we have method like this

```<code>mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
            public void onMapClick(@NonNull LatLng point) {
                Toast.makeText(getActivity(),"on Tap "+point.getLatitude(),Toast.LENGTH_LONG).show();
            }
        });
</code>```

and along with that

mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() { ... }) will display the annotation.

Don't we have same kind of concept in iOS ?

The actual problem is in iOS is, when I add singleTapGesture on mapView of Mapbox

```<code>UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.mapView addGestureRecognizer:singleTapGesture];
</code>```

the delegate method of mapView of mapbox will not call.

```<code>- (nullable UIView <MGLCalloutView> *)mapView:(MGLMapView *)mapView calloutViewForAnnotation:(id <MGLAnnotation>)annotation;
</code>```

to make sure the delegate method must call, then I dont have to use singleTapGesture

Here the situation is either this or that, but as per me need I needed both.

Looking forward of any solution.
Thanks,

答:
Try swift 3

```<code>//determined is Point inner to realm polygons
func determinedInPoligon(point:CLLocationCoordinate2D, poligon:[CLLocationCoordinate2D]) -> Bool {

    var result:Bool = false
    var j = poligon.count - 1

    for i in 0 ..< poligon.count {

        if  (poligon[i].longitude < point.longitude && poligon[j].longitude >= point.longitude || poligon[j].longitude < point.longitude && poligon[i].longitude >= point.longitude) &&
            (poligon[i].latitude + (point.longitude - poligon[i].longitude) / (poligon[j].longitude - poligon[i].longitude) * (poligon[j].latitude - poligon[i].latitude) < point.latitude) {
            result = !result;
        }
        j = i;

    }
    return result
}

func squareFrom(location: CGPoint, radius: Double) -> CGRect {//return rect with CGPoint center and radius
    let length = radius
    return CGRect(x: Double(location.x - CGFloat(length / 2)), y:
   Double(location.y - CGFloat(length / 2)), width: length, height: length)
}
</code>```

function handle

```<code>func handleTap(_ gesture: UITapGestureRecognizer) {

    // Get the CGPoint where the user tapped.
    let spot = gesture.location(in: mapView)

    let my_features = mapView.visibleFeatures(at: spot)
    let strZoomValue = mapView.zoomLevel > 15 ? "6" : "4"
    //the feature structur object value not equal annotation object
    for value in my_features.enumerated() {// feature items
        if value.element is MGLPointAnnotation  {

            for annot in (mapView.annotations?.enumerated())! { // annotation items
                if annot.element is MGLPointAnnotation {

                    //rounded lat and lng value
                    var arr_cllocation = [CLLocationCoordinate2D]()
                    for cllocation in [(annot.element as! MGLPointAnnotation).coordinate, (value.element as! MGLPointAnnotation).coordinate] {

                        let strLat = String(format: "%."+strZoomValue+"f", cllocation.latitude)
                        let strLon = String(format: "%."+strZoomValue+"f", cllocation.longitude)
                        arr_cllocation.append(
                            CLLocationCoordinate2D(latitude: CLLocationDegrees(strLat)!, longitude: CLLocationDegrees(strLon)!) )
                    }

                    if arr_cllocation.count == 2 &&
                        memcmp(&arr_cllocation[0], &arr_cllocation[1], MemoryLayout<CLLocationCoordinate2D>.size) == 0 {// 0 if equal object
                        // to do custom popup view
                        let instViewPopupLineClass = UINib(nibName: "ViewPopupBase", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView

                        for objectInst in instViewPopupLineClass.subviews.enumerated() {

                            if objectInst.element is UILabel {
                                let asdasdas = (annot.element as! MGLPointAnnotation).subtitle
                                (objectInst.element as! UILabel).text = asdasdas
                                MyCustomPopup(customView: instViewPopupLineClass, positionXY: spot)
                                break
                            }
                        }
                    }
                }
            } //for end

        }
    }
}
</code>```

OR not accurate method, but a worker ;)

```<code>func handleTap(_ gesture: UITapGestureRecognizer) {// Get the CGPoint where the user tapped.

    let spot = gesture.location(in: mapView)
    let cllcordinatTap = mapView.convert(spot, toCoordinateFrom: mapView)
                 //for determined zoom scala
            let  deltScalaMap = abs(self.mapView.maximumZoomLevel - self.mapView.zoomLevel)
           //The large is zoom maps, then smal size is tap location, and vice versa.
            let checkScalaMap = deltScalaMap == 0 ? 1 : deltScalaMap
            let _rect = squareFrom(location: CGPoint(x: cllcordinatTap.latitude, y: cllcordinatTap.longitude), radius: 0.00005 * checkScalaMap)
  for annot in (mapView.annotations?.enumerated())! {

       if annot.element is MGLPointAnnotation {
          let _cordinatCurrentAnnotation = (annot.element as! MGLPointAnnotation).coordinate

          if  determinedInPoligon(point: _cordinatCurrentAnnotation, poligon:
              [CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.minX), longitude: CLLocationDegrees(_rect.minY)),
               CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.maxX), longitude: CLLocationDegrees(_rect.minY)),
               CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.maxX), longitude: CLLocationDegrees(_rect.maxY)),
               CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.minX), longitude: CLLocationDegrees(_rect.maxY))
          ]) {

              // to do, if tap MGLPointAnnotation, annot.element

          }
      }
  }
}
</code>```

Body:
Requirment on iOS for mapBox map. (I am not talking about MKMapView)
how can we detect if singleTap was tapped or annotation on mapView? I need that singleTap will be handled only on empty area of map (without pins), and didSelectAnnotation called when i tap on pin.

But I found on android we have method like this

mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
            public void onMapClick(@NonNull LatLng point) {
                Toast.makeText(getActivity(),"on Tap "+point.getLatitude(),Toast.LENGTH_LONG).show();
            }
        });

and along with that

mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() { ... }) will display the annotation.

Don't we have same kind of concept in iOS ?

The actual problem is in iOS is, when I add singleTapGesture on mapView of Mapbox

UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.mapView addGestureRecognizer:singleTapGesture];

the delegate method of mapView of mapbox will not call.

- (nullable UIView <MGLCalloutView> *)mapView:(MGLMapView *)mapView calloutViewForAnnotation:(id <MGLAnnotation>)annotation;

to make sure the delegate method must call, then I dont have to use singleTapGesture

Here the situation is either this or that, but as per me need I needed both.

Looking forward of any solution.
Thanks,

Body:
Try swift 3

//determined is Point inner to realm polygons
func determinedInPoligon(point:CLLocationCoordinate2D, poligon:[CLLocationCoordinate2D]) -> Bool {

    var result:Bool = false
    var j = poligon.count - 1

    for i in 0 ..< poligon.count {

        if  (poligon[i].longitude < point.longitude && poligon[j].longitude >= point.longitude || poligon[j].longitude < point.longitude && poligon[i].longitude >= point.longitude) &&
            (poligon[i].latitude + (point.longitude - poligon[i].longitude) / (poligon[j].longitude - poligon[i].longitude) * (poligon[j].latitude - poligon[i].latitude) < point.latitude) {
            result = !result;
        }
        j = i;

    }
    return result
}

func squareFrom(location: CGPoint, radius: Double) -> CGRect {//return rect with CGPoint center and radius
    let length = radius
    return CGRect(x: Double(location.x - CGFloat(length / 2)), y:
   Double(location.y - CGFloat(length / 2)), width: length, height: length)
}

function handle

func handleTap(_ gesture: UITapGestureRecognizer) {

    // Get the CGPoint where the user tapped.
    let spot = gesture.location(in: mapView)

    let my_features = mapView.visibleFeatures(at: spot)
    let strZoomValue = mapView.zoomLevel > 15 ? "6" : "4"
    //the feature structur object value not equal annotation object
    for value in my_features.enumerated() {// feature items
        if value.element is MGLPointAnnotation  {

            for annot in (mapView.annotations?.enumerated())! { // annotation items
                if annot.element is MGLPointAnnotation {

                    //rounded lat and lng value
                    var arr_cllocation = [CLLocationCoordinate2D]()
                    for cllocation in [(annot.element as! MGLPointAnnotation).coordinate, (value.element as! MGLPointAnnotation).coordinate] {

                        let strLat = String(format: "%."+strZoomValue+"f", cllocation.latitude)
                        let strLon = String(format: "%."+strZoomValue+"f", cllocation.longitude)
                        arr_cllocation.append(
                            CLLocationCoordinate2D(latitude: CLLocationDegrees(strLat)!, longitude: CLLocationDegrees(strLon)!) )
                    }

                    if arr_cllocation.count == 2 &&
                        memcmp(&arr_cllocation[0], &arr_cllocation[1], MemoryLayout<CLLocationCoordinate2D>.size) == 0 {// 0 if equal object
                        // to do custom popup view
                        let instViewPopupLineClass = UINib(nibName: "ViewPopupBase", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView

                        for objectInst in instViewPopupLineClass.subviews.enumerated() {

                            if objectInst.element is UILabel {
                                let asdasdas = (annot.element as! MGLPointAnnotation).subtitle
                                (objectInst.element as! UILabel).text = asdasdas
                                MyCustomPopup(customView: instViewPopupLineClass, positionXY: spot)
                                break
                            }
                        }
                    }
                }
            } //for end

        }
    }
}

OR not accurate method, but a worker ;)

func handleTap(_ gesture: UITapGestureRecognizer) {// Get the CGPoint where the user tapped.

    let spot = gesture.location(in: mapView)
    let cllcordinatTap = mapView.convert(spot, toCoordinateFrom: mapView)
                 //for determined zoom scala
            let  deltScalaMap = abs(self.mapView.maximumZoomLevel - self.mapView.zoomLevel)
           //The large is zoom maps, then smal size is tap location, and vice versa.
            let checkScalaMap = deltScalaMap == 0 ? 1 : deltScalaMap
            let _rect = squareFrom(location: CGPoint(x: cllcordinatTap.latitude, y: cllcordinatTap.longitude), radius: 0.00005 * checkScalaMap)
  for annot in (mapView.annotations?.enumerated())! {

       if annot.element is MGLPointAnnotation {
          let _cordinatCurrentAnnotation = (annot.element as! MGLPointAnnotation).coordinate

          if  determinedInPoligon(point: _cordinatCurrentAnnotation, poligon:
              [CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.minX), longitude: CLLocationDegrees(_rect.minY)),
               CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.maxX), longitude: CLLocationDegrees(_rect.minY)),
               CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.maxX), longitude: CLLocationDegrees(_rect.maxY)),
               CLLocationCoordinate2D(latitude: CLLocationDegrees(_rect.minX), longitude: CLLocationDegrees(_rect.maxY))
          ]) {

              // to do, if tap MGLPointAnnotation, annot.element

          }
      }
  }
}


问:
HTML removing all events from element
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

```<code>function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}
</code>```

but there is an error (in console):

```<code>jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent
</code>```

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

答: You're calling jQuery methods on objects returned by getElementsByTagName. getElementsByTagName does not return back jQuery objects. You need to either do $(elems[i]).unbind(); in your existing code or better off, find the anchor tags like $("a", "body") and then work with them

Title: HTML removing all events from element

Body:
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}

but there is an error (in console):

jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?


问:
How to allow CORS with Node.js (without using Express)
I tried answers from other questions and used (updated from https://gist.github.com/balupton/3696140):

```<code>var http = require('http');
var cors = require('cors');

http.createServer(app).listen(3000).use();

function app(request, response) {

response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');

...

}
</code>```

It returns: http.createServer(...).listen(...).use is not a function

After the update it runs but I am still getting 405 error on the client side.

答:
You don't want to use Express but yet trying to use it's middle-ware mechanism.

if

```<code>var server = http.createServer(app).listen(3000)
</code>```

then server doesn't have the .use function, the cors module was designed as a middle-ware which means you need to use Express/Connect in order to use it.

You can keep being wihtout expressjs and find different ways than using cors, for e.g see here https://gist.github.com/balupton/3696140

Body:
I tried answers from other questions and used (updated from https://gist.github.com/balupton/3696140):

var http = require('http');
var cors = require('cors');

http.createServer(app).listen(3000).use();

function app(request, response) {

response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');

...

}

It returns: http.createServer(...).listen(...).use is not a function

After the update it runs but I am still getting 405 error on the client side.

Body:
You don't want to use Express but yet trying to use it's middle-ware mechanism.

if

var server = http.createServer(app).listen(3000)

then server doesn't have the .use function, the cors module was designed as a middle-ware which means you need to use Express/Connect in order to use it.

You can keep being wihtout expressjs and find different ways than using cors, for e.g see here https://gist.github.com/balupton/3696140


问:
How to run ARM Assembly?
I have learned ARM & Neon instruction set from reference manual. Now i want to use that in ARM processor,

```<code>void addArr(int *a,int *b){ int i=0;
 for(i=0;i<4;i++){
  a[i]=a[i]+b[i];
  }
}
int main(){
 int a[4]={0,1,2,3};
 int b[4]={0,1,2,3};
 addArr(a,b);
 return 0;
}
</code>```

for above function addArr(), i have written assembly code as

```<code>@by default r0- address of a, r1- address of b

 VLD1.I32 D0,D1,[R0]!        @loading 128 bit of input , i.e 4 element(32*4=128) of a
 VLD1.I32 D2,D3,[R1]!        @loading 128 bit of input , i.e 4 element(32*4=128) of b
 VADD.I32 Q0, Q1, Q2         @q0(0:31)=1st element of a + 1st element of b ... till 4 element
</code>```

now how to interconnect between them? there must be some syntax for arm assembly..i dnt know that. please share some good reading.
Note: please don't check logic & don't suggest intrinsic method

答:
You need to follow the Procedure Call Standard.

Then you need to link some identifiers to let C know where to find addArr().
In the assembler you need EXPORT  addArr, and in C you will need a declaration like __asm void addArr()

This depends on your toolchain.

Title: How to run ARM Assembly?

Body:
I have learned ARM & Neon instruction set from reference manual. Now i want to use that in ARM processor,

void addArr(int *a,int *b){ int i=0;
 for(i=0;i<4;i++){
  a[i]=a[i]+b[i];
  }
}
int main(){
 int a[4]={0,1,2,3};
 int b[4]={0,1,2,3};
 addArr(a,b);
 return 0;
}

for above function addArr(), i have written assembly code as

@by default r0- address of a, r1- address of b

 VLD1.I32 D0,D1,[R0]!        @loading 128 bit of input , i.e 4 element(32*4=128) of a
 VLD1.I32 D2,D3,[R1]!        @loading 128 bit of input , i.e 4 element(32*4=128) of b
 VADD.I32 Q0, Q1, Q2         @q0(0:31)=1st element of a + 1st element of b ... till 4 element

now how to interconnect between them? there must be some syntax for arm assembly..i dnt know that. please share some good reading.
Note: please don't check logic & don't suggest intrinsic method


问:
How to generate simpler xml in c#?
if there any way to generate xml file in c# with form like this:

```<code><data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>
</code>```

I tried

```<code>System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")
</code>```

and my xml has body like:

```<code><tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>
</code>```

答:
using XElement from LINQ to XML API is probably the simplest way:

```<code>XElement data =
    new XElement("data",
        new XElement("tableName",
            new XElement("fieldname", "value"),
            new XElement("fieldname", "value2"),
            new XElement("fieldname", "value3")
        )
    );
</code>```

Microsoft has great tutorial on LINQ to XML or specifically Creating XML Trees with bunch of examples.

Title: How to generate simpler xml in c#?

Body:
if there any way to generate xml file in c# with form like this:

<data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>

I tried

System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")

and my xml has body like:

<tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>

Body:
using XElement from LINQ to XML API is probably the simplest way:

XElement data =
    new XElement("data",
        new XElement("tableName",
            new XElement("fieldname", "value"),
            new XElement("fieldname", "value2"),
            new XElement("fieldname", "value3")
        )
    );

Microsoft has great tutorial on LINQ to XML or specifically Creating XML Trees with bunch of examples.


问:
Get TYPO3 Extbase mm relation count
We created a simple mm relation between to models like so:

```<code><?php
namespace VENDOR\COMPANY\Domain\Model;

class Posts extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{

//..

 /**
   * users
   *
   * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\VENDOR\COMPANY\Domain\Model\Users>
   */
   protected $likedBy = null;

 //..

}
</code>```

The MySQL database creates a new mm table and also creates a counter column users in the ..domain_post table. Is there a "lighter" way to get this counting than call all related users and count them?

```<code>$amountLikes = $post->getLikedBy()->count();
</code>```

Imagine a list of posts with ~ 30000 likes each. The script starts to build up 30000 objects in the memory. Asking the posts table for the number sounds more realistic to me. But how to?

答:
If your concern here is the performance, you may want to consider redefining your relationship model. TYPO3 keeps relation fields for MM-relations in entities that automatically maintain the amount of related entities. You can then write a custom query that resolves the actual column content, which will be the amount of likes. Heres a blog post as a good starting point on how to do that.

http://lbrmedia.net/codebase/Eintrag/extbase-bidirektionale-mm-relation/

You also need to understand lazy loading relations, as, judging by your current model, the relation to users isn't lazy, which means that Extbase will instanciate all these users for every Post you load.

https://docs.typo3.org/typo3cms/ExtbaseFluidBook/5-Domain/2-implementing-the-domain-model.html

Title: Get TYPO3 Extbase mm relation count

Body:
We created a simple mm relation between to models like so:

<?php
namespace VENDOR\COMPANY\Domain\Model;

class Posts extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{

//..

 /**
   * users
   *
   * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\VENDOR\COMPANY\Domain\Model\Users>
   */
   protected $likedBy = null;

 //..

}

The MySQL database creates a new mm table and also creates a counter column users in the ..domain_post table. Is there a "lighter" way to get this counting than call all related users and count them?

$amountLikes = $post->getLikedBy()->count();

Imagine a list of posts with ~ 30000 likes each. The script starts to build up 30000 objects in the memory. Asking the posts table for the number sounds more realistic to me. But how to?


问:
IOS : containsObject Check for String
i have Array of String like:
Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

```<code>if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE
</code>```

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..

答:
Objective c

You can use NSPredicate for that.

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", @"P123"];
NSArray *filterArray = [yourArray filteredArrayUsingPredicate: predicate];
if (filterArray.count > 0) {
    print("Contains")
}
else {
    print("Not")
}
</code>```

Swift

Yes, You can check like that, you need to simply use contains(where:) for that.

```<code>if yourArray.contains(where: { $0.hasPrefix("P123") }) {
    print("Contains")
}
else {
    print("Not")
}
</code>```

Edit: If you want to ignore the trailing zeros you can truncate the trailing  zero before comparing it with array.

```<code>NSString *str = @"P12300";
NSRange range = [str rangeOfString:@"0*$" options:NSRegularExpressionSearch];
str = [str stringByReplacingCharactersInRange:range withString:@""];
NSLog(@"%@", str); //P123
//Now use this str to check its inside the array or not
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", str];
</code>```

Title: IOS : containsObject Check for String

Body:
i have Array of String like:
Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..

Body:
Objective c

You can use NSPredicate for that.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", @"P123"];
NSArray *filterArray = [yourArray filteredArrayUsingPredicate: predicate];
if (filterArray.count > 0) {
    print("Contains")
}
else {
    print("Not")
}

Swift

Yes, You can check like that, you need to simply use contains(where:) for that.

if yourArray.contains(where: { $0.hasPrefix("P123") }) {
    print("Contains")
}
else {
    print("Not")
}

Edit: If you want to ignore the trailing zeros you can truncate the trailing  zero before comparing it with array.

NSString *str = @"P12300";
NSRange range = [str rangeOfString:@"0*$" options:NSRegularExpressionSearch];
str = [str stringByReplacingCharactersInRange:range withString:@""];
NSLog(@"%@", str); //P123
//Now use this str to check its inside the array or not
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", str];


问:
Getting error while moving expandable table view?
I am getting error while moving expandable table view up and down.
This is my error
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 0]'

```<code>arr = [[NSArray alloc]initWithObjects:@"obj1",@"obj2",@"obj3",@"obj4",nil];
arr1 = [[NSArray alloc]initWithObjects:@"Name1", @"name2", @"name3", @"name4", @"name5", @"name6", nil];
arr2 = [[NSArray alloc]initWithObjects:@"arr2obj", nil];
arr3 = [[NSArray alloc]initWithObjects:@"arr3obj", nil];
arr4 = [[NSArray alloc]initWithObjects:@"arr4obj", nil];
</code>```

This is my code...

```<code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
    {
        if (section == 0) {
            return arr1.count;
        } else if (section == 1) {
            return arr2.count ;
        } else if (section == 2) {
            return arr3.count;
        }else if (section == 3) {
            return arr4.count;
        }
    } else {

        return 0;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ViewControllerCell *cell; // = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell"];

    cell= (ViewControllerCell *)[tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell" forIndexPath:indexPath];

    cell.faqLbl.text = [tempArr objectAtIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
    ViewControllerCellHeader *headerView = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCellHeader"];

    headerView.faqLblTitle.numberOfLines = 0;
    headerView.faqLblTitle.lineBreakMode = NSLineBreakByWordWrapping;
    headerView.faqLblTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];

    if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
    {
        headerView.faqLblTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:25.0];

    }

    if (headerView ==nil)
    {
        [tblView registerClass:[ViewControllerCellHeader class] forCellReuseIdentifier:@"ViewControllerCellHeader"];

        headerView = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCellHeader"];
    }

    headerView.faqLblTitle.text = [arr objectAtIndex:section];

    if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
    {
        headerView.faqBtnShowHide.selected = YES;
    }

    [[headerView faqBtnShowHide] setTag:section];
    headerView.faqBtnShowHide.tag = section;

    [[headerView faqBtnShowHide] addTarget:self action:@selector(btnTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];

    return headerView.contentView;
}

-(IBAction)btnTapShowHideSection:(UIButton*)sender
{
    if (!sender.selected)
    {
        [arrSelectedSectionIndex addObject:[NSNumber numberWithInteger:sender.tag]];

        sender.selected = YES;
    }else{
        sender.selected = NO;

        if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:sender.tag]])
        {
            [arrSelectedSectionIndex removeObject:[NSNumber numberWithInteger:sender.tag]];
        }
    }

    [tblView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    - (IBAction)dropDownButton:(UIButton *)sender {

        if(sender.tag == 0) {
            tempArr = arr1;
        } else if (sender.tag == 1) {
            tempArr = arr2;
        } else if (sender.tag == 2) {
            tempArr = arr3;
        } else if (sender.tag == 3) {
            tempArr = arr4;
        }
}
</code>```

答:
```<code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   if(indexPath.section == 0) {
        tempArr = arr1;
    } else if (indexPath.section == 1) {
        tempArr = arr2;
    } else if (indexPath.section == 2) {
        tempArr = arr3;
    } else if (indexPath.section == 3) {
        tempArr = arr4;
    }

    ViewControllerCell *cell; // = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell"];

    cell= (ViewControllerCell *)[tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell" forIndexPath:indexPath];

    cell.faqLbl.text = [tempArr objectAtIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
}
</code>```

You were calling reload section without initializing tempArr numberOfRowsInSection is considering the actual data sources like arr1,arr2 etc but cellForRowAtIndexPath is depending on tempArr to populate cell. Obviously if tempArr's value is not same as the actual data source which returned the number of cells it will break.

Body:
I am getting error while moving expandable table view up and down.
This is my error
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 0]'

arr = [[NSArray alloc]initWithObjects:@"obj1",@"obj2",@"obj3",@"obj4",nil];
arr1 = [[NSArray alloc]initWithObjects:@"Name1", @"name2", @"name3", @"name4", @"name5", @"name6", nil];
arr2 = [[NSArray alloc]initWithObjects:@"arr2obj", nil];
arr3 = [[NSArray alloc]initWithObjects:@"arr3obj", nil];
arr4 = [[NSArray alloc]initWithObjects:@"arr4obj", nil];

This is my code...

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
    {
        if (section == 0) {
            return arr1.count;
        } else if (section == 1) {
            return arr2.count ;
        } else if (section == 2) {
            return arr3.count;
        }else if (section == 3) {
            return arr4.count;
        }
    } else {

        return 0;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ViewControllerCell *cell; // = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell"];

    cell= (ViewControllerCell *)[tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell" forIndexPath:indexPath];

    cell.faqLbl.text = [tempArr objectAtIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
    ViewControllerCellHeader *headerView = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCellHeader"];

    headerView.faqLblTitle.numberOfLines = 0;
    headerView.faqLblTitle.lineBreakMode = NSLineBreakByWordWrapping;
    headerView.faqLblTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];

    if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
    {
        headerView.faqLblTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:25.0];

    }

    if (headerView ==nil)
    {
        [tblView registerClass:[ViewControllerCellHeader class] forCellReuseIdentifier:@"ViewControllerCellHeader"];

        headerView = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCellHeader"];
    }

    headerView.faqLblTitle.text = [arr objectAtIndex:section];

    if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
    {
        headerView.faqBtnShowHide.selected = YES;
    }

    [[headerView faqBtnShowHide] setTag:section];
    headerView.faqBtnShowHide.tag = section;

    [[headerView faqBtnShowHide] addTarget:self action:@selector(btnTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];

    return headerView.contentView;
}

-(IBAction)btnTapShowHideSection:(UIButton*)sender
{
    if (!sender.selected)
    {
        [arrSelectedSectionIndex addObject:[NSNumber numberWithInteger:sender.tag]];

        sender.selected = YES;
    }else{
        sender.selected = NO;

        if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:sender.tag]])
        {
            [arrSelectedSectionIndex removeObject:[NSNumber numberWithInteger:sender.tag]];
        }
    }

    [tblView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    - (IBAction)dropDownButton:(UIButton *)sender {

        if(sender.tag == 0) {
            tempArr = arr1;
        } else if (sender.tag == 1) {
            tempArr = arr2;
        } else if (sender.tag == 2) {
            tempArr = arr3;
        } else if (sender.tag == 3) {
            tempArr = arr4;
        }
}

Body:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   if(indexPath.section == 0) {
        tempArr = arr1;
    } else if (indexPath.section == 1) {
        tempArr = arr2;
    } else if (indexPath.section == 2) {
        tempArr = arr3;
    } else if (indexPath.section == 3) {
        tempArr = arr4;
    }

    ViewControllerCell *cell; // = [tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell"];

    cell= (ViewControllerCell *)[tableView dequeueReusableCellWithIdentifier:@"ViewControllerCell" forIndexPath:indexPath];

    cell.faqLbl.text = [tempArr objectAtIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
}

You were calling reload section without initializing tempArr numberOfRowsInSection is considering the actual data sources like arr1,arr2 etc but cellForRowAtIndexPath is depending on tempArr to populate cell. Obviously if tempArr's value is not same as the actual data source which returned the number of cells it will break.


问:
What is run time environment?
Can some one explain what it means in simple terms. Does it mean the environment (DOS, Windows, Linux, etc) where the application codes are run?</p>

答: It refers to the collection of software and hardware resources that enable a software program to be executed on a computer system. The runtime system is a composite mechanism designed to provide program execution services, regardless of the programming language being used</p>

Title: What is run time environment?


问:
Serialization and archiving object
I need to do the same operation but in one stream. May you help me, please?</p>

```<code>public static byte[] archivingAndSerialization(Object object){

  ByteArrayOutputStream serializationByteArray = new ByteArrayOutputStream();
  ByteArrayOutputStream archvingByteArray = new ByteArrayOutputStream();
  try {

     ObjectOutputStream byteStream = new ObjectOutputStream(serializationByteArray);
     byteStream.writeObject(object);
     ZipOutputStream out = new ZipOutputStream(archvingByteArray);
     out.putNextEntry(new ZipEntry("str"));
     out.write(serializationByteArray.toByteArray());
     out.flush();
     out.close();

     } catch (IOException e) {
logger.error("Error while IOException!", e);
     }
  return archvingByteArray.toByteArray();
}
</code>```

答:
Try

```<code>ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(new DeflatingOutputStream(baos));
oos.writeObject(object);
oos.close();
return baos.toByteArray();
</code>```

Note: Unless the object is medium to large in size, compressing it will make it bigger, as it add a header. ;)

To deserialize

```<code>ObjectInputStream ois = new ObjectInputStream(
    new InflatorInputStream(new ByteArrayInputStream(bytes)));
return ois.readObject();
</code>```

Title: Serialization and archiving object

Body:
I need to do the same operation but in one stream. May you help me, please?

public static byte[] archivingAndSerialization(Object object){

  ByteArrayOutputStream serializationByteArray = new ByteArrayOutputStream();
  ByteArrayOutputStream archvingByteArray = new ByteArrayOutputStream();
  try {

     ObjectOutputStream byteStream = new ObjectOutputStream(serializationByteArray);
     byteStream.writeObject(object);
     ZipOutputStream out = new ZipOutputStream(archvingByteArray);
     out.putNextEntry(new ZipEntry("str"));
     out.write(serializationByteArray.toByteArray());
     out.flush();
     out.close();

     } catch (IOException e) {
logger.error("Error while IOException!", e);
     }
  return archvingByteArray.toByteArray();
}

Body:
Try

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(new DeflatingOutputStream(baos));
oos.writeObject(object);
oos.close();
return baos.toByteArray();

Note: Unless the object is medium to large in size, compressing it will make it bigger, as it add a header. ;)

To deserialize

ObjectInputStream ois = new ObjectInputStream(
    new InflatorInputStream(new ByteArrayInputStream(bytes)));
return ois.readObject();


问:
Amchart annotations . Returning back to normal mode from annotations mode
I am using external buttons for am charts export. when i enter into annotations mode and do export, the chart gets exported with annotations. But when the chart gets reloaded , the annotations mode does not revert back.

Could somebody let me know how to go back from annotations to normal mode.

```<code> if (chart.export.drawing.buffer.enabled === true) {
                 // Exporting the annotated chart with out "
                 //chart.export.capture"
                chart.export.toPNG({}, function (data) {
                    chartimage.postImageData(data, chart_image_name)
                });
            } else {

                chart.export.capture({
                    // action: "draw"

                }, function () {
                    this.toPNG({

                    }, function (data) {
                        images.push({
                            "image": data,
                            "fit": [523.28, 769.89]
                        });
                        pending--;
                        if (pending === 0) {
                            chart.export.toPNG({
                                content: images
                            }, function (data) {
                                chartimage.postImageData(data, chart_image_name)
                            });
                        }
                    });
                });
            }

        }
</code>```

答:
Please find the workaround below..

First capture the events for set and cancel annotations using menu reviewer

```<code>menuReviver: function (item, li) {
    if (item.format === "XLSX" || item.format === "JSON") {
    li.style.display = "none";
    }

    $(li).click(function () {
    if (item.action == "draw") {
        $("#chart_annotations").val(1);
    }
    if (item.action == "cancel") {
        $("#chart_annotations").val(0);
    }

    });

    return li;
}
</code>```

Now while exporting the chart image use $("#chart_annotations").val() value as a
flag whether to export annotated chart or a normal chart. Please find the code below...

```<code>if (window.fabric) {
    if ($("#chart_annotations").val() == 1) {
        chart.export.toPNG({}, function (data) {
        chartimage.postImageData(data, chart_image_name)
        });
    } else {

        chart.export.capture({
        //action: "change"

        }, function () {
        this.toPNG({

        }, function (data) {
            images.push({
            "image": data,
            "fit": [523.28, 769.89]
            });
            pending--;
            if (pending === 0) {
            chart.export.toPNG({
                content: images
            }, function (data) {
                 //post the image data using ajax
                chartimage.postImageData(data, chart_image_name)
            });
            }
        });
        });
    }
</code>```

Body:
I am using external buttons for am charts export. when i enter into annotations mode and do export, the chart gets exported with annotations. But when the chart gets reloaded , the annotations mode does not revert back.

Could somebody let me know how to go back from annotations to normal mode.

 if (chart.export.drawing.buffer.enabled === true) {
                 // Exporting the annotated chart with out "
                 //chart.export.capture"
                chart.export.toPNG({}, function (data) {
                    chartimage.postImageData(data, chart_image_name)
                });
            } else {

                chart.export.capture({
                    // action: "draw"

                }, function () {
                    this.toPNG({

                    }, function (data) {
                        images.push({
                            "image": data,
                            "fit": [523.28, 769.89]
                        });
                        pending--;
                        if (pending === 0) {
                            chart.export.toPNG({
                                content: images
                            }, function (data) {
                                chartimage.postImageData(data, chart_image_name)
                            });
                        }
                    });
                });
            }

        }

Body:
Please find the workaround below..

First capture the events for set and cancel annotations using menu reviewer

menuReviver: function (item, li) {
    if (item.format === "XLSX" || item.format === "JSON") {
    li.style.display = "none";
    }

    $(li).click(function () {
    if (item.action == "draw") {
        $("#chart_annotations").val(1);
    }
    if (item.action == "cancel") {
        $("#chart_annotations").val(0);
    }

    });

    return li;
}

Now while exporting the chart image use $("#chart_annotations").val() value as a
flag whether to export annotated chart or a normal chart. Please find the code below...

if (window.fabric) {
    if ($("#chart_annotations").val() == 1) {
        chart.export.toPNG({}, function (data) {
        chartimage.postImageData(data, chart_image_name)
        });
    } else {

        chart.export.capture({
        //action: "change"

        }, function () {
        this.toPNG({

        }, function (data) {
            images.push({
            "image": data,
            "fit": [523.28, 769.89]
            });
            pending--;
            if (pending === 0) {
            chart.export.toPNG({
                content: images
            }, function (data) {
                 //post the image data using ajax
                chartimage.postImageData(data, chart_image_name)
            });
            }
        });
        });
    }


问:
Joining columns for today and yesterday in mySQL
I have two tables in a mySQL database:

Prices:

```<code>Date         Security   Price
2017-06-06   A          3.1
2017-06-06   B          4.1
2017-06-06   C          5.1
2017-06-05   A          3
2017-06-05   B          4
2017-06-05   C          5
... more prices
</code>```

Trades:

```<code>Date         Security   Description
2017-06-06   A          adesc
2017-06-06   B          bdesc
2017-06-06   C          cdesc
... more trades
</code>```

I will like to create a view which adds 2 more columns to the current Trades table, based on today's date and the date before. For example, if today's date was 2017-06-06, then the output I'm looking for will be:

Trades:

```<code>Date         Security   Description   Price(Today)  Price(Yesterday)
2017-06-06   A          adesc         3.1           3
2017-06-06   B          bdesc         4.1           4
2017-06-06   C          cdesc         5.1           5
... more trades
</code>```

I know that I can do a left join based on the date to get one of the columns (ie SELECT * FROM Trades LEFT JOIN Prices ON Prices.Date=DATE(NOW()), but is it possible to extend the syntax to allow for multple columns to be added as shown in the example?

Any help is greatly appreciated!

答:
Yes, give this a try:</p>

```<code>LEFT JOIN Prices AS TodaysPrices ON Prices.Date=CURDATE()
LEFT JOIN Prices AS YesterdaysPrices ON Prices.Date=SUBDATE(CURDATE(), 1)
</code>```

Body:
I have two tables in a mySQL database:

Prices:

Date         Security   Price
2017-06-06   A          3.1
2017-06-06   B          4.1
2017-06-06   C          5.1
2017-06-05   A          3
2017-06-05   B          4
2017-06-05   C          5
... more prices

Trades:

Date         Security   Description
2017-06-06   A          adesc
2017-06-06   B          bdesc
2017-06-06   C          cdesc
... more trades

I will like to create a view which adds 2 more columns to the current Trades table, based on today's date and the date before. For example, if today's date was 2017-06-06, then the output I'm looking for will be:

Trades:

Date         Security   Description   Price(Today)  Price(Yesterday)
2017-06-06   A          adesc         3.1           3
2017-06-06   B          bdesc         4.1           4
2017-06-06   C          cdesc         5.1           5
... more trades

I know that I can do a left join based on the date to get one of the columns (ie SELECT * FROM Trades LEFT JOIN Prices ON Prices.Date=DATE(NOW()), but is it possible to extend the syntax to allow for multple columns to be added as shown in the example?

Any help is greatly appreciated!

Body:
Yes, give this a try:

LEFT JOIN Prices AS TodaysPrices ON Prices.Date=CURDATE()
LEFT JOIN Prices AS YesterdaysPrices ON Prices.Date=SUBDATE(CURDATE(), 1)


问:
elasticsearch boost query in feild having multiple value
I have some document in elasticsearch index. Here is the sample document

DOC1

```<code>{
"feild1":["hi","hello","goodmorning"]
"feild2":"some string"
"feild3":{}
}
</code>```

DOC2

```<code>{
"feild1":["hi","goodmorning"]
"feild2":"some string"
"feild3":{}
}
</code>```

DOC3

```<code>{
"feild1":["hi","hello"]
"feild2":"some string"
"feild3":{}
}
</code>```

I want to query for feild1 having values "hi" and "hello" if both is present then that document should come first if any one is present then it should come after that.
for example:
result should be in order of  DOC1, DOC3, DOC2. I tried with boost query. but it is retuning not in the order that I want. Here is the query that I am trying.

```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "match_phrase": {
                       "avail_status": true
                    }
                },
               {
                   "bool": {
                       "should": [
                          {
                               "constant_score": {
                                  "filter": {
                                  "terms": {
                                     "feild1": [
                                        "hi"
                                     ]
                                  }
                                  },
                                  "boost": 20
                               }
                           },
                           {
                               "constant_score": {
                                  "filter": {
                                  "terms": {
                                     "feild1": [
                                        "hello"
                                     ]
                                  }
                                  },
                                  "boost": 18
                               }
                           }
                       ]
                   }
               }
            ]
        }
    }
}
</code>```

this is returning me first those document having "hi" and then those having "hello". Thanks in advance!

答:
To add extra boost for documents with larger field1, you can put funtion_score script score.

Mappings

```<code>{
  "mappings": {
    "document_type" : {
      "properties": {
        "field1" : {
          "type": "text",
          "fielddata": true
        },
        "field2" : {
          "type": "text"
        },
        "field3" : {
          "type": "text"
        }
      }
    }
  }
}
</code>```

Index documents

```<code>POST custom_score_index1/document_type

{
"feild1":["hi","hello","goodmorning"],
"feild2":"some string",
"feild3":{}
}

POST custom_score_index1/document_type

{
"feild1":["hi","goodmorning"],
"feild2":"some string",
"feild3":{}
}

POST custom_score_index1/document_type

{
"feild1":["hi","hello"],
"feild2":"some string",
"feild3":{}
}
</code>```

Query with function score add extra _score for larger size for field1

```<code>POST custom_score_index1/document_type/_search
{
    "query": {
        "function_score": {
            "query": {
                "bool": {
                    "must": [{
                            "match_phrase": {
                                "avail_status": true
                            }
                        },
                        {
                            "bool": {
                                "should": [{
                                        "constant_score": {
                                            "filter": {
                                                "terms": {
                                                    "feild1": [
                                                        "hi"
                                                    ]
                                                }
                                            },
                                            "boost": 20
                                        }
                                    },
                                    {
                                        "constant_score": {
                                            "filter": {
                                                "terms": {
                                                    "feild1": [
                                                        "hello"
                                                    ]
                                                }
                                            },
                                            "boost": 18
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            },
            "functions": [{
                "script_score": {
                    "script": {
                        "inline": "_score + 10000 * doc['field1'].length"
                    }
                }
            }],
            "score_mode": "sum",
            "boost_mode": "sum"
        }
    }
}
</code>```

Body:
I have some document in elasticsearch index. Here is the sample document

DOC1

{
"feild1":["hi","hello","goodmorning"]
"feild2":"some string"
"feild3":{}
}

DOC2

{
"feild1":["hi","goodmorning"]
"feild2":"some string"
"feild3":{}
}

DOC3

{
"feild1":["hi","hello"]
"feild2":"some string"
"feild3":{}
}

I want to query for feild1 having values "hi" and "hello" if both is present then that document should come first if any one is present then it should come after that.
for example:
result should be in order of  DOC1, DOC3, DOC2. I tried with boost query. but it is retuning not in the order that I want. Here is the query that I am trying.

{
    "query": {
        "bool": {
            "must": [
                {
                    "match_phrase": {
                       "avail_status": true
                    }
                },
               {
                   "bool": {
                       "should": [
                          {
                               "constant_score": {
                                  "filter": {
                                  "terms": {
                                     "feild1": [
                                        "hi"
                                     ]
                                  }
                                  },
                                  "boost": 20
                               }
                           },
                           {
                               "constant_score": {
                                  "filter": {
                                  "terms": {
                                     "feild1": [
                                        "hello"
                                     ]
                                  }
                                  },
                                  "boost": 18
                               }
                           }
                       ]
                   }
               }
            ]
        }
    }
}

this is returning me first those document having "hi" and then those having "hello". Thanks in advance!

Body:
To add extra boost for documents with larger field1, you can put funtion_score script score.

Mappings

{
  "mappings": {
    "document_type" : {
      "properties": {
        "field1" : {
          "type": "text",
          "fielddata": true
        },
        "field2" : {
          "type": "text"
        },
        "field3" : {
          "type": "text"
        }
      }
    }
  }
}

Index documents

POST custom_score_index1/document_type

{
"feild1":["hi","hello","goodmorning"],
"feild2":"some string",
"feild3":{}
}

POST custom_score_index1/document_type

{
"feild1":["hi","goodmorning"],
"feild2":"some string",
"feild3":{}
}

POST custom_score_index1/document_type

{
"feild1":["hi","hello"],
"feild2":"some string",
"feild3":{}
}

Query with function score add extra _score for larger size for field1

POST custom_score_index1/document_type/_search
{
    "query": {
        "function_score": {
            "query": {
                "bool": {
                    "must": [{
                            "match_phrase": {
                                "avail_status": true
                            }
                        },
                        {
                            "bool": {
                                "should": [{
                                        "constant_score": {
                                            "filter": {
                                                "terms": {
                                                    "feild1": [
                                                        "hi"
                                                    ]
                                                }
                                            },
                                            "boost": 20
                                        }
                                    },
                                    {
                                        "constant_score": {
                                            "filter": {
                                                "terms": {
                                                    "feild1": [
                                                        "hello"
                                                    ]
                                                }
                                            },
                                            "boost": 18
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            },
            "functions": [{
                "script_score": {
                    "script": {
                        "inline": "_score + 10000 * doc['field1'].length"
                    }
                }
            }],
            "score_mode": "sum",
            "boost_mode": "sum"
        }
    }
}


问:
cpp how to make main thread wait until other threads are finished in cycle
I'm trying to run a cpp code in a cycle in different threads, and want my main thread to wait until all other threads are done. I'm doing like this:

```<code>MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
        }
        for(int i = 0; i < size; ++i) {
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}
</code>```

But the code returns the wrong answer, however, if I do like this

```<code>MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}
</code>```

the code returns right answer but does not give an advantage in speed. It seems that I do something wrong in the code, can someone help me? Thanks!
problem occurs when I call scheme.multModSwitchAndEqualVec

method implemented in Scheme

答:
when u do join the main thread will wait until the thread will finish, so if u run on loop then main will wait for every thread to finish.
i think what u try to do, is let all the thread detach for but when (i==size-1) let him join. </p>

Body:
I'm trying to run a cpp code in a cycle in different threads, and want my main thread to wait until all other threads are done. I'm doing like this:

MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
        }
        for(int i = 0; i < size; ++i) {
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}

But the code returns the wrong answer, however, if I do like this

MyClass {
    function(Obj1& res, Obj2& input);
}

AnotherClass {
    MyClass class;
    anotherFunction(int size) {
        Obj1* resvec = new Obj1[size];
        Obj2* inputvec = new Obj2[size];

        doSmth1(resvec, inputvec);

        thread* thpool = new thread[size];
        for(int i = 0; i < size; ++i) {
            thpool[i] = thread(MyClass::function, class, ref(resvec[i]), ref(inputvec[i]));
            thpool[i].join();
        }

        doSmth2(resvec);

    }
}

the code returns right answer but does not give an advantage in speed. It seems that I do something wrong in the code, can someone help me? Thanks!
problem occurs when I call scheme.multModSwitchAndEqualVec

method implemented in Scheme


问:
Defining and reusing restriction in XSD
In my XSD, I have a restriction that I use frequently. The same restriction is used in several places and it could be missed when updating it. I understand that there are tools (find/replace) but I think it is nicer to have these restrictions defined globally. This way, we only have to change it in one place in stead of x-times.

An extra problem I have, is that the name of the element is always different and there is no way to change it (e.g. long_summary, short_summary, ...)

Setup of the XSD

```<code><xs:schema>
    <xs:complexType name="eventType">
        <xs:sequence>
            <xs:element name="short_summary">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:pattern value="([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)?"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
            <xs:element name="long_summary">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:pattern value="([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)?"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
         </xs:sequence>
    </xs:complexType>
</xs:schema>
</code>```

Basically I want to define the restriction ([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)? only once and reuse it for short_summary and long_summary.

Any advice or directions are appreciated. In the meantime, I will look further and if I find the answer, I will put it here.

答:
The answer to my question:

Global restriction

```<code><xs:simpleType name="Text">
        <xs:restriction base="xs:string">
            <xs:pattern value="([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)?"/>
        </xs:restriction>
</xs:simpleType>
</code>```

Used in XSD

```<code>....
<xs:element name="short_summary" type="Text"/>
<xs:element name="long_summary" type="Text"/>
....
</code>```

Title: Defining and reusing restriction in XSD

Body:
In my XSD, I have a restriction that I use frequently. The same restriction is used in several places and it could be missed when updating it. I understand that there are tools (find/replace) but I think it is nicer to have these restrictions defined globally. This way, we only have to change it in one place in stead of x-times.

An extra problem I have, is that the name of the element is always different and there is no way to change it (e.g. long_summary, short_summary, ...)

Setup of the XSD

<xs:schema>
    <xs:complexType name="eventType">
        <xs:sequence>
            <xs:element name="short_summary">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:pattern value="([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)?"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
            <xs:element name="long_summary">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:pattern value="([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)?"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
         </xs:sequence>
    </xs:complexType>
</xs:schema>

Basically I want to define the restriction ([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)? only once and reuse it for short_summary and long_summary.

Any advice or directions are appreciated. In the meantime, I will look further and if I find the answer, I will put it here.

Body:
The answer to my question:

Global restriction

<xs:simpleType name="Text">
        <xs:restriction base="xs:string">
            <xs:pattern value="([\p{L}\p{M}\p{N}\p{P}\p{Z}\p{S}\p{C}]+)?"/>
        </xs:restriction>
</xs:simpleType>

Used in XSD

....
<xs:element name="short_summary" type="Text"/>
<xs:element name="long_summary" type="Text"/>
....