问:
Alias templates or specialized derived classes?
```<code>template<typename T, int V>
class AwesomeClass    // [1]
{
public:

    AwesomeClass(T baseValue)
        : m_value(baseValue + V)
    {
    }

    T get() const
    {
        return m_value;
    }

private:

    T m_value;
};

#ifdef USE_ALIAS_TEMPLATES    // [2]

template<typename T>
using AwesomeClassWithOne = AwesomeClass<T, 1>;

template<typename T>
using AwesomeClassWithTwo = AwesomeClass<T, 2>;

#else    // [4]

template<typename T>
class AwesomeClassWithOne: public AwesomeClass<T, 1>
{
    using AwesomeClass<T, 1>::AwesomeClass;
};

template<typename T>
class AwesomeClassWithTwo: public AwesomeClass<T, 2>
{
    using AwesomeClass<T, 2>::AwesomeClass;
};

AwesomeClassWithOne(int) -> AwesomeClassWithOne<int>;
AwesomeClassWithTwo(int) -> AwesomeClassWithTwo<int>;

#endif

int main()
{
    AwesomeClassWithOne firstObj(20);    // [3]
    AwesomeClassWithTwo secondObj(20);

    return firstObj.get() + secondObj.get();
}
</code>```

I have a class, AwesomeClass [1], which takes two template parameters, typename T and int V. V is an internal detail that I don't want to expose to users of the class, so instead I want to provide aliases such as AwesomeClassWithOne and AwesomeClassWithTwo which take only T as a template parameter, and have V already bound to some value (1 and 2 respectively in my example).

Alias templates seemed to be appropriate for this [2]. However, as of C++17, it appears that argument deduction cannot be used with alias templates, so I can't do [3].

So I came up with an alternative [4] which involves creating new derived classes for each "alias" type I want, inheriting all the constructors from the base class, then creating deduction guides to make automatic deduction work (base class constructors don't seem to result in automatic deduction guides like normal constructors do; related question).

Does this seem like an appropriate workaround? Can I expect to see any weird side-effects compared to the alias template solution?

答:
Use alias templates.

Class template argument deduction doesn't work with alias templates (and unclear what that could mean), but it's not exactly clear that class template argument deduction works with inherited constructors either. It's still an open question and needs to be addressed.

Moreover, you don't actually want to introduce a new type anyway. You very much want AwesomeClass<T, 1> to be the type. So it could lead to problems if AwesomeClassWithOne<T> and AwesomeClass<T, 1> were actually different. These aren't the kind of problems you really want to get yourself into, especially if your sole reason for doing this is to allow for class template argument deduction.

If you really need that feature, just provide make_*() helpers like we're used to having to write.

Body:
template<typename T, int V>
class AwesomeClass    // [1]
{
public:

    AwesomeClass(T baseValue)
        : m_value(baseValue + V)
    {
    }

    T get() const
    {
        return m_value;
    }

private:

    T m_value;
};

#ifdef USE_ALIAS_TEMPLATES    // [2]

template<typename T>
using AwesomeClassWithOne = AwesomeClass<T, 1>;

template<typename T>
using AwesomeClassWithTwo = AwesomeClass<T, 2>;

#else    // [4]

template<typename T>
class AwesomeClassWithOne: public AwesomeClass<T, 1>
{
    using AwesomeClass<T, 1>::AwesomeClass;
};

template<typename T>
class AwesomeClassWithTwo: public AwesomeClass<T, 2>
{
    using AwesomeClass<T, 2>::AwesomeClass;
};

AwesomeClassWithOne(int) -> AwesomeClassWithOne<int>;
AwesomeClassWithTwo(int) -> AwesomeClassWithTwo<int>;

#endif

int main()
{
    AwesomeClassWithOne firstObj(20);    // [3]
    AwesomeClassWithTwo secondObj(20);

    return firstObj.get() + secondObj.get();
}

I have a class, AwesomeClass [1], which takes two template parameters, typename T and int V. V is an internal detail that I don't want to expose to users of the class, so instead I want to provide aliases such as AwesomeClassWithOne and AwesomeClassWithTwo which take only T as a template parameter, and have V already bound to some value (1 and 2 respectively in my example).

Alias templates seemed to be appropriate for this [2]. However, as of C++17, it appears that argument deduction cannot be used with alias templates, so I can't do [3].

So I came up with an alternative [4] which involves creating new derived classes for each "alias" type I want, inheriting all the constructors from the base class, then creating deduction guides to make automatic deduction work (base class constructors don't seem to result in automatic deduction guides like normal constructors do; related question).

Does this seem like an appropriate workaround? Can I expect to see any weird side-effects compared to the alias template solution?


来源: stackexchange

问:
Rspec view testing with capybara and rails3
I really like the way RSpec is able to separate controller and view tests but have some problems with getting capybara matchers to work in a view test. What i basically try to achieve is sth like this:

```<code>describe "some page" do
  it "should render with lots of stuff" do
    assign ..
    render
    rendered.should have_button ('Any button') #or any capybara matcher, really
  end
end
</code>```

I've seen some posts on the net showing how to configure capybara and rails3 to work smoothly with cucumber or rspec controller tests, but this is not really what I want - that is, testing the views at the lowest level possible.

Also if there's another way to do this (not requiring lots of custom code, couse I know i could write some matchers that extract given selectors from rendered using nokogiri or whatever tool suitable) that'd be great too - using capybara is not a requirement.

答:
At the bottom of this page, in the "Webrat and Capybara" section, it looks like Capybara is unsupported for rspec view specs

http://relishapp.com/rspec/rspec-rails

ContentLicense: CC BY-SA 2.5

Body:
I really like the way RSpec is able to separate controller and view tests but have some problems with getting capybara matchers to work in a view test. What i basically try to achieve is sth like this:

describe "some page" do
  it "should render with lots of stuff" do
    assign ..
    render
    rendered.should have_button ('Any button') #or any capybara matcher, really
  end
end

I've seen some posts on the net showing how to configure capybara and rails3 to work smoothly with cucumber or rspec controller tests, but this is not really what I want - that is, testing the views at the lowest level possible.

Also if there's another way to do this (not requiring lots of custom code, couse I know i could write some matchers that extract given selectors from rendered using nokogiri or whatever tool suitable) that'd be great too - using capybara is not a requirement.


问:
open generated pdf file in new tab instead of downloading..Web API
.Net 4.6.1 C#

I generate a pdf file at runtime and can download it successfully. I want to open the newly created pdf file in a new tab instead of downloading it. Here's my code (Web API 2.1 method):

```<code>  public HttpResponseMessage ToPDF(string cn)
    {

        var stream = new MemoryStream();
            stream = GeneratePDF();

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        return result;

    }
</code>```

I thought this would work, but it doesn't. I have target="_blank" on my anchor tag as well. How do i open my newly generated pdf file in a new tab instead of the browser wanting to download it to the user's hard drive? Thanks

答:
Just change the Media type from application/octet-stream to application/pdf .It should work.I guess you can also change the return type to FileResult instead of HttpResponseMessage.

 result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

ContentLicense: CC BY-SA 3.0

Body:
.Net 4.6.1 C#

I generate a pdf file at runtime and can download it successfully. I want to open the newly created pdf file in a new tab instead of downloading it. Here's my code (Web API 2.1 method):

  public HttpResponseMessage ToPDF(string cn)
    {

        var stream = new MemoryStream();
            stream = GeneratePDF();

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        return result;

    }

I thought this would work, but it doesn't. I have target="_blank" on my anchor tag as well. How do i open my newly generated pdf file in a new tab instead of the browser wanting to download it to the user's hard drive? Thanks


问:
How do I look inside a Python object?
I'm starting to code in various projects using Python (including Django web development and Panda3D game development).

To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties.

So say I have a Python object, what would I need to print out its contents? Is that even possible?

答: vars(obj) returns the attributes of an object.

Title: How do I look inside a Python object?

ContentLicense: CC BY-SA 4.0


问:
How to limit framerate when using Android's GLSurfaceView.RENDERMODE_CONTINUOUSLY?
I have a C++ game running through JNI in Android. The frame rate varies from about 20-45fps due to scene complexity. Anything above 30fps is silly for the game; it's just burning battery. I'd like to limit the frame rate to 30 fps.

I could switch to RENDERMODE_WHEN_DIRTY, and use a Timer or ScheduledThreadPoolExecutor to requestRender(). But that adds a whole mess of extra moving parts that might or might not work consistently and correctly.

I tried injecting Thread.sleep() when things are running quickly, but this doesn't seem to work at all for small time values. And it may just be backing events into the queue anyway, not actually pausing.

Is there a "capFramerate()" method hiding in the API? Any reliable way to do this?

答:
When using GLSurfaceView, you perform the drawing in your Renderer's onDrawFrame which is handled in a separate thread by the GLSurfaceView. Simply make sure that each call to onDrawFrame takes (1000/[frames]) milliseconds, in your case something like 33ms.

To do this: (in your onDrawFrame)

Measure the current time before your start drawing using System.currentTimeMillis (Let's call it startTime)

Perform the drawing

Measure time again (Let's call it endTime)

deltaT = endTime - starTime

if deltaT < 33, sleep (33-deltaT)

That's it.


问:
c# - What would be more effective to remove null values from a list?
I want to remove all null values from a List in C# and i wonder what would be more effective and why?

Option #1:

```<code>myList.RemoveAll(item => item == null);
</code>```

Option #2:

```<code>myList = myList.Where(x => x != null).ToList();
</code>```

Thank you!

答:
I would say the first. Mainly because of 2 reasons.

It's more easily to read.

You don't have to call .ToList(). Basically, you are creating a new list, which costs a lot of resoures.

Body:
I want to remove all null values from a List in C# and i wonder what would be more effective and why?

Option #1:

myList.RemoveAll(item => item == null);

Option #2:

myList = myList.Where(x => x != null).ToList();

Thank you!


问:
How to get a value from mysql query outside the query statement?
Here is the function see below console.log

```<code>function quo (value){
    value = connection.query(
       'SELECT role from `roles` where `id` = 1' ,
       function (error, results, fields) {
           if (error) throw error;
           console.log('The role is: ', results[0].role);// result here The role is : admin
          });
    console.log(value);
}
</code>```

The result here is query object Query {domain:null,_events:{error: .. etc} ##

I invoke this like so:

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

答:
tl;dr everything happens in a callback.

You're tripping up on the asynchronous nature of Javascript.  By the time your console.log(value); call runs, the query is not (necessarily) completed. So, there's no way for the result of the query to be available at that time.

Many developers use a pattern like this, with a callback function to handle the next step when the query result arrives.

```<code>function quo (success){
    value = connection.query(
       'SELECT role from `roles` where `id` = 1' ,
       function (error, results, fields) {
           if (error) throw error;
           console.log('The role is: ', results[0].role);
           success (results[0].role);
       });
}

quo (function (role) {
   console.log(role);
   /* do something useful with the role that came back from the query */
});
</code>```

Promise objects make this sort of thing easier to read in node.js. But explaining them is beyond the scope of a Stack Overflow answer anyhow.

Body:
Here is the function see below console.log

function quo (value){
    value = connection.query(
       'SELECT role from `roles` where `id` = 1' ,
       function (error, results, fields) {
           if (error) throw error;
           console.log('The role is: ', results[0].role);// result here The role is : admin
          });
    console.log(value);
}

The result here is query object Query {domain:null,_events:{error: .. etc} ##

I invoke this like so:

quo();

Body:
tl;dr everything happens in a callback.

You're tripping up on the asynchronous nature of Javascript.  By the time your console.log(value); call runs, the query is not (necessarily) completed. So, there's no way for the result of the query to be available at that time.

Many developers use a pattern like this, with a callback function to handle the next step when the query result arrives.

function quo (success){
    value = connection.query(
       'SELECT role from `roles` where `id` = 1' ,
       function (error, results, fields) {
           if (error) throw error;
           console.log('The role is: ', results[0].role);
           success (results[0].role);
       });
}

quo (function (role) {
   console.log(role);
   /* do something useful with the role that came back from the query */
});

Promise objects make this sort of thing easier to read in node.js. But explaining them is beyond the scope of a Stack Overflow answer anyhow.


问:
Quickly scrape the content of a page using capybara despite some useless assets on the page taking too long to load

I am using Capybara to scrape websites to check if they use cookies and if they have banners that explain why they use cookies (that may be generated using javascript).

Here is the code to initialize Capybara :

```<code>def init_capybara
  require 'capybara/poltergeist'

  Capybara.register_driver :poltergeist do |app|
    Capybara::Poltergeist::Driver.new(app, phantomjs: Phantomjs.path, js_errors: false)
  end

Capybara.default_driver = :poltergeist
end
</code>```

Here is my code for the scraper :

```<code>def presence(url)
  init_capybara

  @browser = Capybara.current_session
  @browser.visit(url)

  cookies = @browser.evaluate_script("document.cookie")

  return cookies
end
</code>```

The scraper for the banner works the same way.

I expect to get a string of all the cookies used in the website.

But I get a timeout error if I try to scrape a webpage that needs content that takes a long time to load (e.g. an analytics tool that takes a minute to load) although I do not need this content to proceed.

I do not want to just put a longer "default_max_wait_time" because the analysis needs to take only a few second and for most of the websites it's the case.

答:
I don't think there's an easy solution, except editing /etc/hosts while testing in order to disable the offending domains.

Edit: it seems to be a better solution:

```<code># spec/rails_helper.rb
config.before(:each, js: true) do
  page.driver.browser.url_blacklist = ["http://use.typekit.net"]
end
</code>```

Source: https://robots.thoughtbot.com/speed-up-javascript-capybara-specs-by-blacklisting-urls#a-better-way

Body:
I am using Capybara to scrape websites to check if they use cookies and if they have banners that explain why they use cookies (that may be generated using javascript).

Here is the code to initialize Capybara :

def init_capybara
  require 'capybara/poltergeist'

  Capybara.register_driver :poltergeist do |app|
    Capybara::Poltergeist::Driver.new(app, phantomjs: Phantomjs.path, js_errors: false)
  end

Capybara.default_driver = :poltergeist
end

Here is my code for the scraper :

def presence(url)
  init_capybara

  @browser = Capybara.current_session
  @browser.visit(url)

  cookies = @browser.evaluate_script("document.cookie")

  return cookies
end

The scraper for the banner works the same way.

I expect to get a string of all the cookies used in the website.

But I get a timeout error if I try to scrape a webpage that needs content that takes a long time to load (e.g. an analytics tool that takes a minute to load) although I do not need this content to proceed.

I do not want to just put a longer "default_max_wait_time" because the analysis needs to take only a few second and for most of the websites it's the case.

Body:
I don't think there's an easy solution, except editing /etc/hosts while testing in order to disable the offending domains.

Edit: it seems to be a better solution:

# spec/rails_helper.rb
config.before(:each, js: true) do
  page.driver.browser.url_blacklist = ["http://use.typekit.net"]
end

Source: https://robots.thoughtbot.com/speed-up-javascript-capybara-specs-by-blacklisting-urls#a-better-way


问:
iOS icon jiggle algorithm
I am writing an iPad app that presents user documents similar to the way Pages presents them (as large icons of the actual document).  I also want to mimic the jiggling behavior when the user taps the edit button.  This is the same jiggle pattern that icons make on the home screen when you tap and hold on them on both the iPhone and iPad.

I've searched the Internet and have found a few algorithms but they just cause the view to rock back and forth which is not at all like the Apple jiggle.  It seems there is some randomness in there as each icon jiggles a little differently.

Does anyone have or know of some code that can re-create the same jiggle pattern (or something very close to it)?  Thanks!!!

答:
@mientus Original Apple Jiggle code in Swift 4, with optional parameters to adjust the duration (i.e. speed), displacement (i.e. position change) and degrees (i.e. rotation amount).</p>

```<code>private func degreesToRadians(_ x: CGFloat) -> CGFloat {
    return .pi * x / 180.0
}

func startWiggle(
    duration: Double = 0.25,
    displacement: CGFloat = 1.0,
    degreesRotation: CGFloat = 2.0
    ) {
    let negativeDisplacement = -1.0 * displacement
    let position = CAKeyframeAnimation.init(keyPath: "position")
    position.beginTime = 0.8
    position.duration = duration
    position.values = [
        NSValue(cgPoint: CGPoint(x: negativeDisplacement, y: negativeDisplacement)),
        NSValue(cgPoint: CGPoint(x: 0, y: 0)),
        NSValue(cgPoint: CGPoint(x: negativeDisplacement, y: 0)),
        NSValue(cgPoint: CGPoint(x: 0, y: negativeDisplacement)),
        NSValue(cgPoint: CGPoint(x: negativeDisplacement, y: negativeDisplacement))
    ]
    position.calculationMode = "linear"
    position.isRemovedOnCompletion = false
    position.repeatCount = Float.greatestFiniteMagnitude
    position.beginTime = CFTimeInterval(Float(arc4random()).truncatingRemainder(dividingBy: Float(25)) / Float(100))
    position.isAdditive = true

    let transform = CAKeyframeAnimation.init(keyPath: "transform")
    transform.beginTime = 2.6
    transform.duration = duration
    transform.valueFunction = CAValueFunction(name: kCAValueFunctionRotateZ)
    transform.values = [
        degreesToRadians(-1.0 * degreesRotation),
        degreesToRadians(degreesRotation),
        degreesToRadians(-1.0 * degreesRotation)
    ]
    transform.calculationMode = "linear"
    transform.isRemovedOnCompletion = false
    transform.repeatCount = Float.greatestFiniteMagnitude
    transform.isAdditive = true
    transform.beginTime = CFTimeInterval(Float(arc4random()).truncatingRemainder(dividingBy: Float(25)) / Float(100))

    self.layer.add(position, forKey: nil)
    self.layer.add(transform, forKey: nil)
}
</code>```

Title: iOS icon jiggle algorithm

Body:
@mientus Original Apple Jiggle code in Swift 4, with optional parameters to adjust the duration (i.e. speed), displacement (i.e. position change) and degrees (i.e. rotation amount).

private func degreesToRadians(_ x: CGFloat) -> CGFloat {
    return .pi * x / 180.0
}

func startWiggle(
    duration: Double = 0.25,
    displacement: CGFloat = 1.0,
    degreesRotation: CGFloat = 2.0
    ) {
    let negativeDisplacement = -1.0 * displacement
    let position = CAKeyframeAnimation.init(keyPath: "position")
    position.beginTime = 0.8
    position.duration = duration
    position.values = [
        NSValue(cgPoint: CGPoint(x: negativeDisplacement, y: negativeDisplacement)),
        NSValue(cgPoint: CGPoint(x: 0, y: 0)),
        NSValue(cgPoint: CGPoint(x: negativeDisplacement, y: 0)),
        NSValue(cgPoint: CGPoint(x: 0, y: negativeDisplacement)),
        NSValue(cgPoint: CGPoint(x: negativeDisplacement, y: negativeDisplacement))
    ]
    position.calculationMode = "linear"
    position.isRemovedOnCompletion = false
    position.repeatCount = Float.greatestFiniteMagnitude
    position.beginTime = CFTimeInterval(Float(arc4random()).truncatingRemainder(dividingBy: Float(25)) / Float(100))
    position.isAdditive = true

    let transform = CAKeyframeAnimation.init(keyPath: "transform")
    transform.beginTime = 2.6
    transform.duration = duration
    transform.valueFunction = CAValueFunction(name: kCAValueFunctionRotateZ)
    transform.values = [
        degreesToRadians(-1.0 * degreesRotation),
        degreesToRadians(degreesRotation),
        degreesToRadians(-1.0 * degreesRotation)
    ]
    transform.calculationMode = "linear"
    transform.isRemovedOnCompletion = false
    transform.repeatCount = Float.greatestFiniteMagnitude
    transform.isAdditive = true
    transform.beginTime = CFTimeInterval(Float(arc4random()).truncatingRemainder(dividingBy: Float(25)) / Float(100))

    self.layer.add(position, forKey: nil)
    self.layer.add(transform, forKey: nil)
}


问:
How to serve static content using Webflux?
I am learning webflux and I would like to know how to serve static content on a MicroService using webflux but I didn´t find information to do it.</p>

答:
Thanks wildloop worked for me with following properties:

```<code>spring.webflux.static-path-pattern: "/**"
spring.resources.static-locations: "classpath:/public-web-resources/"
</code>```

Spring boot adds following log line:

```<code>15:51:43.776 INFO  Adding welcome page: class path resource [public-web-resources/index.html] - WebMvcAutoConfiguration$WelcomePageHandlerMapping.<init>
</code>```

And it works as welcome page for http://localhost:port/myapp/

Wish there was a way to invoke it on /myapp/docs

Body:
Thanks wildloop worked for me with following properties:

spring.webflux.static-path-pattern: "/**"
spring.resources.static-locations: "classpath:/public-web-resources/"

Spring boot adds following log line:

15:51:43.776 INFO  Adding welcome page: class path resource [public-web-resources/index.html] - WebMvcAutoConfiguration$WelcomePageHandlerMapping.<init>

And it works as welcome page for http://localhost:port/myapp/

Wish there was a way to invoke it on /myapp/docs


问:
Filtering JavaScript objects using values from multiple arrays
If I have array of objects.

```<code>var products = [{
       names: ["hammer", "nail", "rubber duck"],
       colors: ["yellow", "red", "pink"]
    },
    {
       names: ["saw", "tractor", "bowling ball"],
       colors: ["gray", "purple", "green"]
    }]
</code>```

Then I have object with arrays of filter values:

```<code>var filters = {names: ["saw", "bowling ball"], colors:["purple"]}
</code>```

I need to filter the objects so that if I've got no filters I get all objects back. If I've got any filter values in "names" I get objects back with matching names. If I've got any filter values in both "names" and "colors" I get objects back with matching values on both.

For example:

```<code>var filters = {names: ["saw", "bowling ball"], colors:["purple"]}
</code>```

would return

```<code>[{
names: ["saw", "tractor" "bowling ball"],
colors: ["gray", "purple", "green"]
}]
</code>```

答:
You could take a nested approach by filtering the given array with all items with the object for the wanted items and get the keys of it, take the arrays and look if the value is in the item's list with the same key.

var products = [{ names: ["hammer", "nail", "rubber duck"], colors: ["yellow", "red", "pink"] }, { names: ["saw", "tractor", "bowling ball"], colors: ["gray", "purple", "green"] }],
    filters = { names: ["saw", "bowling ball"], colors: ["purple"] },
    result = products.filter(function (p) {
        return Object.keys(filters).every(function (k) {
            return filters[k].some(function (v) {
                return p[k].indexOf(v) !== -1;
            });
        });
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
If I have array of objects.

var products = [{
       names: ["hammer", "nail", "rubber duck"],
       colors: ["yellow", "red", "pink"]
    },
    {
       names: ["saw", "tractor", "bowling ball"],
       colors: ["gray", "purple", "green"]
    }]

Then I have object with arrays of filter values:

var filters = {names: ["saw", "bowling ball"], colors:["purple"]}

I need to filter the objects so that if I've got no filters I get all objects back. If I've got any filter values in "names" I get objects back with matching names. If I've got any filter values in both "names" and "colors" I get objects back with matching values on both.

For example:

var filters = {names: ["saw", "bowling ball"], colors:["purple"]}

would return

[{
names: ["saw", "tractor" "bowling ball"],
colors: ["gray", "purple", "green"]
}]

Body:
You could take a nested approach by filtering the given array with all items with the object for the wanted items and get the keys of it, take the arrays and look if the value is in the item's list with the same key.

var products = [{ names: ["hammer", "nail", "rubber duck"], colors: ["yellow", "red", "pink"] }, { names: ["saw", "tractor", "bowling ball"], colors: ["gray", "purple", "green"] }],
    filters = { names: ["saw", "bowling ball"], colors: ["purple"] },
    result = products.filter(function (p) {
        return Object.keys(filters).every(function (k) {
            return filters[k].some(function (v) {
                return p[k].indexOf(v) !== -1;
            });
        });
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
HDFS Data node Reconnects on failure/Restart
Is there a functionality, configuration in HDFS, wherein if a data node fails/restarts, upon restarting it would be able to reconnect to the cluster and transact data? </p>

答:
Once the namenode detects an RPC connection to a running datanode process, yes, it can transact data.

Whether the datanode process starts on a reboot is up to your installation & OS

For example, the latest version of Apache Ambari supports Service Auto start


问:
How to get unicode input from xcb without further ado
during GameDev for a cross-platform title the questions arises how to support full Unicode input in ingame-chat.  Using WinAPI on Windows and xcb on Linux for general key input there are the WM_KEY_* messages and xcb_key_* events respectively. This is just fine if you want to be notified about a pressed key on the keyboard.

Now this doesn't give you full text input. For example on Windows there is a additional message called WM_CHAR explicitly for text input. Key codes a translated to Unicode codepoints including the handling of ModifierKeys like shift. Even chinese input is possible.

Now what about xcb? All I can find according to that topic is outdated for at least four years now. Has there some progress been made? Is is now possible to get at least the translation from dead characters to KeySyms (like XFilterEvent did)? I don't need full Unicode input like holding alt-key and type a number on the numpad to get the corresp. codepoint on screen. Also I do not want to link huge libraries like GTK just for translating keyboard input to Unicode.

I know this is a repeated questions, but all are outdated so I ask again for the current state of text input in xcb.

Thank you!

答:
Not sure if it will be of any help, but...

You are probably looking for a family of X*LookupString functions:

http://www.xfree86.org/current/Xutf8LookupString.3.html

Now, I had the same problem as you, that is, I needed to port an application using WinAPI's WM_CHAR to one that uses xcb coupled with X11 (as such coupling is necessary for an OpenGL window). I didn't exactly need Unicode, but I was still lost because there was nothing to let me obtain composed input from the keystrokes (e.g. pressing shift and 7 should result in &)

Unfortunately, to quote xcb's to-do list:

Current status

Currently, XCB only implements the bits given in the X Window System
  Protocol, and even this support is not complete compared to Xlib
  (character encoding, no XLookupString()...).

So, if you have to use xcb, it makes things all the harder, as there are no equivalent X*LookupString functions for the key press event returned by xcb - xcb_key_press_event_t. What you need to do is to convert it to XKeyEvent understandable by, for example, XLookupString.

Now, looking at the source of XLookupString , we can see it only ever uses three fields of XKeyEvent:

display - your Display

keycode- the pressed key

state - the state of the modifier keys, e.g. shift or caps lock

It just so happens that there are corresponding fields in xcb_key_press_event_t that are pretty much identical to the ones we need. What I did to make my particular application work was this:

```<code>    // This is your generic event returned by, for example, xcb_poll_for_event
    const xcb_generic_event_t* event = ...;

    const auto* const press = reinterpret_cast<const xcb_key_press_event_t*>(event);

    // Now we have to prepare input understandable by the lookup function

    XKeyEvent keyev;
    keyev.display = display; // here you'll need to supply your Display*
    keyev.keycode = press->detail;
    keyev.state = press->state;

    std::array<char, 16> buf {};

    if (XLookupString(&keyev, buf.data(), buf.size(), nullptr, nullptr)) {
        // Now buf should contain a string with your characters;
        // I just need ascii so I always take only buf[0] and it works fine
    }
    else {
        // Something's wrong... report error or something
    }
</code>```

It also looks like XLookupString outputs a keysym correspondent to the composed character, via its in-out KeySym *keysym_return argument. As you say that you also need keysyms, you might want to use it.

I'm not doing a professional application, so this is all I needed, and I'm not really sure what's the course of action for full Unicode support, but if I ever get to it, I'll let you know.

Body:
Not sure if it will be of any help, but...

You are probably looking for a family of X*LookupString functions:

http://www.xfree86.org/current/Xutf8LookupString.3.html

Now, I had the same problem as you, that is, I needed to port an application using WinAPI's WM_CHAR to one that uses xcb coupled with X11 (as such coupling is necessary for an OpenGL window). I didn't exactly need Unicode, but I was still lost because there was nothing to let me obtain composed input from the keystrokes (e.g. pressing shift and 7 should result in &)

Unfortunately, to quote xcb's to-do list:

Current status

Currently, XCB only implements the bits given in the X Window System
  Protocol, and even this support is not complete compared to Xlib
  (character encoding, no XLookupString()...).

So, if you have to use xcb, it makes things all the harder, as there are no equivalent X*LookupString functions for the key press event returned by xcb - xcb_key_press_event_t. What you need to do is to convert it to XKeyEvent understandable by, for example, XLookupString.

Now, looking at the source of XLookupString , we can see it only ever uses three fields of XKeyEvent:

display - your Display

keycode- the pressed key

state - the state of the modifier keys, e.g. shift or caps lock

It just so happens that there are corresponding fields in xcb_key_press_event_t that are pretty much identical to the ones we need. What I did to make my particular application work was this:

    // This is your generic event returned by, for example, xcb_poll_for_event
    const xcb_generic_event_t* event = ...;

    const auto* const press = reinterpret_cast<const xcb_key_press_event_t*>(event);

    // Now we have to prepare input understandable by the lookup function

    XKeyEvent keyev;
    keyev.display = display; // here you'll need to supply your Display*
    keyev.keycode = press->detail;
    keyev.state = press->state;

    std::array<char, 16> buf {};

    if (XLookupString(&keyev, buf.data(), buf.size(), nullptr, nullptr)) {
        // Now buf should contain a string with your characters;
        // I just need ascii so I always take only buf[0] and it works fine
    }
    else {
        // Something's wrong... report error or something
    }

It also looks like XLookupString outputs a keysym correspondent to the composed character, via its in-out KeySym *keysym_return argument. As you say that you also need keysyms, you might want to use it.

I'm not doing a professional application, so this is all I needed, and I'm not really sure what's the course of action for full Unicode support, but if I ever get to it, I'll let you know.


问:
Autoshrink on a UILabel with multiple lines
Is it possible to use the autoshrink property in conjunction on multiple lines on a UILabel? for example, the large text size possible on 2 available lines.

答:
```<code>extension UILabel{

func adjustFont(minSize:Int, maxSize:Int){
    var newFont = self.font
    for index in stride(from: maxSize, to: minSize, by: -1) {
        newFont = UIFont.systemFont(ofSize: CGFloat(index))
        let size = CGSize(width: self.frame.width, height: CGFloat(Int.max))
        let size2 = (self.text! as NSString).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font:newFont!], context: nil).size
        if size2.height < self.frame.size.height{
            break
        }
    }
    self.font = newFont
}
</code>```

}

you need to assign value to the numberOfLines property of UILabel as well.

Body:
extension UILabel{

func adjustFont(minSize:Int, maxSize:Int){
    var newFont = self.font
    for index in stride(from: maxSize, to: minSize, by: -1) {
        newFont = UIFont.systemFont(ofSize: CGFloat(index))
        let size = CGSize(width: self.frame.width, height: CGFloat(Int.max))
        let size2 = (self.text! as NSString).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font:newFont!], context: nil).size
        if size2.height < self.frame.size.height{
            break
        }
    }
    self.font = newFont
}

}

you need to assign value to the numberOfLines property of UILabel as well.


问:
Rake gems:install says "could not find table", rake db:migrate says "required gems missing"
I just cloned a github repo on a fresh Ubuntu machine, running sqlite3 for all environments. rake db:create says development.sqlite3 already exists. rake db:migrate says I'm missing a bunch of required gems and should run rake gems:install. rake gems:install, of course, says it Could not find table 'studies', which sounds to me like something rake db:migrate should fix.

I looked around the net and while lots of people have gotten 'could not find table' errors, they all got them from rake db:migrate, not rake gems:install. I'm suspecting it's an application-specific error, but still, any ideas would be appreciated.

PS: Ruby 1.8.7, Rails 2.3.8.

答:
Did you try running with the trace option? Might help pin down the failing gem:

rake -t gems:install


问:
angular-uiroute error as $cookieStore.get is undefind
here im trying to fetch my Stored cookie value in $roortScope why im getting Error as .get of undefind  <code>$cookieStore.get('mycookie');</code>  </p>

```<code>angular.module('MyApp', ['ui.router', 'ui.bootstrap', 'ngCookies']).controller('HomeCtrl', function ($scope, $cookies, $state) {
 .run(function ($rootScope) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope,$cookieStore) {
            var Getcookies = $cookieStore.get('mycookie');

            if (toState.module == "Private" && !Getcookies.lenth=='undefind')
  {
            }
</code>```

答:
The $cookies service needs to be injected as a parameter in the .run construction function:

```<code>̶.̶r̶u̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶)̶ ̶{̶
.run(function ($rootScope, $cookies) {

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope,$cookieStore) {
        var Getcookies = $cookies.get('mycookie');

        //...

    });
})
</code>```

Body:
here im trying to fetch my Stored cookie value in $roortScope why im getting Error as .get of undefind  $cookieStore.get('mycookie');

angular.module('MyApp', ['ui.router', 'ui.bootstrap', 'ngCookies']).controller('HomeCtrl', function ($scope, $cookies, $state) {
 .run(function ($rootScope) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope,$cookieStore) {
            var Getcookies = $cookieStore.get('mycookie');

            if (toState.module == "Private" && !Getcookies.lenth=='undefind')
  {
            }

Body:
The $cookies service needs to be injected as a parameter in the .run construction function:

̶.̶r̶u̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶)̶ ̶{̶
.run(function ($rootScope, $cookies) {

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope,$cookieStore) {
        var Getcookies = $cookies.get('mycookie');

        //...

    });
})


问:
c# File1's text keeps replacing file2's when I run it
All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace RandomName
{
class Program
{
    static void Main(string[] args)
    {

        string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";

        string fileName = "file1.txt";
        StreamReader reader = new StreamReader(winDir + fileName);

        string outputFileName = "upperfile" + fileName;
        StreamWriter writer = new StreamWriter(outputFileName);

        int n = 0;
        string st = "";
        string upperString = "";
        int n2 = 0;
        string st2 = "";
        string upperString2 = "";

        string fileName2 = "file2.txt";

        StreamReader reader2 = new StreamReader(winDir + fileName2);
        string outputFileName2 = "output" + fileName2;
        StreamWriter writer2 = new StreamWriter(outputFileName2);

        do
        {
            ++n;
            st = reader.ReadLine();  // read one line from disk file
            Console.WriteLine("Line #" + n + ": " + st);  // write to the console
            writer.WriteLine(st);  // write line to disk file instead, using WriteLine() method
            upperString = upperString + "\n" + st;  // append each line to the big string

        }
        while (!reader.EndOfStream);

        do
        {
            ++n2;
            st2 = reader2.ReadLine();  // read one line from disk file
            Console.WriteLine("Line #" + n2 + ": " + st2);  // write to the
console
            writer2.WriteLine(st2);  // write line to disk file instead,
using WriteLine() method
            upperString2 = upperString2 + "\n" + st2;  // append each line
to the big string
        }
        while (!reader2.EndOfStream);
        reader.Close();
        writer.Close();

        Console.WriteLine("\nHere is the entire file in a string:");
        Console.WriteLine(upperString);
        Console.WriteLine(upperString2);

        UpperString b = new UpperString(upperString);
        UpperString2 c = new UpperString2(upperString2);

        Console.WriteLine("\nThe string in reverse case: ");
        b.showReverseCase();
        Console.WriteLine("\n");

        c.readingFile2();
        c.toNewFile2();

    }

}
}
</code>```

"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.

Here is the class

```<code>class UpperString2
{
    private string upperString2;

    public UpperString2() { }

    public UpperString2(string c) { upperString2 = c; }

    public void readingFile2()
    {
        string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");

        System.Console.WriteLine("\nAnother Poem  \n");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine(line);
        }

    }

    public void toNewFile2()
    {
        using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
        {
            string newText = (upperString2.ToUpper()).ToString();

            writetext.WriteLine(newText);
        }

    }
</code>```

I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!

答:
The problem is "outputfile2" was already opened by reader2 in Main().

```<code>string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)
</code>```

Then it raises an exception when you try to open the same file for writting in toNewFile2():

```<code>public void toNewFile2()
{
    using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
    {
        string newText = (upperString2.ToUpper()).ToString();

        writetext.WriteLine(newText);
    }
}
</code>```

This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.

Since you have moved the code to a class, call that class instead.

Body:
All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace RandomName
{
class Program
{
    static void Main(string[] args)
    {

        string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";

        string fileName = "file1.txt";
        StreamReader reader = new StreamReader(winDir + fileName);

        string outputFileName = "upperfile" + fileName;
        StreamWriter writer = new StreamWriter(outputFileName);

        int n = 0;
        string st = "";
        string upperString = "";
        int n2 = 0;
        string st2 = "";
        string upperString2 = "";

        string fileName2 = "file2.txt";

        StreamReader reader2 = new StreamReader(winDir + fileName2);
        string outputFileName2 = "output" + fileName2;
        StreamWriter writer2 = new StreamWriter(outputFileName2);

        do
        {
            ++n;
            st = reader.ReadLine();  // read one line from disk file
            Console.WriteLine("Line #" + n + ": " + st);  // write to the console
            writer.WriteLine(st);  // write line to disk file instead, using WriteLine() method
            upperString = upperString + "\n" + st;  // append each line to the big string

        }
        while (!reader.EndOfStream);

        do
        {
            ++n2;
            st2 = reader2.ReadLine();  // read one line from disk file
            Console.WriteLine("Line #" + n2 + ": " + st2);  // write to the
console
            writer2.WriteLine(st2);  // write line to disk file instead,
using WriteLine() method
            upperString2 = upperString2 + "\n" + st2;  // append each line
to the big string
        }
        while (!reader2.EndOfStream);
        reader.Close();
        writer.Close();

        Console.WriteLine("\nHere is the entire file in a string:");
        Console.WriteLine(upperString);
        Console.WriteLine(upperString2);

        UpperString b = new UpperString(upperString);
        UpperString2 c = new UpperString2(upperString2);

        Console.WriteLine("\nThe string in reverse case: ");
        b.showReverseCase();
        Console.WriteLine("\n");

        c.readingFile2();
        c.toNewFile2();

    }

}
}

"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.

Here is the class

class UpperString2
{
    private string upperString2;

    public UpperString2() { }

    public UpperString2(string c) { upperString2 = c; }

    public void readingFile2()
    {
        string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");

        System.Console.WriteLine("\nAnother Poem  \n");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine(line);
        }

    }

    public void toNewFile2()
    {
        using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
        {
            string newText = (upperString2.ToUpper()).ToString();

            writetext.WriteLine(newText);
        }

    }

I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!

Body:
The problem is "outputfile2" was already opened by reader2 in Main().

string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)

Then it raises an exception when you try to open the same file for writting in toNewFile2():

public void toNewFile2()
{
    using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
    {
        string newText = (upperString2.ToUpper()).ToString();

        writetext.WriteLine(newText);
    }
}

This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.

Since you have moved the code to a class, call that class instead.


问:
Can i connect to a second DB Host if the First fail?
I have a question about a connection to a second host if the first fail down or connection limit reached.

My Host is OVH in France on a shared host (I can't modify apache/php/sql config) and the MAX USER_CONNECTIONS (sql) is 30.

I wanted to switch Host is the first one reach the limit and refuse connection.

Can I use ?:

```<code>$dbhost = 'localhost';
$dbname = 'dbname';
$dbuser = 'dbuser';
$dbpswd = 'dbpass';
try{
    $db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname,$dbuser,$dbpswd,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(PDOexception $e){
    $dbhost2 = 'secondhost';
    $dbname2 = 'dbname';
    $dbuser2 = 'dbuser';
    $dbpswd2 = 'dbpass';
    try{
        $db = new PDO('mysql:host='.$dbhost2.';dbname='.$dbname2,$dbuser2,$dbpswd2,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    }catch(PDOexception $e){
        die("DB Error please contact the web admin.");
    }
}
</code>```

Or if you have a better option..

NB: I do not have much experience in programming, I do not use OOP yet.

答:
The idea is right, but this particular implementation is inflexible and unhelpful towards the site admin who is supposed to fix errors.

Imagine a case when a password has been changed for the main server. Your code will start connecting to the backup server 100% of time, thanks to the unconditional algorithm, and nobody would have an idea on that.

Given you want to overcome a particular error ("too many connections"), in your catch block you should test whether it is the error you are expecting to, and at least log the error message otherwise. So the site ad min will notice a problem and will have an idea what's going on.

die("DB Error please contact the web admin."); won't be of a much use for the site admin either, as he won't have an idea what happened with the backup server in turn.

So for the second one do not catch its exception right in place, but follow the common error handling routine for your site. The easiest one would be a global try catch around the whole code, which looks rather blunt but at least better than several dozens local try catches with its own error message each

So it should be like

```<code>$dboptions = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)

try{
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpswd,$dboptions);
}catch(PDOexception $e){
    if ($e->getMessage() != "whatever particular error message you get") {
        error_log($e);
    }
    $dbhost2 = 'secondhost';
    $dbname2 = 'dbname';
    $dbuser2 = 'dbuser';
    $dbpswd2 = 'dbpass';
    $db = new PDO("mysql:host=$dbhost2;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpswd,$dboptions);
}
</code>```

Body:
I have a question about a connection to a second host if the first fail down or connection limit reached.

My Host is OVH in France on a shared host (I can't modify apache/php/sql config) and the MAX USER_CONNECTIONS (sql) is 30.

I wanted to switch Host is the first one reach the limit and refuse connection.

Can I use ?:

$dbhost = 'localhost';
$dbname = 'dbname';
$dbuser = 'dbuser';
$dbpswd = 'dbpass';
try{
    $db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname,$dbuser,$dbpswd,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(PDOexception $e){
    $dbhost2 = 'secondhost';
    $dbname2 = 'dbname';
    $dbuser2 = 'dbuser';
    $dbpswd2 = 'dbpass';
    try{
        $db = new PDO('mysql:host='.$dbhost2.';dbname='.$dbname2,$dbuser2,$dbpswd2,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    }catch(PDOexception $e){
        die("DB Error please contact the web admin.");
    }
}

Or if you have a better option..

NB: I do not have much experience in programming, I do not use OOP yet.

Body:
The idea is right, but this particular implementation is inflexible and unhelpful towards the site admin who is supposed to fix errors.

Imagine a case when a password has been changed for the main server. Your code will start connecting to the backup server 100% of time, thanks to the unconditional algorithm, and nobody would have an idea on that.

Given you want to overcome a particular error ("too many connections"), in your catch block you should test whether it is the error you are expecting to, and at least log the error message otherwise. So the site ad min will notice a problem and will have an idea what's going on.

die("DB Error please contact the web admin."); won't be of a much use for the site admin either, as he won't have an idea what happened with the backup server in turn.

So for the second one do not catch its exception right in place, but follow the common error handling routine for your site. The easiest one would be a global try catch around the whole code, which looks rather blunt but at least better than several dozens local try catches with its own error message each

So it should be like

$dboptions = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)

try{
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpswd,$dboptions);
}catch(PDOexception $e){
    if ($e->getMessage() != "whatever particular error message you get") {
        error_log($e);
    }
    $dbhost2 = 'secondhost';
    $dbname2 = 'dbname';
    $dbuser2 = 'dbuser';
    $dbpswd2 = 'dbpass';
    $db = new PDO("mysql:host=$dbhost2;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpswd,$dboptions);
}


问:
raspberry pi 3 Ethernet with 802.1X
I want to connect my raspberry pi 3 via Ethernet to the Interet. The problem is that in my student dorm they use 802.1X as network authentication. I found this tutorial: https://help.ubuntu.com/community/Network802.1xAuthentication and did the steps.
So i modified /etc/wpa_supplicant/wpa_supplicant.conf. It looks like this now:

```<code>ctrl_interface=/var/run/wpa_supplicant
eapol_version=2
ap_scan=0
network={
key_mgmt=IEEE8021X
eap=PEAP
identity="loginname"
password="password"
phase1="peaplabel=0"
phase2="auth=MSCHAPV2"
}
</code>```

But when i run:

```<code>sudo wpa_supplicant -c /etc/wpa_supplicant/wpa_supplicant.conf -D wired -i eth0
</code>```

The output is:

```<code>Succesfully initialized wpa_supplicant
ioctl[SIOCGIFFLAGS]: No such device
setsockopt: No such device
ioctl[SIOC{ADD/DEL}MULTI]: No such device
ioctl[SIOCGIFFLAGS]: No such device
wpa_driver_wired_init: Could not get interface flags
eth0: Failed to initialize driver interface
</code>```

And i dont have a connection.

答:
I've absolute no knowledge about the protocol you ask about, but as far as I know the new raspbian, has changed the names of the network interface "eth0" to enp3s0 or so.

You can verify my assuption by performing sudo ifconfig -a.

Then you get a list off all your interfaces. If "eth0" is not in this list, there should be something like "enpXsY". In this case you just have to change the "eth0" in the command above to the new interface name. E.g.:

```<code>sudo wpa_supplicant -c /etc/wpa_supplicant/wpa_supplicant.conf -D wired -i enp0s3
</code>```

Hope that helps!

Title: raspberry pi 3 Ethernet with 802.1X

Body:
I want to connect my raspberry pi 3 via Ethernet to the Interet. The problem is that in my student dorm they use 802.1X as network authentication. I found this tutorial: https://help.ubuntu.com/community/Network802.1xAuthentication and did the steps.
So i modified /etc/wpa_supplicant/wpa_supplicant.conf. It looks like this now:

ctrl_interface=/var/run/wpa_supplicant
eapol_version=2
ap_scan=0
network={
key_mgmt=IEEE8021X
eap=PEAP
identity="loginname"
password="password"
phase1="peaplabel=0"
phase2="auth=MSCHAPV2"
}

But when i run:

sudo wpa_supplicant -c /etc/wpa_supplicant/wpa_supplicant.conf -D wired -i eth0

The output is:

Succesfully initialized wpa_supplicant
ioctl[SIOCGIFFLAGS]: No such device
setsockopt: No such device
ioctl[SIOC{ADD/DEL}MULTI]: No such device
ioctl[SIOCGIFFLAGS]: No such device
wpa_driver_wired_init: Could not get interface flags
eth0: Failed to initialize driver interface

And i dont have a connection.

Body:
I've absolute no knowledge about the protocol you ask about, but as far as I know the new raspbian, has changed the names of the network interface "eth0" to enp3s0 or so.

You can verify my assuption by performing sudo ifconfig -a.

Then you get a list off all your interfaces. If "eth0" is not in this list, there should be something like "enpXsY". In this case you just have to change the "eth0" in the command above to the new interface name. E.g.:

sudo wpa_supplicant -c /etc/wpa_supplicant/wpa_supplicant.conf -D wired -i enp0s3

Hope that helps!


问:
How much secure data stored in sessionstorage and localstorage in Browsers
I am a newbie in web application development.Recently i got  a chance to use
SessionStorage and LocalStorage . I have seen most browsers saving the data in browser cache in sqlite or as web storge either in Base64 or in plain text format.
How much secure this or we need to implemnent some encryption before saving into the storage?</p>

答:
There are two types of web storage, which differ in scope and lifetime:

Local storage (window.localStorage) — The local storage uses the localStorage object to store data for your entire website, permanently. That means the stored local data will be available on the next day, the next week, or the next year unless you remove it.

Session storage (window.sessionStorage) — The session storage uses the sessionStorage object to store data on a temporary basis, for a single window (or tab). The data disappears when session ends i.e. when the user closes that window (or tab).

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Also check this thread
 Does HTML5 web storage (localStorage) offer a security advantage over cookies?


问:
wpdb::prepare was called incorrectly. Unsupported value type (object)
I an recieving this notice in my error log since switching to wpdb->prepare, I am using SimpleXML to bring in data then input into a table

```<code>[code]
    $dataset = new SimpleXMLElement($html);
        foreach($dataset->item as $list) {
            $wpdb->query($wpdb->prepare("INSERT INTO table (`id`,`number`,`string`) VALUES (%d,%d,%s) ", $list->id, $list->number, $list->string ) ) ;
        }
    }
[/code]
</code>```

THe insert is working, but each time throuws the OBJECT warning.  Can I not use the $list object even though I am using its value as $list->xxx

Thanks

答:
Doing a var dump of list, empty items returned an object :

object(SimpleXMLElement)#1776 (0)

I believe this is throwing the error as expected while using an object.

Body:
I an recieving this notice in my error log since switching to wpdb->prepare, I am using SimpleXML to bring in data then input into a table

[code]
    $dataset = new SimpleXMLElement($html);
        foreach($dataset->item as $list) {
            $wpdb->query($wpdb->prepare("INSERT INTO table (`id`,`number`,`string`) VALUES (%d,%d,%s) ", $list->id, $list->number, $list->string ) ) ;
        }
    }
[/code]

THe insert is working, but each time throuws the OBJECT warning.  Can I not use the $list object even though I am using its value as $list->xxx

Thanks


问:
Command to use restoring npm packages
When I download a project from my repo with a package.json in its root, which command is the right one to use npm install or npm install restore?

答:
The behaviour of npm install is

npm install without any argument will install all packages found in package.json in node_modules folder.

npm install <package_name> will install package_name. In your case will download restore package and will save it in node_modules folder. (https://www.npmjs.com/package/restore)

Title: Command to use restoring npm packages


问:
How to change default kivy logo with another image logo?
How can I change the default kivy icon logo? I tried in buildozer spec but nothing happens - when I convert my app in the apk the icon does not change.</p>

答:
According to the documentation for the icon:

icon.filename: String, icon of your application.
  The icon of your application. It must be a PNG of 512x512 size to be able to cover all the various platform requirements.

You must use a PNG format image.

Here is my complete spec file: buildozer.spec


问:
Shiny dashboard and DT table not showing
I have a dashboard where I would like to show a table, but I cant figure out why my table is not showing. If I replace the table for example with some text, h2(....) it does show. I would like to click on "Species" and have the table show on the right when clicking it.

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL,
      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      ),
      actionButton("Gobtn", "Get data"),
      menuItem("Specs", tabName = "Specs", icon = NULL)
    )
  )),

  dashboardBody(tabItems(
    tabItem(tabName = "Species",
            DT::renderDataTable("Table1")),
    tabItem(tabName = "Specs",
            h2("Hi"))
  ))
)
</code>```

server.r

```<code>  server <- shinyServer(function(input, output, session) {
  output$Table1 <- DT::renderDataTable({
    iris
  })
})

shinyApp(ui, server)
</code>```

答:
Few things to get your code up and running here. Couple have been noted by other contributors.

We need to use DT::dataTableOutput("Table1") on the UI side as renderDataTable will not work here, that is the server side function.

The other would be that using the switchInput within the menuItem may confused the app, as these are not standard parameters to pass into the function. From what I can see from your code, which is a common challenge, is that you want to be able to show this switchInput only when the 'Species' tab is selected. We can account for this using conditionalPanel. To do this, we can set id = "tabs" within the sidebarMenu and then reference this sidebarMenu within the conditionalPanel:

```<code>conditionalPanel(
  condition = "input.tabs== 'Species' ",
  switchInput(
    inputId = "long1",
    onLabel = "Go",
    offLabel = "NoGo",
    value = T
  )
)
</code>```

To finish, I have altered the layouts of the ui.R and server.R, as the shinyApp function was not needed for the app to work with the server and ui files. This is how I lay out my dashboards. It may show you a few other possible ways you can use the app structure within Shiny, but equally you could just align the changes to the basic layout.

ui.R

```<code>header <- dashboardHeader(title = "Basic dashboard")

sidebar <- dashboardSidebar(
  sidebarMenu(id = "tabs",
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL),

    conditionalPanel(
      condition = "input.tabs== 'Species' ",
      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      )
    ),

    actionButton("Gobtn", "Get data"),

    menuItem("Specs", tabName = "Spec", icon = NULL)
  )
)

body <- dashboardBody(
  tabItems(
    tabItem(tabName = "Species",
            DT::dataTableOutput("Table1")),

    tabItem(tabName = "Spec",
            h2("Hi"))
  )
)

dashboardPage(skin = "blue", header = header, sidebar = sidebar, body = body)
</code>```

server.R

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

shinyServer(function(input, output, session){

  output$Table1 <- DT::renderDataTable({
    datatable(iris)
  })

})
</code>```

Body:
I have a dashboard where I would like to show a table, but I cant figure out why my table is not showing. If I replace the table for example with some text, h2(....) it does show. I would like to click on "Species" and have the table show on the right when clicking it.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL,
      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      ),
      actionButton("Gobtn", "Get data"),
      menuItem("Specs", tabName = "Specs", icon = NULL)
    )
  )),

  dashboardBody(tabItems(
    tabItem(tabName = "Species",
            DT::renderDataTable("Table1")),
    tabItem(tabName = "Specs",
            h2("Hi"))
  ))
)

server.r

  server <- shinyServer(function(input, output, session) {
  output$Table1 <- DT::renderDataTable({
    iris
  })
})

shinyApp(ui, server)

Body:
Few things to get your code up and running here. Couple have been noted by other contributors.

We need to use DT::dataTableOutput("Table1") on the UI side as renderDataTable will not work here, that is the server side function.

The other would be that using the switchInput within the menuItem may confused the app, as these are not standard parameters to pass into the function. From what I can see from your code, which is a common challenge, is that you want to be able to show this switchInput only when the 'Species' tab is selected. We can account for this using conditionalPanel. To do this, we can set id = "tabs" within the sidebarMenu and then reference this sidebarMenu within the conditionalPanel:

conditionalPanel(
  condition = "input.tabs== 'Species' ",
  switchInput(
    inputId = "long1",
    onLabel = "Go",
    offLabel = "NoGo",
    value = T
  )
)

To finish, I have altered the layouts of the ui.R and server.R, as the shinyApp function was not needed for the app to work with the server and ui files. This is how I lay out my dashboards. It may show you a few other possible ways you can use the app structure within Shiny, but equally you could just align the changes to the basic layout.

ui.R

header <- dashboardHeader(title = "Basic dashboard")

sidebar <- dashboardSidebar(
  sidebarMenu(id = "tabs",
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL),

    conditionalPanel(
      condition = "input.tabs== 'Species' ",
      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      )
    ),

    actionButton("Gobtn", "Get data"),

    menuItem("Specs", tabName = "Spec", icon = NULL)
  )
)

body <- dashboardBody(
  tabItems(
    tabItem(tabName = "Species",
            DT::dataTableOutput("Table1")),

    tabItem(tabName = "Spec",
            h2("Hi"))
  )
)

dashboardPage(skin = "blue", header = header, sidebar = sidebar, body = body)

server.R

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

shinyServer(function(input, output, session){

  output$Table1 <- DT::renderDataTable({
    datatable(iris)
  })

})


问:
Translate from sql statement to linq statment
How can I translate

```<code>select * from employees where (emp_id=@emp or @emp is null) and (dep_id=@dep or @dep is null)
</code>```

to a LINQ statment?

答:
C#

```<code>int empID = [whatever...]

var e = from e in db.Employees
        where e.emp_id == empID || e.emp_id == null
        select e;
</code>```

I'm assuming the @emp is null part is a typo, and you wanted emp_id is null. If not, just switch it around.

I'd suggest reading some more on LINQ.

Body:
How can I translate

select * from employees where (emp_id=@emp or @emp is null) and (dep_id=@dep or @dep is null)

to a LINQ statment?

Body:
C#

int empID = [whatever...]

var e = from e in db.Employees
        where e.emp_id == empID || e.emp_id == null
        select e;

I'm assuming the @emp is null part is a typo, and you wanted emp_id is null. If not, just switch it around.

I'd suggest reading some more on LINQ.


问:
How do you create a wiggle animation similar to iphone deletion animation
We are currently developing an application that contains a series of icons.  We want the icons to wiggle like the app deletion animations when pressed.  What would be the best way to code this animation sequence?</p>

答:
Answered in another thread a Swift 4 version of what is apparently Apple's own algorithm reverse engineered:
https://stackoverflow.com/a/47730519/5018607</p>


问:
c# - What would be more effective to remove null values from a list?
I want to remove all null values from a List in C# and i wonder what would be more effective and why?

Option #1:

```<code>myList.RemoveAll(item => item == null);
</code>```

Option #2:

```<code>myList = myList.Where(x => x != null).ToList();
</code>```

Thank you!

答:
The two approaches are very different in their semantics:

The first approach is "destructive," in the sense that myList is changed, while

The second approach is "non-destructive," as a new List is created. Your code also discards the original, but it does not need to do so.

Both ways of removing elements have O(n) time complexity. The second way requires creation of a new List, while the first way may require copying of the "tail" of the list. Overall, you should see reasonably similar performance when the number of items you keep is similar to the number of items you discard.

One situation when the first approach is a clear winner is when all items are non-null, in which case the method performs no copying or re-allocations. If you expect the search for null be unsuccessful most of the time, use the first approach.

Body:
I want to remove all null values from a List in C# and i wonder what would be more effective and why?

Option #1:

myList.RemoveAll(item => item == null);

Option #2:

myList = myList.Where(x => x != null).ToList();

Thank you!


问:
How to split String on two different chars
I already splitted the String value2 on the char "-" and saved its values in a new array as you can see. Now I wanna seperate the String again on the "," and save it again in a new array but it doesn't work. It always just seperates the second name with the number. And overrites the first. So I got in the first Array on [0]: Peter,2 and in [1]: Leo,1
and in the second array just on [0] Leo and on [1] 1.

I know my for loop is wrong and I don't know how to fix it.

```<code>    final int value = 2;
    final String value2 = "Peter,2-Leo,1";

    String[] splittedStringOne = new String[value];
    String[] splittedStringTwo = new String[splittedStringOne.length*2];

    splittedStringOne = value2.split("-");

    for(int i=0;i<splittedStringOne.length;i++) {
        splittedStringTwo=splittedStringOne[i].split(",");
</code>```

答:
You can use arraycopy to copy the result of splittedStringOne[i].split(","); to the correct position of splittedStringTwo

like:

```<code>public class ArrayCopyTest {

    @Test public void test() {
        final String value2 = "Peter,2-Leo,1";

        String[] splittedStringOne = value2.split("-");
        String[] splittedStringTwo = new String[splittedStringOne.length*2];

        for(int i=0;i<splittedStringOne.length;i++) {
            // splittedStringTwo = splittedStringOne[i].split(",");
            System.arraycopy(splittedStringOne[i].split(","), 0, splittedStringTwo, i * 2, 2);
        }
        Assert.assertArrayEquals(splittedStringTwo, new String[]{"Peter", "2", "Leo", "1"});
    }

}
</code>```

Body:
I already splitted the String value2 on the char "-" and saved its values in a new array as you can see. Now I wanna seperate the String again on the "," and save it again in a new array but it doesn't work. It always just seperates the second name with the number. And overrites the first. So I got in the first Array on [0]: Peter,2 and in [1]: Leo,1
and in the second array just on [0] Leo and on [1] 1.

I know my for loop is wrong and I don't know how to fix it.

    final int value = 2;
    final String value2 = "Peter,2-Leo,1";

    String[] splittedStringOne = new String[value];
    String[] splittedStringTwo = new String[splittedStringOne.length*2];

    splittedStringOne = value2.split("-");

    for(int i=0;i<splittedStringOne.length;i++) {
        splittedStringTwo=splittedStringOne[i].split(",");

Body:
You can use arraycopy to copy the result of splittedStringOne[i].split(","); to the correct position of splittedStringTwo

like:

public class ArrayCopyTest {

    @Test public void test() {
        final String value2 = "Peter,2-Leo,1";

        String[] splittedStringOne = value2.split("-");
        String[] splittedStringTwo = new String[splittedStringOne.length*2];

        for(int i=0;i<splittedStringOne.length;i++) {
            // splittedStringTwo = splittedStringOne[i].split(",");
            System.arraycopy(splittedStringOne[i].split(","), 0, splittedStringTwo, i * 2, 2);
        }
        Assert.assertArrayEquals(splittedStringTwo, new String[]{"Peter", "2", "Leo", "1"});
    }

}


问:
Can you explain why support v4 and v7 on android
I was checking support library for android, but i cant understand why they divided into v4 and v7 ?

Why just don't use one support library for all versions? Or even all classes on support, be on SDK properly?

答:
v4 support library and v7 support library both support android version 2.3(API level 9) and higher and required for backward compatibility for older devices.

difference

v4 has largest set of API's than others like App component, User Interface Feature, data handling ,network connectivity and utilities.

v7 provided specfic feature sets that can be included in your app independently.

There is also v7 AppCompact and v13 SupportLbrary :

v7 AppCompact - for ActionBar user interface and design . it required v4 also.

v13 SupportLbrary - android version 3.2(API level 13) and higher and supports fragment user interface Pattern


问:
Reading a fasta file format into python dictionary
I have a file with the following format:

```<code>>seq1
ATGGGTGTGTGTGTG
>seq2
ATGTGTTTGTGTGCTCCTCCTC
>seq3
AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA
</code>```

I want to read this file as a dictionary in Python. I am aware of BIO-python functions but I want to learn scripting in python in addition to getting my job done. I have tried this code so far:

```<code>import sys
sequence = ' '
fasta = {}
with open(sys.argv[1]) as file_one:
    file_one_content = file_one.read()
    for line in file_one_content.split("\n"):
        if not line.strip():
            continue
        if line.startswith(">"):
            sequence_name = line.rstrip('\n').replace(">", "")
        else:
            sequence = line.rstrip('\n')
        if sequence_name not in fasta:
            fasta[sequence_name] = []
        fasta[sequence_name].append(sequence)
print fasta
</code>```

I get the following output:

```<code>{'seq3': ['ATGTGTTTGTGTGCTCCTCCTC', 'AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2': ['ATGGGTGTGTGTGTG', 'ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': [' ', 'ATGGGTGTGTGTGTG']}
</code>```

My expected output file is:

{'seq3': ['AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2': ['ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': [ 'ATGGGTGTGTGTGTG']}

I have been trying to understand why the dictionary is printed in a wrong way but I can't find the mistake. As I want to learn, it would be great if you could let me know how I could correct the mistake in my code. Thanks.

答:
Using biopython SeqIO and a dict comprehension:</p>

```<code>from Bio import SeqIO
seq_dict = {rec.id : rec.seq for rec in SeqIO.parse("myfile.fasta", "fasta")}
</code>```

Body:
I have a file with the following format:

>seq1
ATGGGTGTGTGTGTG
>seq2
ATGTGTTTGTGTGCTCCTCCTC
>seq3
AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA

I want to read this file as a dictionary in Python. I am aware of BIO-python functions but I want to learn scripting in python in addition to getting my job done. I have tried this code so far:

import sys
sequence = ' '
fasta = {}
with open(sys.argv[1]) as file_one:
    file_one_content = file_one.read()
    for line in file_one_content.split("\n"):
        if not line.strip():
            continue
        if line.startswith(">"):
            sequence_name = line.rstrip('\n').replace(">", "")
        else:
            sequence = line.rstrip('\n')
        if sequence_name not in fasta:
            fasta[sequence_name] = []
        fasta[sequence_name].append(sequence)
print fasta

I get the following output:

{'seq3': ['ATGTGTTTGTGTGCTCCTCCTC', 'AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2': ['ATGGGTGTGTGTGTG', 'ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': [' ', 'ATGGGTGTGTGTGTG']}

My expected output file is:

{'seq3': ['AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2': ['ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': [ 'ATGGGTGTGTGTGTG']}

I have been trying to understand why the dictionary is printed in a wrong way but I can't find the mistake. As I want to learn, it would be great if you could let me know how I could correct the mistake in my code. Thanks.

Body:
Using biopython SeqIO and a dict comprehension:

from Bio import SeqIO
seq_dict = {rec.id : rec.seq for rec in SeqIO.parse("myfile.fasta", "fasta")}


答:
splittedStringTwo has to be 2 dimensional.

```<code>String[][] splittedStringTwo = new String[splitedStringOne.length][2];

for(int i =0; i < splittedStringTwo.length; i++)
    splittedStringTwo[i] = splittedStringOne[i].split(",");
</code>```

Or if you dont want a 2 dimensional array:

```<code>String[] splittedStringTwo = new String[splittedStringOne.length*2];

for(int i = 0; i < splittedStringTwo.length; i+=2){
    String[] split = splittedStringOne[i].split(",");
    splittedStringTwo[i] = split[0];
    splittedStringTwo[i+1] = split[1];
}
</code>```

EDIT:
For question in the comments. Try this out, it is not tested but it should work

```<code>String[][] splittedStringTwo = new String[splittedStringOne.length*2][2];

for(int i = 0; i < splittedStringTwo.length; i+=2){
    String[] split1 = splittedStringOne[i].split(",");
    String[] split2 = splittedStringOne[i+1].split(",");
    splittedStringTwo[i][0] = split1[0]
    splittedStringTwo[i][1] = split2[0];
    splittedStringTwo[i+1][0] = split1[1]
    splittedStringTwo[i+1][1] = split2[1];
}
</code>```

Title: How to split String on two different chars

Body:
splittedStringTwo has to be 2 dimensional.

String[][] splittedStringTwo = new String[splitedStringOne.length][2];

for(int i =0; i < splittedStringTwo.length; i++)
    splittedStringTwo[i] = splittedStringOne[i].split(",");

Or if you dont want a 2 dimensional array:

String[] splittedStringTwo = new String[splittedStringOne.length*2];

for(int i = 0; i < splittedStringTwo.length; i+=2){
    String[] split = splittedStringOne[i].split(",");
    splittedStringTwo[i] = split[0];
    splittedStringTwo[i+1] = split[1];
}

EDIT:
For question in the comments. Try this out, it is not tested but it should work

String[][] splittedStringTwo = new String[splittedStringOne.length*2][2];

for(int i = 0; i < splittedStringTwo.length; i+=2){
    String[] split1 = splittedStringOne[i].split(",");
    String[] split2 = splittedStringOne[i+1].split(",");
    splittedStringTwo[i][0] = split1[0]
    splittedStringTwo[i][1] = split2[0];
    splittedStringTwo[i+1][0] = split1[1]
    splittedStringTwo[i+1][1] = split2[1];
}


问:
SnapLogic - can you paramertize db connection
In SnapLogic, is there a way to paramertize the database connection info so you can create a reusable pipeline that can pass the db connection info for the account of a select snap?  </p>

答:
The database connection information cannot be passed as parameters (and it should not be). You have to create separate accounts for each connection.

As per this answer here, you can pass the account name as a pipeline parameter and configure the database read snap to connect to whatever instance it is supposed to connect to.

A better way to do this is to have an expression library file that will contain the account information and pass the schema name and table name as pipeline parameters. In this way, you can use the same pipeline to extract data from different tables in various schema using the same connection. This can be done by dragging and dropping this pipeline wherever you need it or using pipeline execute to call it from a different pipeline. You can maintain multiple such expression library files configured to different accounts.

Creating a pipeline with schema name and table name passed as pipeline parameter and an expression library file containing the account information:

Configuring the schema name and table name in the settings tab of the snap:

Getting the account information from the expression library file:

The expression library file config.expr used in this example:

```<code>{
  "account": "../shared/TEST"
}
</code>```

It works:

Note: As you can see, I created a Generic Database Account named TEST in the shared folder of the project space I was working in. This account contains all the connection information.

Hope this helps :)

Body:
The database connection information cannot be passed as parameters (and it should not be). You have to create separate accounts for each connection.

As per this answer here, you can pass the account name as a pipeline parameter and configure the database read snap to connect to whatever instance it is supposed to connect to.

A better way to do this is to have an expression library file that will contain the account information and pass the schema name and table name as pipeline parameters. In this way, you can use the same pipeline to extract data from different tables in various schema using the same connection. This can be done by dragging and dropping this pipeline wherever you need it or using pipeline execute to call it from a different pipeline. You can maintain multiple such expression library files configured to different accounts.

Creating a pipeline with schema name and table name passed as pipeline parameter and an expression library file containing the account information:

Configuring the schema name and table name in the settings tab of the snap:

Getting the account information from the expression library file:

The expression library file config.expr used in this example:

{
  "account": "../shared/TEST"
}

It works:

Note: As you can see, I created a Generic Database Account named TEST in the shared folder of the project space I was working in. This account contains all the connection information.

Hope this helps :)


问:
Javascript method chaining on slice not working
I am trying to reorganize an array to use it in a for loop.
I have tried slicing it then merging with sliced elements but i get the error

```<code>TypeError: images.slice(...).merge is not a function
</code>```

Here is an example of what I am trying

```<code>var images = ["0", "1", "2", "3", "4", "5"];
var f_iamges = images.slice(2).merge(images.slice(0, 2))

console.log(f_iamges)
</code>```

I expected output ["2", "3", "4", "5", "0", "1"]
I also want the original copy to remain unchanged.

答:
Try with concat:

```<code>images.slice(2).concat(images.slice(0, 2))
</code>```

Body:
I am trying to reorganize an array to use it in a for loop.
I have tried slicing it then merging with sliced elements but i get the error

TypeError: images.slice(...).merge is not a function

Here is an example of what I am trying

var images = ["0", "1", "2", "3", "4", "5"];
var f_iamges = images.slice(2).merge(images.slice(0, 2))

console.log(f_iamges)

I expected output ["2", "3", "4", "5", "0", "1"]
I also want the original copy to remain unchanged.

Body:
Try with concat:

images.slice(2).concat(images.slice(0, 2))


问:
how can i sort 2 dimensional array based on index array in PHP?
I have an array in PHP like this :

Array
(
    [0] => Array
        (
            [0] => black
            [2] => brown
            [1] => red
        )

```<code>[1] => Array
    (
        [2] => car
        [0] => bicycle
        [1] => motorcycle
    )
</code>```

)

How do I get the array, like this :

Result:

Array
(
    [0] => Array
        (
            [0] => black
            [1] => red
            [2] => brown
        )

```<code>[1] => Array
    (

        [0] => bicycle
        [1] => motorcycle
        [2] => car
    )
</code>```

)

Thanks

答: Use the krsort() function to sort an associative array in descending order, according to the key.</p>

Body:
I have an array in PHP like this :

Array
(
    [0] => Array
        (
            [0] => black
            [2] => brown
            [1] => red
        )

[1] => Array
    (
        [2] => car
        [0] => bicycle
        [1] => motorcycle
    )

)

How do I get the array, like this :

Result:

Array
(
    [0] => Array
        (
            [0] => black
            [1] => red
            [2] => brown
        )

[1] => Array
    (

        [0] => bicycle
        [1] => motorcycle
        [2] => car
    )

)

Thanks


问:
FireFox word breaks OK with css, but one letter at a time, not where hyphens go
FireFox word breaks OK with css, but one letter at a time, not where hyphens are supposed to be???

NOT FireFox:

FireFox:

Here's the CSS:

```<code>.superLongStuff {
    /*
        SUPER LOOOOOOOOOOOONG WORD STUFF ...
    */
    /* These are technically the same, but use both */
    overflow-wrap: break-word;
    word-wrap:     break-word;

    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break:     break-all;
    /* Instead use this non-standard one: */
    word-break:     break-word;

    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}
</code>```

答:
Remove the word-wrap when you're using hyphens. Since, you used word-wrap they will just wrap where the word is breaking to the next line.

We use hyphens to demonstrate or show which word is being continued in the next line, but break-word divides the word into two and it's no longer a single segment of word that's why you don't see any hyphen.

Here's the demonstration of both:

#a {
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}

#b {
  overflow-wrap: break-word;
  word-wrap: break-word;
  -ms-word-break: break-all;
  word-break: break-all;
  word-break: break-word;
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article id="a" lang="en">
  <h1>Article A</h1>
  <p>As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible.For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you. The purpose of this is so the person viewing the prototype has a chance
    to actually feel and understand the idea behind what you have created.
  Now in some circumstances, designers may use squares and rectangles to help you visualize what should and could be in a specific location.We all have our own techniques, but one of the most effective techniques is to actually put some text where text goes and some pictures where pictures go to make sure everyone can see the vision you’ve created.
Coming up with filler text on the fly is not easy, but it is becoming more and more of a requirement. Fortunately, some designers and developers around the web know this and have put together a bunch of text generators to help you present your vision.Some are standard (like the always popular ‘Lorem Ipsum’ generators) and some are really fun. Either way, pick one of your favorites from below and start generating text and completing your vision.</p>
</article>
<br><br><hr><br>
<article id="b" lang="en">
<h1>Article B</h1>
  <p>As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible.For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you. The purpose of this is so the person viewing the prototype has a chance
    to actually feel and understand the idea behind what you have created.
  Now in some circumstances, designers may use squares and rectangles to help you visualize what should and could be in a specific location.We all have our own techniques, but one of the most effective techniques is to actually put some text where text goes and some pictures where pictures go to make sure everyone can see the vision you’ve created.
Coming up with filler text on the fly is not easy, but it is becoming more and more of a requirement. Fortunately, some designers and developers around the web know this and have put together a bunch of text generators to help you present your vision.Some are standard (like the always popular ‘Lorem Ipsum’ generators) and some are really fun. Either way, pick one of your favorites from below and start generating text and completing your vision.</p>
</article></code>```

Body:
FireFox word breaks OK with css, but one letter at a time, not where hyphens are supposed to be???

NOT FireFox:

FireFox:

Here's the CSS:

.superLongStuff {
    /*
        SUPER LOOOOOOOOOOOONG WORD STUFF ...
    */
    /* These are technically the same, but use both */
    overflow-wrap: break-word;
    word-wrap:     break-word;

    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break:     break-all;
    /* Instead use this non-standard one: */
    word-break:     break-word;

    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}

Body:
Remove the word-wrap when you're using hyphens. Since, you used word-wrap they will just wrap where the word is breaking to the next line.

We use hyphens to demonstrate or show which word is being continued in the next line, but break-word divides the word into two and it's no longer a single segment of word that's why you don't see any hyphen.

Here's the demonstration of both:

#a {
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}

#b {
  overflow-wrap: break-word;
  word-wrap: break-word;
  -ms-word-break: break-all;
  word-break: break-all;
  word-break: break-word;
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}

<article id="a" lang="en">
  <h1>Article A</h1>
  <p>As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible.For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you. The purpose of this is so the person viewing the prototype has a chance
    to actually feel and understand the idea behind what you have created.
  Now in some circumstances, designers may use squares and rectangles to help you visualize what should and could be in a specific location.We all have our own techniques, but one of the most effective techniques is to actually put some text where text goes and some pictures where pictures go to make sure everyone can see the vision you’ve created.
Coming up with filler text on the fly is not easy, but it is becoming more and more of a requirement. Fortunately, some designers and developers around the web know this and have put together a bunch of text generators to help you present your vision.Some are standard (like the always popular ‘Lorem Ipsum’ generators) and some are really fun. Either way, pick one of your favorites from below and start generating text and completing your vision.</p>
</article>
<br><br><hr><br>
<article id="b" lang="en">
<h1>Article B</h1>
  <p>As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible.For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you. The purpose of this is so the person viewing the prototype has a chance
    to actually feel and understand the idea behind what you have created.
  Now in some circumstances, designers may use squares and rectangles to help you visualize what should and could be in a specific location.We all have our own techniques, but one of the most effective techniques is to actually put some text where text goes and some pictures where pictures go to make sure everyone can see the vision you’ve created.
Coming up with filler text on the fly is not easy, but it is becoming more and more of a requirement. Fortunately, some designers and developers around the web know this and have put together a bunch of text generators to help you present your vision.Some are standard (like the always popular ‘Lorem Ipsum’ generators) and some are really fun. Either way, pick one of your favorites from below and start generating text and completing your vision.</p>
</article>


问:
Is Gesture typing a part of AOSP LatinIME?
I can build the AOSP Stock keyboard (LatinIME) from source available here but gesture typing does not seem to work. Some sources tell me that gesture typing is not a part of AOSP as it is proprietary to Google. Is it true?</p>

答: Indeed, it is true that swipe/gesture typing is not included in the AOSP app. If you want, you can, however, extract the library used for this from the GApps and manually install it.</p>


问:
Is there a way to get CommandText after replacing parameter values, programmatically?
Is there a way to get CommandText after replacing paramater values programmatically in .NET?

Assume we have a command:

```<code>let cmd = conn.CreateCommand()
cmd.CommandText <- "select * from smsqueue where smsqueueid=:pid"
cmd.CommandType <- CommandType.Text
cmd.Parameters.Add("pid", 0)
</code>```

I want to get the prepared command text; which would be like this:

```<code>select * from smsqueue where smsqueueid=0
</code>```

There are profilers to get this information, but I want to do this explicitly in code (e.g., F# or C#).

答:
The replacement probably won't be performed in text - indeed it would be more hassle to do so. Why bother working out how to escape strings, represents dates in a particular text format etc when the driver can transmit them separately in a pre-planned binary format?

What goal are you trying to achieve? If this is for the purpose of logging, I would just log the command text and the parameters separately. Apart from being easier, that will make it clearer if you end up with a problem: you'll be able to tell whether the SQL was properly parameterized or not.

Body:
Is there a way to get CommandText after replacing paramater values programmatically in .NET?

Assume we have a command:

let cmd = conn.CreateCommand()
cmd.CommandText <- "select * from smsqueue where smsqueueid=:pid"
cmd.CommandType <- CommandType.Text
cmd.Parameters.Add("pid", 0)

I want to get the prepared command text; which would be like this:

select * from smsqueue where smsqueueid=0

There are profilers to get this information, but I want to do this explicitly in code (e.g., F# or C#).


问:
Getting Time out error and run time error in test case 2 and 3 in hackerrank. How to resolve this?
The objective of this code is to print sum of multiples of 3 and 5 between given range. In hackerrank, I am getting error in test case 2 and 3. Anyone knows how to resolve the issue?</p>

```<code>t =int(raw_input())
for i in range(0,t):
range = int(raw_input())
a=3
b=5
aa=[]
res=[]
def forA(a):  #Calculating Multiple of 3
    while True:
        if a >=range :
            a = a-3
            break
        else:
            aa.append(a)
            a += 3;

def forB(b):  #Calculating Multiple of 5
    while True:
        if b >=range :
            b=b-5
            return b
            break
        else:
            aa.append(b)
            b += 5;

forA(a)
forB(b)
for i in aa:    #eliminate duplicate values of multiples.
    if i not in res:
        res.append(i)

print sum(res)
</code>```

答:
This might resolve your problems because it uses pythons builtin features that are "smart" instead of creating a list one item a time yourself. Therefore they are faster... which might solve the timing errors you get.

You get all the numbers up to your input from 3 or 5 till t by

```<code>from itertools import chain
t =15

threes = range(0,t+1,3) # range provides [lower..higher[ not including higher value
fives = range(0,t+1,5)

sums = sum(chain(threes,fives)) # without itertools: sums=sum(threes) + sum(fives)
print(threes)
print(fives)
print(sums)
</code>```

If you want to avoid multiples, avoid chain(..), uses sets and join them together before summing them up

```<code>s = set(threes) | set(fives)

print(sum(s))
</code>```

Output:

```<code>[0, 3, 6, 9, 12, 15] # threes up to 15
[0, 5, 10, 15] # fives up to 15
75 # sum of chained ones
60 # sum of set
</code>```

Body:
The objective of this code is to print sum of multiples of 3 and 5 between given range. In hackerrank, I am getting error in test case 2 and 3. Anyone knows how to resolve the issue?

t =int(raw_input())
for i in range(0,t):
range = int(raw_input())
a=3
b=5
aa=[]
res=[]
def forA(a):  #Calculating Multiple of 3
    while True:
        if a >=range :
            a = a-3
            break
        else:
            aa.append(a)
            a += 3;

def forB(b):  #Calculating Multiple of 5
    while True:
        if b >=range :
            b=b-5
            return b
            break
        else:
            aa.append(b)
            b += 5;

forA(a)
forB(b)
for i in aa:    #eliminate duplicate values of multiples.
    if i not in res:
        res.append(i)

print sum(res)

Body:
This might resolve your problems because it uses pythons builtin features that are "smart" instead of creating a list one item a time yourself. Therefore they are faster... which might solve the timing errors you get.

You get all the numbers up to your input from 3 or 5 till t by

from itertools import chain
t =15

threes = range(0,t+1,3) # range provides [lower..higher[ not including higher value
fives = range(0,t+1,5)

sums = sum(chain(threes,fives)) # without itertools: sums=sum(threes) + sum(fives)
print(threes)
print(fives)
print(sums)

If you want to avoid multiples, avoid chain(..), uses sets and join them together before summing them up

s = set(threes) | set(fives)

print(sum(s))

Output:

[0, 3, 6, 9, 12, 15] # threes up to 15
[0, 5, 10, 15] # fives up to 15
75 # sum of chained ones
60 # sum of set