fixing error of required non-static field - entity-framework

I wanna create an article as content part for a content type in migration of my module, but when I added the article, code show me an error.
here's the code:
public int UpdateFrom3() {
ContentDefinitionManager.AlterPartDefinition(typeof(TourPart).Name, cfg => cfg.Attachable());
ContentDefinitionService.AddPartToType("Article" + "Part", "Tour");
ContentDefinitionManager.AlterPartDefinition(
"Article" + "Part",
b => b
.WithField("Name", f => f
.OfType("InputField").WithDisplayName("Name"))
.WithField("ImageField", f => f
.OfType("MediaLibraryPickerField").WithDisplayName("Images")
.WithSetting("MediaLibraryPickerField.Hint", "Images everywhere!").WithSetting("MediaLibraryPickerFieldSettings.Required", "False")
.WithSetting("MediaLibraryPickerFieldSettings.Multiple", "True"))
.WithField("ShortDesc", f => f
.OfType("TextField").WithDisplayName("Short Description")
.WithSetting("TextFieldSettings.Flavor", "Html"))
.WithField("LongDesc", f => f
.OfType("TextField").WithDisplayName("Long Description")
.WithSetting("TextFieldSettings.Flavor", "Html")));
return 4;
}
at the ContentDefinitionService.AddPartToType("Article" + "Part", "Tour"); section, code show me this:
An object reference is required for non-static field
what can I do to my code accept this?

I find the answer by my self , Here's the solution:
public int UpdateFrom3()
{
ContentDefinitionManager.AlterPartDefinition(typeof(TourPart).Name, cfg => cfg.Attachable());
ContentDefinitionManager.AlterTypeDefinition("Tour",
cfg => cfg
.WithPart(typeof(TourPart).Name)
.WithPart("General")
);
ContentDefinitionManager.AlterPartDefinition(
"General",
b => b
.WithField("Name", f => f
.OfType("InputField").WithDisplayName("Name"))
.WithField("NameManage", f => f
.OfType("InputField").WithDisplayName("NameManage"))
.WithField("TourTypes", f => f
.OfType("InputField").WithDisplayName("TourTypes"))
.WithField("TourTitle", f => f
.OfType("InputField").WithDisplayName("TourTitle"))
.WithField("TourSubTitle", f => f
.OfType("InputField").WithDisplayName("TourSubTitle"))
.WithField("TourSummary", f => f
.OfType("InputField").WithDisplayName("TourSummary"))
.WithField("AboutTour", f => f
.OfType("TextField").WithDisplayName("AboutTour")
.WithSetting("TextFieldSettings.Flavor", "Html"))
.WithField("Duration", f => f
.OfType("InputField").WithDisplayName("Duration"))
.WithField("Cities", f => f
.OfType("TextField").WithDisplayName("Cities")
.WithSetting("TextFieldSettings.Flavor", "Html"))
.WithField("TourIncludes", f => f
.OfType("TextField").WithDisplayName("TourIncludes")
.WithSetting("TextFieldSettings.Flavor", "Html"))
.WithField("TourDestination", f => f
.OfType("InputField").WithDisplayName("TourDestination")));
return 4;
}

Related

Scala Monix: Collect data from Observer.foldLeft

By using Observer, I'm trying to build the code, which:
1.Generate some (random) values;
2.Combine this values;
3.If someone combined value exceed the threshold, the value have to be passed to another handler.
So I expect the resulted value to be returned for further usage
My code:
//generate
val o: Observable[Int] = Observable.repeatEval(Random.nextInt(10))
//handle
val f = o.foldLeft(0) { (acc, el) =>
if (acc < 15) {
el + acc
} else {
println("handled " + acc)
acc
}
}
//use handled
.flatMap{res =>
println("mapped " + res + 1)
Observable(res + 1)
}
But nothing passed to the flatMap-method.
The output is following for example:
0
3
7
11
12
handled 20
What am I doing wrong?
You want to use mapAccumulate + collect instead.
def groupWhile[A, B](o: Observable[A], s: B)(op: (B, A) => B)(predicate: B => Boolean): Observable[B] =
o.mapAccumulate(seed = s) {
case (b, a) =>
val bb = op(b, a)
if (predicate(bb)) (bb, None) else (s, Some(bb))
} collect {
case Some(b) => b
}
Use it like:
// Generate.
val o: Observable[Int] = Observable.repeatEval(Random.nextInt(10))
// Handle.
val f = groupWhile(o, 0)((acc, i) => acc + i)(r => r <= 15)
// Use handled.
f.mapEval { x =>
val res = x + 1
Task(println("Mapped: ${res}")).as(res)
}
As I always say, the Scaladoc is your friend.

Boolean logic in lambda calculus in Scala

I am trying to implement basic Boolean logic in lambda calculus in Scala, but I am stuck at the beginning.
I have two types:
type λ_T[T] = T => T
type λ_λ_T[T] = λ_T[T] => T => T
And 'false', that works pretty well:
def λfalse[T]: λ_λ_T[T] = (s: λ_T[T]) => (z: T) => z
But when I try to implement 'true', as It is given in math background of lambda calculus, I get wrong type:
def λtrue[T]: λ_λ_T[T] = (s: λ_T[T]) => (z: T) => s
Outcome error: Expression of type λ_T[T] doesn't conform to expected type T
How can I implement this?
A Church encoding of Booleans is of type
[X] => X -> X -> X
where [X] => means that the X -> X -> X-part is polymorphic in X.
Here are two proposals how you could express this in Scala.
Booleans as generic methods, type inference at call-site
Here is a type that would be appropriate for booleans where the required polymorphic type parameter can be inferred directly at the call-site:
type B[X] = X => X => X
Here are the definitions of true and false, together with a few operations:
def churchTrue[X]: B[X] = a => b => a
def churchFalse[X]: B[X] = a => b => b
def ifThenElse[X](b: B[X], thenResult: X, elseResult: X) =
b(thenResult)(elseResult)
def and[X](a: B[B[X]], b: B[X]): B[X] = a(b)(churchFalse)
def or[X](a: B[B[X]], b: B[X]): B[X] = a(churchTrue)(b)
def not[X](a: B[B[X]]) = a(churchFalse)(churchTrue)
Example:
println("t & t = " + and[String](churchTrue, churchTrue)("t")("f"))
println("t & f = " + and[String](churchTrue, churchFalse)("t")("f"))
println("f & t = " + and[String](churchFalse,churchTrue)("t")("f"))
println("f & f = " + and[String](churchFalse,churchFalse)("t")("f"))
Note that this does not allow you to express the idea of a "Church-Boolean per-se", because it requires a fixed type of the arguments to which it can be applied (String in the above example). As soon as you try to extract the expression from one particular call site and move it elsewhere, you have to readjust all the type parameters, and this is annoying.
Truly polymorphic Church encodings of Booleans
If you want to represent a truly polymorphic function as first-class object, you have to define a trait or abstract class. For booleans, this would be something like
trait B {
def apply[X](trueCase: X, elseCase: X): X
}
Note that now the apply method is polymorphic in X. This allows you to implement Church encodings of Booleans as first-class objects that can be passed around (returned from methods, saved in lists, etc.):
trait B { self =>
def apply[X](thenCase: X, elseCase: X): X
def |(other: B): B = new B {
def apply[A](t: A, e: A) = self(True, other)(t, e)
}
def &(other: B): B = new B {
def apply[A](t: A, e: A) = self(other, False)(t, e)
}
def unary_~ : B = self(False, True)
}
object True extends B { def apply[X](a: X, b: X) = a }
object False extends B { def apply[X](a: X, b: X) = b }
Here is how you can apply it to some actual values:
def toBoolean(b: B): Boolean = b(true, false)
The above line will invoke apply[Boolean](...).
An example:
println("And: ")
println(toBoolean(True & True))
println(toBoolean(True & False))
println(toBoolean(False & True))
println(toBoolean(False & False))
println("Or:")
println(toBoolean(True | True))
println(toBoolean(True | False))
println(toBoolean(False | True))
println(toBoolean(False | False))
println("Funny expresssion that should be `true`:")
println(toBoolean((False | True) & (True & ~False)))
prints:
And:
true
false
false
false
Or:
true
true
true
false
Funny expresssion that should be `true`:
true

Scala for-comprehension yielding result from multiple variable bindings

I am very curious how Scala desugars the following for-comprehension:
for {
a <- Option(5)
b = a * 2
c <- if (b == 10) Option(100) else None
} yield b + c
My difficulty comes from having both b and c in the yield, because they seem to be bound at different steps
This is the sanitized output of desugar - a command available in Ammonite REPL:
Option(5)
.map { a =>
val b = a * 2;
(a, b)
}
.flatMap { case (a, b) =>
(if (b == 10) Option(100) else None)
.map(c => b + c)
}
Both b and c can be present in yield because it does not desugar to chained calls to map/flatMap, but rather to nested calls.
You can even ask the compiler. The following command:
scala -Xprint:parser -e "for {
a <- Option(5)
b = a * 2
c <- if (b == 10) Option(100) else None
} yield b + c"
yields this output
[[syntax trees at end of parser]] // scalacmd7617799112170074915.scala
package <empty> {
object Main extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
def main(args: Array[String]): scala.Unit = {
final class $anon extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
Option(5).map(((a) => {
val b = a.$times(2);
scala.Tuple2(a, b)
})).flatMap(((x$1) => x$1: #scala.unchecked match {
case scala.Tuple2((a # _), (b # _)) => if (b.$eq$eq(10))
Option(100)
else
None.map(((c) => b.$plus(c)))
}))
};
new $anon()
}
}
}
Taking only the piece you are interested in and improving the readability, you get this:
Option(5).map(a => {
val b = a * 2
(a, b)
}).flatMap(_ match {
case (_, b) =>
if (b == 10)
Option(100)
else
None.map(c => b + c)
})
Edit
As reported in a comment, literally translating from the compiler output seems to highlight a bug in how the desugared expression is rendered. The sum should be mapped on the result of the if expression, rather then on the None in the else branch:
Option(5).map(a => {
val b = a * 2
(a, b)
}).flatMap(_ match {
case (_, b) =>
(if (b == 10) Option(100) else None).map(c => b + c)
})
It's probably worth it to ask the compiler team if this is a bug.
These two codes are equivalent:
scala> for {
| a <- Option(5)
| b = a * 2
| c <- if (b == 10) Option(100) else None
| } yield b + c
res70: Option[Int] = Some(110)
scala> for {
| a <- Option(5)
| b = a * 2
| if (b == 10)
| c <- Option(100)
| } yield b + c
res71: Option[Int] = Some(110)
Since there is no collection involved, yielding multiple values, there is only one big step - or, arguable, 3 to 4 small steps. If a would have been None, the whole loop would have been terminated early, yielding a None.
The desugaring is a flatMap/withFilter/map.

scala Either.RightProjection confusion (for comprehension de-sugaring)

I can use an = in a scala for-comprehension (as specified in section 6.19 of the SLS) as follows:
Option
Suppose I have some function String => Option[Int]:
scala> def intOpt(s: String) = try { Some(s.toInt) } catch { case _ => None }
intOpt: (s: String)Option[Int]
Then I can use it thus
scala> for {
| str <- Option("1")
| i <- intOpt(str)
| val j = i + 10 //Note use of = in generator
| }
| yield j
res18: Option[Int] = Some(11)
It was my understanding that this was essentially equivalent to:
scala> Option("1") flatMap { str => intOpt(str) } map { i => i + 10 } map { j => j }
res19: Option[Int] = Some(11)
That is, the embedded generator was a way of injecting a map into a sequence of flatMap calls. So far so good.
Either.RightProjection
What I actually want to do: use a similar for-comprehension as the previous example using the Either monad.
However, if we use it in a similar chain, but this time using the Either.RightProjection monad/functor, it doesn't work:
scala> def intEither(s: String): Either[Throwable, Int] =
| try { Right(s.toInt) } catch { case x => Left(x) }
intEither: (s: String)Either[Throwable,Int]
Then use:
scala> for {
| str <- Option("1").toRight(new Throwable()).right
| i <- intEither(str).right //note the "right" projection is used
| val j = i + 10
| }
| yield j
<console>:17: error: value map is not a member of Product with Serializable with Either[java.lang.Throwable,(Int, Int)]
i <- intEither(str).right
^
The issue has something to do with the function that a right-projection expects as an argument to its flatMap method (i.e. it expects an R => Either[L, R]). But modifying to not call right on the second generator, it still won't compile.
scala> for {
| str <- Option("1").toRight(new Throwable()).right
| i <- intEither(str) // no "right" projection
| val j = i + 10
| }
| yield j
<console>:17: error: value map is not a member of Either[Throwable,Int]
i <- intEither(str)
^
Mega-Confusion
But now I get doubly confused. The following works just fine:
scala> for {
| x <- Right[Throwable, String]("1").right
| y <- Right[Throwable, String](x).right //note the "right" here
| } yield y.toInt
res39: Either[Throwable,Int] = Right(1)
But this does not:
scala> Right[Throwable, String]("1").right flatMap { x => Right[Throwable, String](x).right } map { y => y.toInt }
<console>:14: error: type mismatch;
found : Either.RightProjection[Throwable,String]
required: Either[?,?]
Right[Throwable, String]("1").right flatMap { x => Right[Throwable, String](x).right } map { y => y.toInt }
^
I thought these were equivalent
What is going on?
How can I embed an = generator in a for comprehension across an Either?
The fact that you cannot embed the = in the for-comprehension is related to this issue reported by Jason Zaugg; the solution is to Right-bias Either (or create a new data type isomorphic to it).
For your mega-confusion, you expanded the for sugar incorrectly. The desugaring of
for {
b <- x(a)
c <- y(b)
} yield z(c)
is
x(a) flatMap { b =>
y(b) map { c =>
z(c) }}
and not
x(a) flatMap { b => y(b)} map { c => z(c) }
Hence you should have done this:
scala> Right[Throwable, String]("1").right flatMap { x => Right[Throwable, String](x).right map { y => y.toInt } }
res49: Either[Throwable,Int] = Right(1)
More fun about desugaring (the `j = i + 10` issue)
for {
b <- x(a)
c <- y(b)
x1 = f1(b)
x2 = f2(b, x1)
...
xn = fn(.....)
d <- z(c, xn)
} yield w(d)
is desugared into
x(a) flatMap { b =>
y(b) map { c =>
x1 = ..
...
xn = ..
(c, x1, .., xn)
} flatMap { (_c1, _x1, .., _xn) =>
z(_c1, _xn) map w }}
So in your case, y(b) has result type Either which doesn't have map defined.

Avoiding repetition using lenses whilst deep-copying into Map values

I have an immutable data structure where I have nested values in Maps, like so:
case class TradingDay(syms: Map[String, SymDay] = Map.empty)
case class SymDay(sym: String, traders: Map[String, TraderSymDay] = Map.empty)
case class TraderSymDay(trader: String, sym: String, trades: List[Trade] = Nil)
Separately I have a list of all trades over the day, and I want to generate the TradingDay structure, where
case class Trade(sym: String, trader: String, qty: Int)
I am trying to figure out how I would update this structure with lenses (see appendix) by folding through my trades:
(TradingDay() /: trades) { (trd, d) =>
def sym = trd.sym
def trader = trd.trader
import TradingDay._
import SymDay._
import TraderSymDay._
val mod =
for {
_ <- (Syms member sym).mods(
_ orElse some(SymDay(sym)))
_ <- (Syms at sym andThen Traders member trader).mods(
_ orElse some(TraderSymDay(trader, sym)))
_ <- (Syms at sym andThen (Traders at trader) andThen Trades).mods(
trd :: _)
x <- init
} yield x
mod ! d
}
This works; but I'm wondering whether I could be less repetitive (in terms of adding to a map and then modifying the value at the key of a map. It doesn't seem that much less annoying than the associated deep-copy.
Appendix - the lenses
object TradingDay {
val Syms = Lens[TradingDay, Map[String, SymDay]](_.syms, (d, s) => d.copy(syms = s))
}
object SymDay {
val Traders = Lens[SymDay, Map[String, TraderSymDay]](_.traders, (d, t) => d.copy(traders = t))
}
object TraderSymDay {
val Trades = Lens[TraderSymDay, List[Trade]](_.trades, (d, f) => d.copy(trades = f))
}
with
type #>[A,B] = Lens[A, B]
and by keeping this lens
val Syms : Lens[TradingDay, Map[String, SymDay]]
and defining those lenses:
val F : Map[String, SymDay] #> Option[SymDay] = ...
val G : Option[SymDay] #> Map[String, TraderSymDay] = ...
val H : Map[String, TraderSymDay] #> Option[TraderSymDay] = ...
val I : Option[TraderSymDay] #> List[Trade] = ...
val J: TradingDay #> List[Trade] = Syms >=> F >=> G >=> H >=> I
you could get this:
(trades /: TradingDay()){ (trd, d) => (J.map(trd :: _).flatMap(_ => init)) ! d }
Answer provided by Jordan West (#_jrwest)
It's only a slight change and involves introducing the following conversion:
implicit def myMapLens[S,K,V] = MyMapLens[S,K,V](_)
case class MyMapLens[S,K,V](lens: Lens[S,Map[K,V]]) {
def putIfAbsent(k: K, v: => V)
= lens.mods(m => m get k map (_ => m) getOrElse (m + (k -> v)))
}
Then we can use this as follows:
(TradingDay() /: trades) { (d, trade) =>
def sym = trade.sym
def trader = trade.trader
def traders = Syms at sym andThen Traders
def trades = Syms at sym andThen (Traders at trader) andThen Trades
val upd =
for {
_ <- Syms putIfAbsent (sym, SymDay(sym))
_ <- traders putIfAbsent (trader, TraderSymDay(trader, sym))
_ <- trades.mods(trade :: _)
} yield ()
upd ~> d
}