问:
List and Array of structs value vs variable
I'm trying to understand/reconcile my understanding of how C# structs operate when chaining using List and Arrays.  I follow Eric's explanation in this post
Performance of array of struct types

but I'm taking this one step further.

struct Foo { public int A; public int B; public Foo[] ChildFoos; }

Foo parentFoo = new Foo();
parentFoo.ChildFoos = new Foo[1];
parentFoo.ChildFoos[0] = new Foo();

List<Foo> list = new List<Foo>();
list.Add(parentFoo);
```

<p>But the behavior changes when you chain the calls.  list[0] should be returning a value (not a variable) where as ChildFoos[0] should be returning a variable.</p>

<pre class="lang-cs prettyprint-override"><code>list[0].ChildFoos[0].A = 4545;
</code>```

In this case what appears to be happening is list[0] is being treated as a variable instead of a value.  ChildFoos[0].A maintains it's new value in the parentFoo within the List.  How is this possible?

Compare this with attempting to set A on the parent Foo struct which won't compile.

list[0].A = 877;
```

This will not compile

答:
So, as you have correctly stated, list[0] is a copy of the value in the list.  It's a value, and not a variable.  One of the values in that struct is ChildFoos.  The value of that field is not a whole bunch of Foo instances; instead it's a reference to a bunch of information stored elsewhere (because arrays are reference types).  The copy of the Foo instance you're given back has a copy of the reference that the instance inside of the list has.

If you were to mutate the reference itself, say by assigning a new array to ChildFoos, you'd see the same error that you see when you try to mutate any other field of that struct, like when you try to mutate A.  As it is you're only reading the value of the reference that the struct stores (and not mutating the struct instance), then going and getting the first item in that array, and since the array indexer return a variable, not a value (again, as you noted correctly in the question) mutating that returned Foo instance is mutating the instance in the array, as it's not a copy, so when you access that same array again, later, you'll be able to observe the change.

Body:
I'm trying to understand/reconcile my understanding of how C# structs operate when chaining using List and Arrays.  I follow Eric's explanation in this post
Performance of array of struct types

but I'm taking this one step further.

struct Foo { public int A; public int B; public Foo[] ChildFoos; }

Foo parentFoo = new Foo();
parentFoo.ChildFoos = new Foo[1];
parentFoo.ChildFoos[0] = new Foo();

List<Foo> list = new List<Foo>();
list.Add(parentFoo);

But the behavior changes when you chain the calls.  list[0] should be returning a value (not a variable) where as ChildFoos[0] should be returning a variable.

list[0].ChildFoos[0].A = 4545;

In this case what appears to be happening is list[0] is being treated as a variable instead of a value.  ChildFoos[0].A maintains it's new value in the parentFoo within the List.  How is this possible?

Compare this with attempting to set A on the parent Foo struct which won't compile.

list[0].A = 877;

This will not compile


来源: stackexchange

问:
hide lines of text not fully visible with javascript & css
I think this might be impossible, but is there some way using JQuery to prevent lines of text not fully visible from showing up on the screen when a user scrolls until the entire line is visible? That is, we want to prevent something like this from showing up:

Thanks!

答:
I believe I have had this problem also, in that you have a div with a specific height and overflow hidden.

Thinking about it i would resize the div based on the line-height of the text in the div.

Change the height of div so that it equals a multiple of the line height of the containing text....
ie 3 lines of text with line-height = 16 change the div height from 50 to 48px.

( i posted this at the same time as rahmanisback'  answer )

ContentLicense: CC BY-SA 2.5


问:
Specific regex not working in R
I'm trying to find whether a string pattern; (<double num><space><an operator><space><double num>) e.g. (14.0 + 46.0) exists in a given string using a regex in R. There can be 4 operators +,-,* and /.

There are two main patterns. Regex for the 1st pattern identifies that the pattern exists in the string "s"

```<code>#Pattern 1
s = "(14.0 + 46.0)"

#Regex
grep("^\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\)$", s)
</code>```

I'm trying to find the same pattern in a different string s1 and s2. I modified the first regex by adding .*  (any character) to the beginning and end of the string ("^.*   .*$"). I have checked the regex in this online checker and it works. But it doesn't work in R studio.

```<code>#Pattern 2
s1 = "((5.0 - 50.0) - 15.0)"
s2 = "(15.0 - (5.0 - 50.0))"

#Regex
grep("^.*\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*$", s1)
</code>```

答:
Brief

Just to explain why I made so many changes to your regex (I actually just rewrote it).

You use {1}. While this is valid, it is redundant, so the {1} can be removed.

You don't need to escape every character in a list, only specific ones (i.e. slash and hyphen, but only hyphen when it's not at the start/end of the set or after a range - so I moved it to the start of the set).

Your regex allows .1 to be valid, not sure if that was intentional, and if it was you can edit my regex to your liking. I just felt that a more correct solution would force a number before the . such that .1 is invalid, but 0.1 is valid.

You have repeating parts in your pattern so I changed these to named capture groups. This allows the pattern to be very easily manipulated to your liking. It also allows you to define pattern parts in one location instead of multiple spots. - Recursion

Recursion is the only way (or balancing groups in C#) that I know of that you can properly determine matched open/closing tags (in this case left and right parentheses). The g group in my pattern handles the recursion.

Code

See regex in use here

```<code>(?(DEFINE)
  (?<n>[-+]?\d+(?:\.\d+)?)
  (?<a>\s*[-+*\/]\s*)
  (?<g>\((?:(?&n)|(?&g))(?&a)(?:(?&n)|(?&g))\))
)
^(?&g)$
</code>```

Flags: gmx

Usage

See the code in use here

```<code>r <- "(?(DEFINE)(?<n>[-+]?\\d+(?:\\.\\d+)?)(?<a>\\s*[-+*\\/]\\s*)(?<g>\\((?:(?&n)|(?&g))(?&a)(?:(?&n)|(?&g))\\)))^(?&g)$"
x <- c("(14.0 + 46.0)", "((5.0 - 50.0) - 15.0)", "(15.0 - (5.0 - 50.0))", "(15.0 - (5.0 - 50.0)")
grep(r, x, perl=TRUE)
</code>```

Results

Input

```<code>(14.0 + 46.0)
((5.0 - 50.0) - 15.0)
(15.0 - (5.0 - 50.0))
</code>```

Output

Only matches shown below.

```<code>(14.0 + 46.0)
((5.0 - 50.0) - 15.0)
(15.0 - (5.0 - 50.0))
</code>```

Explanation

(?(DEFINE)) Subpattern definition construct. This is completely ignored by regex. It gets treated as a var name="value", whereas you can recall the specific pattern for use via its name.

(?<n>[-+]?\d+(?:\.\d+)?) Subpattern n defines a valid number as follows

[-+]? Match zero or one of any character in the set -+

\d+ Match any digit one or more times

(?:\.\d+)? Match zero or one of a literal dot . followed by one or more digits

(?\s*[-+*\/]\s*) Subpattern a defines all valid arithmetic symbols

\s* Match any number of whitespace characters

[-+*\/] Match a character in the set -+*/

\s* Match any number of whitespace characters

(?<g>\((?:(?&n)|(?&g))(?&a)(?:(?&n)|(?&g))\)) Match the following

\( Match a literal left parenthesis (

(?:(?&n)|(?&g)) Match either the n or g patterns (recursion)

(?&a) Match the a pattern (recursion)

(?:(?&n)|(?&g)) Match either the n or g patterns (recursion)

\) Match a literal right parenthesis )

^(?&g)$ Match the following

^ Assert position at the end of the line

(?&g) Match the g pattern (recursion)

$ Assert position at the end of the line

ContentLicense: CC BY-SA 3.0

Title: Specific regex not working in R

Body:
I'm trying to find whether a string pattern; (<double num><space><an operator><space><double num>) e.g. (14.0 + 46.0) exists in a given string using a regex in R. There can be 4 operators +,-,* and /.

There are two main patterns. Regex for the 1st pattern identifies that the pattern exists in the string "s"

#Pattern 1
s = "(14.0 + 46.0)"

#Regex
grep("^\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\)$", s)

I'm trying to find the same pattern in a different string s1 and s2. I modified the first regex by adding .*  (any character) to the beginning and end of the string ("^.*   .*$"). I have checked the regex in this online checker and it works. But it doesn't work in R studio.

#Pattern 2
s1 = "((5.0 - 50.0) - 15.0)"
s2 = "(15.0 - (5.0 - 50.0))"

#Regex
grep("^.*\\(-?\\d*\\.\\d{1}\\s[\\+\\-\\*\\/]\\s-?\\d*\\.\\d{1}\\).*$", s1)

Body:
Brief

Just to explain why I made so many changes to your regex (I actually just rewrote it).

You use {1}. While this is valid, it is redundant, so the {1} can be removed.

You don't need to escape every character in a list, only specific ones (i.e. slash and hyphen, but only hyphen when it's not at the start/end of the set or after a range - so I moved it to the start of the set).

Your regex allows .1 to be valid, not sure if that was intentional, and if it was you can edit my regex to your liking. I just felt that a more correct solution would force a number before the . such that .1 is invalid, but 0.1 is valid.

You have repeating parts in your pattern so I changed these to named capture groups. This allows the pattern to be very easily manipulated to your liking. It also allows you to define pattern parts in one location instead of multiple spots. - Recursion

Recursion is the only way (or balancing groups in C#) that I know of that you can properly determine matched open/closing tags (in this case left and right parentheses). The g group in my pattern handles the recursion.

Code

See regex in use here

(?(DEFINE)
  (?<n>[-+]?\d+(?:\.\d+)?)
  (?<a>\s*[-+*\/]\s*)
  (?<g>\((?:(?&n)|(?&g))(?&a)(?:(?&n)|(?&g))\))
)
^(?&g)$

Flags: gmx

Usage

See the code in use here

r <- "(?(DEFINE)(?<n>[-+]?\\d+(?:\\.\\d+)?)(?<a>\\s*[-+*\\/]\\s*)(?<g>\\((?:(?&n)|(?&g))(?&a)(?:(?&n)|(?&g))\\)))^(?&g)$"
x <- c("(14.0 + 46.0)", "((5.0 - 50.0) - 15.0)", "(15.0 - (5.0 - 50.0))", "(15.0 - (5.0 - 50.0)")
grep(r, x, perl=TRUE)

Results

Input

(14.0 + 46.0)
((5.0 - 50.0) - 15.0)
(15.0 - (5.0 - 50.0))

Output

Only matches shown below.

(14.0 + 46.0)
((5.0 - 50.0) - 15.0)
(15.0 - (5.0 - 50.0))

Explanation

(?(DEFINE)) Subpattern definition construct. This is completely ignored by regex. It gets treated as a var name="value", whereas you can recall the specific pattern for use via its name.

(?<n>[-+]?\d+(?:\.\d+)?) Subpattern n defines a valid number as follows

[-+]? Match zero or one of any character in the set -+

\d+ Match any digit one or more times

(?:\.\d+)? Match zero or one of a literal dot . followed by one or more digits

(?<a>\s*[-+*\/]\s*) Subpattern a defines all valid arithmetic symbols

\s* Match any number of whitespace characters

[-+*\/] Match a character in the set -+*/

\s* Match any number of whitespace characters

(?<g>\((?:(?&n)|(?&g))(?&a)(?:(?&n)|(?&g))\)) Match the following

\( Match a literal left parenthesis (

(?:(?&n)|(?&g)) Match either the n or g patterns (recursion)

(?&a) Match the a pattern (recursion)

(?:(?&n)|(?&g)) Match either the n or g patterns (recursion)

\) Match a literal right parenthesis )

^(?&g)$ Match the following

^ Assert position at the end of the line

(?&g) Match the g pattern (recursion)

$ Assert position at the end of the line


问:
Tensorboard Expand Node Glitch
I keep unexpectedly running into some kind of weird glitch where Tensorboard fails to expand a node in the graph. When I hit the plus button (in the top right of the node) the node doesn't expand. Instead, the name of the node gets slightly larger. Hitting the minus sign reverses the effect.

Has anyone run into this before? If so, how and or why does it happen?

答: Fixed it by upgrading Tensorflow from 1.1 to 1.4.</p>

Title: Tensorboard Expand Node Glitch


问:
Building triangle with nested loops
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);```

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

答:
The reason your code does it is you are updating line on each iteration and you keep appending to it. If you want to do the nested loops, than you need to reset the variable line each time you are in the outer loop.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  line =""
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);```
</div>
</div>
</p>

<p>Or you can keep what you have and dump the inner loop and every iteration you just add one character to the line.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  line += "#";
  triangle += line + "\n";
}

console.log(triangle);</code>```

Title: Building triangle with nested loops

Body:
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

Body:
The reason your code does it is you are updating line on each iteration and you keep appending to it. If you want to do the nested loops, than you need to reset the variable line each time you are in the outer loop.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  line =""
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);

Or you can keep what you have and dump the inner loop and every iteration you just add one character to the line.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  line += "#";
  triangle += line + "\n";
}

console.log(triangle);


问:
Should I use the  element?
I've stumbled about the  element on w3schools but as far as caniuse.com told me, the element isn't supported by IE, Opera Mini and the UC Browser for Android.

Would I be better by going with a  element or should I stick with a
?

答:
From the looks of it I wouldn't worry about compatibility, unless you are trying to support IE 8 and below.. You can cover all your bases by using both  per MDN

The  element is widely supported. For Internet Explorer 11 and
  below, it is suggested that an ARIA role of "main" be added to the
   element to ensure it is accessible (screen readers like JAWS,
  used in combination with older versions of Internet Explorer, will be
  able to understand the semantic meaning of the  element once
  this role attribute is included).

Title: Should I use the <main> element?

Body:
From the looks of it I wouldn't worry about compatibility, unless you are trying to support IE 8 and below.. You can cover all your bases by using both <main role="main"> per MDN

The  element is widely supported. For Internet Explorer 11 and
  below, it is suggested that an ARIA role of "main" be added to the
   element to ensure it is accessible (screen readers like JAWS,
  used in combination with older versions of Internet Explorer, will be
  able to understand the semantic meaning of the  element once
  this role attribute is included).


问:
JSON encode MySQL results
How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?

答:
Try this, this will create your object properly</p>

```<code> $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);
</code>```

OwnerDisplayName: Trick Jarrett

Title: JSON encode MySQL results

Body:
Try this, this will create your object properly

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);


问:
What should be size of query for creating a view in redshift using java program
I am able to create view in redshift with the size of approx 12kb data but when I increased the size of query it terminate and give below error

java.sql.SQLException: Amazon The server closed the connection.
      at com.amazon.support.channels.TLSSocketChannel.read(Unknown Source)
  Caused by: com.amazon.support.exceptions.GeneralException: Amazon The server closed the connection.
      ... 1 more.

Can anybody tell me if there is any limitation in java to send number of queries to database or any property is there after adding it should we able to run it.

答:
Redshift limits are documented here. The ones relevant for you:

The number of concurrent user connections that can be made to a cluster is 500.

A workload management (WLM) configuration can define a total concurrency level of 50 for all user-defined queues. For more information, see Defining Query Queues in the Amazon Redshift Database Developer Guide.

If there are more queries than the concurrency level, then the queries wait in a queue to be processed.

So unless you have 500 user connections I don't expect that your connection issues are a result of the number of queries sent to the database.


问:
CDATA section as string using service reference
Using c# and visual studio 2015

I'm working with an external webservice and I have build a service reference using a delivered WSDL. That is all working, and I can call the service, but I get a error because the request is not in correct format...

Part of the service definition is this:

```<code><xsd:complexType name="GCTPLookupRequestType">
    <xsd:sequence>
    <xsd:element name="gctpMessage" type="xsd:string" minOccurs="1" maxOccurs="1" />
    </xsd:sequence>
  </xsd:complexType>
</code>```

The gctpMessage is a string element but is expected to contain a CDATA section like this:

```<code><![CDATA[
<Gctp v="1.0">
<System r="CprSoeg">
<Service r="STAM+">
<CprServiceHeader r="STAM+">
<Key>
<Field r="PNR" v="0000000000"/>
</Key>
</CprServiceHeader>
</Service>
</System>
</Gctp>
]]>
</code>```

If I append this as a string as expected to the gctpMessage property all seems fine, but when I inspect the request using Fiddler I se that it is all wrong:

```<code><gctpMessage>
<![CDATA[<Gctp v="1.0"><System r="CprSoeg"><
Service r="STAM+"><CprServiceHeader r="STAM+"><Key><
Field r="PNR" v="0000000000"/></Key></CprServiceHeader></
Service></System></Gctp>]]>
</gctpMessage>
</code>```

I know this is caused by the XML serializer enterpreting this as a string and therefore escapes the tags.

But how do I get around this? The WSDL has defined it as a string and I really want to use the service reference but I do not know how to handle this...
Changing the service is not an option.

Any suggestion would be appriciated :)

答:
Just perfect dbc, it did the trick :)

Thanks for that..

```<code>  [System.Xml.Serialization.XmlIgnore]
        public string gctpMessage {
            get {
                return this.gctpMessageField;
            }
            set {
                this.gctpMessageField = value;
                this.RaisePropertyChanged("gctpMessage");
            }
        }

        [System.Xml.Serialization.XmlElementAttribute(Order = 1, ElementName = "gctpMessage")]
        public XmlNode[] CDataContent
        {
            get
            {
                var dummy = new XmlDocument();
                return new XmlNode[] { dummy.CreateCDataSection(gctpMessage) };
            }
            set
            {
                if (value == null)
                {
                    gctpMessage = null;
                    return;
                }

                if (value.Length != 1)
                {
                    throw new InvalidOperationException(
                        String.Format(
                            "Invalid array length {0}", value.Length));
                }

                gctpMessage = value[0].Value;
            }
        }
</code>```

Body:
Using c# and visual studio 2015

I'm working with an external webservice and I have build a service reference using a delivered WSDL. That is all working, and I can call the service, but I get a error because the request is not in correct format...

Part of the service definition is this:

<xsd:complexType name="GCTPLookupRequestType">
    <xsd:sequence>
    <xsd:element name="gctpMessage" type="xsd:string" minOccurs="1" maxOccurs="1" />
    </xsd:sequence>
  </xsd:complexType>

The gctpMessage is a string element but is expected to contain a CDATA section like this:

<![CDATA[
<Gctp v="1.0">
<System r="CprSoeg">
<Service r="STAM+">
<CprServiceHeader r="STAM+">
<Key>
<Field r="PNR" v="0000000000"/>
</Key>
</CprServiceHeader>
</Service>
</System>
</Gctp>
]]>

If I append this as a string as expected to the gctpMessage property all seems fine, but when I inspect the request using Fiddler I se that it is all wrong:

<gctpMessage>
<![CDATA[<Gctp v="1.0"><System r="CprSoeg"><
Service r="STAM+"><CprServiceHeader r="STAM+"><Key><
Field r="PNR" v="0000000000"/></Key></CprServiceHeader></
Service></System></Gctp>]]>
</gctpMessage>

I know this is caused by the XML serializer enterpreting this as a string and therefore escapes the tags.

But how do I get around this? The WSDL has defined it as a string and I really want to use the service reference but I do not know how to handle this...
Changing the service is not an option.

Any suggestion would be appriciated :)

Body:
Just perfect dbc, it did the trick :)

Thanks for that..

  [System.Xml.Serialization.XmlIgnore]
        public string gctpMessage {
            get {
                return this.gctpMessageField;
            }
            set {
                this.gctpMessageField = value;
                this.RaisePropertyChanged("gctpMessage");
            }
        }

        [System.Xml.Serialization.XmlElementAttribute(Order = 1, ElementName = "gctpMessage")]
        public XmlNode[] CDataContent
        {
            get
            {
                var dummy = new XmlDocument();
                return new XmlNode[] { dummy.CreateCDataSection(gctpMessage) };
            }
            set
            {
                if (value == null)
                {
                    gctpMessage = null;
                    return;
                }

                if (value.Length != 1)
                {
                    throw new InvalidOperationException(
                        String.Format(
                            "Invalid array length {0}", value.Length));
                }

                gctpMessage = value[0].Value;
            }
        }


问:
Apple XCode on multiple machines (how to take my project with me?)
I mainly develop iOS applications on a Mac desktop, but sometimes I travel with a MacBook Air laptop and I often need to continue working on an app while on the road.

Of course, it's possible to just scp the files to my laptop, work on it, then scp it back to the desktop, or use a thumb drive. But I have to believe that thousands of others have a similar need.  Is there a simple way to share the source control and just check in/out while on the road?

What are the best practices for smooth, single-developer track development on multiple devices?

答: Use a free BitBucket account, combined with SourceTree. Apart from being able to use this on multiple computers, you also have version control and backup for free. </p>


问:
Different font rendering between Chrome and Firefox
With the new update of Firefox (Quantum) I decided to do switch between Chrome and Firefox
Meanwhile, I noticed some differences in font rendering between the two browsers.

The CSS used in these two browsers is strictly identical, but the "smooth" renderring is totally different.
Do you know what browser parameter could cause this? (I'm trying to have a render similar to Chrome)

答:
Solution found, finally...

Go to address

about:config

then change gfx.font_rendering.cleartype_params.gamma to 4

You can also change contrast with gfx.font_rendering.cleartype_params.enhanced_contrast.

For testing purposes, I suggest you to have a window with text on a side of your screen, and the about:config page on an other side

ContentLicense: CC BY-SA 4.0


问:
How to output JSON from Pentaho xaction?
What's the best way to get a Pentaho xaction to return it's output in JSON format?

I have a dashboard that is driven by Pentaho xactions that return HTML fragments (tables) that I then insert into the page. It works okay, but I would like my xactions to return JSON instead of the HTML fragments to make things a bit more flexible and reusable.

Thanks.

答:
Chuck,

There are several ways to go about adding a service to the Pentaho BIServer (which is what I assume you are doing if you are wanting to return JSON).  Which one to use depends on how much Java you know and how deep you want to get into the inner workings.

Option a: Write an xaction that uses the JavaScriptRule component.  You can pretty much do whatever you want with the JavaScript you write there, including writing whatever you wish to the http repsonse.  This is probably the quickest, but perhaps dirties and least maintainable way to accomplish what you want

Option b: Write a BIServer plugin.  One of the many facets of BIServer plugins you can write is to do this very thing, plug in a new kind of service.  Many of the community contributed plugins do this very thing.  Look at pentaho-cda for example (http://code.google.com/p/pentaho-cda/).  For info on how to write a BIServer plugin, see http://wiki.pentaho.com/display/ServerDoc2x/Developing+Plugins.  Within option b, you need to be mindful of which version of the BIServer you wish to deploy to since the plugin api changes a bit from release to release.  The short story here is if you are planning to deploy to 3.7 or earlier, you want to write a ContentGenerator.  If you can hold off till the next major release (aka Sugar), then you have nicer things at your disposal like the ability to plugin an actual HttpServlet or even a JaxRS annotated class (see the wiki doc).

Finally, ##pentaho in freenode IRC is a great place to come to with questions.

Hope this helps,
Aaron


问:
Inputting Array In Multiline Text In Android
I am new to android and am trying to make an app where the user inputs an array in a text box with inputType = textMultiLine. The problem is that I want to make it so that whenever user hits enter, the app takes input of the next array element and not treat the entire text in the textbox as one element. The code is as below :

```<code>    EditText input = findViewById(R.id.inputtext);
    Button show = findViewById(R.id.button);
    TextView output = findViewById(R.id.output);
    String [] name = new String[3];

    for (int i = 0 ; i < 3 ; i++)
    {
        name[i] = input.getText().toString();
        output.setText(name[i]);
    }
</code>```

But whenever i try to take name[1] after hitting enter the app doesnt treat the next line as name[2] but instead treats it as name[1]. For example if type the names john,steve and frank, then i should get an array that is like this :

```<code>name[0] = john
name[1] = steve
name[2] = frank
</code>```

but instead whenever I typejohn,press enter,type steve, press enter and type frank the app treats it as :

```<code>name[0] = john
          steve
          frank
</code>```

also if i set the output to something like this :

```<code>output.setText(name[i] + i)
</code>```

instead of getting an oupt like this :

```<code>john 0
steve 1
frank 2
</code>```

I get an output like this :

```<code>john
steve
frank2
</code>```

Any and all help would be much appreciated.

Thanks

======================================================================================================================================================

EDIT 1

I tried this code but didn't work:

```<code>String name[] = input .getText().toString().split("\\r?\\n");

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

    output.setText(name[i]);
}
</code>```

Still get only frank when I input john,steve and frank

答:
If you want to put each line to different array item :

```<code>String [] name = input.getText().toString().split("\n");
</code>```

input.getText().toString() gives you string containing whole EditText content with lines separated by new line - "\n". You need to split this string to get each line.

Body:
I am new to android and am trying to make an app where the user inputs an array in a text box with inputType = textMultiLine. The problem is that I want to make it so that whenever user hits enter, the app takes input of the next array element and not treat the entire text in the textbox as one element. The code is as below :

    EditText input = findViewById(R.id.inputtext);
    Button show = findViewById(R.id.button);
    TextView output = findViewById(R.id.output);
    String [] name = new String[3];

    for (int i = 0 ; i < 3 ; i++)
    {
        name[i] = input.getText().toString();
        output.setText(name[i]);
    }

But whenever i try to take name[1] after hitting enter the app doesnt treat the next line as name[2] but instead treats it as name[1]. For example if type the names john,steve and frank, then i should get an array that is like this :

name[0] = john
name[1] = steve
name[2] = frank

but instead whenever I typejohn,press enter,type steve, press enter and type frank the app treats it as :

name[0] = john
          steve
          frank

also if i set the output to something like this :

output.setText(name[i] + i)

instead of getting an oupt like this :

john 0
steve 1
frank 2

I get an output like this :

john
steve
frank2

Any and all help would be much appreciated.

Thanks

======================================================================================================================================================

EDIT 1

I tried this code but didn't work:

String name[] = input .getText().toString().split("\\r?\\n");

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

    output.setText(name[i]);
}

Still get only frank when I input john,steve and frank

Body:
If you want to put each line to different array item :

String [] name = input.getText().toString().split("\n");

input.getText().toString() gives you string containing whole EditText content with lines separated by new line - "\n". You need to split this string to get each line.


问:
NestedScrollview won't start from top
I have a Recyclerview in a NestedScrollview.. everything is working fine except one thig. I have total three view in NestedScrollview First two are LinearLayout then Recyclerview. when i run my app the Activity don't show top two layout it starts from top of the Recyclerview.

How its show my layout:

How its suppose to show:

And i am loading this enite layout under a viewpager and my viewpager is a child of Coordinator Layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/home_layout_background">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <com.daimajia.slider.library.SliderLayout
            android:id="@+id/image_slider"
            android:layout_width="match_parent"
            android:layout_height="@dimen/image_slider_height"
            android:layout_marginTop="@dimen/image_slider_top_margin" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="@dimen/popular_fragment_side_padding"
        android:orientation="horizontal"
        android:weightSum="4">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/free_delivery"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_free_delivery" />

                    <TextView
                        android:id="@+id/btnTextFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFreeDelivery"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/free_delivery_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/flash_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_flash_deals" />

                    <TextView
                        android:id="@+id/btnTextFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFlashDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/flash_deals_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/for_you"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_for_you" />

                    <TextView
                        android:id="@+id/btnTextForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewForYou"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/for_you_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/shake_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_shake_deals" />

                    <TextView
                        android:id="@+id/btnTextShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewShakeDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/shake_deals"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="18dp"
        android:scrollbars="none" />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

My ViewPager Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/home_layout_background"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="center"
        android:background="@drawable/toolbar_background"
        app:layout_scrollFlags="scroll|enterAlways">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/title_home"
            android:textColor="@color/toolbar_title_txt_color"
            android:textSize="@dimen/toolbar_txt_size"
            android:textStyle="bold" />

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

    <android.support.design.widget.TabLayout android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        app:tabMode="scrollable"
        app:tabTextColor="@color/tab_bar_txt"
        app:tabIndicatorColor="@color/tab_bar_txt_selected"
        app:tabSelectedTextColor="@color/tab_bar_txt_selected"
        app:tabTextAppearance="@style/TabTextAppeareance"/>

</android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Add this line in NestedScrollView 's child Layout

```<code>android:descendantFocusability="afterDescendants"
</code>```

Title: NestedScrollview won't start from top

Body:
I have a Recyclerview in a NestedScrollview.. everything is working fine except one thig. I have total three view in NestedScrollview First two are LinearLayout then Recyclerview. when i run my app the Activity don't show top two layout it starts from top of the Recyclerview.

How its show my layout:

How its suppose to show:

And i am loading this enite layout under a viewpager and my viewpager is a child of Coordinator Layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/home_layout_background">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <com.daimajia.slider.library.SliderLayout
            android:id="@+id/image_slider"
            android:layout_width="match_parent"
            android:layout_height="@dimen/image_slider_height"
            android:layout_marginTop="@dimen/image_slider_top_margin" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="@dimen/popular_fragment_side_padding"
        android:orientation="horizontal"
        android:weightSum="4">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/free_delivery"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_free_delivery" />

                    <TextView
                        android:id="@+id/btnTextFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFreeDelivery"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/free_delivery_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/flash_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_flash_deals" />

                    <TextView
                        android:id="@+id/btnTextFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFlashDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/flash_deals_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/for_you"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_for_you" />

                    <TextView
                        android:id="@+id/btnTextForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewForYou"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/for_you_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/shake_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_shake_deals" />

                    <TextView
                        android:id="@+id/btnTextShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewShakeDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/shake_deals"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="18dp"
        android:scrollbars="none" />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

My ViewPager Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/home_layout_background"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="center"
        android:background="@drawable/toolbar_background"
        app:layout_scrollFlags="scroll|enterAlways">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/title_home"
            android:textColor="@color/toolbar_title_txt_color"
            android:textSize="@dimen/toolbar_txt_size"
            android:textStyle="bold" />

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

    <android.support.design.widget.TabLayout android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        app:tabMode="scrollable"
        app:tabTextColor="@color/tab_bar_txt"
        app:tabIndicatorColor="@color/tab_bar_txt_selected"
        app:tabSelectedTextColor="@color/tab_bar_txt_selected"
        app:tabTextAppearance="@style/TabTextAppeareance"/>

</android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

Body:
Add this line in NestedScrollView 's child Layout

android:descendantFocusability="afterDescendants"


问:
r: Fill two dataframe columns with the t-statistic and p-value from t.test
Given the American Community Survey dataset from Lock5Data, I want to calculate the t-stat (and its Bonferroni-corrected p-value) of incomes for each combination of races.  I'd like to store the results in a dataframe with columns 'race1', 'race2, 'tstat', and 'pval'.  This way I can sort the dataframe to show the biggest (or most significant) differences in income.

```<code>library(Lock5Data)
data("ACS")
ACS$Sex <- factor(ACS$Sex, labels = c("Female","Male"))
sub_acs <- subset(ACS, select = c("Income","Sex","Race"))
sub_acs <- na.omit(sub_acs)

# form results df (t_df)
race_unique <- unique(sub_acs$Race)
t_df <- expand.grid(race1 = race_unique, race2 = race_unique)
t_df <- t_df[t_df$race1 != t_df$race2,]
rownames(t_df) <- NULL

# fill df col with t-stat
t_df$tstat <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$statistic

# fill df col with p_val
t_df$pval <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$p.value
</code>```

Unfortunately, the results df t_df appears to only show the first result for each test repeated down all the rows.  How do I correctly map the t-statistic and p-value results?  Answers that make my current solution more elegant and portable are welcome!

答:
Are you looking for something like this?</p>

```<code>cbn <- t(combn(as.character(race_unique), 2))
pval <- numeric(nrow(cbn))
tstat <- numeric(nrow(cbn))

for(i in seq_len(nrow(cbn))){
    a <- subset(sub_acs, Race %in% cbn[i, ])
    tt <- t.test(Income ~ Race, data = a, p.adjust.methods = 'bonferroni')
    pval[i] <- tt$p.value
    tstat[i] <- tt$statistic
}

result <- data.frame(race1 = cbn[, 1], race2 = cbn[, 2], p.value = pval, statistic = tstat)
result
#  race1 race2     p.value  statistic
#1 white black 0.190337465 -1.3173942
#2 white other 0.007776557 -2.7231317
#3 white asian 0.203332407  1.2831045
#4 black other 0.365064209  0.9092968
#5 black asian 0.050391428  1.9782605
#6 other asian 0.005943459  2.8158303
</code>```

Body:
Given the American Community Survey dataset from Lock5Data, I want to calculate the t-stat (and its Bonferroni-corrected p-value) of incomes for each combination of races.  I'd like to store the results in a dataframe with columns 'race1', 'race2, 'tstat', and 'pval'.  This way I can sort the dataframe to show the biggest (or most significant) differences in income.

library(Lock5Data)
data("ACS")
ACS$Sex <- factor(ACS$Sex, labels = c("Female","Male"))
sub_acs <- subset(ACS, select = c("Income","Sex","Race"))
sub_acs <- na.omit(sub_acs)

# form results df (t_df)
race_unique <- unique(sub_acs$Race)
t_df <- expand.grid(race1 = race_unique, race2 = race_unique)
t_df <- t_df[t_df$race1 != t_df$race2,]
rownames(t_df) <- NULL

# fill df col with t-stat
t_df$tstat <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$statistic

# fill df col with p_val
t_df$pval <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$p.value

Unfortunately, the results df t_df appears to only show the first result for each test repeated down all the rows.  How do I correctly map the t-statistic and p-value results?  Answers that make my current solution more elegant and portable are welcome!

Body:
Are you looking for something like this?

cbn <- t(combn(as.character(race_unique), 2))
pval <- numeric(nrow(cbn))
tstat <- numeric(nrow(cbn))

for(i in seq_len(nrow(cbn))){
    a <- subset(sub_acs, Race %in% cbn[i, ])
    tt <- t.test(Income ~ Race, data = a, p.adjust.methods = 'bonferroni')
    pval[i] <- tt$p.value
    tstat[i] <- tt$statistic
}

result <- data.frame(race1 = cbn[, 1], race2 = cbn[, 2], p.value = pval, statistic = tstat)
result
#  race1 race2     p.value  statistic
#1 white black 0.190337465 -1.3173942
#2 white other 0.007776557 -2.7231317
#3 white asian 0.203332407  1.2831045
#4 black other 0.365064209  0.9092968
#5 black asian 0.050391428  1.9782605
#6 other asian 0.005943459  2.8158303


问:
Looking for an in-memory database with same SQL syntax as Oracle
I'm looking for a in-memory database that can be used for automatic testing of legacy ADO.NET code against Oracle. So the in-memory database should have the same SQL syntax as Oracle.

Any suggestions?

答:
Well Oracle IMDB Cache is the ideal product. I think automated testing would require a license, but see what you can negotiate with your local Oracle sales rep.

But I'd start with a regular DB, NOARCHIVELOG mode. Perhaps with temp and logs on some form of ram disk since you've got no need of recovery.

Also talk to Oracle Support as there are some hidden parameters that can be set to improve speed at the expense of recoverability (ie not generate redo at the expense of not being able to handle instance recovery).


问:
Firebase function: check if multiple keys exist
Is there a short/efficient way to check if multiple keys exist (even better if I can read several keys in a single call)?
The only way I manage to achieve a similar result is by checking if key1 exists, .then check if key2 exists etc. Make it very ugly if I have 5 keys to check.
The keys are in completely different locations, so I don't want to just get the common ancestor and read the snap, as it's too much data.

答: Check all the keys without using then(), but collect all the promises into an array (I'll call it promises), then use Promise.all(promises) to get another promise that's resolved after all the others resolve.  They can now potentially execute in parallel without having to wait for each other.


问:
How do I retrieve the private key for a certificate generated on AWS Certificate Manager?
Someone purchased a wildcard certificate via AWS Certificate Manager for their domain name and I need to transfer it to Heroku for an app that uses a sub-domain of the domain name.

I can't figure out, either through the AWS Console or through their CLI, how I would get the private key used to generate the CSR for this certificate? Can anyone on here help me?

答:
You can't. That's one of the points of using AWS Certificate Manager: the private keys won't leave AWS infrastructure. You can't even use AWS Certificate Manager certs on EC2 today, only on specific services. More information here and here.

Edit: You can now use private certificates issued with ACM Private CA with EC2 instances, see more info here. However, that is only useful for private networks, as major browsers won't recognize ACM Private CA by default.


问:
How can I ensure that all primitives are at least null-initialized in my iOS app?
Under ARC, all objects are nil-initialized if they are declared but not used, but the same is not true of primitives. I'd like to trade some performance for safety and make sure that they're always initialized. Is there some flag I can pass to clang to have it nil-initialize everything by default?</p>

答: You should switch to Swift, which will ensure that you initialise everything to something sensible.


问:
Remove rows having same value in all columns
I have a pandas dataframe that I'm trying to drop rows based on all columns having exact same value. Here's an example to help understand the idea.

Input:

```<code>index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 1     2  2  2  2  2  2
 2     5  5  5  5  5  5
 3     7  7  6  7  7  7
</code>```

Output:

```<code>index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 3     7  7  6  7  7  7
</code>```

There can be many columns here.

答:
Using nunique

```<code>df=df[df.nunique(1)>1]
df
Out[286]:
       A  B  C  D  E  F
index
0      1  2  3  1  3  4
3      7  7  6  7  7  7
</code>```

Body:
I have a pandas dataframe that I'm trying to drop rows based on all columns having exact same value. Here's an example to help understand the idea.

Input:

index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 1     2  2  2  2  2  2
 2     5  5  5  5  5  5
 3     7  7  6  7  7  7

Output:

index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 3     7  7  6  7  7  7

There can be many columns here.

Body:
Using nunique

df=df[df.nunique(1)>1]
df
Out[286]:
       A  B  C  D  E  F
index
0      1  2  3  1  3  4
3      7  7  6  7  7  7


问:
How to generate JaxB-Classes with java.util.Optional?
I use the jaxb2-maven-plugin to generate JaxB-Classes from a given XSD.
It works fine.
But now I want to use java.util.Optional in the generated Classes. But JaxB generated the Classes without the Optionals. So I'm forced to make a Null-Check of every Variable.

Did anybody know how the jaxb2-maven-plugin has to be configured to use the java.util.Optional?

Thanks for you help!

答:
Maybe you could find something more generic but i'm not sure if this is possible.
Anyway you can still define custom Adapter for types you want to be optional.

Here is an example of Integer

First, create an Adapter

```<code>public final class IntegerOptionalAdapter extends OptionalAdapter<Integer>
{
}
</code>```

Then use this adapter in your binding

```<code>@XmlAttribute
@XmlJavaTypeAdapter(IntegerOptionalAdapter.class)
private Optional<Integer> someInteger;
</code>```

Body:
Maybe you could find something more generic but i'm not sure if this is possible.
Anyway you can still define custom Adapter for types you want to be optional.

Here is an example of Integer

First, create an Adapter

public final class IntegerOptionalAdapter extends OptionalAdapter<Integer>
{
}

Then use this adapter in your binding

@XmlAttribute
@XmlJavaTypeAdapter(IntegerOptionalAdapter.class)
private Optional<Integer> someInteger;


问:
Ogr2ogr encoding utf-8 linux
I have a problem shell command ogr 2 ogr

```<code>ogr2ogr -f OCI OCI:user_name/password@DATABASE:GAS /opt/imp/ready/Gas.shp -skipfailures -overwrite -lco DIM=2 -lco PRECISION=no -lco SRID=2400000 -lco LAUNDER=YES -lco ADD_LAYER_GTYPE=NO -lco GEOMETRY_NAME=GEOM
</code>```

when I call ogr 2 ogr in shell windows its all ok,
but I call to command in php, in database Armenian and Russian fonts inserting ??????????? hieroglyph.

答:
Make sure that you have below line at the top of PHP file:

```<code>header('Content-Type: text/html; charset=utf-8');
</code>```

Reference:

http://us2.php.net/manual/en/function.utf8-encode.php

Title: Ogr2ogr encoding utf-8 linux

Body:
I have a problem shell command ogr 2 ogr

ogr2ogr -f OCI OCI:user_name/password@DATABASE:GAS /opt/imp/ready/Gas.shp -skipfailures -overwrite -lco DIM=2 -lco PRECISION=no -lco SRID=2400000 -lco LAUNDER=YES -lco ADD_LAYER_GTYPE=NO -lco GEOMETRY_NAME=GEOM

when I call ogr 2 ogr in shell windows its all ok,
but I call to command in php, in database Armenian and Russian fonts inserting ??????????? hieroglyph.

Body:
Make sure that you have below line at the top of PHP file:

header('Content-Type: text/html; charset=utf-8');

Reference:

http://us2.php.net/manual/en/function.utf8-encode.php


问:
hide lines of text not fully visible with javascript & css
I think this might be impossible, but is there some way using JQuery to prevent lines of text not fully visible from showing up on the screen when a user scrolls until the entire line is visible? That is, we want to prevent something like this from showing up:

Thanks!

答:
Hypothetically you could measure the height of text area, measure the height of the line, find scroll position do some math and then have some way of hiding text that is not fully exposed yet (eg Using a white div of x height depending on your math).  However, it seems like a lot of trouble to go to for something that is usually a non-issue.  You might also be able to do something with the overflow property, but you might have some issues with that I'm not sure.

I thought of an alternate method that would be easier to implement.  Capture scroll events and then change it to the closest multiple of line height.


问:
WCF Timeout - WSDualHttpBinding, How to set OperationTimeout
I'm creating a WSDualHttpBinding (from code), setting the following timeout values:

```<code> peerBinding.CloseTimeout = TimeSpan.FromSeconds(ServiceConnector_Constants.CLOSETIMEOUT);
            peerBinding.OpenTimeout = TimeSpan.FromSeconds(ServiceConnector_Constants.OPENTIMEOUT);
            peerBinding.SendTimeout = TimeSpan.FromSeconds(ServiceConnector_Constants.SENDTIMEOUT);
</code>```

These constant (for exasperation purposes) values are 600 seconds.

One client connects fine, the others log the following error :

"The open operation did not complete within the allotted timeout of 00:01:00"

This is at the following line of code :

```<code>                            _clientFactory.Open();

                        //Log(String.Format("Create Client IN 6"));
                        LogMessage("Creating client...");
                        _serviceConnection = _clientFactory.CreateChannel();
                        LogMessage("Client Created...");
</code>```

The last logged line is "Creating Client". It appears that the CreateChannel is causing the problem.

But I've set the value > 1 minute. Whatever value I set, the Timeout is
ALWAYS reported as 00:01:00!!

I don't understand.

I've read and read about this and the OperationTimeout property. But I cannot find anyway of setting it on a WSDualHttpBinding.

Can anyone please help.

Thanks

答:
The solution is NOT to use wsDualHTTPBinding as advised in this excellent SO solution :why NOT to use wsDualHttpBinding in client/server

Now all is well in the world - and faster.

Body:
I'm creating a WSDualHttpBinding (from code), setting the following timeout values:

 peerBinding.CloseTimeout = TimeSpan.FromSeconds(ServiceConnector_Constants.CLOSETIMEOUT);
            peerBinding.OpenTimeout = TimeSpan.FromSeconds(ServiceConnector_Constants.OPENTIMEOUT);
            peerBinding.SendTimeout = TimeSpan.FromSeconds(ServiceConnector_Constants.SENDTIMEOUT);

These constant (for exasperation purposes) values are 600 seconds.

One client connects fine, the others log the following error :

"The open operation did not complete within the allotted timeout of 00:01:00"

This is at the following line of code :

                            _clientFactory.Open();

                        //Log(String.Format("Create Client IN 6"));
                        LogMessage("Creating client...");
                        _serviceConnection = _clientFactory.CreateChannel();
                        LogMessage("Client Created...");

The last logged line is "Creating Client". It appears that the CreateChannel is causing the problem.

But I've set the value > 1 minute. Whatever value I set, the Timeout is
ALWAYS reported as 00:01:00!!

I don't understand.

I've read and read about this and the OperationTimeout property. But I cannot find anyway of setting it on a WSDualHttpBinding.

Can anyone please help.

Thanks


问:
Loop through a date range with JavaScript
Given two Date() objects, where one is less than the other, how do I loop every day between the dates?

```<code>for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{

}
</code>```

Would this sort of loop work?  But how can I add one day to the loop counter?

Thanks!

答:
Here simple working code, worked for me

var from = new Date(2012,0,1);
var to = new Date(2012,1,20);

// loop for every day
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {
   // your day is here
   console.log(day)
}```

Body:
Given two Date() objects, where one is less than the other, how do I loop every day between the dates?

for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{

}

Would this sort of loop work?  But how can I add one day to the loop counter?

Thanks!


问:
Coldfusion PayPal IPN Connection Failure
I am trying to get a sandbox PayPal IPN working with the Coldfusion example shown here:

https://github.com/paypal/ipn-code-samples/tree/master/coldfusion

I've added the location of my IPN file to PayPal and the page is being called by it but all I get is a 'Connection Failure' message in the text file. The IPN file is being called from an https location so not sure what is wrong.

Any ideas?

答: The JRE (version 7) that comes with ColdFusion 10, doesn't support TLS 1.2, which you require to talk to the PayPal API. You need to either update the JRE to 113+ and enable TLS 1.2 via argument or upgrade altogether to JRE 8. To upgrade, you have to let the jvm.config point to the installation and replace the tools.jar in CF with the one from the JDK 8. (Also make sure to have at least update 14 installed on your ColdFusion 10 server.)


问:
Parse doesn't update a specific class
I've got a very strange problem...
I have a button that needs to clean all the QR-cards in the parse database. I have a class QRCard for this and updating this class doesn't work, I created a new class Test and didn't change anything in the code beside classname and here it works perfectly...
I checked the ACL settings on both but they're identically.
I cleared my cache etc, but nothing helps, I also deleted en recreated the class but didn't work either. Anyone has a idea what I'm doing wrong?

```<code>function clearAllQR() {
var QRCard = Parse.Object.extend("QRCard");
var query = new Parse.Query(QRCard);

query.find({
    success: function(results) {

    var emptyArr = new Array();
    var updateArray = new Array();

    for (i = 0; i < results.length; i++) {
        results[i].set("aankopen", emptyArr);
        updateArray.push(results[i]);
    }

    console.log(results);

    Parse.Object.saveAll(updateArray, {
        success: function(list) {
        },
        error: function(error) {
            console.log(error);
        },
      });
},
error: function(object, error) {}
});
</code>```

}

答:
I think you don't have Class Level Permission.

Remove it using Parse Dashboard or make your call with masterKey

Title: Parse doesn't update a specific class

Body:
I've got a very strange problem...
I have a button that needs to clean all the QR-cards in the parse database. I have a class QRCard for this and updating this class doesn't work, I created a new class Test and didn't change anything in the code beside classname and here it works perfectly...
I checked the ACL settings on both but they're identically.
I cleared my cache etc, but nothing helps, I also deleted en recreated the class but didn't work either. Anyone has a idea what I'm doing wrong?

function clearAllQR() {
var QRCard = Parse.Object.extend("QRCard");
var query = new Parse.Query(QRCard);

query.find({
    success: function(results) {

    var emptyArr = new Array();
    var updateArray = new Array();

    for (i = 0; i < results.length; i++) {
        results[i].set("aankopen", emptyArr);
        updateArray.push(results[i]);
    }

    console.log(results);

    Parse.Object.saveAll(updateArray, {
        success: function(list) {
        },
        error: function(error) {
            console.log(error);
        },
      });
},
error: function(object, error) {}
});

}


问:
Model in header doesn't appear in views that use the header
Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't.

Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :)

Model defined in models.py:

```<code>from django.db import models
from django.utils import timezone

# Create your models here.
class Propaganda(models.Model):
    slogan = models.CharField(max_length=140, blank=True, null=True)

    def __str__(self):
        return self.slogan
</code>```

header.html

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Christopher's weblog</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Blog site.">

        <!-- Let's get the static files where we use them, but this could be before the html tag -->
        {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <!-- <link rel="stylesheet" href="{% static 'blog/css/cupar.css' %}" type="text/css" /> -->
    </head>
    <body>

        <section class="hero is-success is-bold">
            <div class="hero-body">
                <div class="container">
                    {% block slogan %}
                        {% for propaganda in propagandas %}
                            <h6>{{ propaganda.slogan }} it's</h6>
                        {% endfor %}
                    {% endblock %}
                    <h1 class="title" style="display: inline-block;">
                        <span class="icon">
                            <i class="fa fa-home"></i>
                            </span>
                        <a href="{% url 'post_list' %}">The Guide</a>
                    </h1>

                    {% if user.is_authenticated %}
                    <div class="field">
                        <div class="control">
                            <a href="{% url 'post_new' %}" class="button is-warning is-pulled-right">
                                <span class="icon">
                                    <i class="fa fa-plus-square"></i>
                                </span>
                                <span>New post</span>
                            </a>
                        </div>
                    </div>
                    {% endif %}

                </div><!-- @container -->
            </div>
        </section>
        <!-- content under header in here-> -->
        {% block content %}
        {% endblock %}
    </body>
</html>
</code>```

views.py

```<code>from django.template import RequestContext
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Propaganda
from .forms import PostForm
from django.utils import timezone

# Create your views here.
def post_list(request):
    posts = Post.objects.all()
    propagandas = Propaganda.objects.all().order_by('?')[:1]
    return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})
</code>```

post_detail.html (where the model does not appear):

```<code>{% extends 'blog/header.html' %}

{% block content  %}
some html / form that has nothing to do with the header.
{% endblock %}
</code>```

post_list.html (the 'index' page where the model works fine)

```<code>{% extends "blog/header.html" %}

{% block content %}

    {% for post in posts %}
        <section class="section">
        more html
{% endblock %}
</code>```

答:
First: Why are you not showing the view of post_detail. Isn't that the one that does not work?

Second: Even though you are extending a base template you still have to pass the appropriate context in order to generate the desired dynamic data.

I hope it helps.

Body:
Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't.

Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :)

Model defined in models.py:

from django.db import models
from django.utils import timezone

# Create your models here.
class Propaganda(models.Model):
    slogan = models.CharField(max_length=140, blank=True, null=True)

    def __str__(self):
        return self.slogan

header.html

<!DOCTYPE html>

        <title>Christopher's weblog</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Blog site.">

        {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                    {% block slogan %}
                        {% for propaganda in propagandas %}

{{ propaganda.slogan }} it's

                        {% endfor %}
                    {% endblock %}

                        The Guide

                    {% if user.is_authenticated %}

                                New post

                    {% endif %}

        {% block content %}
        {% endblock %}

views.py

from django.template import RequestContext
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Propaganda
from .forms import PostForm
from django.utils import timezone

# Create your views here.
def post_list(request):
    posts = Post.objects.all()
    propagandas = Propaganda.objects.all().order_by('?')[:1]
    return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})

post_detail.html (where the model does not appear):

{% extends 'blog/header.html' %}

{% block content  %}
some html / form that has nothing to do with the header.
{% endblock %}

post_list.html (the 'index' page where the model works fine)

{% extends "blog/header.html" %}

{% block content %}

    {% for post in posts %}

        more html
{% endblock %}


问:
Select values that meet different conditions on different rows?
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

```<code>userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1
</code>```

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

答: If you need any kind of generality here (different 3-role combinations or different n-role combinations)...I'd suggest you use a bit masking system for your roles and use the bitwise operators to perform your queries...</p>

OwnerDisplayName: John

Body:
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

LastEditorDisplayName: John

OwnerDisplayName: JPunyon


问:
Hooking API Calls in Current Process?
How do I go about hooking/redirecting a function in a DLL (say, CreateThread from Kernel32.dll) loaded in the current process?

(I don't have control over which pieces of code call CreateThread, so it's not like I can just have the code something else instead.)

The language doesn't matter much; I'm guessing C/C++ would be the best choices for this.

Update:

I forgot to mention: I'm not looking for solutions that require the bundling of extra libraries into my program; I was looking for a manual way of doing the hooking (such as by rewriting the address of the function), not for using an external library to do this.

But thanks to those who mentioned an external library; sorry I didn't say this earlier.

答: there's MS library for this: Detours</p>

Title: Hooking API Calls in Current Process?

Body: there's MS library for this: Detours