问:
How to get ajax accordion selected index from javascript
Hi I have used Ajax accordion. what I need is to get current selected index when I click on accordion tab that is on billing information I should get selectedindex=0 in Javascript or in jquery

I have set javascript as

Note : billing information is a class which is set in OPCPanels

```<code><script type="text/javascript">
    function pageLoad(sender, args) {

        $(".billinginformation").click(function (event, ui) {
            alert("hi");

            alert($(".billinginformation").accordion("option", "active"))
        });
    }
</script>
</code>```

HTML code

```<code> <ajax:Accordion ID="OPCPanels" runat="server" SelectedIndex="0" HeaderCssClass="widget billinginformation" ContentCssClass="content" AutoSize="None">
        <Panes>
        <ajax:AccordionPane ID="BillingInformation" runat="server" CssClass="widget">
            <Header><h2>Billing Information</h2></Header>
            <Content>HI</Content>
        </ajax:AccordionPane>
        <ajax:AccordionPane ID="ShippingInformation" runat="server" CssClass="widget">
            <Header>Shipping Information</Header>
            <Content>hello</content>
        </ajax:AccordionPane>
    </Panes>
</ajax:Accordion>
</code>```

I have set billinginformation class to my main accordion and on click of any accordion I get the alert of "hi".

but how should I get that which selected Index I have selected in JavaScript?

答:
This appears to be the ASP.NET Ajax Toolkit accordion.  Try:

```<code>$find('OPCPanels').get_SelectedIndex()
</code>```

EDIT:

There's not much documentation left around on the AJAX toolkit.  See what you can scrounge from these links.

Accordion SelectedIndex behind code of last item selected?
http://www.dotnetcurry.com/ShowArticle.aspx?ID=215

Body:
Hi I have used Ajax accordion. what I need is to get current selected index when I click on accordion tab that is on billing information I should get selectedindex=0 in Javascript or in jquery

I have set javascript as

Note : billing information is a class which is set in OPCPanels

HTML code

 <ajax:Accordion ID="OPCPanels" runat="server" SelectedIndex="0" HeaderCssClass="widget billinginformation" ContentCssClass="content" AutoSize="None">
        <Panes>
        <ajax:AccordionPane ID="BillingInformation" runat="server" CssClass="widget">

Billing Information

            <Content>HI</Content>
        </ajax:AccordionPane>
        <ajax:AccordionPane ID="ShippingInformation" runat="server" CssClass="widget">
            Shipping Information
            <Content>hello</content>
        </ajax:AccordionPane>
    </Panes>
</ajax:Accordion>

I have set billinginformation class to my main accordion and on click of any accordion I get the alert of "hi".

but how should I get that which selected Index I have selected in JavaScript?

Body:
This appears to be the ASP.NET Ajax Toolkit accordion.  Try:

$find('OPCPanels').get_SelectedIndex()

EDIT:

There's not much documentation left around on the AJAX toolkit.  See what you can scrounge from these links.

Accordion SelectedIndex behind code of last item selected?
http://www.dotnetcurry.com/ShowArticle.aspx?ID=215


来源: stackexchange

问:
How to replace all occurrences of a match pattern in a line?
Suppose I have a line like:

```<code>"[foo] and (foo) along with foofrancis.foo = foo"
</code>```

Where the match pattern "foo" is always contiguous to non a-zA-Z characters but may occur any number of times in a line.

I want to replace all occurrences of "foo" with "bar" when foo is not contiguous to an a-z or A-Z character and output a newline.

Where foo and bar are both variables I am passing in. Sort of like:

```<code> foo = "Hello"
 bar = "Goodbye"
 line = "[Hello] and (Hello) along with Hellofrancis.Hello = Hello"
 newline = re.sub(<Unsure what goes here>,line)
 print newline
</code>```

Output:

[Goodbye] and (Goodbye) along with Hellofrancis.Goodbye = Goodbye
```

I'm not sure how I configure my re.sub

答:
```<code>import re

foo = re.escape("Hello")
bar = re.escape("Goodbye")
line = "[Hello] and (Hello) along with Hellofrancis.Hello = Hello"
newline = re.sub("\\b" + foo + "\\b", bar, line)
print (newline)
</code>```

That should do what you are looking for.  re.sub takes requires 3 params.  What you are replacing, to what, and the text.  The \b is a word boundry. notice the Hellofrancis won't change as per your request to contigious.  I also escaped your foo and bar so if the data coming in has regex characters like a period it won't mess with your output.

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a line like:

"[foo] and (foo) along with foofrancis.foo = foo"

Where the match pattern "foo" is always contiguous to non a-zA-Z characters but may occur any number of times in a line.

I want to replace all occurrences of "foo" with "bar" when foo is not contiguous to an a-z or A-Z character and output a newline.

Where foo and bar are both variables I am passing in. Sort of like:

 foo = "Hello"
 bar = "Goodbye"
 line = "[Hello] and (Hello) along with Hellofrancis.Hello = Hello"
 newline = re.sub(<Unsure what goes here>,line)
 print newline

Output:

[Goodbye] and (Goodbye) along with Hellofrancis.Goodbye = Goodbye

I'm not sure how I configure my re.sub

Body:
import re

foo = re.escape("Hello")
bar = re.escape("Goodbye")
line = "[Hello] and (Hello) along with Hellofrancis.Hello = Hello"
newline = re.sub("\\b" + foo + "\\b", bar, line)
print (newline)

That should do what you are looking for.  re.sub takes requires 3 params.  What you are replacing, to what, and the text.  The \b is a word boundry. notice the Hellofrancis won't change as per your request to contigious.  I also escaped your foo and bar so if the data coming in has regex characters like a period it won't mess with your output.


问:
SQL Update and Join updating wrong records
I am trying to use an UPDATE statement with a JOIN on SQL Server.

if I run the below SELECT statement it returns 42 rows.

```<code>SELECT * FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b
on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]
</code>```

However when I use it as a condition within my update statement (below), the query updates 44 records.

```<code>update [DaisyCompare].[dbo].[Baseline]

set Disposition = ('Match')

where exists (
SELECT * FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b

on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description] )
</code>```

Presumably my syntax is wrong, but I am not sure where.

Any help greatly appreciated.

答:
You can use normal update syntax with a join, and you only need the join predicates, the where clause is redundant:</p>

```<code>UPDATE b
SET Disposition = 'Match'
FROM [dbo].[Imported] i
INNER JOIN [DaisyCompare].[dbo].[Baseline] b
ON
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]
</code>```

Body:
I am trying to use an UPDATE statement with a JOIN on SQL Server.

if I run the below SELECT statement it returns 42 rows.

SELECT * FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b
on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

However when I use it as a condition within my update statement (below), the query updates 44 records.

update [DaisyCompare].[dbo].[Baseline]

set Disposition = ('Match')

where exists (
SELECT * FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b

on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description] )

Presumably my syntax is wrong, but I am not sure where.

Any help greatly appreciated.

Body:
You can use normal update syntax with a join, and you only need the join predicates, the where clause is redundant:

UPDATE b
SET Disposition = 'Match'
FROM [dbo].[Imported] i
INNER JOIN [DaisyCompare].[dbo].[Baseline] b
ON
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]


问:
Scala type programming resources
According to this question, Scala's type system is Turing complete. What resources are available that enable a newcomer to take advantage of the power of type-level programming?

Here are the resources I've found so far:

Daniel Spiewak's High Wizardry in the Land of Scala

Apocalisp's Type-Level Programming in Scala

Jesper's HList

These resources are great, but I feel like I'm missing the basics, and so do not have a solid foundation on which to build. For instance, where is there an introduction to type definitions? What operations can I perform on types?

Are there any good introductory resources?

答:
Overview

Type-level programming has many similarities with traditional, value-level programming. However, unlike value-level programming, where the computation occurs at runtime, in type-level programming, the computation occurs at compile time. I will try to draw parallels between programming at the value-level and programming at the type-level.

Paradigms

There are two main paradigms in type-level programming: "object-oriented" and "functional". Most examples linked to from here follow the object-oriented paradigm.

A good, fairly simple example of type-level programming in the object-oriented paradigm can be found in apocalisp's implementation of the lambda calculus, replicated here:

```<code>// Abstract trait
trait Lambda {
  type subst[U <: Lambda] <: Lambda
  type apply[U <: Lambda] <: Lambda
  type eval <: Lambda
}

// Implementations
trait App[S <: Lambda, T <: Lambda] extends Lambda {
  type subst[U <: Lambda] = App[S#subst[U], T#subst[U]]
  type apply[U] = Nothing
  type eval = S#eval#apply[T]
}

trait Lam[T <: Lambda] extends Lambda {
  type subst[U <: Lambda] = Lam[T]
  type apply[U <: Lambda] = T#subst[U]#eval
  type eval = Lam[T]
}

trait X extends Lambda {
  type subst[U <: Lambda] = U
  type apply[U] = Lambda
  type eval = X
}
</code>```

As can be seen in the example, the object-oriented paradigm for type-level programming proceeds as follows:

First: define an abstract trait with various abstract type fields (see below for what an abstract field is). This is a template for guaranteeing that certain types fields exist in all implementations without forcing an implementation. In the lambda calculus example, this corresponds to trait Lambda that guarantees that the following types exist: subst, apply, and eval.

Next: define subtraits that extend the abstract trait and implement the various abstract type fields

Often, these subtraits will be parameterized with arguments. In the lambda calculus example, the subtypes are trait App extends Lambda which is parameterized with two types (S and T, both must be subtypes of Lambda), trait Lam extends Lambda parameterized with one type (T), and trait X extends Lambda (which is not parameterized).

the type fields are often implemented by referring to the type parameters of the subtrait and sometimes referencing their type fields via the hash operator: # (which is very similar to the dot operator: . for values). In trait App of the lambda calculus example, the type eval is implemented as follows: type eval = S#eval#apply[T]. This is essentially calling the eval type of the trait's parameter S, and calling apply with parameter T on the result. Note, S is guaranteed to have an eval type because the parameter specifies it to be a subtype of Lambda. Similarly, the result of eval must have an apply type, since it is specified to be a subtype of Lambda, as specified in the abstract trait Lambda.

The Functional paradigm consists of defining lots of parameterized type constructors that are not grouped together in traits.

Comparison between value-level programming and type-level programming

abstract class

value-level: abstract class C { val x }

type-level: trait C { type X }

path dependent types

C.x (referencing field value/function x in object C)

C#x (referencing field type x in trait C)

function signature (no implementation)

value-level: def f(x:X) : Y

type-level: type f[x <: X] <: Y (this is called a "type constructor" and usually occurs in the abstract trait)

function implementation

value-level: def f(x:X) : Y = x

type-level: type f[x <: X] = x

conditionals

see here

checking equality

value-level: a:A == b:B

type-level: implicitly[A =:= B]

value-level: Happens in the JVM via a unit test at runtime (i.e. no runtime errors):

in essense is an assert: assert(a == b)

type-level: Happens in the compiler via a typecheck (i.e. no compiler errors):

in essence is a type comparison: e.g. implicitly[A =:= B]

A <:< B, compiles only if A is a subtype of B

A =:= B, compiles only if A is a subtype of B and B is a subtype of A

A <%< B, ("viewable as") compiles only if A is viewable as B (i.e. there is an implicit conversion from A to a subtype of B)

an example

more comparison operators

Converting between types and values

In many of the examples, types defined via traits are often both abstract and sealed, and therefore can neither be instantiated directly nor via anonymous subclass. So it is common to use null as a placeholder value when doing a value-level computation using some type of interest:

e.g. val x:A = null, where A is the type you care about

Due to type-erasure, parameterized types all look the same. Furthermore, (as mentioned above) the values you're working with tend to all be null, and so conditioning on the object type (e.g. via a match statement) is ineffective.

The trick is to use implicit functions and values. The base case is usually an implicit value and the recursive case is usually an implicit function. Indeed, type-level programming makes heavy use of implicits.

Consider this example (taken from metascala and apocalisp):

```<code>sealed trait Nat
sealed trait _0 extends Nat
sealed trait Succ[N <: Nat] extends Nat
</code>```

Here you have a peano encoding of the natural numbers. That is, you have a type for each non-negative integer: a special type for 0, namely _0; and each integer greater than zero has a type of the form Succ[A], where A is the type representing a smaller integer. For instance, the type representing 2 would be: Succ[Succ[_0]] (successor applied twice to the type representing zero).

We can alias various natural numbers for more convenient reference. Example:

```<code>type _3 = Succ[Succ[Succ[_0]]]
</code>```

(This is a lot like defining a val to be the result of a function.)

Now, suppose we want to define a value-level function def toInt[T <: Nat](v : T) which takes in an argument value, v, that conforms to Nat and returns an integer representing the natural number encoded in v's type. For example, if we have the value val x:_3 = null (null of type Succ[Succ[Succ[_0]]]), we would want toInt(x) to return 3.

To implement toInt, we're going to make use of the following class:

```<code>class TypeToValue[T, VT](value : VT) { def getValue() = value }
</code>```

As we will see below, there will be an object constructed from class TypeToValue for each Nat from _0 up to (e.g.) _3, and each will store the value representation of the corresponding type (i.e. TypeToValue[_0, Int] will store the value 0, TypeToValue[Succ[_0], Int] will store the value 1, etc.). Note, TypeToValue is parameterized by two types: T and VT. T corresponds to the type we're trying to assign values to (in our example, Nat) and VT corresponds to the type of value we're assigning to it (in our example, Int).

Now we make the following two implicit definitions:

```<code>implicit val _0ToInt = new TypeToValue[_0, Int](0)
implicit def succToInt[P <: Nat](implicit v : TypeToValue[P, Int]) =
     new TypeToValue[Succ[P], Int](1 + v.getValue())
</code>```

And we implement toInt as follows:

```<code>def toInt[T <: Nat](v : T)(implicit ttv : TypeToValue[T, Int]) : Int = ttv.getValue()
</code>```

To understand how toInt works, let's consider what it does on a couple of inputs:

```<code>val z:_0 = null
val y:Succ[_0] = null
</code>```

When we call toInt(z), the compiler looks for an implicit argument ttv of type TypeToValue[_0, Int] (since z is of type _0). It finds the object _0ToInt, it calls the getValue method of this object and gets back 0. The important point to note is that we did not specify to the program which object to use, the compiler found it implicitly.

Now let's consider toInt(y). This time, the compiler looks for an implicit argument ttv of type TypeToValue[Succ[_0], Int] (since y is of type Succ[_0]). It finds the function succToInt, which can return an object of the appropriate type (TypeToValue[Succ[_0], Int]) and evaluates it. This function itself takes an implicit argument (v) of type TypeToValue[_0, Int] (that is, a TypeToValue where the first type parameter is has one fewer Succ[_]). The compiler supplies _0ToInt (as was done in the evaluation of toInt(z) above), and succToInt constructs a new TypeToValue object with value 1. Again, it is important to note that the compiler is providing all of these values implicitly, since we do not have access to them explicitly.

Checking your work

There are several ways to verify that your type-level computations are doing what you expect. Here are a few approaches. Make two types A and B, that you want to verify are equal. Then check that the following compile:

Equal[A, B]

with: trait Equal[T1 >: T2 <: T2, T2] (taken from apocolisp)

implicitly[A =:= B]

Alternatively, you can convert the type to a value (as shown above) and do a runtime check of the values. E.g. assert(toInt(a) == toInt(b)), where a is of type A and b is of type B.

Additional Resources

The complete set of available constructs can be found in the types section of the scala reference manual (pdf).

Adriaan Moors has several academic papers about type constructors and related topics with examples from scala:

Generics of a higher kind (pdf)

Type Constructor Polymorphism for Scala: Theory and Practice (pdf) (PhD thesis, which includes the previous paper by Moors)

Type Constructor Polymorphism Inference

Apocalisp is a blog with many examples of type-level programming in scala.

Type-Level Programming in Scala is a fantastic guided tour of some type-level programming which includes booleans, natural numbers (as above), binary numbers, heterogeneous lists, and more.

More Scala Typehackery is the lambda calculus implementation above.

ScalaZ is a very active project that is providing functionality that extends the Scala API using various type-level programming features. It is a very interesting project that has a big following.

MetaScala is a type-level library for Scala, including meta types for natural numbers, booleans, units, HList, etc. It is a project by Jesper Nordenberg (his blog).

The Michid (blog) has some awesome examples of type-level programming in Scala (from other answer):

Meta-Programming with Scala Part I: Addition

Meta-Programming with Scala Part II: Multiplication

Meta-Programming with Scala Part III: Partial function application

Meta-Programming with Scala: Conditional Compilation and Loop Unrolling

Scala type level encoding of the SKI calculus

Debasish Ghosh (blog) has some relevant posts as well:

Higher order abstractions in scala

Static typing gives you a head start

Scala implicits type classes, here I come

Refactoring into scala type-classes

Using generalized type constraints

How scalas type system words for you

Choosing between abstract type members

(I've been doing some research on this subject and here's what I've learned. I'm still new to it, so please point out any inaccuracies in this answer.)

Title: Scala type programming resources

Body:
Overview

Type-level programming has many similarities with traditional, value-level programming. However, unlike value-level programming, where the computation occurs at runtime, in type-level programming, the computation occurs at compile time. I will try to draw parallels between programming at the value-level and programming at the type-level.

Paradigms

There are two main paradigms in type-level programming: "object-oriented" and "functional". Most examples linked to from here follow the object-oriented paradigm.

A good, fairly simple example of type-level programming in the object-oriented paradigm can be found in apocalisp's implementation of the lambda calculus, replicated here:

// Abstract trait
trait Lambda {
  type subst[U <: Lambda] <: Lambda
  type apply[U <: Lambda] <: Lambda
  type eval <: Lambda
}

// Implementations
trait App[S <: Lambda, T <: Lambda] extends Lambda {
  type subst[U <: Lambda] = App[S#subst[U], T#subst[U]]
  type apply[U] = Nothing
  type eval = S#eval#apply[T]
}

trait Lam[T <: Lambda] extends Lambda {
  type subst[U <: Lambda] = Lam[T]
  type apply[U <: Lambda] = T#subst[U]#eval
  type eval = Lam[T]
}

trait X extends Lambda {
  type subst[U <: Lambda] = U
  type apply[U] = Lambda
  type eval = X
}

As can be seen in the example, the object-oriented paradigm for type-level programming proceeds as follows:

First: define an abstract trait with various abstract type fields (see below for what an abstract field is). This is a template for guaranteeing that certain types fields exist in all implementations without forcing an implementation. In the lambda calculus example, this corresponds to trait Lambda that guarantees that the following types exist: subst, apply, and eval.

Next: define subtraits that extend the abstract trait and implement the various abstract type fields

Often, these subtraits will be parameterized with arguments. In the lambda calculus example, the subtypes are trait App extends Lambda which is parameterized with two types (S and T, both must be subtypes of Lambda), trait Lam extends Lambda parameterized with one type (T), and trait X extends Lambda (which is not parameterized).

the type fields are often implemented by referring to the type parameters of the subtrait and sometimes referencing their type fields via the hash operator: # (which is very similar to the dot operator: . for values). In trait App of the lambda calculus example, the type eval is implemented as follows: type eval = S#eval#apply[T]. This is essentially calling the eval type of the trait's parameter S, and calling apply with parameter T on the result. Note, S is guaranteed to have an eval type because the parameter specifies it to be a subtype of Lambda. Similarly, the result of eval must have an apply type, since it is specified to be a subtype of Lambda, as specified in the abstract trait Lambda.

The Functional paradigm consists of defining lots of parameterized type constructors that are not grouped together in traits.

Comparison between value-level programming and type-level programming

abstract class

value-level: abstract class C { val x }

type-level: trait C { type X }

path dependent types

C.x (referencing field value/function x in object C)

C#x (referencing field type x in trait C)

function signature (no implementation)

value-level: def f(x:X) : Y

type-level: type f[x <: X] <: Y (this is called a "type constructor" and usually occurs in the abstract trait)

function implementation

value-level: def f(x:X) : Y = x

type-level: type f[x <: X] = x

conditionals

see here

checking equality

value-level: a:A == b:B

type-level: implicitly[A =:= B]

value-level: Happens in the JVM via a unit test at runtime (i.e. no runtime errors):

in essense is an assert: assert(a == b)

type-level: Happens in the compiler via a typecheck (i.e. no compiler errors):

in essence is a type comparison: e.g. implicitly[A =:= B]

A <:< B, compiles only if A is a subtype of B

A =:= B, compiles only if A is a subtype of B and B is a subtype of A

A <%< B, ("viewable as") compiles only if A is viewable as B (i.e. there is an implicit conversion from A to a subtype of B)

an example

more comparison operators

Converting between types and values

In many of the examples, types defined via traits are often both abstract and sealed, and therefore can neither be instantiated directly nor via anonymous subclass. So it is common to use null as a placeholder value when doing a value-level computation using some type of interest:

e.g. val x:A = null, where A is the type you care about

Due to type-erasure, parameterized types all look the same. Furthermore, (as mentioned above) the values you're working with tend to all be null, and so conditioning on the object type (e.g. via a match statement) is ineffective.

The trick is to use implicit functions and values. The base case is usually an implicit value and the recursive case is usually an implicit function. Indeed, type-level programming makes heavy use of implicits.

Consider this example (taken from metascala and apocalisp):

sealed trait Nat
sealed trait _0 extends Nat
sealed trait Succ[N <: Nat] extends Nat

Here you have a peano encoding of the natural numbers. That is, you have a type for each non-negative integer: a special type for 0, namely _0; and each integer greater than zero has a type of the form Succ[A], where A is the type representing a smaller integer. For instance, the type representing 2 would be: Succ[Succ[_0]] (successor applied twice to the type representing zero).

We can alias various natural numbers for more convenient reference. Example:

type _3 = Succ[Succ[Succ[_0]]]

(This is a lot like defining a val to be the result of a function.)

Now, suppose we want to define a value-level function def toInt[T <: Nat](v : T) which takes in an argument value, v, that conforms to Nat and returns an integer representing the natural number encoded in v's type. For example, if we have the value val x:_3 = null (null of type Succ[Succ[Succ[_0]]]), we would want toInt(x) to return 3.

To implement toInt, we're going to make use of the following class:

class TypeToValue[T, VT](value : VT) { def getValue() = value }

As we will see below, there will be an object constructed from class TypeToValue for each Nat from _0 up to (e.g.) _3, and each will store the value representation of the corresponding type (i.e. TypeToValue[_0, Int] will store the value 0, TypeToValue[Succ[_0], Int] will store the value 1, etc.). Note, TypeToValue is parameterized by two types: T and VT. T corresponds to the type we're trying to assign values to (in our example, Nat) and VT corresponds to the type of value we're assigning to it (in our example, Int).

Now we make the following two implicit definitions:

implicit val _0ToInt = new TypeToValue[_0, Int](0)
implicit def succToInt[P <: Nat](implicit v : TypeToValue[P, Int]) =
     new TypeToValue[Succ[P], Int](1 + v.getValue())

And we implement toInt as follows:

def toInt[T <: Nat](v : T)(implicit ttv : TypeToValue[T, Int]) : Int = ttv.getValue()

To understand how toInt works, let's consider what it does on a couple of inputs:

val z:_0 = null
val y:Succ[_0] = null

When we call toInt(z), the compiler looks for an implicit argument ttv of type TypeToValue[_0, Int] (since z is of type _0). It finds the object _0ToInt, it calls the getValue method of this object and gets back 0. The important point to note is that we did not specify to the program which object to use, the compiler found it implicitly.

Now let's consider toInt(y). This time, the compiler looks for an implicit argument ttv of type TypeToValue[Succ[_0], Int] (since y is of type Succ[_0]). It finds the function succToInt, which can return an object of the appropriate type (TypeToValue[Succ[_0], Int]) and evaluates it. This function itself takes an implicit argument (v) of type TypeToValue[_0, Int] (that is, a TypeToValue where the first type parameter is has one fewer Succ[_]). The compiler supplies _0ToInt (as was done in the evaluation of toInt(z) above), and succToInt constructs a new TypeToValue object with value 1. Again, it is important to note that the compiler is providing all of these values implicitly, since we do not have access to them explicitly.

Checking your work

There are several ways to verify that your type-level computations are doing what you expect. Here are a few approaches. Make two types A and B, that you want to verify are equal. Then check that the following compile:

Equal[A, B]

with: trait Equal[T1 >: T2 <: T2, T2] (taken from apocolisp)

implicitly[A =:= B]

Alternatively, you can convert the type to a value (as shown above) and do a runtime check of the values. E.g. assert(toInt(a) == toInt(b)), where a is of type A and b is of type B.

Additional Resources

The complete set of available constructs can be found in the types section of the scala reference manual (pdf).

Adriaan Moors has several academic papers about type constructors and related topics with examples from scala:

Generics of a higher kind (pdf)

Type Constructor Polymorphism for Scala: Theory and Practice (pdf) (PhD thesis, which includes the previous paper by Moors)

Type Constructor Polymorphism Inference

Apocalisp is a blog with many examples of type-level programming in scala.

Type-Level Programming in Scala is a fantastic guided tour of some type-level programming which includes booleans, natural numbers (as above), binary numbers, heterogeneous lists, and more.

More Scala Typehackery is the lambda calculus implementation above.

ScalaZ is a very active project that is providing functionality that extends the Scala API using various type-level programming features. It is a very interesting project that has a big following.

MetaScala is a type-level library for Scala, including meta types for natural numbers, booleans, units, HList, etc. It is a project by Jesper Nordenberg (his blog).

The Michid (blog) has some awesome examples of type-level programming in Scala (from other answer):

Meta-Programming with Scala Part I: Addition

Meta-Programming with Scala Part II: Multiplication

Meta-Programming with Scala Part III: Partial function application

Meta-Programming with Scala: Conditional Compilation and Loop Unrolling

Scala type level encoding of the SKI calculus

Debasish Ghosh (blog) has some relevant posts as well:

Higher order abstractions in scala

Static typing gives you a head start

Scala implicits type classes, here I come

Refactoring into scala type-classes

Using generalized type constraints

How scalas type system words for you

Choosing between abstract type members

(I've been doing some research on this subject and here's what I've learned. I'm still new to it, so please point out any inaccuracies in this answer.)


问:
Vagrant up doesn't work
When I run 'vagrant up', I am getting below errors. I haven't any idea. Previously I was run without error. I sold SSD Harddisk and took it. When I want setup again, encountered this errors.</p>

```<code>/Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:106:in `read': No such file or directory @ rb_sysopen - /Users/KerimCaglar/KerimCaglar/.ssh/id_rsa (Errno::ENOENT)
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:106:in `block (2 levels) in configure'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/plugins/kernel_v2/config/vm_provisioner.rb:72:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/plugins/kernel_v2/config/vm_provisioner.rb:72:in `add_config'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/plugins/kernel_v2/config/vm.rb:321:in `provision'
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:103:in `block in configure'
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:102:in `each'
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:102:in `configure'
from /Users/KerimCaglar/sites/Homestead/Vagrantfile:20:in `block in <top (required)>'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/v2/loader.rb:37:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/v2/loader.rb:37:in `load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:113:in `block (2 levels) in load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:107:in `each'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:107:in `block in load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:104:in `each'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:104:in `load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/vagrantfile.rb:28:in `initialize'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:740:in `new'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:740:in `vagrantfile'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:486:in `host'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:208:in `block in action_runner'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/action/runner.rb:33:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/action/runner.rb:33:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:473:in `hook'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:722:in `unload'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/bin/vagrant:177:in `ensure in <main>'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/bin/vagrant:177:in `<main>'
</code>```

答: If you've got Git installed, all you have to do is simply go generate your ssh key through the GUI. Help -> Show Key

Title: Vagrant up doesn't work

Body:
When I run 'vagrant up', I am getting below errors. I haven't any idea. Previously I was run without error. I sold SSD Harddisk and took it. When I want setup again, encountered this errors.

/Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:106:in `read': No such file or directory @ rb_sysopen - /Users/KerimCaglar/KerimCaglar/.ssh/id_rsa (Errno::ENOENT)
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:106:in `block (2 levels) in configure'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/plugins/kernel_v2/config/vm_provisioner.rb:72:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/plugins/kernel_v2/config/vm_provisioner.rb:72:in `add_config'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/plugins/kernel_v2/config/vm.rb:321:in `provision'
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:103:in `block in configure'
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:102:in `each'
from /Users/KerimCaglar/sites/Homestead/scripts/homestead.rb:102:in `configure'
from /Users/KerimCaglar/sites/Homestead/Vagrantfile:20:in `block in <top (required)>'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/v2/loader.rb:37:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/v2/loader.rb:37:in `load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:113:in `block (2 levels) in load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:107:in `each'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:107:in `block in load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:104:in `each'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/config/loader.rb:104:in `load'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/vagrantfile.rb:28:in `initialize'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:740:in `new'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:740:in `vagrantfile'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:486:in `host'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:208:in `block in action_runner'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/action/runner.rb:33:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/action/runner.rb:33:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:473:in `hook'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/lib/vagrant/environment.rb:722:in `unload'
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/bin/vagrant:177:in `ensure in '
from /opt/vagrant/embedded/gems/gems/vagrant-1.8.1/bin/vagrant:177:in `'


问:
Parallel commands in cmake
I have a (simplified) CMAKE file like so:

```<code>cmake_minimum_required( VERSION 3.6 )

function(BUILD_SIMULINK model)

   set(OUTPUT_FILE ${model}.dll)
   set(SOURCE_FILE ${model}.slx)
   set(EXECUTE_COMMAND
      matlab -nojvm -nodisplay -nodesktop -nosplash -wait -r "rtwbuild(${model})"
   )

   add_custom_target(
      ${model}  ALL
      DEPENDS  ${OUTPUT_FILE}
   )

   add_custom_command(
      COMMAND    ${EXECUTE_COMMAND}
      DEPENDS    ${SOURCE_FILE}
      OUTPUT     ${OUTPUT_FILE}
   )

   install( TARGETS ${OUTPUT_FILE}
            DESTINATION lib
   )

endfunction(BUILD_SIMULINK)

project(SimulinkBuild VERSION 1.0.0)
build_simulink( model1 )
build_simulink( model2 )
build_simulink( model3 )
...
build_simulink( modeln )  # Arbitrarily large number of models
</code>```

My problem is that it takes several hours to do a clean build because I am calling one command at a time, using only one core at a time.  I'd like to build my files in parallel, taking advantage of the multiple cores on my machine.  How can we achieve executing parallel commands from cmake?

When I build I do this:

```<code>cmake ..
cmake --build . --target install
</code>```

答:
The solution is how to invoke cmake, and isn't part of the cmake file itself.</p>

```<code>cmake ..
cmake --build . -- /m  # Visual Studio
cmake --build . -- -j  # Gnu make
</code>```

Title: Parallel commands in cmake

Body:
I have a (simplified) CMAKE file like so:

cmake_minimum_required( VERSION 3.6 )

function(BUILD_SIMULINK model)

   set(OUTPUT_FILE ${model}.dll)
   set(SOURCE_FILE ${model}.slx)
   set(EXECUTE_COMMAND
      matlab -nojvm -nodisplay -nodesktop -nosplash -wait -r "rtwbuild(${model})"
   )

   add_custom_target(
      ${model}  ALL
      DEPENDS  ${OUTPUT_FILE}
   )

   add_custom_command(
      COMMAND    ${EXECUTE_COMMAND}
      DEPENDS    ${SOURCE_FILE}
      OUTPUT     ${OUTPUT_FILE}
   )

   install( TARGETS ${OUTPUT_FILE}
            DESTINATION lib
   )

endfunction(BUILD_SIMULINK)

project(SimulinkBuild VERSION 1.0.0)
build_simulink( model1 )
build_simulink( model2 )
build_simulink( model3 )
...
build_simulink( modeln )  # Arbitrarily large number of models

My problem is that it takes several hours to do a clean build because I am calling one command at a time, using only one core at a time.  I'd like to build my files in parallel, taking advantage of the multiple cores on my machine.  How can we achieve executing parallel commands from cmake?

When I build I do this:

cmake ..
cmake --build . --target install

Body:
The solution is how to invoke cmake, and isn't part of the cmake file itself.

cmake ..
cmake --build . -- /m  # Visual Studio
cmake --build . -- -j  # Gnu make


问:
Android - What is the difference between getArguments and Bundle received in the onCreate
What is the difference between getArguments Bundle and Bundle received in the onCreate?

答:
I would like to add to N15M0_jk's answer.
Sometimes there's no need to save fragment state (for static fragments) and you could use only getArguments() for re-creation since the arguments set with setArguments() are retained even after destroy.

See the reference on setArguments()

ContentLicense: CC BY-SA 4.0


问:
Flattening multiple repeated fields in Google BigQuery
I'm trying to flatten data from repeated fields in Big Query. I have had a look at this Querying multiple repeated fields in BigQuery, however I can't seem to get this to work.

My data looks like the following:

```<code>[
  {
    "visitorId": null,
    "visitNumber": "15",

    "device": {
      "browser": "Safari (in-app)",
      "browserVersion": "(not set)",
      "browserSize": "380x670",
      "operatingSystem": "iOS",
    },
    "hits": [
      {
        "isEntrance": "true",
        "isExit": "true",
        "referer": null,
        "page": {
          "pagePath": "/news/bla-bla-bla",
          "hostname": "www.example.com",
          "pageTitle": "Win tickets!!",
          "searchKeyword": null,
          "searchCategory": null,
          "pagePathLevel1": "/news/",
          "pagePathLevel2": "/bla-bla-bla",
          "pagePathLevel3": "",
          "pagePathLevel4": ""
        },
        "transaction": null
      }
    ]
  }
]
</code>```

What I want is the fields in the hits-page repeated fields.

For instance i want to fetch the hits.page.pagePath (with the value "/news/bla-bla-bla")

I have tried with the following query, but i get an error:

```<code>SELECT
visitorId,
visitNumber,
device.browser,
hits.page.pagePath
FROM
`Project.Page`
LIMIT 1000
</code>```

The error i'm getting is this

```<code>Error: Cannot access field page on a value with type ARRAY<STRUCT<hitNumber INT64, time INT64, hour INT64, ...>>
</code>```

答:
In ga_sessions schema, the field hits is represented as an ARRAY type.

Usually when working with this type field you need to apply the UNNEST operation in order to open the array.

Specifically, in the FROM clause, you can apply a CROSS JOIN (you unnest arrays by applying a cross join operation, which can be represented as a comma followed by the UNNEST function) like so:

```<code>SELECT
  visitorId,
  visitNumber,
  device.browser,
  hits.page.pagePath
FROM `Project.Page`,
UNNEST(hits) hits
LIMIT 1000
</code>```

If you want specific pagePaths, you can filter them out like so:

```<code>SELECT
  visitorId,
  visitNumber,
  device.browser,
  hits.page.pagePath
FROM `Project.Page`,
UNNEST(hits) hits
WHERE regexp_contains(hits.page.pagePath, r'/news/bla-bla-bla')
LIMIT 1000
</code>```

Make sure to follow through BigQuery documentation on this topic, it's really well written and you'll learn a lot on new techniques to process big data.

Body:
I'm trying to flatten data from repeated fields in Big Query. I have had a look at this Querying multiple repeated fields in BigQuery, however I can't seem to get this to work.

My data looks like the following:

[
  {
    "visitorId": null,
    "visitNumber": "15",

    "device": {
      "browser": "Safari (in-app)",
      "browserVersion": "(not set)",
      "browserSize": "380x670",
      "operatingSystem": "iOS",
    },
    "hits": [
      {
        "isEntrance": "true",
        "isExit": "true",
        "referer": null,
        "page": {
          "pagePath": "/news/bla-bla-bla",
          "hostname": "www.example.com",
          "pageTitle": "Win tickets!!",
          "searchKeyword": null,
          "searchCategory": null,
          "pagePathLevel1": "/news/",
          "pagePathLevel2": "/bla-bla-bla",
          "pagePathLevel3": "",
          "pagePathLevel4": ""
        },
        "transaction": null
      }
    ]
  }
]

What I want is the fields in the hits-page repeated fields.

For instance i want to fetch the hits.page.pagePath (with the value "/news/bla-bla-bla")

I have tried with the following query, but i get an error:

SELECT
visitorId,
visitNumber,
device.browser,
hits.page.pagePath
FROM
`Project.Page`
LIMIT 1000

The error i'm getting is this

Error: Cannot access field page on a value with type ARRAY<STRUCT<hitNumber INT64, time INT64, hour INT64, ...>>

Body:
In ga_sessions schema, the field hits is represented as an ARRAY type.

Usually when working with this type field you need to apply the UNNEST operation in order to open the array.

Specifically, in the FROM clause, you can apply a CROSS JOIN (you unnest arrays by applying a cross join operation, which can be represented as a comma followed by the UNNEST function) like so:

SELECT
  visitorId,
  visitNumber,
  device.browser,
  hits.page.pagePath
FROM `Project.Page`,
UNNEST(hits) hits
LIMIT 1000

If you want specific pagePaths, you can filter them out like so:

SELECT
  visitorId,
  visitNumber,
  device.browser,
  hits.page.pagePath
FROM `Project.Page`,
UNNEST(hits) hits
WHERE regexp_contains(hits.page.pagePath, r'/news/bla-bla-bla')
LIMIT 1000

Make sure to follow through BigQuery documentation on this topic, it's really well written and you'll learn a lot on new techniques to process big data.


答:
You can alias the aggregations directly:</p>

```<code>pivoted = df_data \
    .groupby(df_data.id, df_data.type) \
    .pivot("date") \
    .agg(
       avg('cost').alias('cost'),
       first("ship").alias('ship')
    )

pivoted.printSchema()
##root
##|-- id: long (nullable = true)
##|-- type: string (nullable = true)
##|-- 201601_cost: double (nullable = true)
##|-- 201601_ship: string (nullable = true)
##|-- 201602_cost: double (nullable = true)
##|-- 201602_ship: string (nullable = true)
##|-- 201603_cost: double (nullable = true)
##|-- 201603_ship: string (nullable = true)
</code>```

Title: Rename pivoted and aggregated column in PySpark Dataframe

Body:
With a dataframe as follows:

from pyspark.sql.functions import avg, first

rdd = sc.parallelize(
    [
        (0, "A", 223,"201603", "PORT"),
        (0, "A", 22,"201602", "PORT"),
        (0, "A", 422,"201601", "DOCK"),
        (1,"B", 3213,"201602", "DOCK"),
        (1,"B", 3213,"201601", "PORT"),
        (2,"C", 2321,"201601", "DOCK")
    ]
)
df_data = sqlContext.createDataFrame(rdd, ["id","type", "cost", "date", "ship"])

df_data.show()

I do a pivot on it,

df_data.groupby(df_data.id, df_data.type).pivot("date").agg(avg("cost"), first("ship")).show()

+---+----+----------------+--------------------+----------------+--------------------+----------------+--------------------+
| id|type|201601_avg(cost)|201601_first(ship)()|201602_avg(cost)|201602_first(ship)()|201603_avg(cost)|201603_first(ship)()|
+---+----+----------------+--------------------+----------------+--------------------+----------------+--------------------+
|  2|   C|          2321.0|                DOCK|            null|                null|            null|                null|
|  0|   A|           422.0|                DOCK|            22.0|                PORT|           223.0|                PORT|
|  1|   B|          3213.0|                PORT|          3213.0|                DOCK|            null|                null|
+---+----+----------------+--------------------+----------------+--------------------+----------------+--------------------+

But I get these really complicated names for the columns. Applying alias on the aggregation usually works, but because of the pivot in this case the names are even worse:

+---+----+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+
| id|type|201601_(avg(cost),mode=Complete,isDistinct=false) AS cost#1619|201601_(first(ship)(),mode=Complete,isDistinct=false) AS ship#1620|201602_(avg(cost),mode=Complete,isDistinct=false) AS cost#1619|201602_(first(ship)(),mode=Complete,isDistinct=false) AS ship#1620|201603_(avg(cost),mode=Complete,isDistinct=false) AS cost#1619|201603_(first(ship)(),mode=Complete,isDistinct=false) AS ship#1620|
+---+----+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+
|  2|   C|                                                        2321.0|                                                              DOCK|                                                          null|                                                              null|                                                          null|                                                              null|
|  0|   A|                                                         422.0|                                                              DOCK|                                                          22.0|                                                              PORT|                                                         223.0|                                                              PORT|
|  1|   B|                                                        3213.0|                                                              PORT|                                                        3213.0|                                                              DOCK|                                                          null|                                                              null|
+---+----+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+

Is there a way to rename the column names on the fly on the pivot and aggregation?

Body:
You can alias the aggregations directly:

pivoted = df_data \
    .groupby(df_data.id, df_data.type) \
    .pivot("date") \
    .agg(
       avg('cost').alias('cost'),
       first("ship").alias('ship')
    )

pivoted.printSchema()
##root
##|-- id: long (nullable = true)
##|-- type: string (nullable = true)
##|-- 201601_cost: double (nullable = true)
##|-- 201601_ship: string (nullable = true)
##|-- 201602_cost: double (nullable = true)
##|-- 201602_ship: string (nullable = true)
##|-- 201603_cost: double (nullable = true)
##|-- 201603_ship: string (nullable = true)


问:
Swift: Extracting Int16 & Int8 from Data
I am trying to retrieve data from two BLE characteristics values. They both contain structures, and I want to save this data as structures in my application too. Data from first BLE characteristic is all Int16, I was able to save it. But the problem is that second characteristic contains both Int8 & Int16, and I can't find a solution to deal with it.

In my application, I have created two different structures for both characteristics. The first structure looks like this, it's all Int16.

```<code>     struct FirstStruct {
     let a1: Int16
     ...
     let a6: Int16 }
</code>```

The second is like that, has 2 types:

```<code>     struct SecondStruct {
     let b1: Int16
     let b2: Int8
     let b3: Int8
</code>```

}

When I get data from characteristic.value for first characteristic, I am able to simply do it like this:

```<code>    data = characteristic.value
    let firstData = data.withUnsafeBytes {(int16Ptr: UnsafePointer<Int16>)-> FirstStruct in
            FirstStruct(a1: Int16(littleEndian: int16Ptr[0]),
                        ...
                        a6: Int16(littleEndian: int16Ptr[5]))
        }
</code>```

But how can I do it for the 2nd characteristic? Same way doesn't work, because it has both Int16 & Int8, results in error. I guess, I could try to interpret all values as Int16 and then convert to Int8? But this is probably a bad idea? Is there other way to extract the data from second characteristic and put it into my desired structure?

答:
May be this will help you:

```<code>let a:Int8 = 1
let b:Int16 = 1
let aSize = MemoryLayout.size(ofValue:a)
print(aSize) // will return 1
let bSize = MemoryLayout.size(ofValue:b)
print(bSize) // will return 2
</code>```

Using this code, you can check the size of received values.

Body:
I am trying to retrieve data from two BLE characteristics values. They both contain structures, and I want to save this data as structures in my application too. Data from first BLE characteristic is all Int16, I was able to save it. But the problem is that second characteristic contains both Int8 & Int16, and I can't find a solution to deal with it.

In my application, I have created two different structures for both characteristics. The first structure looks like this, it's all Int16.

     struct FirstStruct {
     let a1: Int16
     ...
     let a6: Int16 }

The second is like that, has 2 types:

     struct SecondStruct {
     let b1: Int16
     let b2: Int8
     let b3: Int8

}

When I get data from characteristic.value for first characteristic, I am able to simply do it like this:

    data = characteristic.value
    let firstData = data.withUnsafeBytes {(int16Ptr: UnsafePointer<Int16>)-> FirstStruct in
            FirstStruct(a1: Int16(littleEndian: int16Ptr[0]),
                        ...
                        a6: Int16(littleEndian: int16Ptr[5]))
        }

But how can I do it for the 2nd characteristic? Same way doesn't work, because it has both Int16 & Int8, results in error. I guess, I could try to interpret all values as Int16 and then convert to Int8? But this is probably a bad idea? Is there other way to extract the data from second characteristic and put it into my desired structure?

Body:
May be this will help you:

let a:Int8 = 1
let b:Int16 = 1
let aSize = MemoryLayout.size(ofValue:a)
print(aSize) // will return 1
let bSize = MemoryLayout.size(ofValue:b)
print(bSize) // will return 2

Using this code, you can check the size of received values.


问:
Non-capturing lambda seems to nevertheless capture the enclosing instance
I wrote this code:

```<code>import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main();
    }

    private Main() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable) () -> new Thread() {};
        new ObjectOutputStream(System.out).writeObject(supplier);
    }
}
</code>```

If I run it, I'll get an exception:

```<code>Exception in thread "main" java.io.NotSerializableException: Main
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1378)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at Main.<init>(Main.java:28)
</code>```

However, my understanding is that I properly made the lambda Serializable and I declared it such that it doesn't refer to any surrounding context, being therefore a non-capturing lambda. Yet the Main instance is captured and the result of the lambda expression fails to be serialized. I realize I'm declaring an anonymous class inside the lambda, but I would expect the lambda instance itself to be its enclosing instance, not the surrounding Main type.

Is this behavior expected by the Java Language Specification and, if yes, how come?

答:
Put simply:

anonymous classes always reference enclosing instance when created in a non-static context

this in lambda is the lambda's enclosing instance (not the lambda itself)

From this follows, that anonymous class inside a lambda expression captures the instance enclosing the lambda expression. In your example it captures the instance of Main, which is not serializable.

Possible solutions:

create the lambda in static context: in a static method or assign to a static field

replace the anonymous class with static nested class:

```<code>import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main();
    }

    private Main() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable) MyThread::new;
        new ObjectOutputStream(System.out).writeObject(supplier);
    }

    private static class MyThread extends Thread {
    }
}
</code>```

Body:
I wrote this code:

import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main();
    }

    private Main() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable) () -> new Thread() {};
        new ObjectOutputStream(System.out).writeObject(supplier);
    }
}

If I run it, I'll get an exception:

Exception in thread "main" java.io.NotSerializableException: Main
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1378)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at Main.<init>(Main.java:28)

However, my understanding is that I properly made the lambda Serializable and I declared it such that it doesn't refer to any surrounding context, being therefore a non-capturing lambda. Yet the Main instance is captured and the result of the lambda expression fails to be serialized. I realize I'm declaring an anonymous class inside the lambda, but I would expect the lambda instance itself to be its enclosing instance, not the surrounding Main type.

Is this behavior expected by the Java Language Specification and, if yes, how come?

Body:
Put simply:

anonymous classes always reference enclosing instance when created in a non-static context

this in lambda is the lambda's enclosing instance (not the lambda itself)

From this follows, that anonymous class inside a lambda expression captures the instance enclosing the lambda expression. In your example it captures the instance of Main, which is not serializable.

Possible solutions:

create the lambda in static context: in a static method or assign to a static field

replace the anonymous class with static nested class:

import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main();
    }

    private Main() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable) MyThread::new;
        new ObjectOutputStream(System.out).writeObject(supplier);
    }

    private static class MyThread extends Thread {
    }
}


问:
encode image to base64 is not equal to original
I am trying to encode/decode an image view and I looked at more than 50 examples but it still does´t work.

I did a simple thing to start with:

1) i am using the simple base 64 data from http://codebeautify.org/base64-to-image-converter#

2) i put it into a blob field of a mysql db (hosted in a remote server)

3) in android I get it correctly via a web service, decode it and show in an image view

```<code>public static Bitmap decodeBase64(String input)
{
    byte[] decodedByte = Base64.decode(input.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
</code>```

(so far so good)

4) i am encoding what is in the image view (placed in step 3) and generate a base64 code using

```<code>    imageGrupo.buildDrawingCache();
    Bitmap bitmap = imageGrupo.getDrawingCache();
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
    byte[] image=stream.toByteArray();
    finalImagemStr = Base64.encodeToString(image, 0);
</code>```

5) if i compare the generated base64 with the one I received in 3 they are not the same.

They should be right?

6) when placing the base64 string generated in 4) in the remote database and reading it again it says

```<code>  java.lang.IllegalArgumentException: bad base-64
</code>```

I am going crazy at this point... Any ideas?

Thanks
Regards

答: Try my solution which explains how to encode bitmap to base64 and decode base64 back to bitmap successfully. You can skip the scale image part of the code if you require the exact original image.</p>

Body:
I am trying to encode/decode an image view and I looked at more than 50 examples but it still does´t work.

I did a simple thing to start with:

1) i am using the simple base 64 data from http://codebeautify.org/base64-to-image-converter#

2) i put it into a blob field of a mysql db (hosted in a remote server)

3) in android I get it correctly via a web service, decode it and show in an image view

public static Bitmap decodeBase64(String input)
{
    byte[] decodedByte = Base64.decode(input.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}

(so far so good)

4) i am encoding what is in the image view (placed in step 3) and generate a base64 code using

    imageGrupo.buildDrawingCache();
    Bitmap bitmap = imageGrupo.getDrawingCache();
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
    byte[] image=stream.toByteArray();
    finalImagemStr = Base64.encodeToString(image, 0);

5) if i compare the generated base64 with the one I received in 3 they are not the same.

They should be right?

6) when placing the base64 string generated in 4) in the remote database and reading it again it says

  java.lang.IllegalArgumentException: bad base-64

I am going crazy at this point... Any ideas?

Thanks
Regards


问:
Using Wordpress, how can I create a new menu item that links to an archive of a custom post type?
I have a function that programmatically creates menu items in Wordpress. I am able to create menu items to individual pages and posts, but how can I create a menu item for a custom post type archive? Specifically, what are the arguments passed to wp_update_nav_menu_item()?

```<code>$args = []; // what goes in this array?

wp_update_nav_menu_item($menuID, 0, $args);
</code>```

答:
After searching through the core Wordpress files, I found the necessary arguments. The key is setting menu-item-object to be the slug of your post type and the menu-item-type to be post_type_archive.

```<code>$args = [
    'menu-item-position' => $position,
    'menu-item-status' => 'publish',
    'menu-item-parent-id' => 0,
    'menu-item-object' => 'my-post-type',
    'menu-item-type' => 'post_type_archive'
];

wp_update_nav_menu_item($menuID, 0, $args);
</code>```

Body:
I have a function that programmatically creates menu items in Wordpress. I am able to create menu items to individual pages and posts, but how can I create a menu item for a custom post type archive? Specifically, what are the arguments passed to wp_update_nav_menu_item()?

$args = []; // what goes in this array?

wp_update_nav_menu_item($menuID, 0, $args);

Body:
After searching through the core Wordpress files, I found the necessary arguments. The key is setting menu-item-object to be the slug of your post type and the menu-item-type to be post_type_archive.

$args = [
    'menu-item-position' => $position,
    'menu-item-status' => 'publish',
    'menu-item-parent-id' => 0,
    'menu-item-object' => 'my-post-type',
    'menu-item-type' => 'post_type_archive'
];

wp_update_nav_menu_item($menuID, 0, $args);


问:
Included module cannot call instance variable of parent class
For example, I have a class that defined a instance variable:

```<code> class ApplicationApi < Grape::API
    include WithGrapeLogging
    @api_environment_name = "Android"
  end
</code>```

Here is my custom module, in this custom module, I called instance variable of above class:

```<code>require 'grape_logging'
module WithGrapeLogging
  extend ActiveSupport::Concern
  included do
      logger.formatter = GrapeLogging::Formatters::Default.new

      use GrapeLogging::Middleware::RequestLogger,
        logger: logger,
        formatter: GrapeLoggerFormatter.new(@api_environment_name),
        include: [ GrapeLogging::Loggers::Response.new,
                   GrapeLogging::Loggers::FilterParameters.new,
                   GrapeLogging::Loggers::ClientEnv.new,
                   GrapeLogging::Loggers::RequestHeaders.new ]
  end
end
</code>```

I don't know what that variable is null. Please figure me how.

答:
Let's take a look at the Module#include method's source code:

```<code>               static VALUE
rb_mod_include(int argc, VALUE *argv, VALUE module)
{
    int i;
    ID id_append_features, id_included;

    CONST_ID(id_append_features, "append_features");
    CONST_ID(id_included, "included");

    for (i = 0; i < argc; i++)
        Check_Type(argv[i], T_MODULE);
    while (argc--) {
        rb_funcall(argv[argc], id_append_features, 1, module);
        rb_funcall(argv[argc], id_included, 1, module);
    }
    return module;
}
</code>```

We can see that for each of the arguments passed to Module#include, it calls the block passed to included (via rb_funcall)

When you include your module on the second line of your class definition, it calls the block provided to included in your module definition. When it's running through that block, Ruby identifies that @api_environment_name has not been defined and throws an error. If you put the definition of that instance variable before you include the module, it will recognize it.

Body:
For example, I have a class that defined a instance variable:

 class ApplicationApi < Grape::API
    include WithGrapeLogging
    @api_environment_name = "Android"
  end

Here is my custom module, in this custom module, I called instance variable of above class:

require 'grape_logging'
module WithGrapeLogging
  extend ActiveSupport::Concern
  included do
      logger.formatter = GrapeLogging::Formatters::Default.new

      use GrapeLogging::Middleware::RequestLogger,
        logger: logger,
        formatter: GrapeLoggerFormatter.new(@api_environment_name),
        include: [ GrapeLogging::Loggers::Response.new,
                   GrapeLogging::Loggers::FilterParameters.new,
                   GrapeLogging::Loggers::ClientEnv.new,
                   GrapeLogging::Loggers::RequestHeaders.new ]
  end
end

I don't know what that variable is null. Please figure me how.

Body:
Let's take a look at the Module#include method's source code:

               static VALUE
rb_mod_include(int argc, VALUE *argv, VALUE module)
{
    int i;
    ID id_append_features, id_included;

    CONST_ID(id_append_features, "append_features");
    CONST_ID(id_included, "included");

    for (i = 0; i < argc; i++)
        Check_Type(argv[i], T_MODULE);
    while (argc--) {
        rb_funcall(argv[argc], id_append_features, 1, module);
        rb_funcall(argv[argc], id_included, 1, module);
    }
    return module;
}

We can see that for each of the arguments passed to Module#include, it calls the block passed to included (via rb_funcall)

When you include your module on the second line of your class definition, it calls the block provided to included in your module definition. When it's running through that block, Ruby identifies that @api_environment_name has not been defined and throws an error. If you put the definition of that instance variable before you include the module, it will recognize it.


答:
The "exists" is definitely the issue.  You could use an IN and reference whatever the Primary Key is.</p>

```<code>update [DaisyCompare].[dbo].[Baseline]

set Disposition = ('Match')

where [DaisyCompare].[dbo].[Baseline].[PrimaryID] IN
 (
SELECT [b.PrimaryID] FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b

on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description] )
</code>```

Title: SQL Update and Join updating wrong records

Body:
I am trying to use an UPDATE statement with a JOIN on SQL Server.

if I run the below SELECT statement it returns 42 rows.

SELECT * FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b
on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

However when I use it as a condition within my update statement (below), the query updates 44 records.

update [DaisyCompare].[dbo].[Baseline]

set Disposition = ('Match')

where exists (
SELECT * FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b

on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description] )

Presumably my syntax is wrong, but I am not sure where.

Any help greatly appreciated.

Body:
The "exists" is definitely the issue.  You could use an IN and reference whatever the Primary Key is.

update [DaisyCompare].[dbo].[Baseline]

set Disposition = ('Match')

where [DaisyCompare].[dbo].[Baseline].[PrimaryID] IN
 (
SELECT [b.PrimaryID] FROM [dbo].[Imported] i
inner join [DaisyCompare].[dbo].[Baseline] b

on
b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description]

WHERE b.[CLI]=i.[CLI] AND
b.[Quantity]=i.[Quantity] AND
b.[UnitCost]=i.[UnitCost] AND
b.[TotalCost]=i.[TotalCost] AND
b.[Description]=i.[Description] )


问:
Create a new dictionary in python with unique values based in the second parameter
I have a dictionary like this

```<code>{id : ['string',[1,2,3,4,5]], .....}
</code>```

I would like to create a new dictionary with unique strings.
But if we have strings that are equal, filter one of them based on the biggest average of the second value.
As an example, I have

```<code>{x:['ABC', [1,2,3,4,5], y:['ABC',[6,7,8,9,10],...}
</code>```

in this case, x and y have the same string for the first value, but, the average of 6,7,8,9,10 is > than 1,2,3,4,5. So y would be appended to the new dictionary

Body:
I have a dictionary like this

{id : ['string',[1,2,3,4,5]], .....}

I would like to create a new dictionary with unique strings.
But if we have strings that are equal, filter one of them based on the biggest average of the second value.
As an example, I have

{x:['ABC', [1,2,3,4,5], y:['ABC',[6,7,8,9,10],...}

in this case, x and y have the same string for the first value, but, the average of 6,7,8,9,10 is > than 1,2,3,4,5. So y would be appended to the new dictionary

Body:
Use the following approach:

# exemplary dict
d = {'x':['ABC', [1,2,3,4,5]], 'y':['ABC',[6,7,8,9,10]], 'z': ['BCA', [1,2,3]]}
new_d = {}

for k,v in d.items():
    if v[0] not in new_d or sum(v[1])/len(v[1]) > sum(new_d[v[0]][0])/len(new_d[v[0]][0]):
        new_d[v[0]] = [v[1], k]

new_d = {v[1]:[k, v[0]] for k,v in new_d.items()}
print(new_d)

The output:

{'y': ['ABC', [6, 7, 8, 9, 10]], 'z': ['BCA', [1, 2, 3]]}


问:
Multiple Thread Writer with Single Thread Reader using PipedOutputStream and PipedInputStream
I have a Multiple Writer Threads with Single Reader Thread model.
The ThreadMultipleDateReceiver class is designed to read from multiple Threads.

```<code>public class ThreadMultipleDateReceiver extends Thread {

  private static final int MAX_CLIENT_THREADS = 4;
  private byte[] incomingBytes;
  private volatile boolean isRunning;
  private volatile List<ThreadStreamDateWriter> lThrdDate;

  private static PipedInputStream pipedInputStream;

  public ThreadMultipleDateReceiver() {
    lThrdDate = Collections.synchronizedList(new ArrayList<>(MAX_CLIENT_THREADS));
    pipedInputStream = new PipedInputStream();
    System.out.println("ThreadMultipleDateReceiver Created");
  }

  @Override public void run() {
    isRunning = true;
    while (isRunning) {
      if (!lThrdDate.isEmpty()) {
        System.out.println("ThreadMultipleDateReceiver has:" + lThrdDate.size());
        for (int i = lThrdDate.size(); i > 0; i--) {
          if (lThrdDate.get(i - 1).getState() == Thread.State.TERMINATED) {
            lThrdDate.remove(i - 1);
          } else {
            System.out.println("I ThreadMultipleDateReceiver have:" + lThrdDate.get(i - 1).getNameDateWriter());
          }
        }
        incomingBytes = new byte[1024];
        try {
          String str = "";
          int iRd;
          System.out.println("ThreadMultipleDateReceiver waiting:" + str);
          while ((iRd = pipedInputStream.read(incomingBytes)) != -1) {
            if (iRd > 0) {
              str += new String(incomingBytes);
            }
          }
          System.out.println("ThreadMultipleDateReceiver Received:\n\t:" + str);
        } catch (IOException e) { }
      } else {
        System.out.println("ThreadMultipleDateReceiver Empty");
      }
    }
    emptyDateWriters();
  }

  public void addDateWriter(ThreadStreamDateWriter threadDateWriter) {
    if (lThrdDate.size() < MAX_CLIENT_THREADS) {
      lThrdDate.add(threadDateWriter);
    }
  }

  private void emptyDateWriters() {
    if (!lThrdDate.isEmpty()) {
      for (int i = lThrdDate.size(); i > 0; i--) {
        ThreadStreamDateWriter threadDateWriter = lThrdDate.get(i - 1);
        threadDateWriter.stopThread();
        lThrdDate.remove(i - 1);
      }
    }
  }

  public PipedInputStream getPipedInputStream() {
    return pipedInputStream;
  }

  public void stopThread() {
    isRunning = false;
  }

}
</code>```

And the single Writer Thread

```<code>public class ThreadStreamDateWriter extends Thread {
  String Self;
  private byte[] outgoingBytes;
  private volatile boolean isRunning;
  private static PipedOutputStream pipedOutputStream;

  ThreadStreamDateWriter(String name, PipedInputStream snk) {
    Self = name;
    pipedOutputStream = new PipedOutputStream();
    try {
      pipedOutputStream.connect(snk);
    } catch (IOException e) { }
  }

  @Override public void run() {
    isRunning = true;
    while (isRunning) {
      try {
        outgoingBytes = getInfo().getBytes();
        System.out.println("ThreadStreamDateWriter -> write to pipedOutputStream:" + new String(outgoingBytes));
        pipedOutputStream.write(outgoingBytes);
        System.out.println("ThreadStreamDateWriter -> wrote:" + new String(outgoingBytes));
        try { Thread.sleep(4000); } catch (InterruptedException ex) { }
      } catch (IOException | NegativeArraySizeException | IndexOutOfBoundsException e) {
        isRunning = false;
      }
    }
  }

  String getInfo() {
      String sDtTm = new SimpleDateFormat("yyyyMMdd-hhmmss").format(Calendar.getInstance().getTime());
      return Self + " -> " + sDtTm;
  }

  public void stopThread() {
    isRunning = false;
  }

  public String getNameDateWriter() {
    return Self;
  }
}
</code>```

How launch (I'm using Netbeans)?

```<code>ThreadMultipleDateReceiver thrdMDateReceiver = null;
ThreadStreamDateWriter thrdSDateWriter0 = null;
ThreadStreamDateWriter thrdSDateWriter1 = null;
  private void jtbDateExchangerActionPerformed(java.awt.event.ActionEvent evt) {
    if (jtbDateExchanger.isSelected()) {
      if (thrdMDateReceiver == null) {
        thrdMDateReceiver = new ThreadMultipleDateReceiver();
        thrdMDateReceiver.start();
      }
      if (thrdSDateWriter0 == null) {
        thrdSDateWriter0 = new ThreadStreamDateWriter("-0-", thrdMDateReceiver.getPipedInputStream());
        thrdSDateWriter0.start();
        thrdMDateReceiver.addDateWriter(thrdSDateWriter0);
      }
      if (thrdSDateWriter1 == null) {
        thrdSDateWriter1 = new ThreadStreamDateWriter("-1-", thrdMDateReceiver.getPipedInputStream());
        thrdSDateWriter1.start();
        thrdMDateReceiver.addDateWriter(thrdSDateWriter1);
      }
    } else {
      if (thrdMDateReceiver != null) {
        thrdMDateReceiver.stopThread();
      }
    }
  }
</code>```

The OUTPUT

```<code>    run:
ThreadMultipleDateReceiver Created
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
.....
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver has:1
I ThreadMultipleDateReceiver have:-0-
ThreadMultipleDateReceiver waiting:
ThreadStreamDateWriter -> write to pipedOutputStream:-0- -> 20170608-090003
ThreadStreamDateWriter -> write to pipedOutputStream:-1- -> 20170608-090003
BUILD SUCCESSFUL (total time: 1 minute 3 seconds)
</code>```

The ThreadMultipleDateReceiver is blocked, and is not printing:

```<code>ThreadMultipleDateReceiver Received:
    -1- -> 20170608-090003
</code>```

or

```<code>ThreadMultipleDateReceiver Received:
    -0- -> 20170608-090003
</code>```

How solve it?

答:
looks like your piped output stream is static, so every time you construct a ThreadStreamDateWriter, you are stepping on the old value of piped output stream.

try making this an instance variable and pass it into the constructor. so you only have one of them.

edit 1: i made the pipes instance variables and added some printouts. seems to be running longer now (see below):

edit 2: you second pipedOutputStream.connect(snk); is throwing. you can only connect one thing at a time.

```<code>import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class So44438086 {
    public static class ThreadMultipleDateReceiver extends Thread {
        private static final int MAX_CLIENT_THREADS=4;
        private byte[] incomingBytes;
        private volatile boolean isRunning;
        private volatile List<ThreadStreamDateWriter> lThrdDate;
        private /*static*/ PipedInputStream pipedInputStream;
        public ThreadMultipleDateReceiver() {
            lThrdDate=Collections.synchronizedList(new ArrayList<>(MAX_CLIENT_THREADS));
            pipedInputStream=new PipedInputStream();
            System.out.println("ctor setting pipedInputStream to: "+pipedInputStream);
            System.out.println("ThreadMultipleDateReceiver Created");
        }
        @Override public void run() {
            isRunning=true;
            while(isRunning) {
                if(!lThrdDate.isEmpty()) {
                    System.out.println("ThreadMultipleDateReceiver has:"+lThrdDate.size());
                    for(int i=lThrdDate.size();i>0;i--) {
                        if(lThrdDate.get(i-1).getState()==Thread.State.TERMINATED) {
                            lThrdDate.remove(i-1);
                        } else {
                            System.out.println("I ThreadMultipleDateReceiver have:"+lThrdDate.get(i-1).getNameDateWriter());
                        }
                    }
                    incomingBytes=new byte[1024];
                    try {
                        String str="";
                        int iRd;
                        System.out.println("ThreadMultipleDateReceiver waiting:"+str);
                        System.out.println("reading: "+pipedInputStream);
                        while((iRd=pipedInputStream.read(incomingBytes))!=-1) {
                            if(iRd>0) {
                                str+=new String(incomingBytes);
                            }
                        }
                        System.out.println("ThreadMultipleDateReceiver Received:\n\t:"+str);
                    } catch(IOException e) {}
                } else {
                    System.out.println("ThreadMultipleDateReceiver Empty");
                }
            }
            emptyDateWriters();
        }
        public void addDateWriter(ThreadStreamDateWriter threadDateWriter) {
            if(lThrdDate.size()<MAX_CLIENT_THREADS) {
                lThrdDate.add(threadDateWriter);
            }
        }
        private void emptyDateWriters() {
            if(!lThrdDate.isEmpty()) {
                for(int i=lThrdDate.size();i>0;i--) {
                    ThreadStreamDateWriter threadDateWriter=lThrdDate.get(i-1);
                    threadDateWriter.stopThread();
                    lThrdDate.remove(i-1);
                }
            }
        }
        public PipedInputStream getPipedInputStream() {
            return pipedInputStream;
        }
        public void stopThread() {
            isRunning=false;
        }
    }
    public static class ThreadStreamDateWriter extends Thread {
        String Self;
        private byte[] outgoingBytes;
        private volatile boolean isRunning;
        private /*static*/ PipedOutputStream pipedOutputStream;
        ThreadStreamDateWriter(String name,PipedInputStream snk) {
            Self=name;
            pipedOutputStream=new PipedOutputStream();
            System.out.println("ctor setting pipedOutputStream to: "+pipedOutputStream);
            try {
                pipedOutputStream.connect(snk);
                System.out.println(pipedOutputStream+" connectd to: "+snk);
            } catch(IOException e) {}
        }
        @Override public void run() {
            isRunning=true;
            while(isRunning) {
                try {
                    outgoingBytes=getInfo().getBytes();
                    System.out.println("ThreadStreamDateWriter -> write to pipedOutputStream:"+new String(outgoingBytes));
                    System.out.println("writing to: "+pipedOutputStream);
                    pipedOutputStream.write(outgoingBytes);
                    System.out.println("ThreadStreamDateWriter -> wrote:"+new String(outgoingBytes));
                    try {
                        Thread.sleep(4000);
                    } catch(InterruptedException ex) {}
                } catch(IOException|NegativeArraySizeException|IndexOutOfBoundsException e) {
                    isRunning=false;
                }
            }
        }
        String getInfo() {
            String sDtTm=new SimpleDateFormat("yyyyMMdd-hhmmss").format(Calendar.getInstance().getTime());
            return Self+" -> "+sDtTm;
        }
        public void stopThread() {
            isRunning=false;
        }
        public String getNameDateWriter() {
            return Self;
        }
    }
    private void foo() {
        if(thrdMDateReceiver==null) {
            thrdMDateReceiver=new ThreadMultipleDateReceiver();
            thrdMDateReceiver.start();
        }
        if(thrdSDateWriter0==null) {
            thrdSDateWriter0=new ThreadStreamDateWriter("-0-",thrdMDateReceiver.getPipedInputStream());
            thrdSDateWriter0.start();
            thrdMDateReceiver.addDateWriter(thrdSDateWriter0);
        }
        if(thrdSDateWriter1==null) {
            thrdSDateWriter1=new ThreadStreamDateWriter("-1-",thrdMDateReceiver.getPipedInputStream());
            thrdSDateWriter1.start();
            thrdMDateReceiver.addDateWriter(thrdSDateWriter1);
        }
    }
    void run() throws InterruptedException {
        System.out.println(("running"));
        foo();
        System.out.println(("sleeping"));
        Thread.sleep(10000);
        System.out.println(("stopping"));
        if(thrdMDateReceiver!=null) {
            thrdMDateReceiver.stopThread();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        new So44438086().run();
    }
    ThreadMultipleDateReceiver thrdMDateReceiver=null;
    ThreadStreamDateWriter thrdSDateWriter0=null;
    ThreadStreamDateWriter thrdSDateWriter1=null;
}
</code>```

Body:
I have a Multiple Writer Threads with Single Reader Thread model.
The ThreadMultipleDateReceiver class is designed to read from multiple Threads.

public class ThreadMultipleDateReceiver extends Thread {

  private static final int MAX_CLIENT_THREADS = 4;
  private byte[] incomingBytes;
  private volatile boolean isRunning;
  private volatile List<ThreadStreamDateWriter> lThrdDate;

  private static PipedInputStream pipedInputStream;

  public ThreadMultipleDateReceiver() {
    lThrdDate = Collections.synchronizedList(new ArrayList<>(MAX_CLIENT_THREADS));
    pipedInputStream = new PipedInputStream();
    System.out.println("ThreadMultipleDateReceiver Created");
  }

  @Override public void run() {
    isRunning = true;
    while (isRunning) {
      if (!lThrdDate.isEmpty()) {
        System.out.println("ThreadMultipleDateReceiver has:" + lThrdDate.size());
        for (int i = lThrdDate.size(); i > 0; i--) {
          if (lThrdDate.get(i - 1).getState() == Thread.State.TERMINATED) {
            lThrdDate.remove(i - 1);
          } else {
            System.out.println("I ThreadMultipleDateReceiver have:" + lThrdDate.get(i - 1).getNameDateWriter());
          }
        }
        incomingBytes = new byte[1024];
        try {
          String str = "";
          int iRd;
          System.out.println("ThreadMultipleDateReceiver waiting:" + str);
          while ((iRd = pipedInputStream.read(incomingBytes)) != -1) {
            if (iRd > 0) {
              str += new String(incomingBytes);
            }
          }
          System.out.println("ThreadMultipleDateReceiver Received:\n\t:" + str);
        } catch (IOException e) { }
      } else {
        System.out.println("ThreadMultipleDateReceiver Empty");
      }
    }
    emptyDateWriters();
  }

  public void addDateWriter(ThreadStreamDateWriter threadDateWriter) {
    if (lThrdDate.size() < MAX_CLIENT_THREADS) {
      lThrdDate.add(threadDateWriter);
    }
  }

  private void emptyDateWriters() {
    if (!lThrdDate.isEmpty()) {
      for (int i = lThrdDate.size(); i > 0; i--) {
        ThreadStreamDateWriter threadDateWriter = lThrdDate.get(i - 1);
        threadDateWriter.stopThread();
        lThrdDate.remove(i - 1);
      }
    }
  }

  public PipedInputStream getPipedInputStream() {
    return pipedInputStream;
  }

  public void stopThread() {
    isRunning = false;
  }

}

And the single Writer Thread

public class ThreadStreamDateWriter extends Thread {
  String Self;
  private byte[] outgoingBytes;
  private volatile boolean isRunning;
  private static PipedOutputStream pipedOutputStream;

  ThreadStreamDateWriter(String name, PipedInputStream snk) {
    Self = name;
    pipedOutputStream = new PipedOutputStream();
    try {
      pipedOutputStream.connect(snk);
    } catch (IOException e) { }
  }

  @Override public void run() {
    isRunning = true;
    while (isRunning) {
      try {
        outgoingBytes = getInfo().getBytes();
        System.out.println("ThreadStreamDateWriter -> write to pipedOutputStream:" + new String(outgoingBytes));
        pipedOutputStream.write(outgoingBytes);
        System.out.println("ThreadStreamDateWriter -> wrote:" + new String(outgoingBytes));
        try { Thread.sleep(4000); } catch (InterruptedException ex) { }
      } catch (IOException | NegativeArraySizeException | IndexOutOfBoundsException e) {
        isRunning = false;
      }
    }
  }

  String getInfo() {
      String sDtTm = new SimpleDateFormat("yyyyMMdd-hhmmss").format(Calendar.getInstance().getTime());
      return Self + " -> " + sDtTm;
  }

  public void stopThread() {
    isRunning = false;
  }

  public String getNameDateWriter() {
    return Self;
  }
}

How launch (I'm using Netbeans)?

ThreadMultipleDateReceiver thrdMDateReceiver = null;
ThreadStreamDateWriter thrdSDateWriter0 = null;
ThreadStreamDateWriter thrdSDateWriter1 = null;
  private void jtbDateExchangerActionPerformed(java.awt.event.ActionEvent evt) {
    if (jtbDateExchanger.isSelected()) {
      if (thrdMDateReceiver == null) {
        thrdMDateReceiver = new ThreadMultipleDateReceiver();
        thrdMDateReceiver.start();
      }
      if (thrdSDateWriter0 == null) {
        thrdSDateWriter0 = new ThreadStreamDateWriter("-0-", thrdMDateReceiver.getPipedInputStream());
        thrdSDateWriter0.start();
        thrdMDateReceiver.addDateWriter(thrdSDateWriter0);
      }
      if (thrdSDateWriter1 == null) {
        thrdSDateWriter1 = new ThreadStreamDateWriter("-1-", thrdMDateReceiver.getPipedInputStream());
        thrdSDateWriter1.start();
        thrdMDateReceiver.addDateWriter(thrdSDateWriter1);
      }
    } else {
      if (thrdMDateReceiver != null) {
        thrdMDateReceiver.stopThread();
      }
    }
  }

The OUTPUT

    run:
ThreadMultipleDateReceiver Created
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
.....
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver Empty
ThreadMultipleDateReceiver has:1
I ThreadMultipleDateReceiver have:-0-
ThreadMultipleDateReceiver waiting:
ThreadStreamDateWriter -> write to pipedOutputStream:-0- -> 20170608-090003
ThreadStreamDateWriter -> write to pipedOutputStream:-1- -> 20170608-090003
BUILD SUCCESSFUL (total time: 1 minute 3 seconds)

The ThreadMultipleDateReceiver is blocked, and is not printing:

ThreadMultipleDateReceiver Received:
    -1- -> 20170608-090003

or

ThreadMultipleDateReceiver Received:
    -0- -> 20170608-090003

How solve it?

Body:
looks like your piped output stream is static, so every time you construct a ThreadStreamDateWriter, you are stepping on the old value of piped output stream.

try making this an instance variable and pass it into the constructor. so you only have one of them.

edit 1: i made the pipes instance variables and added some printouts. seems to be running longer now (see below):

edit 2: you second pipedOutputStream.connect(snk); is throwing. you can only connect one thing at a time.

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class So44438086 {
    public static class ThreadMultipleDateReceiver extends Thread {
        private static final int MAX_CLIENT_THREADS=4;
        private byte[] incomingBytes;
        private volatile boolean isRunning;
        private volatile List<ThreadStreamDateWriter> lThrdDate;
        private /*static*/ PipedInputStream pipedInputStream;
        public ThreadMultipleDateReceiver() {
            lThrdDate=Collections.synchronizedList(new ArrayList<>(MAX_CLIENT_THREADS));
            pipedInputStream=new PipedInputStream();
            System.out.println("ctor setting pipedInputStream to: "+pipedInputStream);
            System.out.println("ThreadMultipleDateReceiver Created");
        }
        @Override public void run() {
            isRunning=true;
            while(isRunning) {
                if(!lThrdDate.isEmpty()) {
                    System.out.println("ThreadMultipleDateReceiver has:"+lThrdDate.size());
                    for(int i=lThrdDate.size();i>0;i--) {
                        if(lThrdDate.get(i-1).getState()==Thread.State.TERMINATED) {
                            lThrdDate.remove(i-1);
                        } else {
                            System.out.println("I ThreadMultipleDateReceiver have:"+lThrdDate.get(i-1).getNameDateWriter());
                        }
                    }
                    incomingBytes=new byte[1024];
                    try {
                        String str="";
                        int iRd;
                        System.out.println("ThreadMultipleDateReceiver waiting:"+str);
                        System.out.println("reading: "+pipedInputStream);
                        while((iRd=pipedInputStream.read(incomingBytes))!=-1) {
                            if(iRd>0) {
                                str+=new String(incomingBytes);
                            }
                        }
                        System.out.println("ThreadMultipleDateReceiver Received:\n\t:"+str);
                    } catch(IOException e) {}
                } else {
                    System.out.println("ThreadMultipleDateReceiver Empty");
                }
            }
            emptyDateWriters();
        }
        public void addDateWriter(ThreadStreamDateWriter threadDateWriter) {
            if(lThrdDate.size()<MAX_CLIENT_THREADS) {
                lThrdDate.add(threadDateWriter);
            }
        }
        private void emptyDateWriters() {
            if(!lThrdDate.isEmpty()) {
                for(int i=lThrdDate.size();i>0;i--) {
                    ThreadStreamDateWriter threadDateWriter=lThrdDate.get(i-1);
                    threadDateWriter.stopThread();
                    lThrdDate.remove(i-1);
                }
            }
        }
        public PipedInputStream getPipedInputStream() {
            return pipedInputStream;
        }
        public void stopThread() {
            isRunning=false;
        }
    }
    public static class ThreadStreamDateWriter extends Thread {
        String Self;
        private byte[] outgoingBytes;
        private volatile boolean isRunning;
        private /*static*/ PipedOutputStream pipedOutputStream;
        ThreadStreamDateWriter(String name,PipedInputStream snk) {
            Self=name;
            pipedOutputStream=new PipedOutputStream();
            System.out.println("ctor setting pipedOutputStream to: "+pipedOutputStream);
            try {
                pipedOutputStream.connect(snk);
                System.out.println(pipedOutputStream+" connectd to: "+snk);
            } catch(IOException e) {}
        }
        @Override public void run() {
            isRunning=true;
            while(isRunning) {
                try {
                    outgoingBytes=getInfo().getBytes();
                    System.out.println("ThreadStreamDateWriter -> write to pipedOutputStream:"+new String(outgoingBytes));
                    System.out.println("writing to: "+pipedOutputStream);
                    pipedOutputStream.write(outgoingBytes);
                    System.out.println("ThreadStreamDateWriter -> wrote:"+new String(outgoingBytes));
                    try {
                        Thread.sleep(4000);
                    } catch(InterruptedException ex) {}
                } catch(IOException|NegativeArraySizeException|IndexOutOfBoundsException e) {
                    isRunning=false;
                }
            }
        }
        String getInfo() {
            String sDtTm=new SimpleDateFormat("yyyyMMdd-hhmmss").format(Calendar.getInstance().getTime());
            return Self+" -> "+sDtTm;
        }
        public void stopThread() {
            isRunning=false;
        }
        public String getNameDateWriter() {
            return Self;
        }
    }
    private void foo() {
        if(thrdMDateReceiver==null) {
            thrdMDateReceiver=new ThreadMultipleDateReceiver();
            thrdMDateReceiver.start();
        }
        if(thrdSDateWriter0==null) {
            thrdSDateWriter0=new ThreadStreamDateWriter("-0-",thrdMDateReceiver.getPipedInputStream());
            thrdSDateWriter0.start();
            thrdMDateReceiver.addDateWriter(thrdSDateWriter0);
        }
        if(thrdSDateWriter1==null) {
            thrdSDateWriter1=new ThreadStreamDateWriter("-1-",thrdMDateReceiver.getPipedInputStream());
            thrdSDateWriter1.start();
            thrdMDateReceiver.addDateWriter(thrdSDateWriter1);
        }
    }
    void run() throws InterruptedException {
        System.out.println(("running"));
        foo();
        System.out.println(("sleeping"));
        Thread.sleep(10000);
        System.out.println(("stopping"));
        if(thrdMDateReceiver!=null) {
            thrdMDateReceiver.stopThread();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        new So44438086().run();
    }
    ThreadMultipleDateReceiver thrdMDateReceiver=null;
    ThreadStreamDateWriter thrdSDateWriter0=null;
    ThreadStreamDateWriter thrdSDateWriter1=null;
}


问:
Running spring MVC along side of JSF
I want to write some new functionality in spring MVC, the problem is that the current site is written in JSF 1.2.

It does use spring 2.5 application context, but thats all.

I am thinking i can drop in spring MVC, write a single page in it, and then see what kind of hoops ill have to jump through to be able to have seamless sessions between spring mvc and jsf.

can someone offer some wise words to me about this venture?

答:
The session will not be a problem. It will be the same session, because it's a lower-level concept than JSF and spring-mvc.

The URL mapping of the respective servlets (the dispatcher servlet and the faces servlet) might be a problem. Your faces servlet would be mapped to *.jsf, and then your dispatcher servlet should be mapped to something like /mvc/*

The question remains whether mixing frameworks like that is a good option. I'd rather suggest using JSF everywhere in this project.

If you need some RESTful services, you can use spring-mvc, or you can use some JAX-RS provider, like CXF or RESTEasy.

ContentLicense: CC BY-SA 2.5

Title: Running spring MVC along side of JSF


问:
How to represent a value from an object as boolean
The following object  is being returned from a SQL call:

```<code>#<Health:0x007fc8533f2de8 @type=:diabetic, @value="N", @data_source=nil, @measured_at=nil>
</code>```

The value could be 'Y' or 'N' and can be accessed as health.value.

How do I represent this value as a boolean?

答:
```<code>{"Y" => true, "N" => false}[health.value.upcase]
</code>```

Body:
The following object  is being returned from a SQL call:

#<Health:0x007fc8533f2de8 @type=:diabetic, @value="N", @data_source=nil, @measured_at=nil>

The value could be 'Y' or 'N' and can be accessed as health.value.

How do I represent this value as a boolean?