问:
With Redux-Form, how to have multiple inputs with the same name?
I'm working to build the redux-form below to collect emails as user input. The fields should all have the same name="email"

The problem is when the component renders, and I focus and type in one field, all the fields instantly update with the latest value from the first input field. All three of the fields seem to be tied together.

With redux-form, how do I enable the form to have inputs with the same name?

```<code>import React from 'react';
import { Field, reduxForm } from 'redux-form';
import {connect} from 'react-redux';

class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
  }

  render() {

    return (
      <div>
        <h1>Invites</h1>
          <form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))}>
            <div>
              <label>Email address</label>
              <div>
                <Field
                  name="email"
                  component="input"
                  type="email"
                  placeholder="Email"
                />
              </div>
              <div>
                <Field
                  name="email"
                  component="input"
                  type="email"
                  placeholder="Email"
                />
              </div>
              <div>
                <Field
                  name="email"
                  component="input"
                  type="email"
                  placeholder="Email"
                />
              </div>
            </div>

            <div>
              <button type="submit">Submit</button>
            </div>

          </form>
      </div>
    );
  }

}

InvitePage = reduxForm({
  form: 'InvitePage'
})(InvitePage);

export default InvitePage;
</code>```

答:
If you use a FieldArray instead of 3 Fields, it can handle generating a unique name in redux-form's state for each field and you can use a renderer which hardcodes (or allows you to override) the name field to whatever you want, as redux-form generates an onChange handler for each field which updates the correct piece of state regardless of what you render for the name attribute.

Here's an example which shows that in action:

Live version

Full example source

Relevant code snippet:

```<code>// For the sake of this example, we're hard-coding the name to 'email'
let renderEmailField = ({input, label, type, meta: {touched, error}}) =>
  <div>
    <label>{label}</label>
    <div>
      <input {...input} name="email" type="email"/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>

let renderEmails = ({fields, meta: {submitFailed, error}}) =>
  <ul>
    <li>
      <button type="button" onClick={() => fields.push()}>Add Email</button>
    </li>
    {fields.map((email, index) =>
      <li key={index}>
        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />
      </li>
    )}
    {submitFailed && error && <li className="error">{error}</li>}
  </ul>

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />
    <div>
      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>
    </div>
  </form>

EmailsForm = reduxForm({
  form: 'emailsForm',
  // Provide 3 initial values to show 3 email fields
  initialValues: {
    emails: ['', '', '']
  }
})
</code>```

Body:
I'm working to build the redux-form below to collect emails as user input. The fields should all have the same name="email"

The problem is when the component renders, and I focus and type in one field, all the fields instantly update with the latest value from the first input field. All three of the fields seem to be tied together.

With redux-form, how do I enable the form to have inputs with the same name?

import React from 'react';
import { Field, reduxForm } from 'redux-form';
import {connect} from 'react-redux';

class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
  }

  render() {

    return (

Invites

          <form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))}>

              Email address

                <Field
                  name="email"
                  component="input"
                  type="email"
                  placeholder="Email"
                />

                <Field
                  name="email"
                  component="input"
                  type="email"
                  placeholder="Email"
                />

                <Field
                  name="email"
                  component="input"
                  type="email"
                  placeholder="Email"
                />

              <button type="submit">Submit</button>

          </form>

    );
  }

}

InvitePage = reduxForm({
  form: 'InvitePage'
})(InvitePage);

export default InvitePage;

Body:
If you use a FieldArray instead of 3 Fields, it can handle generating a unique name in redux-form's state for each field and you can use a renderer which hardcodes (or allows you to override) the name field to whatever you want, as redux-form generates an onChange handler for each field which updates the correct piece of state regardless of what you render for the name attribute.

Here's an example which shows that in action:

Live version

Full example source

Relevant code snippet:

// For the sake of this example, we're hard-coding the name to 'email'
let renderEmailField = ({input, label, type, meta: {touched, error}}) =>
  <div>
    <label>{label}</label>
    <div>
      <input {...input} name="email" type="email"/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>

let renderEmails = ({fields, meta: {submitFailed, error}}) =>
  <ul>
    <li>
      <button type="button" onClick={() => fields.push()}>Add Email</button>
    </li>
    {fields.map((email, index) =>
      <li key={index}>
        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />
      </li>
    )}
    {submitFailed && error && <li className="error">{error}</li>}
  </ul>

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />
    <div>
      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>
    </div>
  </form>

EmailsForm = reduxForm({
  form: 'emailsForm',
  // Provide 3 initial values to show 3 email fields
  initialValues: {
    emails: ['', '', '']
  }
})


来源: stackexchange

问:
Ruby: How to solve a simple grep function using regular expression?
I am trying to find a way to solve this:

Implement a simple grep function that takes a string x as input, and prints the lines of a file having any occurrences of string x anywhere in a line. You need to do a simple regular expression match after reading lines from a file. The output should also include the line numbers.

Here is a sample of the code I have written.  NOTE: I did not create a function just yet, I first need to get the code to recognize the file and display the corresponding message.

```<code>x=/you/

aFile = File.open("filename1.txt", "r")

a = ""

aFile.each {|line|
    a << line
}

sentence = a.split(".")

puts sentence

if sentence=~x
    puts "yes"
else
    puts "no"
end

aFile.close
</code>```

And here is the contents of filename1.txt:

```<code>See you tomorrow. Have a good day Mr. Jones. See you tomorrow. Have a good
day. See you tomorrow. See you tomorrow.
</code>```

I can display the file but cannot compare it to a regular expression.  It has been printing out an error when I try to compare it. Could someone point out the error in my code and help me find the solution to my problem?

答:
The results are unexpected since sentence is an array. I'm not sure what error you might be getting, but the result I get is a single 'no' response. To see the results for each individual sentence, you need to use a loop:

```<code>sentence.each do |s|
  puts s
  if s =~ x
    puts "yes"
  else
    puts "no"
  end
end
</code>```

That produces the following results:

```<code>See you tomorrow
yes
 Have a good day Mr
no
 Jones
no
 See you tomorrow
yes
 Have a good
day
no
 See you tomorrow
yes
 See you tomorrow
yes

no
</code>```

The final result occurs because split inserts an element in the array for both sides of the separator. The final sentence doesn't have anything after it, so the split method adds an empty string to the array.

Notice there's also a problem extracting sentences using periods when the period is used for an abbreviation ("Mr. Jones"). It also wouldn't work for sentences that end with a question or exclamation mark. Finally, ellipsis will add 4 sentences with this technique!

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find a way to solve this:

Implement a simple grep function that takes a string x as input, and prints the lines of a file having any occurrences of string x anywhere in a line. You need to do a simple regular expression match after reading lines from a file. The output should also include the line numbers.

Here is a sample of the code I have written.  NOTE: I did not create a function just yet, I first need to get the code to recognize the file and display the corresponding message.

x=/you/

aFile = File.open("filename1.txt", "r")

a = ""

aFile.each {|line|
    a << line
}

sentence = a.split(".")

puts sentence

if sentence=~x
    puts "yes"
else
    puts "no"
end

aFile.close

And here is the contents of filename1.txt:

See you tomorrow. Have a good day Mr. Jones. See you tomorrow. Have a good
day. See you tomorrow. See you tomorrow.

I can display the file but cannot compare it to a regular expression.  It has been printing out an error when I try to compare it. Could someone point out the error in my code and help me find the solution to my problem?

Body:
The results are unexpected since sentence is an array. I'm not sure what error you might be getting, but the result I get is a single 'no' response. To see the results for each individual sentence, you need to use a loop:

sentence.each do |s|
  puts s
  if s =~ x
    puts "yes"
  else
    puts "no"
  end
end

That produces the following results:

See you tomorrow
yes
 Have a good day Mr
no
 Jones
no
 See you tomorrow
yes
 Have a good
day
no
 See you tomorrow
yes
 See you tomorrow
yes

no

The final result occurs because split inserts an element in the array for both sides of the separator. The final sentence doesn't have anything after it, so the split method adds an empty string to the array.

Notice there's also a problem extracting sentences using periods when the period is used for an abbreviation ("Mr. Jones"). It also wouldn't work for sentences that end with a question or exclamation mark. Finally, ellipsis will add 4 sentences with this technique!


问:
Webpack Karma middleware:source-files not showing requested object
I am following the tutorial Angular/Webpack with one modification, the Angular app is located in src/ng2 instead of /src.

It works, when starting webpack-dev-server, but it fails loading all resources when starting karma. The following message is shown:

```<code>... :DEBUG [middleware:source-files]: Requesting /[object%20Object] /
... :DEBUG [middleware:source-files]: Fetching /[object Object]
... :WARN [web-server]: 404: /[object%20Object]
</code>```

Most of other resources are shown properly with there name. How I can investigate which object causes the problem.

The full project is available on https://github.com/ManfredSteiner/app14. To reproduce the Problem call npm run test2 (after npm install).

答:
karma.conf.js looks ok, however null-loader is used instead of required file-loader in webpack.test.js.

Replace section in webpack.test.js as per below:

from:

```<code>{
  test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
  loader: 'null-loader'
}
</code>```

to:

```<code>{
  test : /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
  loader: 'file-loader?name=assets/[name].[hash].[ext]'
}
</code>```

and everything should works!

Body:
I am following the tutorial Angular/Webpack with one modification, the Angular app is located in src/ng2 instead of /src.

It works, when starting webpack-dev-server, but it fails loading all resources when starting karma. The following message is shown:

... :DEBUG [middleware:source-files]: Requesting /[object%20Object] /
... :DEBUG [middleware:source-files]: Fetching /[object Object]
... :WARN [web-server]: 404: /[object%20Object]

Most of other resources are shown properly with there name. How I can investigate which object causes the problem.

The full project is available on https://github.com/ManfredSteiner/app14. To reproduce the Problem call npm run test2 (after npm install).

Body:
karma.conf.js looks ok, however null-loader is used instead of required file-loader in webpack.test.js.

Replace section in webpack.test.js as per below:

from:

{
  test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
  loader: 'null-loader'
}

to:

{
  test : /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
  loader: 'file-loader?name=assets/[name].[hash].[ext]'
}

and everything should works!


问:
How to control column width in jira
I am (unsuccessfully) trying to control the width of columns in jira. Does anyone know how to format tables so they don't look like the image below?

i am currently formatting by:

||Document Library||combination of Report, white papers / articles, case study, document library, press kit, publication, report, fact sheet, campaign|| || || ||
|Field Group|Field name|Field type|Existing field|description|
| |Title|title|x| |```

答:
This is a kludge but it works for me (Jira 7.3).

Go to text mode editor.

Place text like this in a squeezed cell

```<code>{color:#ffffff}================={color}
</code>```

This will persist in visual edit mode. It places some white non-breaking text in the cell.  Using color:#eeeeee might be better so you can just see what's going on.

Title: How to control column width in jira

Body:
This is a kludge but it works for me (Jira 7.3).

Go to text mode editor.

Place text like this in a squeezed cell

{color:#ffffff}================={color}

This will persist in visual edit mode. It places some white non-breaking text in the cell.  Using color:#eeeeee might be better so you can just see what's going on.


问:
Having an issue getting ANYTHING to apply styles within nested DIVs
I've already asked Google about this, and I've spent quite a long time experimenting. I can't possibly recreate the entire HTML and CSS environment this is occurring in, but this is part of it:

#footer-copyright{
    clear:both;
    color:black !important;
    font-size: 12px !important;
    text-align:center !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer id="footer" class="fullwidth">
    <div class="container">
        <div id="footer-section-one" class="col-sm-7 col-xs-12">
            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>
        </div>
        <div id="footer-section-two" class="col-sm-5 col-xs-12">
            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>
        </div>
    </div>
    <div class="container">
        <p id="footer-copyright">This text is immune to formatting</p>
    </div>
    </footer></code>```

No matter what I've tried, the text "This text is immune to formatting" is displayed in the p style for the footer object. I've tried making the CSS ID more specific (footer.footer-copyright). I've tried putting the ID on the DIV, and then specifying the style is for "#footer-copyright p{". I've tried footer-copyright as a class style and as a style for that particular ID (as it is now). I don't want to bore you listing all the things I've tried, but think permutations and combinations.

I've spent quite a bit of time in Chrome inspecting the paragraph, and it mostly seems to have no style at all, or to take the style defined by #footer p.

The only thing that I've found works is to completely override the CSS and put the style info into the paragraph itself ("

If you can, please explain why I can't seem to override the parent object's CSS style, and how to use Chrome's reporting of the HTML hierarchy to understand how to specify the CSS style.

THANKS!

答:
It does work in the snippet which uses your code (see below)

If you need a more specific selector, you can use this one:

```<code>footer#footer > div.container > p#footer-copyright { ... }
</code>```

This takes into account all tags, classes and IDs you included in your code.

(I added a background color to the rule to verify it)

footer#footer > div.container > p#footer-copyright {
  clear: both;
  color: black !important;
  font-size: 12px !important;
  text-align: center !important;
  background: #fa0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer id="footer" class="fullwidth">
  <div class="container">
    <div id="footer-section-one" class="col-sm-7 col-xs-12">
      <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>
    </div>
    <div id="footer-section-two" class="col-sm-5 col-xs-12">
      <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>
    </div>
  </div>
  <div class="container">
    <p id="footer-copyright">This text is actually NOT immune to formatting</p>
  </div>
</footer></code>```

Body:
I've already asked Google about this, and I've spent quite a long time experimenting. I can't possibly recreate the entire HTML and CSS environment this is occurring in, but this is part of it:

#footer-copyright{
    clear:both;
    color:black !important;
    font-size: 12px !important;
    text-align:center !important;
}

            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>

            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>

This text is immune to formatting

No matter what I've tried, the text "This text is immune to formatting" is displayed in the p style for the footer object. I've tried making the CSS ID more specific (footer.footer-copyright). I've tried putting the ID on the DIV, and then specifying the style is for "#footer-copyright p{". I've tried footer-copyright as a class style and as a style for that particular ID (as it is now). I don't want to bore you listing all the things I've tried, but think permutations and combinations.

I've spent quite a bit of time in Chrome inspecting the paragraph, and it mostly seems to have no style at all, or to take the style defined by #footer p.

The only thing that I've found works is to completely override the CSS and put the style info into the paragraph itself ("

If you can, please explain why I can't seem to override the parent object's CSS style, and how to use Chrome's reporting of the HTML hierarchy to understand how to specify the CSS style.

THANKS!

Body:
It does work in the snippet which uses your code (see below)

If you need a more specific selector, you can use this one:

footer#footer > div.container > p#footer-copyright { ... }

This takes into account all tags, classes and IDs you included in your code.

(I added a background color to the rule to verify it)

footer#footer > div.container > p#footer-copyright {
  clear: both;
  color: black !important;
  font-size: 12px !important;
  text-align: center !important;
  background: #fa0;
}

<footer id="footer" class="fullwidth">
  <div class="container">
    <div id="footer-section-one" class="col-sm-7 col-xs-12">
      <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>
    </div>
    <div id="footer-section-two" class="col-sm-5 col-xs-12">
      <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>
    </div>
  </div>
  <div class="container">
    <p id="footer-copyright">This text is actually NOT immune to formatting</p>
  </div>
</footer>


问:
How to create a border of solid colour around all the items in a collection view with a seperate colour for the collection view background?
Given that using the minimumInteritemSpacing / minimumLineSpacing settings on an iOS collection view creates a space rather than a solid border between cells, how can we style a solid border of consistent width around each cell in a collection view grid with a seperate colour applied as the background to the main collection view (so that after the border of the last cell a different background colour is visible) using these methods?

This is the best example of a solution I have seen so far but it is for objective C only rather than swift 3. The author also outlines the shortcomings of a couple of approaches I have already tried:

UICollectionView custom line separators

As an additional note the grid contains items of varying dimensions as illustrated here:

github.com/Antondomashnev/ADMozaicCollectionViewLayout

Edit -  Here is an image of the effect I'm trying to achieve:

 Custom CollectionView

It also highlights the problem that whil]1st the blue borders are most easily created using minimumInteritemSpacing / minimumLineSpacing the spaces created (whilst accurate and evenly spaced) just show the colour of the background view beneath the cells so you are left with one solid colour as opposed to the blue and yellow combination shown in the image.

答: I was able to get the result I wanted by setting a minimumLineSpacing and minimumInterimItemSpacing value of 0 to group the cells together and dynamically adding / removing borders as CALayers using krotov's answer here: UIView bottom border?</p>


问:
Query document string
I am trying to unwrap the contents of an html document string. I'm being given back a full html document from the froala rich text editor, that includes a head, title, and body tag which I want to remove.

The problem is that any selector I try gives me back an array that has a HTMLTitleElement, and then an array item for each root element in the document contents.

So, for example:

```<code>$('<!DOCTYPE html><html><head><title></title></head><body><h2>Summary</h2><div>Some content here</div></body></html>');
</code>```

gives me back an array that has 3 elements: HTMLTitleElement, HTMLHeadingElement, HTMLDivElement.

I was hoping for a single HTMLBodyElement, or something that I could call .html() on, in order to get the content entered into the editor without all the other html document wrappers.

答:
You can use regular expression to get body content.</p>

```<code>var htmlContent = "<!DOCTYPE html><html><head><title></title></head><body><h2>Summary</h2><div>Some content here</div></body></html>";

var bodyContent= /<body.*?>([\s\S]*)<\/body>/.exec(htmlContent)[1];
</code>```

Title: Query document string

Body:
I am trying to unwrap the contents of an html document string. I'm being given back a full html document from the froala rich text editor, that includes a head, title, and body tag which I want to remove.

The problem is that any selector I try gives me back an array that has a HTMLTitleElement, and then an array item for each root element in the document contents.

So, for example:

$('<!DOCTYPE html><title></title>
Summary

Some content here
');

gives me back an array that has 3 elements: HTMLTitleElement, HTMLHeadingElement, HTMLDivElement.

I was hoping for a single HTMLBodyElement, or something that I could call .html() on, in order to get the content entered into the editor without all the other html document wrappers.

Body:
You can use regular expression to get body content.

var htmlContent = "<!DOCTYPE html><html><head><title></title></head><body><h2>Summary</h2><div>Some content here</div></body></html>";

var bodyContent= /<body.*?>([\s\S]*)<\/body>/.exec(htmlContent)[1];


问:
Browser does not load angular app component

Here's my index.html file and main.ts file. The browser just shows "loading..." and doesn't loads the component that i have created. Please help me out.

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">

<blog>Loading...</blog>

```

<p>main.ts</p>

<pre class="lang-js prettyprint-override"><code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SignInComponent } from './Login/SignIn/signin.component';
import { SignUpComponent } from './Login/SignUp/signup.component';
import { routing } from './app.routes';

@NgModule({
imports: [ BrowserModule, FormsModule, routing ],
declarations: [ AppComponent, SignUpComponent, SignInComponent],
bootstrap: [ AppComponent ]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);`
</code>```

答: Try adding <base href="/"> in your index.html page as the first line inside head tag

Body:
Here's my index.html file and main.ts file. The browser just shows "loading..." and doesn't loads the component that i have created. Please help me out.

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">

<blog>Loading...</blog>

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SignInComponent } from './Login/SignIn/signin.component';
import { SignUpComponent } from './Login/SignUp/signup.component';
import { routing } from './app.routes';

@NgModule({
imports: [ BrowserModule, FormsModule, routing ],
declarations: [ AppComponent, SignUpComponent, SignInComponent],
bootstrap: [ AppComponent ]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);`


问:
Combining Vue-i18n Single File Component syntax with root messages
I'm experimenting with the excellent vue-i18n plugin for Vue. It has a neat feature that allows me to embed translations directly into the template that needs them. However if I use them, I'm unable to access the root translation node. Is this model supported or am I just doing it wrong?

main.js

import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: 'en',
  messages: {
    en: {
      'company-name': 'billy-bob\'s fine steaks.'
    }
  }
});
```
<p><strong>Sample.vue</strong></p>
<pre class="lang-html prettyprint-override"><code><i18n>
  {
    "en": {
      "title": "@:company-name - yeee hawwww!!!"
    }
  }
</i18n>

<template>
  <div id="app" class="container">
    <site-header :title="$t('title')"></site-header>
  </div>
</template>
</code>```

答:
It appears that the i18n definitions are merged together so that, in the component, you would have access to both the parent and child i18n definitions, with the child definitions overriding the parents where there was any overlap (for example, if you had a title key in the parent and the child, the child's would be used).

However the syntax you are using clearly doesn't work. In this case I think I would define a computed that combines the two translated values and use that.

```<code>computed:{
    title(){
        return this.$t("company-name") + this.$t("title")
    }
}
</code>```

And then just use the computed value in your template.

```<code><template>
  <div id="app" class="container">
    <site-header :title="title"></site-header>
  </div>
</template>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm experimenting with the excellent vue-i18n plugin for Vue. It has a neat feature that allows me to embed translations directly into the template that needs them. However if I use them, I'm unable to access the root translation node. Is this model supported or am I just doing it wrong?

main.js

import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: 'en',
  messages: {
    en: {
      'company-name': 'billy-bob\'s fine steaks.'
    }
  }
});

Sample.vue

<i18n>
  {
    "en": {
      "title": "@:company-name - yeee hawwww!!!"
    }
  }
</i18n>

<template>

    <site-header :title="$t('title')"></site-header>

</template>

Body:
It appears that the i18n definitions are merged together so that, in the component, you would have access to both the parent and child i18n definitions, with the child definitions overriding the parents where there was any overlap (for example, if you had a title key in the parent and the child, the child's would be used).

However the syntax you are using clearly doesn't work. In this case I think I would define a computed that combines the two translated values and use that.

computed:{
    title(){
        return this.$t("company-name") + this.$t("title")
    }
}

And then just use the computed value in your template.

<template>
  <div id="app" class="container">
    <site-header :title="title"></site-header>
  </div>
</template>


问:
Server Error 500 Php
Good day

Im trying to install a GamePanel with PHP called Swiftpanel on my VPS Centos7 64bit

i installed LAMP on my vps and html files work perfectly.
But my gamepanel doesnt work

and the gamepanel is located at:

http://51.255.199.40/gpanel/

as you can see when i try reaching my gpanel it gives me the SERVER ERROR 500

i looked at my apache error logs and this is what i get:

```<code>[Fri Mar 04 15:53:53.533162 2016] [autoindex:error] [pid 18753] [client 46.99.59.98:51034] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive
</code>```

Here is my httpd.conf and php.conf:

http://pastebin.com/HJfH3gWQ

I need some help fixing this, im a begginer in coding.

With respect

Benjamin Selmani

答:
OK, edit your httpd.conf file and change the following line:

Options Indexes FollowSymLinks

to:

Options +Indexes +FollowSymLinks

then restart your Apache server.  If this doesn't work, it's likely we are editing the wrong httpd.conf file.  You'd be surprised how many you might find on your computer including all the conf files in sub directories (look at the last line of your httpd.conf file).  Somewhere there is probably a line that looks like this:

Options -Indexes

Which is the explicit cause of the problem.  But try my earlier suggestion first.

Title: Server Error 500 Php

Body:
Good day

Im trying to install a GamePanel with PHP called Swiftpanel on my VPS Centos7 64bit

i installed LAMP on my vps and html files work perfectly.
But my gamepanel doesnt work

and the gamepanel is located at:

http://51.255.199.40/gpanel/

as you can see when i try reaching my gpanel it gives me the SERVER ERROR 500

i looked at my apache error logs and this is what i get:

[Fri Mar 04 15:53:53.533162 2016] [autoindex:error] [pid 18753] [client 46.99.59.98:51034] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive

Here is my httpd.conf and php.conf:

http://pastebin.com/HJfH3gWQ

I need some help fixing this, im a begginer in coding.

With respect

Benjamin Selmani


问:
Set label font size from data column in gnuplot
I'm trying to plot using labels with varying font size.  For example:

```<code>plot "some_data_file" using 1:2:(20-$3) using labels font sprintf("Helvetica,%d",variable)
</code>```

Or something to that effect.  The label's font size should be 20 minus the value in the third column.  This line doesn't work, but I think it displays what I'm trying to do.  Any ideas?

答:
Look at cities.dem demo on gnuplot.info for a way to do this.

I'll steal the solution there, modified for you:

```<code>plot "some_data_file" using 2:3:(sprintf("{/Helvetica=%d %s}",\
    20-$4, stringcolumn(4))) with labels
</code>```

Body:
I'm trying to plot using labels with varying font size.  For example:

plot "some_data_file" using 1:2:(20-$3) using labels font sprintf("Helvetica,%d",variable)

Or something to that effect.  The label's font size should be 20 minus the value in the third column.  This line doesn't work, but I think it displays what I'm trying to do.  Any ideas?

Body:
Look at cities.dem demo on gnuplot.info for a way to do this.

I'll steal the solution there, modified for you:

plot "some_data_file" using 2:3:(sprintf("{/Helvetica=%d %s}",\
    20-$4, stringcolumn(4))) with labels


问:
resize images over a certain size only
I am using a Wordpress plugin to import blog posts off other sites using RSS feeds. The imported posts contain images which I have set to a uniform size using css

```<code>img {
    width:200px !important;
}
</code>```

This works OK, since only the width size is set the height adjusts to the correct proportion for the original image, and the !important overrides the image size set in the imported posts.

However there are also social-media share images in the imported posts (e.g. from feedburner etc.) which I do not want to resize, e.g.

Can I add a filter to the css image size to only apply to images over a certain size (e.g. over 100 pixels wide)?

N.B. I tried adding this in the header

```
</div>
</div>
</p>

<p>Where the div with the images I want to resize is</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-html lang-html prettyprint-override"><code><DIV class="myDivClass"></code>```

But this didn't work.

答:
Used this in the end

    ```

Title: resize images over a certain size only

Body:
I am using a Wordpress plugin to import blog posts off other sites using RSS feeds. The imported posts contain images which I have set to a uniform size using css

img {
    width:200px !important;
}

This works OK, since only the width size is set the height adjusts to the correct proportion for the original image, and the !important overrides the image size set in the imported posts.

However there are also social-media share images in the imported posts (e.g. from feedburner etc.) which I do not want to resize, e.g.

Can I add a filter to the css image size to only apply to images over a certain size (e.g. over 100 pixels wide)?

N.B. I tried adding this in the header

Where the div with the images I want to resize is

But this didn't work.

Body:
Used this in the end

    <script>

    $( document ).ready(function() {
  $(".MyDivClass img").width(200);
    });

    </script>


问:
Powershell: Filtering flat arrays
I'm working on a PS script for making some of our processes easier and more automated and I've quickly found myself well outside my (limited) PowerShell knowledge.

Context: I'm building a UI that has two ComboBox controls and a handful of text boxes for creating resource calendars. The first ComboBox has a static list of 3 sub-divisions in my organization. The second ComboBox has a list of the offices in that division which should automatically update when a selection is made in the first box.

The end goal is to generate the Exchange Management Shell code necessary to create mailboxes with the necessary uniform naming convention:

```<code>New-Mailbox -Name 'Acme Inc $division $office $subdivision Resource Name' -Alias 'resourcename'-OrganizationalUnit '<path/to/OU>' -UserPrincipalName 'resourcename@acmeinc.lcl' -SamAccountName 'resourcename'
</code>```

Right now I'm thinking I'll build these off of a single array which has three fields that correspond to division, sub-division, and office:

Note: Division 1 has no subdivisions, while division 2 has two subdivisions. Combobox 1 should list division 1, subdivision 1, subdivision 2.

```<code>$arr_AgencyOffices = @(
     'division 1','division 1','Aberdeen'
     'division 1','division 1','Perth'
     'division 1','division 1','Sacramento'
     'division 1','division 1','Long Beach'
     'division 1','division 1','New York'
     'division 1','division 1','Dallas'
     'division 1','division 1','Miami'
     'division 1','division 1','Vancouver'
     'division 2','subdivision 1','Sacramento'
     'division 2','subdivision 1','Tumwater'
     'division 2','subdivision 1','Vancouver'
     'division 2','subdivision 2','Aberdeen'
     'division 2','subdivision 2','Centralia'
     'division 2','subdivision 2','Sacramento'
     'division 2','subdivision 2','Long Beach'
     'division 2','subdivision 2','Shelton'
     'division 2','subdivision 2','Dallas'
     'division 2','subdivision 2','Stevenson'
     'division 2','subdivision 2','Miami'
     'division 2','subdivision 2','Vancouver'
)
</code>```

Specific Question: How do I return only the matching office location values into $arr_Offices given any specific cbo1.SelectedItem?

答:
What you show in your example is not a multi-dimensional array, it's just a regular flat array.

To get a multi-dimensional (or rather, a jagged) array, do:

```<code>$arr_AgencyOffices = @(
    @('division 1','division 1','Aberdeen'),
    @('division 1','division 1','Perth'),
    @('division 1','division 1','Sacramento'),
    @('division 1','division 1','Long Beach'),
    @('division 1','division 1','New York'),
    @('division 1','division 1','Dallas'),
    @('division 1','division 1','Miami'),
    @('division 1','division 1','Vancouver'),
    @('division 2','subdivision 1','Sacramento'),
    @('division 2','subdivision 1','Tumwater'),
    @('division 2','subdivision 1','Vancouver'),
    @('division 2','subdivision 2','Aberdeen'),
    @('division 2','subdivision 2','Centralia'),
    @('division 2','subdivision 2','Sacramento'),
    @('division 2','subdivision 2','Long Beach'),
    @('division 2','subdivision 2','Shelton'),
    @('division 2','subdivision 2','Dallas'),
    @('division 2','subdivision 2','Stevenson'),
    @('division 2','subdivision 2','Miami'),
    @('division 2','subdivision 2','Vancouver')
)
</code>```

Now you can index into the value on two dimensions:

```<code>$arr_AgencyOffices[4][2] # New York
</code>```

That being said, I would probably arrange the offices into a set of nested hashtables, like so:

```<code>$AgencyOffices = @{
    'division 1' = @{
        'division 1' = @(
            'Aberdeen'
            'Perth'
            'Sacramento'
            'Long Beach'
            'New York'
            'Dallas'
            'Miami'
            'Vancouver'
        )
    }
    'division 2' = @{
        'subdivision 1' = @(
            'Sacramento'
            'Tumwater'
            'Vancouver'
        )
        'subdivision 2' = @(
            'Aberdeen'
            'Centralia'
            'Sacramento'
            'Long Beach'
            'Shelton'
            'Dallas'
            'Stevenson'
            'Miami'
            'Vancouver'
        )
    }
}
</code>```

Now you can index into the subdivision arrays using their actual names:

```<code>PS C:\> $AgencyOffices['division 2']['subdivision 1']
Sacramento
Tumwater
Vancouver
</code>```

This makes it trivial to retrieve the correct lists for the comboboxes given that you can just take the selected text of the preceding choice to find the next list:

```<code>$combobox2List = $AgencyOffices[$combobox1.SelectedText].Keys
</code>```

and so on

Title: Powershell: Filtering flat arrays

Body:
I'm working on a PS script for making some of our processes easier and more automated and I've quickly found myself well outside my (limited) PowerShell knowledge.

Context: I'm building a UI that has two ComboBox controls and a handful of text boxes for creating resource calendars. The first ComboBox has a static list of 3 sub-divisions in my organization. The second ComboBox has a list of the offices in that division which should automatically update when a selection is made in the first box.

The end goal is to generate the Exchange Management Shell code necessary to create mailboxes with the necessary uniform naming convention:

New-Mailbox -Name 'Acme Inc $division $office $subdivision Resource Name' -Alias 'resourcename'-OrganizationalUnit '<path/to/OU>' -UserPrincipalName 'resourcename@acmeinc.lcl' -SamAccountName 'resourcename'

Right now I'm thinking I'll build these off of a single array which has three fields that correspond to division, sub-division, and office:

Note: Division 1 has no subdivisions, while division 2 has two subdivisions. Combobox 1 should list division 1, subdivision 1, subdivision 2.

$arr_AgencyOffices = @(
     'division 1','division 1','Aberdeen'
     'division 1','division 1','Perth'
     'division 1','division 1','Sacramento'
     'division 1','division 1','Long Beach'
     'division 1','division 1','New York'
     'division 1','division 1','Dallas'
     'division 1','division 1','Miami'
     'division 1','division 1','Vancouver'
     'division 2','subdivision 1','Sacramento'
     'division 2','subdivision 1','Tumwater'
     'division 2','subdivision 1','Vancouver'
     'division 2','subdivision 2','Aberdeen'
     'division 2','subdivision 2','Centralia'
     'division 2','subdivision 2','Sacramento'
     'division 2','subdivision 2','Long Beach'
     'division 2','subdivision 2','Shelton'
     'division 2','subdivision 2','Dallas'
     'division 2','subdivision 2','Stevenson'
     'division 2','subdivision 2','Miami'
     'division 2','subdivision 2','Vancouver'
)

Specific Question: How do I return only the matching office location values into $arr_Offices given any specific cbo1.SelectedItem?

Body:
What you show in your example is not a multi-dimensional array, it's just a regular flat array.

To get a multi-dimensional (or rather, a jagged) array, do:

$arr_AgencyOffices = @(
    @('division 1','division 1','Aberdeen'),
    @('division 1','division 1','Perth'),
    @('division 1','division 1','Sacramento'),
    @('division 1','division 1','Long Beach'),
    @('division 1','division 1','New York'),
    @('division 1','division 1','Dallas'),
    @('division 1','division 1','Miami'),
    @('division 1','division 1','Vancouver'),
    @('division 2','subdivision 1','Sacramento'),
    @('division 2','subdivision 1','Tumwater'),
    @('division 2','subdivision 1','Vancouver'),
    @('division 2','subdivision 2','Aberdeen'),
    @('division 2','subdivision 2','Centralia'),
    @('division 2','subdivision 2','Sacramento'),
    @('division 2','subdivision 2','Long Beach'),
    @('division 2','subdivision 2','Shelton'),
    @('division 2','subdivision 2','Dallas'),
    @('division 2','subdivision 2','Stevenson'),
    @('division 2','subdivision 2','Miami'),
    @('division 2','subdivision 2','Vancouver')
)

Now you can index into the value on two dimensions:

$arr_AgencyOffices[4][2] # New York

That being said, I would probably arrange the offices into a set of nested hashtables, like so:

$AgencyOffices = @{
    'division 1' = @{
        'division 1' = @(
            'Aberdeen'
            'Perth'
            'Sacramento'
            'Long Beach'
            'New York'
            'Dallas'
            'Miami'
            'Vancouver'
        )
    }
    'division 2' = @{
        'subdivision 1' = @(
            'Sacramento'
            'Tumwater'
            'Vancouver'
        )
        'subdivision 2' = @(
            'Aberdeen'
            'Centralia'
            'Sacramento'
            'Long Beach'
            'Shelton'
            'Dallas'
            'Stevenson'
            'Miami'
            'Vancouver'
        )
    }
}

Now you can index into the subdivision arrays using their actual names:

PS C:\> $AgencyOffices['division 2']['subdivision 1']
Sacramento
Tumwater
Vancouver

This makes it trivial to retrieve the correct lists for the comboboxes given that you can just take the selected text of the preceding choice to find the next list:

$combobox2List = $AgencyOffices[$combobox1.SelectedText].Keys

and so on


问:
Base adapter - empty stack exception?
I keep getting an EmptyStackException in MyAdapter.java (see below) even though the stack is not empty.

I checked and double checked everything, I can't seem to figure it out. Any help would me much appreciated.

MainActivity.java

```<code>package test.testapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Stack;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView lv = (ListView)findViewById(R.id.list);
        ArrayList<Stack<String>> list = new ArrayList<>();

        Stack one = new Stack();
        one.push("a");
        one.push("b");
        list.add(one);

        Stack two = new Stack();
        two.push("c");
        two.push("d");
        list.add(two);

        lv.setAdapter(new MyAdapter(this,list));
    }
}
</code>```

MyAdapter.java

```<code>package test.testapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Stack;

public class MyAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Stack<String>> list;

    public MyAdapter(Context context, ArrayList<Stack<String>> list){
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Stack<String> stack = (Stack) getItem(position);
        LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row,parent,false);

        ((TextView)row.findViewById(R.id.tv1)).setText(stack.pop()); // <--- Empty stack exception here
        ((TextView)row.findViewById(R.id.tv1)).setText(stack.pop());

        return row;
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="test.testapp.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></ListView>

</LinearLayout>
</code>```

row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:paddingTop="20dp"
              android:paddingBottom="20dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center_horizontal">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text 1"/>

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text 2"/>

</LinearLayout>
</code>```

答:
You're not just popping the stack once.

Every single row item is popping the stack, and although you may have two items, I wouldn't be surprised if getView is being called more than twice

Try using a List of Lists, or a Map<String, List<String>> if you're looking for a ExpandableListView

Title: Base adapter - empty stack exception?

Body:
I keep getting an EmptyStackException in MyAdapter.java (see below) even though the stack is not empty.

I checked and double checked everything, I can't seem to figure it out. Any help would me much appreciated.

MainActivity.java

package test.testapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Stack;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView lv = (ListView)findViewById(R.id.list);
        ArrayList<Stack<String>> list = new ArrayList<>();

        Stack one = new Stack();
        one.push("a");
        one.push("b");
        list.add(one);

        Stack two = new Stack();
        two.push("c");
        two.push("d");
        list.add(two);

        lv.setAdapter(new MyAdapter(this,list));
    }
}

MyAdapter.java

package test.testapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Stack;

public class MyAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Stack<String>> list;

    public MyAdapter(Context context, ArrayList<Stack<String>> list){
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Stack<String> stack = (Stack) getItem(position);
        LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row,parent,false);

        ((TextView)row.findViewById(R.id.tv1)).setText(stack.pop()); // <--- Empty stack exception here
        ((TextView)row.findViewById(R.id.tv1)).setText(stack.pop());

        return row;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="test.testapp.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></ListView>

</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:paddingTop="20dp"
              android:paddingBottom="20dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center_horizontal">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text 1"/>

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text 2"/>

</LinearLayout>


问:
Getting error asInvalidSession id while invoking upsert bulk operation in mule salesforce connector
Polling app daily once. We are loading data using upsert bulk operation in salesforce. First day it is working fine . Second day on wards we are getting the below error(InvalidSession id ). I found workaround as reconnection strategy and configured even after it is not working.

```<code>[2017-06-07 10:02:24.519] ERROR   org.mule.retry.notifiers.ConnectNotifier [[test-salesforce-bulk].checkbulkupsert.stage1.05]: Failed to connect/reconnect: Work Descriptor. Root Exception was: InvalidSessionId : Invalid session id. Type: class com.sforce.async.AsyncApiException
[2017-06-07 10:02:24.547] ERROR   org.mule.exception.CatchMessagingExceptionStrategy [[test-salesforce-bulk].checkbulkupsert.stage1.05]:
********************************************************************************
Message               : Failed to invoke upsertBulk.
Element               : /test-salesforce-bulk/processors/4/prepareAccountRequestSubFlow/subprocessors/1 @ test-salesforce-bulk
--------------------------------------------------------------------------------
Exception stack is:
Failed to invoke upsertBulk. (org.mule.api.MessagingException)
  com.sforce.async.BulkConnection.parseAndThrowException(BulkConnection.java:180)
  com.sforce.async.BulkConnection.createOrUpdateJob(BulkConnection.java:164)
  com.sforce.async.BulkConnection.createOrUpdateJob(BulkConnection.java:132)
  com.sforce.async.BulkConnection.createJob(BulkConnection.java:122)
  org.mule.modules.salesforce.SalesforceConnector.createJobInfo(SalesforceConnector.java:2570)
  org.mule.modules.salesforce.SalesforceConnector.upsertBulk(SalesforceConnector.java:672)
  org.mule.modules.salesforce.generated.processors.UpsertBulkMessageProcessor$1.process(UpsertBulkMessageProcessor.java:153)
  (50 more...)

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
</code>```

Can you please help on this.

答:
There error says Invalid Session Id.
This means that the initial session has expired.  Check your login history and see if there's even an attempt to login.  If there's not, you need to update your username in Mulesoft.  If there is and it was unsuccessful, you need to update your password/security token.  If there is and it was successful, then it could be that your Session Settings are set to limit calls to the initial IP address or something like that.</p>

Body:
Polling app daily once. We are loading data using upsert bulk operation in salesforce. First day it is working fine . Second day on wards we are getting the below error(InvalidSession id ). I found workaround as reconnection strategy and configured even after it is not working.

[2017-06-07 10:02:24.519] ERROR   org.mule.retry.notifiers.ConnectNotifier [[test-salesforce-bulk].checkbulkupsert.stage1.05]: Failed to connect/reconnect: Work Descriptor. Root Exception was: InvalidSessionId : Invalid session id. Type: class com.sforce.async.AsyncApiException
[2017-06-07 10:02:24.547] ERROR   org.mule.exception.CatchMessagingExceptionStrategy [[test-salesforce-bulk].checkbulkupsert.stage1.05]:
********************************************************************************
Message               : Failed to invoke upsertBulk.
Element               : /test-salesforce-bulk/processors/4/prepareAccountRequestSubFlow/subprocessors/1 @ test-salesforce-bulk
--------------------------------------------------------------------------------
Exception stack is:
Failed to invoke upsertBulk. (org.mule.api.MessagingException)
  com.sforce.async.BulkConnection.parseAndThrowException(BulkConnection.java:180)
  com.sforce.async.BulkConnection.createOrUpdateJob(BulkConnection.java:164)
  com.sforce.async.BulkConnection.createOrUpdateJob(BulkConnection.java:132)
  com.sforce.async.BulkConnection.createJob(BulkConnection.java:122)
  org.mule.modules.salesforce.SalesforceConnector.createJobInfo(SalesforceConnector.java:2570)
  org.mule.modules.salesforce.SalesforceConnector.upsertBulk(SalesforceConnector.java:672)
  org.mule.modules.salesforce.generated.processors.UpsertBulkMessageProcessor$1.process(UpsertBulkMessageProcessor.java:153)
  (50 more...)

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)

Can you please help on this.


问:
Audio libraries for digital signal processing in C#
My problem is this:

I'm developing a reasonably small application (which needs to be able to grow in the future, but for now, limited functionality will suffice) which recieves audio (16bit mono @ 44.1kHz) and performs fourier transforms and filtering on the data.  My experience with all the fields you can imagine this involves is limited, but i've been researching it a fair bit lately and have some understanding.  My funding is limited, and I am unable to use any libraries which are under the GPL or similar licences (I need to be able to distruibute this app).  For the signal processing I've settled on MathNet libraries, and this seems as though it can handle the bulk of the processing (and I'll write the necessary filters).

The real problem is finding the sound library to use - I was hoping for something in C#, and while it seemed directSound was the best option, I'm reluctant to use it given microsoft has pretty much abandoned it (the company I work for will be upgrading its gear in the near future; I just want to increase the app.'s lifespan as best I can).  Do I use XAudio2? I need to be able to record the raw pcm data from a USB device and process it (+write it out to .wav files), and read the data straight from .wav files.

Any help is appreciated

答:
First, I want to say that DirectSound isn't abandoned by Microsoft, it's still a supported technology (Windows 7) and I don't expect it to stop working in the future.

That said, there are newer audio APIs / SDKs that are more modern: Media Foundation can perform audio capture and there are a number of great samples to jumpstart you.  IF you are looking for the latest and greatest or are looking for hardware accelerated audio you can try and get things working using WASAPI and WaveRT.

Just an FYI, the Media Format SDK is no longer at the URL given in the first post.  Please use this one instead:

http://msdn.microsoft.com/en-us/windows/bb190307

ContentLicense: CC BY-SA 2.5


问:
pycharm with codecs utf-8 encode from system stdout and stderr
hellow all, I'm working with python 3.6.0 on a project in pycharm community edition 2016.3.2. I have this strange error happens in my program whenever I use codecs to encode my input stream:

```<code>import codecs
import sys

sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

print("something")
</code>```

the problem is my program always exit with an exit code 1, and here is the console output:

```<code>Traceback (most recent call last):
  File "C:/Users/jhonsong/Desktop/restfulAPI/findARestaurant.py", line 9, in <module>
    print("something")
  File "C:\Python36-32\lib\codecs.py", line 377, in write
    self.stream.write(data)
TypeError: write() argument must be str, not bytes

Process finished with exit code 1
</code>```

but my input is a string, why is codecs.write think I'm giving it bytes input?

答:
In Python 3, sys.stdout is a Unicode stream.  codecs.getwriter('utf8') needs a byte stream.  sys.stdout.buffer is the raw byte stream, so use:

```<code>sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
sys.stderr = codecs.getwriter('utf8')(sys.stderr.buffer)
</code>```

But this seems like overkill with Python 3.6, where the print should just work.  Normally if you need to force an encoding, say to capture the output of a Python script to a file in a certain encoding, the following script (Windows) would work.  The environment variable dictates the output encoding and overrides whatever the terminal default is.

```<code>set PYTHONIOENCODING=utf8
python some_script.py > output.txt
</code>```

Since you are submitting to a website, that site should be responsible for running your script in a way that they can capture the result properly.

Body:
hellow all, I'm working with python 3.6.0 on a project in pycharm community edition 2016.3.2. I have this strange error happens in my program whenever I use codecs to encode my input stream:

import codecs
import sys

sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

print("something")

the problem is my program always exit with an exit code 1, and here is the console output:

Traceback (most recent call last):
  File "C:/Users/jhonsong/Desktop/restfulAPI/findARestaurant.py", line 9, in <module>
    print("something")
  File "C:\Python36-32\lib\codecs.py", line 377, in write
    self.stream.write(data)
TypeError: write() argument must be str, not bytes

Process finished with exit code 1

but my input is a string, why is codecs.write think I'm giving it bytes input?

Body:
In Python 3, sys.stdout is a Unicode stream.  codecs.getwriter('utf8') needs a byte stream.  sys.stdout.buffer is the raw byte stream, so use:

sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
sys.stderr = codecs.getwriter('utf8')(sys.stderr.buffer)

But this seems like overkill with Python 3.6, where the print should just work.  Normally if you need to force an encoding, say to capture the output of a Python script to a file in a certain encoding, the following script (Windows) would work.  The environment variable dictates the output encoding and overrides whatever the terminal default is.

set PYTHONIOENCODING=utf8
python some_script.py > output.txt

Since you are submitting to a website, that site should be responsible for running your script in a way that they can capture the result properly.


问:
Make that when an image become bigger with css it does it in the front of everything
Rigth now I got an image that becomes bigger when I pass my mouse over it, but I have a navbar above the image and a graph under it, so rigth now  it gets bigger but it does it behin the navbar and the graph but I need it to do it in front of them.

Here is my code (absolutelly really easy):

html:

```<code><div class="image">
    <img src="<?= ISO_ROOT . DS . $img["img_id"].$img["ext"]; ?>" alt="Isobata">
</div>
</code>```

Css:

```<code>img {
    max-width: 100%;
    display: block;
}

.image {
    width: 100%;
    height: 100%;
}

.image img {
    -webkit-transition: all 1s ease; /* Safari and Chrome */
    -moz-transition: all 1s ease; /* Firefox */
    -o-transition: all 1s ease; /* IE 9 */
    -ms-transition: all 1s ease; /* Opera */
    transition: all 1s ease;
}

.image:hover img {
    -webkit-transform:scale(1.5); /* Safari and Chrome */
    -moz-transform:scale(1.5); /* Firefox */
    -ms-transform:scale(1.5); /* IE 9 */
    -o-transform:scale(1.5); /* Opera */
     transform:scale(1.5);
}
</code>```

Let me know if you need more information, and allthe ideas.

Thanks.

答:
Z-index controls how images or divs stack over each other. Div/image with higher z-index value takes front place and lower would stay behind.
Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). Use one of those.

Body:
Rigth now I got an image that becomes bigger when I pass my mouse over it, but I have a navbar above the image and a graph under it, so rigth now  it gets bigger but it does it behin the navbar and the graph but I need it to do it in front of them.

Here is my code (absolutelly really easy):

html:

    <img src="<?= ISO_ROOT . DS . $img["img_id"].$img["ext"]; ?>" alt="Isobata">

Css:

img {
    max-width: 100%;
    display: block;
}

.image {
    width: 100%;
    height: 100%;
}

.image img {
    -webkit-transition: all 1s ease; /* Safari and Chrome */
    -moz-transition: all 1s ease; /* Firefox */
    -o-transition: all 1s ease; /* IE 9 */
    -ms-transition: all 1s ease; /* Opera */
    transition: all 1s ease;
}

.image:hover img {
    -webkit-transform:scale(1.5); /* Safari and Chrome */
    -moz-transform:scale(1.5); /* Firefox */
    -ms-transform:scale(1.5); /* IE 9 */
    -o-transform:scale(1.5); /* Opera */
     transform:scale(1.5);
}

Let me know if you need more information, and allthe ideas.

Thanks.


问:
Slack API Using \n for new lines does not work in chat.postMessage (golang)
I'm using the Slack web API to post messages to a channel in Go. I'm trying to support multi-line messages in the text field. According to the documentation simply adding a \n should work but it's not working. When posting the \n appears in the text and there's no line break.

Here's the code I'm using:

```<code>func PostMessage(token, channelName, userName, text string) error {
    uv := url.Values{}
    uv.Add("token", token)
    uv.Add("channel", channelName)
    uv.Add("username", userName)
    uv.Add("text", text)

    resp, err := http.PostForm("https://slack.com/api/chat.postMessage", uv)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    if err := PostMessage("xxxx", "#test-channel", "API", "This should be the first line\nThis should be the second line"); err != nil {
        panic(err)
    }
}
</code>```

答:
Just escape the newline  "\n" with "`n"

Reference: https://ss64.com/ps/syntax-esc.html

Body:
I'm using the Slack web API to post messages to a channel in Go. I'm trying to support multi-line messages in the text field. According to the documentation simply adding a \n should work but it's not working. When posting the \n appears in the text and there's no line break.

Here's the code I'm using:

func PostMessage(token, channelName, userName, text string) error {
    uv := url.Values{}
    uv.Add("token", token)
    uv.Add("channel", channelName)
    uv.Add("username", userName)
    uv.Add("text", text)

    resp, err := http.PostForm("https://slack.com/api/chat.postMessage", uv)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    if err := PostMessage("xxxx", "#test-channel", "API", "This should be the first line\nThis should be the second line"); err != nil {
        panic(err)
    }
}


问:
How to standardize data with sklearn's cross_val_score()
Let's say I want to use a LinearSVC to perform k-fold-cross-validation on a dataset. How would I perform standardization on the data?

The best practice I have read is to build your standardization model on your training data then apply this model to the testing data.

When one uses a simple train_test_split(), this is easy as we can just do:

```<code>X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)

clf = svm.LinearSVC()

scalar = StandardScaler()
X_train = scalar.fit_transform(X_train)
X_test = scalar.transform(X_test)

clf.fit(X_train, y_train)
predicted = clf.predict(X_test)
</code>```

How would one go about standardizing data while doing k-fold-cross-validation? The problem comes from the fact that every data point will be for training/testing so you cannot standardize everything before cross_val_score(). Wouldn't you need a different standardization for each cross validation?

The docs do not mention standardization happening internally within the function. Am I SOL?

EDIT: This post is super helpful: Python - What is exactly sklearn.pipeline.Pipeline?

答:
You can use a Pipeline to combine both of the processes and then send it into the cross_val_score().

When the fit() is called on the pipeline, it will fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator. And during predict() (Only available if last object in pipeline is an estimator, otherwise transform()) it will apply transforms to the data, and predict with the final estimator.

Like this:

```<code>scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)
</code>```

Check out various examples of pipeline to understand it better:

http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#examples-using-sklearn-pipeline-pipeline

Feel free to ask if any doubt.

Body:
Let's say I want to use a LinearSVC to perform k-fold-cross-validation on a dataset. How would I perform standardization on the data?

The best practice I have read is to build your standardization model on your training data then apply this model to the testing data.

When one uses a simple train_test_split(), this is easy as we can just do:

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)

clf = svm.LinearSVC()

scalar = StandardScaler()
X_train = scalar.fit_transform(X_train)
X_test = scalar.transform(X_test)

clf.fit(X_train, y_train)
predicted = clf.predict(X_test)

How would one go about standardizing data while doing k-fold-cross-validation? The problem comes from the fact that every data point will be for training/testing so you cannot standardize everything before cross_val_score(). Wouldn't you need a different standardization for each cross validation?

The docs do not mention standardization happening internally within the function. Am I SOL?

EDIT: This post is super helpful: Python - What is exactly sklearn.pipeline.Pipeline?

Body:
You can use a Pipeline to combine both of the processes and then send it into the cross_val_score().

When the fit() is called on the pipeline, it will fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator. And during predict() (Only available if last object in pipeline is an estimator, otherwise transform()) it will apply transforms to the data, and predict with the final estimator.

Like this:

scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)

Check out various examples of pipeline to understand it better:

http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#examples-using-sklearn-pipeline-pipeline

Feel free to ask if any doubt.


问:
jquery input[type=checkbox]:checked').length always is 0
I have several input check boxes that share a class called checkboxJobSeekerProfile.  I am trying to write an alert that prints how many of them are checked.  For some the alert always show 0 even when several of the check boxes are checked.  Here is my alert

```<code>alert($('.checkboxJobSeekerProfile input[type=checkbox]:checked').length);
</code>```

Here is my html

```<code><label class="checkbox-inline"><input type="checkbox" class="checkboxJobSeekerProfile entry_level"
                                                  id="entry_level" value="entry_level">Entry-level</label>
            <label class="checkbox-inline"><input type="checkbox" class="checkboxJobSeekerProfile mid_level"
                                                  id="mid_level" value="mid_level">Mid-level</label>
            <label class="checkbox-inline"><input type="checkbox" class="checkboxJobSeekerProfile senior_level"
                                                  id="senior_level" value="senior_level">Senior-level</label>
            <label class="checkbox-inline"><input type="checkbox" class="checkboxJobSeekerProfile executive"
                                                  id="executive" value="executive">Executive</label>
</code>```

答:
You can select strictly by:

```<code>alert($('input[type=checkbox].checkboxJobSeekerProfile:checked').length);
</code>```

JSFiddle Demo

Body:
I have several input check boxes that share a class called checkboxJobSeekerProfile.  I am trying to write an alert that prints how many of them are checked.  For some the alert always show 0 even when several of the check boxes are checked.  Here is my alert

alert($('.checkboxJobSeekerProfile input[type=checkbox]:checked').length);

Here is my html

<input type="checkbox" class="checkboxJobSeekerProfile entry_level"
                                                  id="entry_level" value="entry_level">Entry-level
            <input type="checkbox" class="checkboxJobSeekerProfile mid_level"
                                                  id="mid_level" value="mid_level">Mid-level
            <input type="checkbox" class="checkboxJobSeekerProfile senior_level"
                                                  id="senior_level" value="senior_level">Senior-level
            <input type="checkbox" class="checkboxJobSeekerProfile executive"
                                                  id="executive" value="executive">Executive

Body:
You can select strictly by:

alert($('input[type=checkbox].checkboxJobSeekerProfile:checked').length);

JSFiddle Demo


问:
How to check if mcrypt extension exists in php
I would like to know the simplest and fastest PHP code line to check if mcrypt extension is available/installed.

There is a function that encrypts a string and first it requires to check if mcrypt is usable. If not, it will execute an alternative encrypt solution available on the system.

Thanks!

答:
If you are using a development environment like XXAMP, or WAMP, there should be a default "phpinfo" page. For example, in XXAMP it would be:

http://localhost/dashboard/phpinfo.php

You can also achieve this same screen by viewing a php file that has: phpinfo(); somewhere in the code.

In this screen, simply search for the string "mcrypt support". If installed, you will see a box that says "enabled".


问:
CSS and IE8: How can I get the CSS color property to work consistently on submit inputs in IE8?
I am using an input type='submit' with CSS rules applied that make the background a gradated dark blue and the font color white. I cannot get this input to render consistently in IE 8. In some parts of my site, it looks just fine, with its lovely white type. In other parts, the color assigned to the body trumps the white applied by the CSS rules.

I've done a fair bit of research on this and can't find a solution that works. The one I did find on CSS Tricks recommended adding the css using jQuery. I tried this. I successfully added an inline style, but IE8 still trumped my white. I've switched in and out of Compatibility View, still no dice. 0

Why?

Here is the pertinent markup and CSS.

CSS

```<code>body {
    color:#222;
    font-size: 12px;
    width:100%;
    background:#8A7967 url(images/bg_body.png) top left repeat-x;
}

.buttonBigBlue,
input[type="submit"] {
  color:#FFF!important;
  -webkit-border-radius:12px;
  -moz-border-radius: 12px;
  border-radius:12px;
  padding:3px 9px;
  text-transform:uppercase;
  font-weight:bold;
  text-align:center;
  vertical-align:middle;
  border:1px solid #74a1a9;
  cursor:pointer;
  background: #678382; /* for non-css3 browsers */
  background:-webkit-gradient(linear, left top, left bottom, from(#77A7B1), to(#678382));
  background:-moz-linear-gradient(top,  #77A7B1,  #678382);
  filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382'); /* IE6,IE7 */
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382')"; /* IE8 */
}
</code>```

MARKUP

```<code><input type="submit" class="buttonBigBlue" id="login" value="Login" name="login">
</code>```

This button displays with #222 text in IE8.

```<code><input type="submit" class="buttonBigBlue" id="saveChanges" value="Save Changes" name="saveChanges">
</code>```

This button displays with #FFF text in IE8

UPDATE after further investigation.

The containing div for the inputs that won't display properly is called #loginBox. It's styles are these:

```
#loginBox {
    width:300px;
    margin:25px auto;
    padding: 25px 30px 30px;
    border:1px solid #c9b9a8;
    -webkit-border-radius:9px;
    -moz-border-radius: 9px;
    border-radius:9px 9px 9px 9px;
    -webkit-box-shadow:rgba(0,0,0,.3) 4px 4px 6px;
    -moz-box-shadow: 4px 4px 6px rgba(0,0,0,.3);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845')";
    /* For IE 5.5 - 7*/
    filter: progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845');
    min-height:160px;
    background-color:#fff;
    box-shadow: 4px 4px 6px rgba(0,0,0,.3);
}
```

When I remove the -ms-filter and filter rules that set the box shadow, the input text returns to white.

答:
Both display the same way in my IE8

example: http://www.jsfiddle.net/gaby/9grJP/

Maybe you have other rules overriding these ones.

Body:
I am using an input type='submit' with CSS rules applied that make the background a gradated dark blue and the font color white. I cannot get this input to render consistently in IE 8. In some parts of my site, it looks just fine, with its lovely white type. In other parts, the color assigned to the body trumps the white applied by the CSS rules.

I've done a fair bit of research on this and can't find a solution that works. The one I did find on CSS Tricks recommended adding the css using jQuery. I tried this. I successfully added an inline style, but IE8 still trumped my white. I've switched in and out of Compatibility View, still no dice. 0

Why?

Here is the pertinent markup and CSS.

CSS

body {
    color:#222;
    font-size: 12px;
    width:100%;
    background:#8A7967 url(images/bg_body.png) top left repeat-x;
}

.buttonBigBlue,
input[type="submit"] {
  color:#FFF!important;
  -webkit-border-radius:12px;
  -moz-border-radius: 12px;
  border-radius:12px;
  padding:3px 9px;
  text-transform:uppercase;
  font-weight:bold;
  text-align:center;
  vertical-align:middle;
  border:1px solid #74a1a9;
  cursor:pointer;
  background: #678382; /* for non-css3 browsers */
  background:-webkit-gradient(linear, left top, left bottom, from(#77A7B1), to(#678382));
  background:-moz-linear-gradient(top,  #77A7B1,  #678382);
  filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382'); /* IE6,IE7 */
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#77A7B1', EndColorStr='#678382')"; /* IE8 */
}

MARKUP

<input type="submit" class="buttonBigBlue" id="login" value="Login" name="login">

This button displays with #222 text in IE8.

<input type="submit" class="buttonBigBlue" id="saveChanges" value="Save Changes" name="saveChanges">

This button displays with #FFF text in IE8

UPDATE after further investigation.

The containing div for the inputs that won't display properly is called #loginBox. It's styles are these:

#loginBox {
    width:300px;
    margin:25px auto;
    padding: 25px 30px 30px;
    border:1px solid #c9b9a8;
    -webkit-border-radius:9px;
    -moz-border-radius: 9px;
    border-radius:9px 9px 9px 9px;
    -webkit-box-shadow:rgba(0,0,0,.3) 4px 4px 6px;
    -moz-box-shadow: 4px 4px 6px rgba(0,0,0,.3);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845')";
    /* For IE 5.5 - 7*/
    filter: progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color='#544845');
    min-height:160px;
    background-color:#fff;
    box-shadow: 4px 4px 6px rgba(0,0,0,.3);
}

When I remove the -ms-filter and filter rules that set the box shadow, the input text returns to white.


问:
Cannot open an html file from python in a web browser - notepad opens instead
In python I am trying to plot a graph with the pygal package

```<code>import pygal  # First import pygal
bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])
bar_chart.render_in_browser()
</code>```

Unfortunately, it always opens the HTML file, but not an HTML page in the browser window. I read many posts and I see that people had similar issues in the past. I did not find a solution that works. I also tried to open it via the webbrowser module, but that also opens the HTML file in notepad.

```<code>url='file://C:/Users/User1/AppData/Local/Temp/tmpsblpwtpr.html'
webbrowser.open(url)
</code>```

Anyone any thoughts?

答:
Despite being labelled with the html extension, it isn't.

It's SVG XML.

This is the header from the file:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" id="chart-c252fdc0-451c-4482-b9ae-09f5b513a2fc" class="pygal-chart" viewBox="0 0 800 600">

Either your xml or svg settings are configured for Notepad.

Body:
In python I am trying to plot a graph with the pygal package

import pygal  # First import pygal
bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])
bar_chart.render_in_browser()

Unfortunately, it always opens the HTML file, but not an HTML page in the browser window. I read many posts and I see that people had similar issues in the past. I did not find a solution that works. I also tried to open it via the webbrowser module, but that also opens the HTML file in notepad.

url='file://C:/Users/User1/AppData/Local/Temp/tmpsblpwtpr.html'
webbrowser.open(url)

Anyone any thoughts?

Body:
Despite being labelled with the html extension, it isn't.

It's SVG XML.

This is the header from the file:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" id="chart-c252fdc0-451c-4482-b9ae-09f5b513a2fc" class="pygal-chart" viewBox="0 0 800 600"><!--Generated with pygal 2.3.1 (lxml) Ā©Kozea 2012-2016 on 2017-06-09--><!--http://pygal.org--><!--http://github.com/Kozea/pygal-->

Either your xml or svg settings are configured for Notepad.


问:
send2cy doesn't work in Rstudio ~ Cyrest, Cyotoscape
When I run "send2cy" function in R studio, I got error.

```<code># Basic setup
library(igraph)
library(RJSONIO)
library(httr)
dir <- "/currentdir/"
setwd(dir)
port.number = 1234
base.url = paste("http://localhost:", toString(port.number), "/v1", sep="")
print(base.url)

# Load list of edges as Data Frame
network.df <- read.table("./data/eco_EM+TCA.txt")

# Convert it into igraph object
network <- graph.data.frame(network.df,directed=T)

# Remove duplicate edges & loops
g.tca <- simplify(network, remove.multiple=T, remove.loops=T)

# Name it
g.tca$name = "Ecoli TCA Cycle"

# This function will be published as a part of utility package, but not ready yet.
source('./utility/cytoscape_util.R')

# Convert it into Cytosccape.js JSON
cygraph <- toCytoscape(g.tca)

send2cy(cygraph, 'default%20black', 'circular')

Error in file(con, "r") : cannot open the connection
Called from: file(con, "r")
</code>```

But I didn't find error when I use "send2cy" function from terminal R (Run R from terminal just calling by "R").

Any advice is welcome.

答:
I tested your script with local copies of the network data and utility script, and with updated file paths. The script ran fine for me in R Studio.

Given the error message you are seeing "Error in file..." I suspect the issue is with your local files and file paths... somehow in an R Studio-specific way?

FYI: an updated, consolidated and update set of R scripts for Cytoscape are available here: https://github.com/cytoscape/cytoscape-automation/tree/master/for-scripters/R.  I don't think anything has significantly changed, but perhaps trying in a new context will resolve the issue you are facing.

Body:
When I run "send2cy" function in R studio, I got error.

# Basic setup
library(igraph)
library(RJSONIO)
library(httr)
dir <- "/currentdir/"
setwd(dir)
port.number = 1234
base.url = paste("http://localhost:", toString(port.number), "/v1", sep="")
print(base.url)

# Load list of edges as Data Frame
network.df <- read.table("./data/eco_EM+TCA.txt")

# Convert it into igraph object
network <- graph.data.frame(network.df,directed=T)

# Remove duplicate edges & loops
g.tca <- simplify(network, remove.multiple=T, remove.loops=T)

# Name it
g.tca$name = "Ecoli TCA Cycle"

# This function will be published as a part of utility package, but not ready yet.
source('./utility/cytoscape_util.R')

# Convert it into Cytosccape.js JSON
cygraph <- toCytoscape(g.tca)

send2cy(cygraph, 'default%20black', 'circular')

Error in file(con, "r") : cannot open the connection
Called from: file(con, "r")

But I didn't find error when I use "send2cy" function from terminal R (Run R from terminal just calling by "R").

Any advice is welcome.


问:
How do you check that a number is NaN in JavaScript?
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:</p>

```<code>parseFloat('geoff') == NaN;

parseFloat('geoff') == Number.NaN;
</code>```

答:
marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.

i came up with a isNumber function that will check if it is a number.

function isNumber(i) {
    return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}

console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));```
</div>
</div>
</p>

<p>UPDATE:
i noticed that this code fails for some parameters, so i made it better.</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>function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
 } else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
 } else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
 } else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
 } else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
 } else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
 } else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
 }
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));</code>```

Body:
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:

parseFloat('geoff') == NaN;

parseFloat('geoff') == Number.NaN;

Body:
marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.

i came up with a isNumber function that will check if it is a number.

function isNumber(i) {
    return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}

console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));

UPDATE:
i noticed that this code fails for some parameters, so i made it better.

function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
 } else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
 } else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
 } else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
 } else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
 } else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
 } else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
 }
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));


问:
Simple MVC Timer- Swift
I know this is a super basic question, I am trying to refactor my code atm and am running into trouble with the timer. All I am trying to do is just get a simple countdown timer to print to the console

Here is my code snippet right now

VC------

```<code>var seconds = 60

override func viewDidLoad() {
    super.viewDidLoad()
    self.modelInstance.gameTimerMethod(timeParam: self.seconds)
}
</code>```

MODEL-----

```<code>func gameTimerMethod(timeParam : Int)  {
    gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decreaseGameTimer(secondsParam:)), userInfo: timeParam, repeats: true)
    print (timeParam)
}

func decreaseGameTimer(secondsParam: Int) {
    var printNumber = secondsParam
    printNumber -= 1
    print (printNumber)
}
</code>```

Ideally what I want this to do in the console is simply countdown from 60 for now at a rate of one number per second. Although the console is logging at a rate of one number per second, it is for some reason repeatedly logging the number 105553117734207, instead of a 60 seconds countdown.

Thanks!

答:
Make the printNumber as class variable instead of put in method, So it will not be reset everytime it called by the timer.

Also in gameTimerMethod, set the printNumber to timeParam before call the timer.

Your model will be similarly like below:

```<code>class YourModel {
    var printNumber = 0

    func gameTimerMethod(timeParam : Int)  {

        printNumber = timeParam
        gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decreaseGameTimer(), userInfo: nil, repeats: true)
        print (timeParam)
    }

    func decreaseGameTimer() {
        printNumber -= 1
        print (printNumber)
    }
}
</code>```

Title: Simple MVC Timer- Swift

Body:
I know this is a super basic question, I am trying to refactor my code atm and am running into trouble with the timer. All I am trying to do is just get a simple countdown timer to print to the console

Here is my code snippet right now

VC------

var seconds = 60

override func viewDidLoad() {
    super.viewDidLoad()
    self.modelInstance.gameTimerMethod(timeParam: self.seconds)
}

MODEL-----

func gameTimerMethod(timeParam : Int)  {
    gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decreaseGameTimer(secondsParam:)), userInfo: timeParam, repeats: true)
    print (timeParam)
}

func decreaseGameTimer(secondsParam: Int) {
    var printNumber = secondsParam
    printNumber -= 1
    print (printNumber)
}

Ideally what I want this to do in the console is simply countdown from 60 for now at a rate of one number per second. Although the console is logging at a rate of one number per second, it is for some reason repeatedly logging the number 105553117734207, instead of a 60 seconds countdown.

Thanks!

Body:
Make the printNumber as class variable instead of put in method, So it will not be reset everytime it called by the timer.

Also in gameTimerMethod, set the printNumber to timeParam before call the timer.

Your model will be similarly like below:

class YourModel {
    var printNumber = 0

    func gameTimerMethod(timeParam : Int)  {

        printNumber = timeParam
        gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decreaseGameTimer(), userInfo: nil, repeats: true)
        print (timeParam)
    }

    func decreaseGameTimer() {
        printNumber -= 1
        print (printNumber)
    }
}


问:
Pyxero filtering using the __in
I have a filtering on status using pyxero, but I want filtering on two type of status: AUTHORISED and SUBMITTED.

The actual call is:

xero_conn.invoices.filter(Type='ACCPAY', Status='SUBMITTED')

But checking the code there is not Status__in available. Is there a __in available as in the django orm or I must make 2 calls?

答:
The raw option let to do what pyxero is not able to do. I moved the Status in raw and works. Use the preview to check the raw.

```<code>xero_conn.invoices.filter(Type='ACCPAY', raw="Status='SUBMITTED' OR Status='AUTHORISED'")
</code>```

Title: Pyxero filtering using the __in

Body:
The raw option let to do what pyxero is not able to do. I moved the Status in raw and works. Use the preview to check the raw.

xero_conn.invoices.filter(Type='ACCPAY', raw="Status='SUBMITTED' OR Status='AUTHORISED'")


问:
How to navigate to a route with parameters
I'm on a view with the current route:

http://localhost:4200/#/corp/projects/detail/05940c57/page1

And I want to get to

http://localhost:4200/#/corp/projects/detail/05940c57/page2

Is there a way to change to "page2" using navigate() or navigateByUrl()?

答:
You can use relativeTo:

```<code>constructor (
  private activatedRoute: activatedRoute,
  private router: Router
) { }

myFunc() {
  this.router.navigate(['page2'], { relativeTo: this.activatedRoute });
}
</code>```

Body:
You can use relativeTo:

constructor (
  private activatedRoute: activatedRoute,
  private router: Router
) { }

myFunc() {
  this.router.navigate(['page2'], { relativeTo: this.activatedRoute });
}


问:
Browser does not load angular app component

Here's my index.html file and main.ts file. The browser just shows "loading..." and doesn't loads the component that i have created. Please help me out.

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">

<blog>Loading...</blog>

```

<p>main.ts</p>

<pre class="lang-js prettyprint-override"><code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SignInComponent } from './Login/SignIn/signin.component';
import { SignUpComponent } from './Login/SignUp/signup.component';
import { routing } from './app.routes';

@NgModule({
imports: [ BrowserModule, FormsModule, routing ],
declarations: [ AppComponent, SignUpComponent, SignInComponent],
bootstrap: [ AppComponent ]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);`
</code>```

答:
add <base href="/">

You need to add all the js and CSS files in your build file.If it's angular-cli project the you need to configure in .angular-cli.json file.

```<code>"styles": [
        "styles.css"
      ],
      "scripts": [
        "scripts.js"
],
</code>```

Body:
Here's my index.html file and main.ts file. The browser just shows "loading..." and doesn't loads the component that i have created. Please help me out.

<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">

<blog>Loading...</blog>

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SignInComponent } from './Login/SignIn/signin.component';
import { SignUpComponent } from './Login/SignUp/signup.component';
import { routing } from './app.routes';

@NgModule({
imports: [ BrowserModule, FormsModule, routing ],
declarations: [ AppComponent, SignUpComponent, SignInComponent],
bootstrap: [ AppComponent ]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);`

Body:
add <base href="/">

You need to add all the js and CSS files in your build file.If it's angular-cli project the you need to configure in .angular-cli.json file.

"styles": [
        "styles.css"
      ],
      "scripts": [
        "scripts.js"
],


问:
Tool to decode the page tables and descriptor tables from a RAM snapshot
I need a practical way to analyze a snapshot of RAM+registers and easily visualize (not necessarily in a graphical way) the x86 architecture structures. This would include the page tables, interrupt descriptor tables, global descriptor table, etc.

Note that I'm not interested in OS specific information (e.g., process list, etc.), I'm just interested in the architectural structures.

Obviously one can just figure out the layout for all of these structures (and all versions) from the Intel documentation but I'm wondering if there is already any simple tool that decodes them.

答:
There are several tools for Memory Forensics Analysis listed in the forensicswiki at http://forensicswiki.org/wiki/Linux_Memory_Analysis (part of http://forensicswiki.org/wiki/Memory_analysis; there is also variant for Windows). Some of tools are open-source and active:

The output of a memory acquisition tool is a memory image which contains the raw physical memory of a system. A wide variety of tools can be used to search for strings or other patterns in a memory image, but to extract higher-level information about the state of the system a memory analysis tool is required.

Linux Memory Analysis Tools.
  Active Open Source Projects:

The Volatility Framework is a collection of tools, implemented in Python, for the extraction of digital artifacts from volatile memory (RAM) samples. See the LinuxMemoryForensics page on the Volatility wiki. (Availability/License: GNU GPL)

Rekall includes a Python-based analysis framework which forked from Volatility and has since added a number of features, as well as its own acquisition tools. It is usable as a library and is used as such in the GRR remote live forensics project.

The Red Hat Crash Utility is an extensible Linux kernel core dump analysis program. Although designed as a debugging tool, it also has been utilized for memory forensics. See, for example, the 2008 DFRWS challenge write-up by AAron Walters. (Availability/License: GNU GPL)

(Some inactive projects are also listed, and there is Bibliography)

For example,  Volatility is capable of using kernel and process "DTB (Directory Table Base)" (windows), list pages of linux processes (https://github.com/volatilityfoundation/volatility/wiki/Linux-Command-Reference#process-memory) and parse the memory dump in other ways.

[Rekall] also has GUI: http://www.rekall-forensic.com/pages/at_a_glance.html (pip install rekall-gui) and plugins for searching processes http://www.rekall-forensic.com/docs/Manual/tutorial.html

crash tool from David Anderson @ redhat is not as universal as two previous solutions, but still knows how to parse Linux kernel dumps. It is documented in command-line interface help and paper: http://people.redhat.com/anderson/crash_whitepaper/ "White Paper: Red Hat Crash Utility"

The Red Hat crash analysis utility is loosely based on the SVR4 UNIX crash command, but has been significantly enhanced by completely merging it with the GNU gdb debugger. The marriage of the two effectively combines the kernel-specific nature of the traditional UNIX crash utility with the source code level debugging capabilities of gdb. The utility can be used to investigate: Live Linux systems, Linux kernel core dumps created by the Kdump facility, Compressed Linux kernel core,  ...