repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/SymbolOffset.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait SymbolOffset extends StObject {
/**
* Label of this data item, which will be merged with
* `label` of starting point and ending point.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.label
*/
var label: js.UndefOr[Position] = js.native
/**
* Line style of this data item, which will be merged
* with `lineStyle` of starting point and ending point.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.lineStyle
*/
var lineStyle: js.UndefOr[ShadowOffsetX] = js.native
/**
* Name of the marker, which will display as a label.
*
*
* @see https://ecomfe.github.io/echarts-doc/public/en/option.html#series-pie.markLine.data.1.name
*/
var name: js.UndefOr[String] = js.native
/**
* Symbol of ending point.
*
* Icon types provided by ECharts includes `'circle'`,
* `'rect'`, `'roundRect'`, `'triangle'`, `'diamond'`,
* `'pin'`, `'arrow'`, `'none'`
*
* It can be set to an image with `'image://url'` ,
* in which URL is the link to an image, or `dataURI`
* of an image.
*
* An image URL example:
*
* ```
* 'image://http://xxx.xxx.xxx/a/b.png'
*
* ```
*
* A `dataURI` example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pie.pie.markLine.data.1)
*
* Icons can be set to arbitrary vector path via `'path://'`
* in ECharts.
* As compared with raster image, vector paths prevent
* from jagging and blurring when scaled, and have a
* better control over changing colors.
* Size of vectoer icon will be adapted automatically.
* Refer to
* [SVG PathData](http://www.w3.org/TR/SVG/paths.html#PathData)
* for more information about format of path.
* You may export vector paths from tools like Adobe
* Illustrator.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pie.pie.markLine.data.1)
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.symbol
*/
var symbol: js.UndefOr[String] = js.native
/**
* Whether to keep aspect for symbols in the form of
* `path://`.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.symbolKeepAspect
*/
var symbolKeepAspect: js.UndefOr[Boolean] = js.native
/**
* Offset of ending point symbol relative to original
* position.
* By default, symbol will be put in the center position
* of data.
* But if symbol is from user-defined vector path or
* image, you may not expect symbol to be in center.
* In this case, you may use this attribute to set offset
* to default position.
* It can be in absolute pixel value, or in relative
* percentage value.
*
* For example, `[0, '50%']` means to move upside side
* position of symbol height.
* It can be used to make the arrow in the bottom to
* be at data position when symbol is pin.
*
*
* @default
* [0, 0]
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.symbolOffset
*/
var symbolOffset: js.UndefOr[js.Array[_]] = js.native
/**
* Rotate degree of ending point symbol.
* Note that when `symbol` is set to be `'arrow'` in
* `markLine`, `symbolRotate` value will be ignored,
* and compulsively use tangent angle.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.symbolRotate
*/
var symbolRotate: js.UndefOr[Double] = js.native
/**
* ending point symbol size.
* It can be set to single numbers like `10`, or use
* an array to represent width and height.
* For example, `[20, 10]` means symbol width is `20`,
* and height is`10`.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.symbolSize
*/
var symbolSize: js.UndefOr[js.Array[_] | Double] = js.native
/**
* Label value, which can be ignored.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.value
*/
var value: js.UndefOr[Double] = js.native
/**
* X position according to container, in pixel.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.x
*/
var x: js.UndefOr[Double] = js.native
/**
* Y position according to container, in pixel.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markLine.data.1.y
*/
var y: js.UndefOr[Double] = js.native
}
object SymbolOffset {
@scala.inline
def apply(): SymbolOffset = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[SymbolOffset]
}
@scala.inline
implicit class SymbolOffsetMutableBuilder[Self <: SymbolOffset] (val x: Self) extends AnyVal {
@scala.inline
def setLabel(value: Position): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setLineStyle(value: ShadowOffsetX): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
@scala.inline
def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any])
@scala.inline
def setNameUndefined: Self = StObject.set(x, "name", js.undefined)
@scala.inline
def setSymbol(value: String): Self = StObject.set(x, "symbol", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolKeepAspect(value: Boolean): Self = StObject.set(x, "symbolKeepAspect", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolKeepAspectUndefined: Self = StObject.set(x, "symbolKeepAspect", js.undefined)
@scala.inline
def setSymbolOffset(value: js.Array[_]): Self = StObject.set(x, "symbolOffset", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolOffsetUndefined: Self = StObject.set(x, "symbolOffset", js.undefined)
@scala.inline
def setSymbolOffsetVarargs(value: js.Any*): Self = StObject.set(x, "symbolOffset", js.Array(value :_*))
@scala.inline
def setSymbolRotate(value: Double): Self = StObject.set(x, "symbolRotate", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolRotateUndefined: Self = StObject.set(x, "symbolRotate", js.undefined)
@scala.inline
def setSymbolSize(value: js.Array[_] | Double): Self = StObject.set(x, "symbolSize", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolSizeUndefined: Self = StObject.set(x, "symbolSize", js.undefined)
@scala.inline
def setSymbolSizeVarargs(value: js.Any*): Self = StObject.set(x, "symbolSize", js.Array(value :_*))
@scala.inline
def setSymbolUndefined: Self = StObject.set(x, "symbol", js.undefined)
@scala.inline
def setValue(value: Double): Self = StObject.set(x, "value", value.asInstanceOf[js.Any])
@scala.inline
def setValueUndefined: Self = StObject.set(x, "value", js.undefined)
@scala.inline
def setX(value: Double): Self = StObject.set(x, "x", value.asInstanceOf[js.Any])
@scala.inline
def setXUndefined: Self = StObject.set(x, "x", js.undefined)
@scala.inline
def setY(value: Double): Self = StObject.set(x, "y", value.asInstanceOf[js.Any])
@scala.inline
def setYUndefined: Self = StObject.set(x, "y", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/EdgeLength.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait EdgeLength extends StObject {
/**
* The distance between 2 nodes on edge.
* This distance is also affected by
* [repulsion](https://echarts.apache.org/en/option.html#series-graph.force.repulsion)
* .
*
* It can be an array to represent the range of edge length.
* In this case edge with larger value will be shorter, which
* means two nodes are closer.
* And edge with smaller value will be longer.
*
*
* @default
* 30
* @see https://echarts.apache.org/en/option.html#series-graph.force.edgeLength
*/
var edgeLength: js.UndefOr[js.Array[_] | Double] = js.native
/**
* It will slow down the nodes' movement. The value range is from 0 to 1.
* But it is still an experimental option, see [#11024](https://github.com/apache/incubator-echarts/issues/11024).
*
* Since v4.5.0
*
* @default
* 0.6
* @see https://echarts.apache.org/en/option.html#series-graph.force.friction
*/
var friction: js.UndefOr[Double] = js.native
/**
* The gravity factor enforcing nodes approach to the center.
* The nodes will be closer to the center as the value becomes
* larger.
*
*
* @default
* 0.1
* @see https://echarts.apache.org/en/option.html#series-graph.force.gravity
*/
var gravity: js.UndefOr[Double] = js.native
/**
* The initial layout before force-directed layout, which will
* influence on the result of force-directed layout.
*
* It defaults not to do any layout and use
* [x](https://echarts.apache.org/en/option.html#series-graph.data.x)
* ,
* [y](https://echarts.apache.org/en/option.html#series-graph.data.y)
* provided in
* [node](https://echarts.apache.org/en/option.html#series-graph.data)
* as the position of node.
* If it doesn't exist, the position will be generated randomly.
*
* You can also use circular layout `'circular'`.
*
*
* @see https://echarts.apache.org/en/option.html#series-graph.force.initLayout
*/
var initLayout: js.UndefOr[String] = js.native
/**
* Because the force-directed layout will be steady after several
* iterations, this parameter will be decide whether to show
* the iteration animation of layout.
* It is not recommended to be closed on browser when there
* are a lot of node data (>100) as the layout process will
* cause browser to hang.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-graph.force.layoutAnimation
*/
var layoutAnimation: js.UndefOr[Boolean] = js.native
/**
* The repulsion factor between nodes.
* The repulsion will be stronger and the distance between 2
* nodes becomes further as this value becomes larger.
*
* It can be an array to represent the range of repulsion.
* In this case larger value have larger repulsion and smaller
* value will have smaller repulsion.
*
*
* @default
* 50
* @see https://echarts.apache.org/en/option.html#series-graph.force.repulsion
*/
var repulsion: js.UndefOr[js.Array[_] | Double] = js.native
}
object EdgeLength {
@scala.inline
def apply(): EdgeLength = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[EdgeLength]
}
@scala.inline
implicit class EdgeLengthMutableBuilder[Self <: EdgeLength] (val x: Self) extends AnyVal {
@scala.inline
def setEdgeLength(value: js.Array[_] | Double): Self = StObject.set(x, "edgeLength", value.asInstanceOf[js.Any])
@scala.inline
def setEdgeLengthUndefined: Self = StObject.set(x, "edgeLength", js.undefined)
@scala.inline
def setEdgeLengthVarargs(value: js.Any*): Self = StObject.set(x, "edgeLength", js.Array(value :_*))
@scala.inline
def setFriction(value: Double): Self = StObject.set(x, "friction", value.asInstanceOf[js.Any])
@scala.inline
def setFrictionUndefined: Self = StObject.set(x, "friction", js.undefined)
@scala.inline
def setGravity(value: Double): Self = StObject.set(x, "gravity", value.asInstanceOf[js.Any])
@scala.inline
def setGravityUndefined: Self = StObject.set(x, "gravity", js.undefined)
@scala.inline
def setInitLayout(value: String): Self = StObject.set(x, "initLayout", value.asInstanceOf[js.Any])
@scala.inline
def setInitLayoutUndefined: Self = StObject.set(x, "initLayout", js.undefined)
@scala.inline
def setLayoutAnimation(value: Boolean): Self = StObject.set(x, "layoutAnimation", value.asInstanceOf[js.Any])
@scala.inline
def setLayoutAnimationUndefined: Self = StObject.set(x, "layoutAnimation", js.undefined)
@scala.inline
def setRepulsion(value: js.Array[_] | Double): Self = StObject.set(x, "repulsion", value.asInstanceOf[js.Any])
@scala.inline
def setRepulsionUndefined: Self = StObject.set(x, "repulsion", js.undefined)
@scala.inline
def setRepulsionVarargs(value: js.Any*): Self = StObject.set(x, "repulsion", js.Array(value :_*))
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/ItemStyle.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/ItemStyle.scala
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ItemStyle extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-bar.emphasis.itemStyle
*/
var itemStyle: js.UndefOr[BarBorderWidth] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-bar.emphasis.label
*/
var label: js.UndefOr[BorderRadius] = js.native
}
object ItemStyle {
@scala.inline
def apply(): ItemStyle = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[ItemStyle]
}
@scala.inline
implicit class ItemStyleMutableBuilder[Self <: ItemStyle] (val x: Self) extends AnyVal {
@scala.inline
def setItemStyle(value: BarBorderWidth): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: BorderRadius): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/BorderColor0.scala | <gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BorderColor0 extends StObject {
/**
* Border color of bullish candle stick.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for
* example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported besides
* single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-candlestick.candlestick.data.emphasis.itemStyle)
*
*
* @default
* "#c23531"
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.borderColor
*/
var borderColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Border color of bearish candle stick.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for
* example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported besides
* single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-candlestick.candlestick.data.emphasis.itemStyle)
*
*
* @default
* #314656
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.borderColor0
*/
var borderColor0: js.UndefOr[String] = js.native
/**
* Border width of candlestick.
* There is no border when it is `0`.
*
*
* @default
* 2
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.borderWidth
*/
var borderWidth: js.UndefOr[Double] = js.native
/**
* Fill color of bullish candle stick.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for
* example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported besides
* single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-candlestick.candlestick.data.emphasis.itemStyle)
*
*
* @default
* "#c23531"
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.color
*/
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Fill color of bearish candle stick.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for
* example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported besides
* single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-candlestick.candlestick.data.emphasis.itemStyle)
*
*
* @default
* #314656
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.color0
*/
var color0: js.UndefOr[String] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will
* not be drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-candlestick.candlestick.data.emphasis.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.shadowColor
*/
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-candlestick.data.emphasis.itemStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object BorderColor0 {
@scala.inline
def apply(): BorderColor0 = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[BorderColor0]
}
@scala.inline
implicit class BorderColor0MutableBuilder[Self <: BorderColor0] (val x: Self) extends AnyVal {
@scala.inline
def setBorderColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColor0(value: String): Self = StObject.set(x, "borderColor0", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColor0Undefined: Self = StObject.set(x, "borderColor0", js.undefined)
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColor0(value: String): Self = StObject.set(x, "color0", value.asInstanceOf[js.Any])
@scala.inline
def setColor0Undefined: Self = StObject.set(x, "color0", js.undefined)
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/BackgroundColor.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BackgroundColor extends StObject {
// Background color of exporting image, use backgroundColor in
// option by default.
var backgroundColor: js.UndefOr[String] = js.native
// Excluded components list. e.g. ['toolbox']
var excludeComponents: js.UndefOr[js.Array[String]] = js.native
// Resolution ratio of exporting image, 1 by default.
var pixelRatio: js.UndefOr[Double] = js.native
// Exporting format, can be either png, or jpeg
var `type`: js.UndefOr[String] = js.native
}
object BackgroundColor {
@scala.inline
def apply(): BackgroundColor = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[BackgroundColor]
}
@scala.inline
implicit class BackgroundColorMutableBuilder[Self <: BackgroundColor] (val x: Self) extends AnyVal {
@scala.inline
def setBackgroundColor(value: String): Self = StObject.set(x, "backgroundColor", value.asInstanceOf[js.Any])
@scala.inline
def setBackgroundColorUndefined: Self = StObject.set(x, "backgroundColor", js.undefined)
@scala.inline
def setExcludeComponents(value: js.Array[String]): Self = StObject.set(x, "excludeComponents", value.asInstanceOf[js.Any])
@scala.inline
def setExcludeComponentsUndefined: Self = StObject.set(x, "excludeComponents", js.undefined)
@scala.inline
def setExcludeComponentsVarargs(value: String*): Self = StObject.set(x, "excludeComponents", js.Array(value :_*))
@scala.inline
def setPixelRatio(value: Double): Self = StObject.set(x, "pixelRatio", value.asInstanceOf[js.Any])
@scala.inline
def setPixelRatioUndefined: Self = StObject.set(x, "pixelRatio", js.undefined)
@scala.inline
def setType(value: String): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
@scala.inline
def setTypeUndefined: Self = StObject.set(x, "type", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Icon.scala | <gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Icon extends StObject {
var color: js.UndefOr[String] = js.native
var icon: js.UndefOr[js.Any] = js.native
var margin: js.UndefOr[Double] = js.native
var shadowBlur: js.UndefOr[Double] = js.native
var shadowColor: js.UndefOr[String] = js.native
var shadowOffsetX: js.UndefOr[Double] = js.native
var shadowOffsetY: js.UndefOr[Double] = js.native
var show: js.UndefOr[Boolean] = js.native
var size: js.UndefOr[Double | js.Array[Double]] = js.native
var throttle: js.UndefOr[Double] = js.native
}
object Icon {
@scala.inline
def apply(): Icon = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Icon]
}
@scala.inline
implicit class IconMutableBuilder[Self <: Icon] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: String): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setIcon(value: js.Any): Self = StObject.set(x, "icon", value.asInstanceOf[js.Any])
@scala.inline
def setIconUndefined: Self = StObject.set(x, "icon", js.undefined)
@scala.inline
def setMargin(value: Double): Self = StObject.set(x, "margin", value.asInstanceOf[js.Any])
@scala.inline
def setMarginUndefined: Self = StObject.set(x, "margin", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: String): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setSize(value: Double | js.Array[Double]): Self = StObject.set(x, "size", value.asInstanceOf[js.Any])
@scala.inline
def setSizeUndefined: Self = StObject.set(x, "size", js.undefined)
@scala.inline
def setSizeVarargs(value: Double*): Self = StObject.set(x, "size", js.Array(value :_*))
@scala.inline
def setThrottle(value: Double): Self = StObject.set(x, "throttle", value.asInstanceOf[js.Any])
@scala.inline
def setThrottleUndefined: Self = StObject.set(x, "throttle", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | project/plugins.sbt |
resolvers += Resolver.bintrayRepo("oyvindberg", "converter")
addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.1.16")
addSbtPlugin("org.scalablytyped.converter" % "sbt-converter" % "1.0.0-beta30")
|
eubr-atmosphere/spark-fairness | src/main/scala/br/ufmg/dcc/speed/lemonade/fairness/FairnessEvaluatorTransformer.scala | package br.ufmg.dcc.speed.lemonade.fairness
import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.ml.Transformer
import org.apache.spark.ml.param._
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.functions.{col, count, lit, when}
import org.apache.spark.sql.types.{DataTypes, StructField, StructType}
import org.apache.spark.sql.{Column, DataFrame, Dataset}
import scala.collection.mutable.ListBuffer
private[fairness] trait FairnessEvaluatorParams extends Params {
final val sensitiveColumn = new Param[String](
this, "sensitiveColumn", "column with the sensitive attribute to be checked"
)
final val labelColumn = new Param[String](
this, "labelColumn", "column with the label results"
)
final val scoreColumn = new Param[String](
this, "scoreColumn", "column with the score results"
)
final val baselineValue = new Param[Any](
this, "baselineValue", "value used as base line"
)
final val tau = new FloatParam(
this, "tau", "value used to define boundaries"
)
}
class FairnessEvaluatorTransformer(override val uid: String)
extends Transformer with FairnessEvaluatorParams {
def this() = this(Identifiable.randomUID("fairness"))
override def transform(dataset: Dataset[_]): DataFrame = {
/* Generate basic metrics */
val totals = dataset.select(count("*").alias("total"),
count(when(col($(scoreColumn)) === 1, 1)).alias("positives"),
count(when(col($(scoreColumn)) === 0, 1)).alias("negatives")).first
val aggregations = List[Column](
(count(when(col($(labelColumn)) === 1 && col($(scoreColumn)) === 1, 1)) /
count(when(col($(labelColumn)) === 1, 1))).alias("tpr"),
(count(when(col($(labelColumn)) === 0 && col($(scoreColumn)) === 0, 1)) /
count(when(col($(labelColumn)) === 0, 1))).alias("tnr"),
(count(when(col($(labelColumn)) === 1 && col($(scoreColumn)) === 0, 1)) /
count(when(col($(scoreColumn)) === 0, 1))).alias("for"),
(count(when(col($(labelColumn)) === 0 && col($(scoreColumn)) === 1, 1)) /
count(when(col($(labelColumn)) === 0, 1))).alias("fpr"),
(count(when(col($(labelColumn)) === 1 && col($(scoreColumn)) === 0, 1)) /
count(when(col($(labelColumn)) === 1, 1))).alias("fnr"),
(count(when(col($(labelColumn)) === 0 && col($(scoreColumn)) === 0, 1)) /
count(when(col($(scoreColumn)) === 0, 1))).alias("npv"),
(count(when(col($(labelColumn)) === 1 && col($(scoreColumn)) === 1, 1)) /
count(when(col($(scoreColumn)) === 1, 1))).alias("precision"),
count(when(col($(scoreColumn)) === 1, 1)).alias("pp"),
count(when(col($(scoreColumn)) === 0, 1)).alias("pn"),
(count(when(col($(scoreColumn)) === 1, 1)) / count("*")).alias("pred_pos_ratio_g"),
(count(when(col($(scoreColumn)) === 1, 1)) / totals.getAs[Int]("positives")).alias("pred_pos_ratio_k"),
count(when(col($(labelColumn)) === 0 && col($(scoreColumn)) === 1, 1)).alias("fp"),
count(when(col($(labelColumn)) === 1 && col($(scoreColumn)) === 0, 1)).alias("fn"),
count(when(col($(labelColumn)) === 1 && col($(scoreColumn)) === 1, 1)).alias("tp"),
count(when(col($(labelColumn)) === 0 && col($(scoreColumn)) === 0, 1)).alias("tn"),
(count(when(col($(labelColumn)) === 0 && col($(scoreColumn)) === 1, 1)) /
count(when(col($(scoreColumn)) === 1, 1))).alias("fdr"),
lit(totals.getAs[Int]("positives")).alias("K"),
count(when(col($(labelColumn)) === 1, 1)).alias("grp_label_pos"),
count(when(col($(labelColumn)) === 0, 1)).alias("grp_label_neg"),
count("*").alias("group_size"),
(count(when(col($(labelColumn)) === 1, 1)) / count("*")).alias("prev")
//lit("total_entities").alias("total_entities")
)
var result = dataset.groupBy(col($(sensitiveColumn))).agg(
aggregations.head, aggregations.tail: _*).orderBy(col($(sensitiveColumn)))
val exclude = Array($(sensitiveColumn), "total_entities", "k")
val baselineDf = result.filter(col($(sensitiveColumn)) === $(baselineValue))
val baselineRow = baselineDf.first
val metricsColumns = result.schema.filter(
f => !(exclude contains f.name))
/* Ratio between metrics and baseline value */
val ratios = ListBuffer[Column](col($(sensitiveColumn)), col("for"),
col("fdr"), col("fpr"), col("fnr"), col("pred_pos_ratio_g"),
col("pred_pos_ratio_k"), col("group_size"))
ratios ++= metricsColumns.map(
f => (col(f.name) / baselineRow.getAs[Double](f.name)).alias(f.name + "_disparity"))
result = result.select(ratios: _*)
val disparitiesColumns: Array[String] = getDisparityColumnNames
var parities = ListBuffer[Column](
lit(totals.getAs[Int]("total")).alias("total_records"),
col($(sensitiveColumn)),
lit($(sensitiveColumn)).alias("attribute"), col("for"),
col("fdr"), col("fpr"), col("fnr"), col("pred_pos_ratio_g"),
col("pred_pos_ratio_k"), col("group_size"))
parities ++= result.schema.map(f => col(f.name)).to[ListBuffer]
val inverseTau = 1.0 / $(tau)
parities ++= disparitiesColumns.map(d => {
(col(d) > $(tau) && col(d) < inverseTau).alias(s"${d.replace("_disparity", "")}_parity")
}).to[ListBuffer]
parities += (col("fdr_disparity") > $(tau) && col("fdr_disparity") < inverseTau
&& col("fpr_disparity") > $(tau) && col("fpr_disparity") < inverseTau)
.alias("type_I_parity")
parities += (col("for_disparity") > $(tau) && col("for_disparity") < inverseTau
&& col("fnr_disparity") > $(tau) && col("fnr_disparity") < inverseTau)
.alias("type_II_parity")
parities += (col("pred_pos_ratio_g_disparity") > $(tau) && col("pred_pos_ratio_g_disparity") < inverseTau
&& col("pred_pos_ratio_k_disparity") > $(tau) && col("pred_pos_ratio_k_disparity") < inverseTau)
.alias("unsupervisioned_fairness")
parities += (col("for_disparity") > $(tau) && col("for_disparity") < inverseTau
&& col("fnr_disparity") > $(tau) && col("fnr_disparity") < inverseTau
&& col("fdr_disparity") > $(tau) && col("fdr_disparity") < inverseTau
&& col("fpr_disparity") > $(tau) && col("fpr_disparity") < inverseTau)
.alias("supervisioned_fairness")
result.select(parities: _*)
}
private def getDisparityColumnNames: Array[String] = {
getMainMetricColumns.map(d => s"${d}_disparity")
}
private def getMainMetricColumns: Array[String] = {
Array("fnr", "for", "tnr", "pred_pos_ratio_g", "precision",
"pred_pos_ratio_k", "fdr", "tpr", "fpr", "npv")
}
override def copy(extra: ParamMap): Transformer = {
defaultCopy(extra)
}
@DeveloperApi
override def transformSchema(schema: StructType): StructType = {
val fieldNames = Array("tpr_disparity", "tnr_disparity", "for_disparity",
"fpr_disparity", "fnr_disparity", "npv_disparity", "precision_disparity",
"pp_disparity", "pn_disparity", "pred_pos_ratio_g_disparity",
"pred_pos_ratio_k_disparity", "fp_disparity", "fn_disparity",
"tp_disparity", "tn_disparity", "fdr_disparity", "grp_label_pos_disparity",
"grp_label_neg_disparity", "group_size_disparity", "prev_disparity",
"fnr_parity", "for_parity", "tnr_parity", "pred_pos_ratio_g_parity",
"precision_parity", "pred_pos_ratio_k_parity", "fdr_parity",
"tpr_parity", "fpr_parity", "npv_parity", "type_I_parity",
"type_II_parity", "unsupervisioned_fairness", "supervisioned_fairness")
val fields = ListBuffer(StructField($(sensitiveColumn), DataTypes.StringType,
nullable = false),
StructField("for", DataTypes.DoubleType,
nullable = false),
StructField("fdr", DataTypes.DoubleType,
nullable = false),
StructField("fpr", DataTypes.DoubleType,
nullable = false),
StructField("fnr", DataTypes.DoubleType,
nullable = false),
StructField("pred_pos_ratio_g", DataTypes.DoubleType,
nullable = false),
StructField("pred_pos_ratio_k", DataTypes.DoubleType,
nullable = false))
fields ++= fieldNames.map(
f => StructField(f, DataTypes.LongType, nullable = false)).to[ListBuffer]
StructType(fields)
}
}
|
mturlo/shenzhen | src/main/scala/shenzhen/compiler/Compiler.scala | package shenzhen.compiler
import shenzhen.language.{AST, Jmp, Label, LabeledInstruction}
import shenzhen.lexer.Lexer
import shenzhen.parser.Parser
object Compiler {
val lexer = Lexer
val parser = Parser
private def checkJumpLabels(ast: AST): Either[CompilationError, AST] = {
val jumps: Seq[Jmp] = {
ast.statements.flatMap {
case j: Jmp => Some(j)
case _ => None
}
}
val labels: Seq[Label] = {
ast.statements.flatMap {
case l: Label => Some(l)
case li: LabeledInstruction => Some(li.Label)
case _ => None
}
}
val labelsInJumps: Seq[String] = jumps.map(_.to)
val existingLabels: Seq[String] = labels.map(_.value)
val missingLabels: Seq[String] = labelsInJumps diff existingLabels
missingLabels match {
case Nil => Right(ast)
case someMissingLabels => Left(SyntaxError(s"There are some jumps with non-existent target labels: $someMissingLabels"))
}
}
private def checkSyntax(ast: AST): Either[CompilationError, AST] = {
checkJumpLabels(ast)
}
def compile(input: String): Either[CompilationError, AST] = {
for {
tokens <- lexer.tokenise(input).right
program <- parser.parse(tokens).right
checkedProgram <- checkSyntax(program).right
} yield {
checkedProgram
}
}
}
|
mturlo/shenzhen | src/main/scala/shenzhen/parser/Parser.scala | <reponame>mturlo/shenzhen
package shenzhen.parser
import scala.util.parsing.combinator.Parsers
import scala.util.parsing.input.{NoPosition, Position, Reader}
import shenzhen.compiler.{ErrorHandling, ParsingError}
import shenzhen.language._
import shenzhen.lexer._
object Parser
extends Parsers
with ErrorHandling {
override type Elem = Token
class TokenReader(tokens: Seq[Token]) extends Reader[Token] {
override def first: Token = tokens.head
override def atEnd: Boolean = tokens.isEmpty
override def pos: Position = NoPosition
override def rest: Reader[Token] = new TokenReader(tokens.tail)
}
private def numeric: Parser[NUMERIC] = {
accept("numeric", { case value @ NUMERIC(_) => value })
}
private def identifier: Parser[IDENTIFIER] = {
accept("identifier", { case id @ IDENTIFIER(_) => id })
}
private def label: Parser[Label] = {
identifier ~ COLON ^^ { case id ~ _ => Label(id.str) }
}
private def value: Parser[Value] = {
(identifier | numeric) ^^ {
case IDENTIFIER(str) => Register(str)
case NUMERIC(numValue) => Constant(numValue)
case otherToken => throw new IllegalArgumentException(s"Unexpected token: $otherToken - this should not happen!")
}
}
private def mov: Parser[Mov] = {
MOV ~> value ~ value ^^ { case from ~ to => Mov(from, to) }
}
private def add: Parser[Add] = {
ADD ~> value ^^ Add
}
private def sub: Parser[Sub] = {
SUB ~> value ^^ Sub
}
private def jmp: Parser[Jmp] = {
JMP ~> identifier ^^ (to => Jmp(to.str))
}
private def instruction: Parser[Instruction] = {
mov | add | sub | jmp
}
private def labeledInstruction: Parser[LabeledInstruction] = {
label ~ instruction ^^ { case l ~ i => LabeledInstruction(l, i) }
}
private def statement: Parser[Statement] = {
(labeledInstruction | instruction | label) <~ CRLF
}
private def program: Parser[Program] = {
phrase(rep1(statement)) ^^ Program
}
def parse(tokens: Seq[Token]): Either[ParsingError, AST] = {
val reader = new TokenReader(tokens)
program(reader) match {
case NoSuccess(msg, next) => Left(ParsingError(msg, toLocation(next.pos)))
case Success(result, _) => Right(result)
}
}
}
|
mturlo/shenzhen | project/plugins.sbt | addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0-M14")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "0.8.0")
|
mturlo/shenzhen | src/main/scala/shenzhen/lexer/Tokens.scala | <filename>src/main/scala/shenzhen/lexer/Tokens.scala
package shenzhen.lexer
sealed trait Token
case class NUMERIC(value: Int) extends Token
case class IDENTIFIER(str: String) extends Token
case object COLON extends Token
case object CRLF extends Token
case object MOV extends Token
case object ADD extends Token
case object SUB extends Token
case object JMP extends Token
|
mturlo/shenzhen | build.sbt | name := "shenzhen"
version := "0.1.0-SNAPSHOT"
scalaVersion := "2.11.8"
libraryDependencies ++= {
object Versions {
val parserCombinators = "1.0.5"
val scalatest = "3.0.0"
}
Seq(
// prod
"org.scala-lang.modules" %% "scala-parser-combinators" % Versions.parserCombinators,
// test
"org.scalatest" %% "scalatest" % Versions.scalatest % "test"
).map(_ withSources() withJavadoc())
}
scalacOptions ++= Seq(
"-Xfatal-warnings",
"-feature",
"-deprecation",
"-language:postfixOps"
)
lazy val root = project in file(".")
// scalastyle check on compile
lazy val compileScalastyle = taskKey[Unit]("compileScalastyle")
compileScalastyle := org.scalastyle.sbt.ScalastylePlugin.scalastyle.in(Compile).toTask("").value
(compile in Compile) := ((compile in Compile) dependsOn compileScalastyle).value
|
mturlo/shenzhen | src/main/scala/shenzhen/compiler/Errors.scala | <reponame>mturlo/shenzhen<gh_stars>1-10
package shenzhen.compiler
sealed trait CompilationError {
def message: String
def location: Location
}
case class Location(line: Int, column: Int) {
override def toString: String = {
s"$line:$column"
}
}
object Location {
def zero: Location = Location(0, 0)
}
case class LexicalError(message: String, location: Location) extends CompilationError
case class ParsingError(message: String, location: Location) extends CompilationError
case class SyntaxError(message: String, location: Location = Location.zero) extends CompilationError
|
mturlo/shenzhen | src/main/scala/shenzhen/Shenzhen.scala | package shenzhen
import compiler.Compiler
object Shenzhen extends App {
val testProg =
"""start:
| foo: mov -100 acc
| add 256
| sub 80
| mov acc dat
| mov dat p0
| jmp foo
|""".stripMargin
val input = testProg
println(input)
val program = Compiler.compile(input)
println(program)
}
|
mturlo/shenzhen | src/main/scala/shenzhen/lexer/Lexer.scala | package shenzhen.lexer
import scala.util.parsing.combinator.RegexParsers
import shenzhen.compiler.{ErrorHandling, LexicalError}
import scala.util.matching.Regex
object Lexer
extends RegexParsers
with ErrorHandling {
override val whiteSpace: Regex = "[ \t\r\f]+".r
private def numeric = "-{0,1}\\d+".r ^^ (str => NUMERIC(str.toInt))
private def identifier = "[a-zA-Z][a-zA-Z0-9]*".r ^^ IDENTIFIER
private def colon = ":" ^^ (_ => COLON)
private def crlf = "\\n".r ^^ (_ => CRLF)
private def mov = "mov" ^^ (_ => MOV)
private def add = "add" ^^ (_ => ADD)
private def sub = "sub" ^^ (_ => SUB)
private def jmp = "jmp" ^^ (_ => JMP)
private def instruction = mov | add | sub | jmp
private def tokens = phrase(rep1(colon | instruction | numeric | identifier | crlf))
def tokenise(input: String): Either[LexicalError, List[Token]] = {
parse(tokens, input) match {
case NoSuccess(msg, next) => Left(LexicalError(msg, toLocation(next.pos)))
case Success(tokens, _) => Right(tokens)
}
}
}
|
mturlo/shenzhen | src/main/scala/shenzhen/compiler/ErrorHandling.scala | <reponame>mturlo/shenzhen
package shenzhen.compiler
import scala.util.parsing.input.Position
trait ErrorHandling {
protected def toLocation(position: Position): Location = {
Location(position.line, position.column)
}
}
|
mturlo/shenzhen | src/main/scala/shenzhen/util/EitherUtils.scala | <gh_stars>1-10
package shenzhen.util
trait EitherUtils {
def reduceList[L, R](input: List[Either[L, R]]): Either[List[L], List[R]] = {
input.partition(_.isLeft) match {
case (Nil, rights) => Right(for (Right(i) <- rights) yield i)
case (lefts, _) => Left(for (Left(s) <- lefts) yield s)
}
}
}
object EitherUtils extends EitherUtils
|
mturlo/shenzhen | src/main/scala/shenzhen/language/Language.scala | <gh_stars>1-10
package shenzhen.language
sealed trait AST {
def statements: Seq[Statement]
}
case class Program(statements: Seq[Statement]) extends AST
sealed trait Statement extends AST {
override def statements: Seq[Statement] = Seq(this)
}
sealed trait Instruction extends Statement
case class LabeledInstruction(Label: Label, instruction: Instruction) extends Statement {
override def statements: Seq[Statement] = Seq(instruction)
}
sealed trait Value extends AST {
override def statements: Seq[Statement] = Nil
}
case class Constant(value: Int) extends Value
case class Register(id: String) extends Value
case class Mov(from: Value, to: Value) extends Instruction
case class Add(value: Value) extends Instruction
case class Sub(value: Value) extends Instruction
case class Jmp(to: String) extends Instruction
case class Label(value: String) extends Statement
|
anand-singh/learning-algorithms | project/Dependencies.scala | <reponame>anand-singh/learning-algorithms
import sbt._
object Dependencies {
object Version {
lazy val cats = "2.7.0"
}
lazy val catsCore = "org.typelevel" %% "cats-core" % Version.cats
lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.2.10"
}
|
anand-singh/learning-algorithms | build.sbt | <filename>build.sbt
import Dependencies._
import sbtrelease.ReleaseStateTransformations._
import sbtrelease.ReleasePlugin.autoImport._
ThisBuild / scalaVersion := "2.13.7"
ThisBuild / version := "0.1.0-SNAPSHOT"
lazy val root = (project in file("."))
.settings(
name := "learning-algorithms",
scalastyleFailOnError := true,
scalastyleFailOnWarning := false,
scalafmtOnCompile := true,
libraryDependencies ++= Seq(catsCore, scalaTest % Test)
)
.settings(addCompilerPlugin(kindProjectorSetting))
scalacOptions ++= Seq(
"-feature",
"-unchecked",
"-language:higherKinds",
"-language:postfixOps",
"-deprecation",
"-encoding",
"UTF-8",
"-Xlint"
)
resolvers ++= Seq(
Resolver.mavenLocal,
Resolver.sonatypeRepo("releases"),
Resolver.sonatypeRepo("snapshots"),
"Bintray ".at("https://dl.bintray.com/projectseptemberinc/maven")
)
releaseProcess := Seq(
checkSnapshotDependencies,
inquireVersions,
// publishing locally in the process
releaseStepCommandAndRemaining("+publishLocal"),
releaseStepCommandAndRemaining("+clean"),
releaseStepCommandAndRemaining("+test"),
setReleaseVersion,
commitReleaseVersion,
tagRelease,
setNextVersion,
commitNextVersion,
pushChanges
)
lazy val kindProjectorSetting = "org.typelevel" %% "kind-projector" % "0.13.2" cross CrossVersion.full
addCommandAlias("fmt", ";scalafmtSbt;scalafmt;test:scalafmt")
addCommandAlias("cpl", ";compile;test:compile")
addCommandAlias("validate", ";clean;scalafmtSbtCheck;scalafmtCheck;test:scalafmtCheck;coverage;test;coverageOff;coverageReport;coverageAggregate")
addCommandAlias("testAll", ";clean;test;it:test")
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/DataPrep.scala | package pt.necosta.forecastx
import java.io.File
import java.net.URL
import sys.process._
import org.apache.spark.sql.Dataset
import pt.necosta.forecastx.record.InputRecord
import scala.language.postfixOps
object DataPrep {
def withConfig(sourceFolder: String): DataPrep = {
new DataPrep(sourceFolder)
}
}
class DataPrep(sourceFolder: String) extends WithSpark {
def runImport(): Unit = {
val urlHost = "raw.githubusercontent.com"
val urlPath = "JeffSackmann/tennis_atp/master"
// Import last 10 years of data
(0 to 10).foreach(i => {
val year = 2018 - i
new URL(s"https://$urlHost/$urlPath/atp_matches_$year.csv") #> new File(
s"$sourceFolder/sourceData_$year.csv") !!
})
}
def transformSourceFile(): Dataset[InputRecord] = {
import spark.implicits._
val df = spark.read
.option("inferSchema", "true")
.option("header", "true")
.csv(s"$sourceFolder/sourceData*.csv")
// Remove underscore from all column names
df.columns
.foldLeft(df)((curr, n) =>
curr.withColumnRenamed(n, n.replaceAll("_", "")))
.as[InputRecord]
}
}
|
necosta/forecast-x | src/test/scala/pt/necosta/forecastx/DataForecastSpec.scala | <gh_stars>1-10
package pt.necosta.forecastx
import java.io.File
import org.apache.spark.sql.Dataset
import pt.necosta.forecastx.record.InputRecord
class DataForecastSpec extends TestConfig {
"DataForecast" should "correctly transform input data" in {
val outputDS = DataForecast.prepData(getSourceDs)
outputDS.head().isWinner should be(1.0)
outputDS.head().surface should be("Hard")
}
private def getSourceDs: Dataset[InputRecord] = {
val sourceFilePath = this.getClass
.getResource("/sourceData.csv")
.getFile
DataPrep
.withConfig(new File(sourceFilePath).getParent)
.transformSourceFile()
}
}
|
necosta/forecast-x | src/test/scala/pt/necosta/forecastx/DataPrepSpec.scala | package pt.necosta.forecastx
import java.io.File
import org.apache.spark.sql.SparkSession
class DataPrepSpec extends TestConfig {
"DataPrep" should "correctly import source file as dataset" in {
val spark = SparkSession.builder().getOrCreate()
import spark.implicits._
val sourceFilePath = this.getClass
.getResource("/sourceData.csv")
.getFile
val sourceDS = DataPrep
.withConfig(new File(sourceFilePath).getParent)
.transformSourceFile()
sourceDS.count() should be(20)
sourceDS.map(_.tourneyId).collect().distinct should be(
Array("2018-M020", "2018-7161", "2018-0425"))
sourceDS.map(_.tourneyLevel).collect().distinct should be(Array("A", "B"))
sourceDS.map(_.winnerHand).collect().distinct should be(
Array(Some("L"), Some("R"), Some("U")))
sourceDS.map(_.winnerAge).collect().max should be < 32.0
}
}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/DataAnalysis.scala | <reponame>necosta/forecast-x<gh_stars>1-10
package pt.necosta.forecastx
import org.apache.spark.sql.Dataset
import org.apache.spark.sql.functions._
import pt.necosta.forecastx.record._
object DataAnalysis extends WithSpark {
val percentageColumn = "percentage"
def getTournamentGamesCount: Dataset[InputRecord] => Dataset[GamesCount] = {
import spark.implicits._
ds =>
ds.groupBy($"tourneyId", $"tourneyName")
.agg(count($"tourneyId").alias("tourneyCount"))
.as[GamesCount]
}
def getSurfaceDistribution
: Dataset[InputRecord] => Dataset[SurfaceDistribution] = {
import spark.implicits._
ds =>
{
val total = ds.count
ds.groupBy($"surface")
.agg(count(lit(1)).alias("surfaceCount"))
.withColumn(percentageColumn, col("surfaceCount") * 100 / total)
.as[SurfaceDistribution]
}
}
def getHandDistribution: Dataset[InputRecord] => Dataset[HandDistribution] = {
import spark.implicits._
ds =>
{
val total = ds.count
ds.groupBy($"winnerHand", $"loserHand")
.agg(count(lit(1)).alias("count"))
.withColumn(percentageColumn, col("count") * 100 / total)
.as[HandDistribution]
}
}
}
|
necosta/forecast-x | src/test/scala/pt/necosta/forecastx/TestConfig.scala | package pt.necosta.forecastx
import com.holdenkarau.spark.testing.SharedSparkContext
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
trait TestConfig
extends FlatSpec
with Matchers
with BeforeAndAfterAll
with SharedSparkContext {}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/record/RandomForestRecord.scala | package pt.necosta.forecastx.record
case class RandomForestRecord(isWinner: Double, // label we want to predict
surface: String,
drawSize: Int,
tourneyLevel: String,
seed: Int,
entry: String,
hand: String,
height: Int,
country: String,
age: Double,
rank: Int,
rankPoints: Int,
round: String)
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/WithSpark.scala | package pt.necosta.forecastx
import org.apache.spark.sql.SparkSession
trait WithSpark {
implicit lazy val spark: SparkSession = SparkSession.builder().getOrCreate()
}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/record/InputRecord.scala | package pt.necosta.forecastx.record
case class InputRecord(tourneyId: String, // Tournament Id. Ex: 2018-M020
tourneyName: String, // Tournament Name. Ex: Brisbane
surface: Option[String], // Ex: Hard, Clay, Grass
drawSize: Int, // Ex: 32, 64, 128
tourneyLevel: String, // Ex: A, B, C
tourneyDate: Int, // Ex: 20180423
matchNum: Int, // Ex. 1, 5, 188
winnerId: Int, // Ex: 1, 2, 3
winnerSeed: Option[Int], // Ex: 1, 10, 50
winnerEntry: Option[String], // Ex: Q, WC
winnerName: String,
winnerHand: Option[String], // Ex: R, L, U
winnerHt: Option[Int], // Winner Height. Ex: 183
winnerIoc: String, // Winner Country. Ex: AUS
winnerAge: Double,
winnerRank: Int,
winnerRankPoints: Int,
loserId: Int,
loserSeed: Option[Int],
loserEntry: Option[String],
loserName: String,
loserHand: Option[String],
loserHt: Option[Int],
loserIoc: String,
loserAge: Double,
loserRank: Int,
loserRankPoints: Int,
score: String, // Ex. "7-6(3) 5-7 6-4"
bestOf: Int, // Best of 3 or 5 games
round: String, // Ex. R16
minutes: Int,
wAce: Int,
wDf: Int,
wSvpt: Int,
w1stIn: Int,
w1stWon: Int,
w2ndWon: Int,
wSvGms: Int,
wBpSaved: Int,
wBpFaced: Int,
lAce: Int,
lDf: Int,
lSvpt: Int,
l1stIn: Int,
l1stWon: Int,
l2ndWon: Int,
lSvGms: Int,
lBpSaved: Int,
lBpFaced: Int)
|
necosta/forecast-x | src/test/scala/pt/necosta/forecastx/DataAnalysisSpec.scala | <filename>src/test/scala/pt/necosta/forecastx/DataAnalysisSpec.scala<gh_stars>1-10
package pt.necosta.forecastx
import java.io.File
import org.apache.spark.sql.Dataset
import pt.necosta.forecastx.record.InputRecord
import org.apache.spark.sql.functions._
class DataAnalysisSpec extends TestConfig {
"DataAnalysis" should "correctly get number of games per tournament" in {
val outputDS = getSourceDs.transform(DataAnalysis.getTournamentGamesCount)
outputDS.count() should be(3)
outputDS
.filter(col("tourneyId") === "2018-M020")
.head()
.tourneyCount should be(11)
}
"DataAnalysis" should "correctly get surface distribution" in {
val outputDS = getSourceDs.transform(DataAnalysis.getSurfaceDistribution)
outputDS.count() should be(3)
outputDS
.filter(col("surface") === "Hard")
.head()
.percentage should be(50.0)
}
"DataAnalysis" should "correctly get hand win/lost distribution" in {
val outputDS = getSourceDs.transform(DataAnalysis.getHandDistribution)
outputDS.count() should be(5)
outputDS
.filter(col("winnerHand") === "R" && col("loserHand") === "L")
.head()
.percentage should be(10.0)
}
private def getSourceDs: Dataset[InputRecord] = {
val sourceFilePath = this.getClass
.getResource("/sourceData.csv")
.getFile
DataPrep
.withConfig(new File(sourceFilePath).getParent)
.transformSourceFile()
}
}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/RandomForest.scala | package pt.necosta.forecastx
import org.apache.spark.ml.{Model, Pipeline, PipelineModel, PipelineStage}
import org.apache.spark.ml.classification.RandomForestClassifier
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
import org.apache.spark.ml.feature._
import org.apache.spark.ml.param.ParamMap
import org.apache.spark.ml.tuning.{CrossValidator, ParamGridBuilder}
import org.apache.spark.mllib.evaluation.MulticlassMetrics
import org.apache.spark.sql.{DataFrame, Dataset}
import org.apache.spark.sql.functions._
import pt.necosta.forecastx.record.RandomForestRecord
object RandomForest extends WithSpark {
def start(dataRaw: Dataset[RandomForestRecord]): PipelineModel = {
// Eliminates noisy logging
spark.sparkContext.setLogLevel("ERROR")
// Cache dataset in memory
dataRaw.cache()
val dfs = dataRaw
.randomSplit(Array(0.7, 0.3), 123456L)
val trainDf = dfs(0).withColumnRenamed("isWinner", "label")
val crossDf = dfs(1)
// create pipeline stages for handling categorical
val surfaceStage = handleCategorical("surface")
val drawSizeStage = handleCategorical("drawSize")
val levelStage = handleCategorical("tourneyLevel")
val entryStage = handleCategorical("entry")
val handStage = handleCategorical("hand")
val countryStage = handleCategorical("country")
val roundStage = handleCategorical("round")
val catStages = surfaceStage ++ drawSizeStage ++ levelStage ++ entryStage ++ handStage ++ countryStage ++ roundStage
//columns for training
val cols = Array(
"surface_onehot",
"drawSize_onehot",
"tourneyLevel_onehot",
"entry_onehot",
"hand_onehot",
"country_onehot",
"round_onehot",
"seed",
"height",
"age",
"rank",
"rankPoints"
)
val vectorAssembler =
new VectorAssembler()
.setInputCols(cols)
.setOutputCol("features")
val randomForestClassifier = new RandomForestClassifier()
val pipeline = new Pipeline()
.setStages(
catStages ++ Array(vectorAssembler) ++ Array(randomForestClassifier))
val model = pipeline.fit(trainDf)
val trainScore =
accuracyScore(model.transform(trainDf), "label", "prediction")
val testScore =
accuracyScore(model.transform(crossDf), "isWinner", "prediction")
println(s"train accuracy with pipeline: $trainScore")
println(s"test accuracy with pipeline: $testScore")
//scoreDf(model,trainDf)
//cross validation
val paramMap = new ParamGridBuilder()
.addGrid(randomForestClassifier.impurity, Array("gini", "entropy"))
.addGrid(randomForestClassifier.maxDepth, Array(1, 2, 5))
.addGrid(randomForestClassifier.minInstancesPerNode, Array(1, 2, 4))
.build()
val cvModel = crossValidation(pipeline, paramMap, trainDf)
val trainCvScore =
accuracyScore(cvModel.transform(trainDf), "label", "prediction")
val testCvScore =
accuracyScore(cvModel.transform(crossDf), "isWinner", "prediction")
println(s"train accuracy with cross validation: $trainCvScore")
println(s"test accuracy with cross validation: $testCvScore")
model
}
def save(model: PipelineModel, modelFile: String): Unit = {
model.save(modelFile)
}
def load(modelFile: String): PipelineModel = {
PipelineModel.load(modelFile)
}
def score(model: PipelineModel, records: Array[RandomForestRecord]): Unit = {
import spark.implicits._
val dummyDs = spark.createDataset[RandomForestRecord](records)
scoreDf(model, dummyDs.toDF())
}
private def crossValidation(pipeline: Pipeline,
paramMap: Array[ParamMap],
df: DataFrame): Model[_] = {
new CrossValidator()
.setEstimator(pipeline)
.setEvaluator(new BinaryClassificationEvaluator)
.setEstimatorParamMaps(paramMap)
.setNumFolds(5)
.fit(df)
}
private def handleCategorical(column: String): Array[PipelineStage] = {
val stringIndexer = new StringIndexer()
.setInputCol(column)
.setOutputCol(s"${column}_index")
.setHandleInvalid("skip")
val oneHot = new OneHotEncoder()
.setInputCol(s"${column}_index")
.setOutputCol(s"${column}_onehot")
Array(stringIndexer, oneHot)
}
private def accuracyScore(df: DataFrame,
label: String,
predictCol: String): Double = {
val rdd = df
.select(predictCol, label)
.rdd
.map(row => (row.getDouble(0), row.getDouble(1)))
new MulticlassMetrics(rdd).accuracy
}
private def scoreDf(model: PipelineModel, df: DataFrame): Unit = {
import spark.implicits._
val first = udf((v: org.apache.spark.ml.linalg.Vector, pred: Double) => {
val p = (v.toArray.head * 100).floor / 100
if (pred > 0.0) 1 - p else p
})
model
.transform(df)
.withColumn("prob", first($"probability", $"prediction"))
.select("seed", "prob", "prediction")
.show(20)
}
}
|
necosta/forecast-x | project/plugins.sbt | addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.1")
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "1.15")
|
necosta/forecast-x | build.sbt | <reponame>necosta/forecast-x
lazy val root = (project in file("."))
.settings(
name := "forecastx",
organization := "pt.necosta",
scalaVersion := "2.11.12"
)
val sparkVersion = "2.3.1"
val coreDependencies = Seq("org.apache.spark" %% "spark-sql" % sparkVersion,
"org.apache.spark" %% "spark-mllib" % sparkVersion)
val testDependencies = Seq(
"org.scalatest" %% "scalatest" % "3.0.5" % "test",
"com.holdenkarau" %% "spark-testing-base" % (sparkVersion + "_0.10.0") % "test")
libraryDependencies ++= coreDependencies ++ testDependencies
// Format options
scalafmtOnCompile in ThisBuild := true
scalafmtTestOnCompile in ThisBuild := true
scalafmtFailTest in ThisBuild := true
// Disable parallel execution
parallelExecution in ThisBuild := false
parallelExecution in Test := false
// From: https://medium.com/@mrpowers/how-to-cut-the-run-time-of-a-spark-sbt-test-suite-by-40-52d71219773f
fork in Test := true
javaOptions in Test ++= Seq("-Xms512M",
"-Xmx2048M",
"-XX:+CMSClassUnloadingEnabled")
coverageEnabled in Test := true
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/DataForecast.scala | package pt.necosta.forecastx
import org.apache.spark.sql.{DataFrame, Dataset}
import pt.necosta.forecastx.record.{InputRecord, RandomForestRecord}
import org.apache.spark.sql.functions._
object DataForecast extends WithSpark {
def prepData(sourceDs: Dataset[InputRecord]): Dataset[RandomForestRecord] = {
import spark.implicits._
val winnerDs = sourceDs
.select(
lit(1.0).as("isWinner"),
col("surface"),
col("drawSize"),
col("tourneyLevel"),
col("winnerSeed").alias("seed"),
col("winnerEntry").alias("entry"),
col("winnerHand").alias("hand"),
col("winnerHt").alias("height"),
col("winnerIOC").alias("country"),
col("winnerAge").alias("age"),
col("winnerRank").alias("rank"),
col("winnerRankPoints").alias("rankPoints"),
col("round"),
col("score")
)
val loserDs = sourceDs
.select(
lit(0.0).as("isWinner"),
col("surface"),
col("drawSize"),
col("tourneyLevel"),
col("loserSeed").alias("seed"),
col("loserEntry").alias("entry"),
col("loserHand").alias("hand"),
col("loserHt").alias("height"),
col("loserIOC").alias("country"),
col("loserAge").alias("age"),
col("loserRank").alias("rank"),
col("loserRankPoints").alias("rankPoints"),
col("round"),
col("score")
)
val out = winnerDs
.union(loserDs)
.fillNa[String]("surface", "Hard")
.fillNa[Int]("seed", 999)
.fillNa[String]("entry", "N")
.fillNa[Int]("height", 175)
.fillNa[String]("hand", "U")
.fillNa[Int]("rank", 999)
.fillNa[Int]("rankPoints", 0)
.fillNa[Int]("age", 30)
.as[RandomForestRecord]
//out.show(10)
out
}
protected implicit class fillNa(df: DataFrame) {
def fillNa[T](columnName: String, defaultValue: T): DataFrame = {
defaultValue match {
case _: Int =>
df.na.fill(defaultValue.asInstanceOf[Int], Seq(columnName))
case _: Double =>
df.na.fill(defaultValue.asInstanceOf[Double], Seq(columnName))
case _ => df.na.fill(defaultValue.asInstanceOf[String], Seq(columnName))
}
}
}
}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/ForecastX.scala | package pt.necosta.forecastx
import org.apache.spark.sql.SparkSession
object StartMode extends Enumeration {
type StartMode = Value
val Import, Stats, Analysis, Forecast, Score = Value
}
object ForecastX {
def main(args: Array[String]): Unit = {
println("Starting Spark application")
val spark = SparkSession.builder
.appName("ForecastX")
.getOrCreate()
val sourceFolder = sys.env.getOrElse("SPARK_SOURCE_FOLDER", "/forecastx")
val dataflow = Dataflow.withConfig(sourceFolder)
import StartMode._
if (args.length > 0) {
val arg1 = args(0)
withNameOption(arg1) match {
case Some(Import) => dataflow.startImport()
case Some(Stats) => dataflow.startStatsCollection()
case Some(Analysis) => dataflow.startAnalysis()
case Some(Forecast) => dataflow.startForecast()
case Some(Score) => dataflow.startScoring()
case _ =>
println(
s"Invalid argument: $arg1. Valid values: ${StartMode.values.mkString(",")}")
}
} else {
dataflow.startImport()
dataflow.startStatsCollection()
dataflow.startAnalysis()
dataflow.startForecast()
}
spark.stop()
}
private def withNameOption(name: String): Option[StartMode.Value] =
try {
Some(StartMode.withName(name))
} catch {
case _: NoSuchElementException => None
}
}
|
necosta/forecast-x | src/test/scala/pt/necosta/forecastx/RandomForestSpec.scala | package pt.necosta.forecastx
import java.io.File
class RandomForestSpec extends TestConfig {
"RandomForest" should "prepare data" in {
val sourceFilePath = this.getClass
.getResource("/sourceData.csv")
.getFile
val sourceDs = DataPrep
.withConfig(new File(sourceFilePath).getParent)
.transformSourceFile()
val outDs = DataForecast.prepData(sourceDs)
outDs.count() should be(40)
// ToDo: add tests
//RandomForest.start(outDs)
}
}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/Dataflow.scala | <filename>src/main/scala/pt/necosta/forecastx/Dataflow.scala
package pt.necosta.forecastx
import java.io.File
import org.apache.spark.sql.functions._
import pt.necosta.forecastx.record.{InputRecord, RandomForestRecord}
object Dataflow {
def withConfig(sourceFolder: String): Dataflow = {
new Dataflow(sourceFolder)
}
}
class Dataflow(sourceFolder: String) extends WithSpark {
private val SAVE_FORMAT = "parquet"
val dataPrep: DataPrep = DataPrep.withConfig(sourceFolder)
val outputFile = s"$sourceFolder/output.parquet"
val modelFile = s"$sourceFolder/rf_model"
def startImport(): Unit = {
if (new File(outputFile).exists()) {
println("Skipping data import. File exists.")
return
}
println("Starting data raw import")
dataPrep.runImport()
println("Starting data transformation")
val outputDs = dataPrep.transformSourceFile()
println("Persist dataset as parquet")
outputDs.write.format(SAVE_FORMAT).save(outputFile)
}
def startAnalysis(): Unit = {
import spark.implicits._
val NUMBER_RECORDS = 3
val inputDs = spark.read.parquet(outputFile).as[InputRecord]
println("Starting data analysis")
val tournamentCountDs = inputDs
.transform(DataAnalysis.getTournamentGamesCount)
.orderBy(desc("tourneyCount"))
.take(NUMBER_RECORDS)
// ToDo: Normalize null vs None
val surfaceDistributionDs = inputDs
.transform(DataAnalysis.getSurfaceDistribution)
.orderBy(desc("percentage"))
.collect()
val handDistributionDs = inputDs
.transform(DataAnalysis.getHandDistribution)
.orderBy(desc("percentage"))
.collect()
println(s"\nThe top $NUMBER_RECORDS tournaments with more games:\n")
tournamentCountDs.foreach(r =>
println(s"${r.tourneyId}-${r.tourneyName}: ${r.tourneyCount} games"))
println(s"\nTournaments surface distribution:\n")
surfaceDistributionDs.foreach(r =>
println(s"${r.surface}: ${r.percentage}"))
println(s"\nTournaments hand winning distribution:\n")
handDistributionDs.foreach(
r =>
println(
s"Winner:${r.winnerHand} - Loser:${r.loserHand} => ${r.percentage}"))
}
def startStatsCollection(): Unit = {
import spark.implicits._
val inputDs = spark.read.parquet(outputFile).as[InputRecord]
println("Starting data validation")
val rows = inputDs.count()
val columns = inputDs.columns.length
val years = inputDs.groupBy($"tourneyDate".substr(0, 4)).count().count()
val tournaments = inputDs.groupBy($"tourneyId").count().count()
println(s"Number of rows: $rows")
println(s"Number of columns: $columns")
println(s"Number of years: $years")
println(s"Number of tournaments: $tournaments")
}
def startForecast(): Unit = {
import spark.implicits._
if (new File(modelFile).exists()) {
println("Skipping forecasting. Model exists.")
return
}
val inputDs = spark.read.parquet(outputFile).as[InputRecord]
println("Starting data forecasting")
val model = RandomForest.start(DataForecast.prepData(inputDs))
RandomForest.save(model, modelFile)
}
def startScoring(): Unit = {
if (!new File(modelFile).exists()) {
println("Skipping scoring. Model does not exist.")
return
}
val model = RandomForest.load(modelFile)
// ToDo: Improve collection of new records
// Should predict winner?
val record1 = RandomForestRecord(1.0,
"Grass",
32,
"C",
12,
"N",
"R",
175,
"AUS",
30.5,
12,
1222,
"R16")
// Should predict loser?
val record2 = RandomForestRecord(1.0,
"Hard",
32,
"C",
120,
"N",
"R",
150,
"POR",
35.5,
300,
10,
"R32")
RandomForest.score(model, Array(record1, record2))
}
}
|
necosta/forecast-x | src/main/scala/pt/necosta/forecastx/record/DataAnalysisRecords.scala | <reponame>necosta/forecast-x
package pt.necosta.forecastx.record
case class GamesCount(tourneyId: String,
tourneyName: String,
tourneyCount: BigInt)
case class SurfaceDistribution(surface: String, percentage: Double)
case class HandDistribution(winnerHand: String,
loserHand: String,
percentage: Double)
|
xuwei-k/scalaprops | scalaz/src/test/scala/scalaprops/IdTest.scala | <reponame>xuwei-k/scalaprops
package scalaprops
import scalaz.Id.Id
import scalaz.std.anyVal._
import ScalapropsScalaz._
object IdTest extends Scalaprops {
val test = Properties.list(
scalazlaws.traverse1.all[Id],
scalazlaws.monad.all[Id],
scalazlaws.bindRec.all[Id],
scalazlaws.zip.all[Id],
scalazlaws.align.all[Id],
scalazlaws.comonad.all[Id]
)
}
|
xuwei-k/scalaprops | scalaz/src/test/scala/scalaprops/FreeTTest.scala | <reponame>xuwei-k/scalaprops
package scalaprops
import scalaz._
import scalaz.Id.Id
import scalaz.std.AllInstances._
import ScalapropsScalaz._
object FreeTTest extends Scalaprops {
import FreeTest._
implicit def freeTEqual[S[_]: Functor: Eq1, M[_]: BindRec: Applicative: Eq1, A: Equal]: Equal[FreeT[S, M, A]] =
new Equal[FreeT[S, M, A]] {
def equal(a: FreeT[S, M, A], b: FreeT[S, M, A]) = {
implicit val s = Eq1[S].eq1(freeTEqual[S, M, A])
Eq1[M].eq1[S[FreeT[S, M, A]] \/ A].equal(a.resume, b.resume)
}
}
val isoIList = {
type B = Byte
type F[A] = IList[A]
type X = FreeT[F, Id, B]
type Y = Free[F, B]
scalazlaws.iso.all[X, Y](FreeT.isoFree[F].unlift[B])
}
val isoMaybe = {
type B = Byte
type F[A] = Maybe[A]
type X = FreeT[F, Id, B]
type Y = Free[F, B]
scalazlaws.iso.all[X, Y](FreeT.isoFree[F].unlift[B])
}
val isoTree = {
type B = Byte
type F[A] = Tree[A]
type X = FreeT[F, Id, B]
type Y = Free[F, B]
scalazlaws.iso.all[X, Y](FreeT.isoFree[F].unlift[B])
}
val isoDisjunction = {
type B = Byte
type F[A] = Boolean \/ A
type X = FreeT[F, Id, B]
type Y = Free[F, B]
scalazlaws.iso.all[X, Y](FreeT.isoFree[F].unlift[B])
}
val kleisliMaybe_Maybe = {
type G[A] = Kleisli[Maybe, Byte, A]
type F[A] = FreeT[G, Maybe, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.monadPlus.all[F]
)
}
val maybe_kleisliMaybe = {
type G[A] = Kleisli[Maybe, Byte, A]
type F[A] = FreeT[Maybe, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.monadPlus.all[F]
)
}
val f1Maybe = {
type G[A] = Byte => A
type F[A] = FreeT[G, Maybe, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.monadPlus.all[F]
)
}
val maybeF1 = {
type G[A] = Byte => A
type F[A] = FreeT[Maybe, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.monad.all[F]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.applyComposition)) =>
Param.maxSize(2) andThen Param.minSuccessful(10)
}
val maybeMaybe = {
type F[A] = FreeT[Maybe, Maybe, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadPlus.all[F]
)
}
val maybeIList = {
type F[A] = FreeT[Maybe, IList, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadPlus.all[F]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.bindRecTailrecBindConsistency)) =>
Param.maxSize(20) andThen Param.minSuccessful(10)
}
val iListMaybe = {
type F[A] = FreeT[IList, Maybe, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadPlus.all[F]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.bindRecTailrecBindConsistency)) =>
Param.maxSize(20) andThen Param.minSuccessful(10)
}
val iListIList = {
type F[A] = FreeT[IList, IList, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadPlus.all[F]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.bindRecTailrecBindConsistency)) =>
Param.maxSize(20) andThen Param.minSuccessful(10)
}
val disjunctionDisjunction = {
type E = Byte
type G[A] = E \/ A
type H[A] = Boolean \/ A
type F[A] = FreeT[H, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadError.all[F, E]
)
}
val maybeDisjunction = {
type E = Byte
type G[A] = E \/ A
type F[A] = FreeT[Maybe, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadError.all[F, E]
)
}
val iListDisjunction = {
type E = Byte
type G[A] = E \/ A
type F[A] = FreeT[IList, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadError.all[F, E]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.bindRecTailrecBindConsistency)) =>
Param.maxSize(20) andThen Param.minSuccessful(10)
}
val freeMaybe_Disjunction = {
type E = Byte
type G[A] = E \/ A
type H[A] = Free[Maybe, A]
type F[A] = FreeT[H, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadError.all[F, E]
)
}
val freeIList_Disjunction = {
type E = Byte
type G[A] = E \/ A
type H[A] = Free[IList, A]
type F[A] = FreeT[H, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadError.all[F, E]
)
}
val freeDisjunction_Disjunction = {
type E = Byte
type G[A] = E \/ A
type H[A] = Free[G, A]
type F[A] = FreeT[H, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.traverse.all[F],
scalazlaws.monadError.all[F, E]
)
}
val idState = {
type S = Byte
type G[A] = State[S, A]
type F[A] = FreeT[Id, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.monadState.all[F, S]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.applyComposition)) =>
Param.maxSize(2) andThen Param.minSuccessful(10)
}
val idStateMaybe = {
type S = Byte
type G[A] = StateT[S, Maybe, A]
type F[A] = FreeT[Id, G, A]
Properties.list(
// TODO diverging implicit expansion for type scalaprops.Gen[Int => F[Int]]
// scalazlaws.bindRec.laws[F],
scalazlaws.monadState.all[F, S]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.applyComposition)) =>
Param.maxSize(2) andThen Param.minSuccessful(10)
}
val maybeState = {
type S = Byte
type G[A] = State[S, A]
type F[A] = FreeT[Maybe, G, A]
Properties.list(
scalazlaws.bindRec.laws[F],
scalazlaws.monadState.all[F, S]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.applyComposition)) =>
Param.maxSize(2) andThen Param.minSuccessful(10)
}
val maybeStateIList = {
type S = Byte
type G[A] = StateT[S, IList, A]
type F[A] = FreeT[Maybe, G, A]
Properties.list(
scalazlaws.monadState.all[F, S]
)
}.andThenParamPF { case Or.R(Or.L(ScalazLaw.applyComposition)) =>
Param.maxSize(2) andThen Param.minSuccessful(10)
}
val iListStateIList = {
val laws = Set(ScalazLaw.bindAssociativity, ScalazLaw.applyComposition)
type S = Byte
type G[A] = StateT[S, IList, A]
type F[A] = FreeT[IList, G, A]
Properties
.list(
scalazlaws.monadState.all[F, S]
)
.andThenParam(Param.maxSize(3))
.andThenParamPF {
case Or.R(Or.L(law)) if laws(law) =>
Param.maxSize(2).andThen(Param.minSuccessful(10))
}
}
val monadTransMaybe = scalazlaws.monadTrans.all[({ type l[a[_], b] = FreeT[Maybe, a, b] })#l]
val monadTransIList = scalazlaws.monadTrans.all[({ type l[a[_], b] = FreeT[IList, a, b] })#l]
}
|
xuwei-k/scalaprops | scalaprops/native/src/main/scala/scalaprops/ScalapropsRunner.scala | <gh_stars>10-100
package scalaprops
import sbt.testing._
import scala.collection.mutable.ArrayBuffer
object ScalapropsRunner {
/** call from sbt plugin
* [[https://github.com/scalaprops/sbt-scalaprops/blob/v0.2.5/src/main/scala/scalaprops/ScalapropsPlugin.scala#L66]]
*/
def testFieldNames(clazz: Class[_]): Array[String] =
Scalaprops.testFieldNames(clazz)
private[scalaprops] def getTestObject(
fingerprint: Fingerprint,
testClassName: String,
testClassLoader: ClassLoader
): Scalaprops = {
???
}
private[scalaprops] def findTests(
fingerprint: Fingerprint,
testClassName: String,
testClassLoader: ClassLoader,
only: List[String],
logger: Logger
): Properties[_] = {
???
}
}
final class ScalapropsRunner(
override val args: Array[String],
override val remoteArgs: Array[String],
testClassLoader: ClassLoader
) extends Runner {
private[this] val results = ArrayBuffer.empty[TestResult]
private[this] val arguments = Arguments.parse(args.toList)
private[this] val taskdef2task: TaskDef => sbt.testing.Task = { taskdef =>
new ScalapropsTaskImpl(taskdef, testClassLoader, args, arguments, results, TestStatus())
}
override def tasks(taskDefs: Array[TaskDef]) = taskDefs.map(taskdef2task)
override def done() = {
val result = TestResult.formatResults(results, arguments.showDuration)
println(result)
result
}
}
|
xuwei-k/scalaprops | scalaz/src/test/scala/scalaprops/GenTest.scala | <filename>scalaz/src/test/scala/scalaprops/GenTest.scala
package scalaprops
import scala.util.Random
import scalaz._
import scalaz.std.anyVal._
import scalaz.std.tuple._
import ScalapropsScalaz._
object GenTest extends Scalaprops {
implicit def genGen[A](implicit A: Gen[A]): Gen[Gen[A]] = {
val values = Gen[List[A]].sample(size = 100, seed = Random.nextLong())
Gen.oneOf(
Gen.value(A),
List(
values.map(x => Gen.value(Gen.value(x))),
List.fill(100)(Random.nextInt(Int.MaxValue - 1) + 1).map(x => Gen.value(A.resize(x))),
List
.fill(100)(Random.nextInt(Int.MaxValue - 1) + 1)
.map(x =>
Gen.value(Gen.gen { (i, r) =>
val (r0, a) = A.f(i, r)
(r0.reseed(x), a)
})
)
).flatten: _*
)
}
implicit def genEqual[A](implicit A: Equal[A]): Equal[Gen[A]] =
Equal.equal { (x, y) =>
Iterator.fill(100)((Random.nextInt(), Random.nextLong())).forall { case (size, seed) =>
val r = Rand.standard(seed)
Equal[(Rand, A)].equal(x.f(size, r), y.f(size, r))
}
}
val testLaw =
Properties.list(
scalazlaws.monad.all[Gen],
scalazlaws.bindRec.all[Gen],
scalazlaws.equal.all[Gen[Int]]
)
val `test Gen.elements` = {
val N = 5
Property
.forAllG(
Gen.sequenceNList(10000, Gen[Rand]),
Gen.sequenceNList(N, Gen[Int])
) { (rs, xs) =>
val g = Gen.elements(xs.head, xs.tail: _*)
val r = rs.map(r => g.f(Int.MaxValue, r)._2)
(r.toSet == xs.toSet) && (xs.toSet.size == N)
}
.toProperties((), Param.rand(Rand.fromSeed()))
}
val `test Gen.sequenceNList` = {
val min = 5
val max = 30
val a = -500
val b = 20000
Property.forAllG(
Gen.choose(min, max).flatMap { size => Gen.sequenceNList(size, Gen.choose(a, b)).map(size -> _) }
) { case (size, values) =>
(values.length == size) && (min <= size && size <= max) && values.forall { x => a <= x && x <= b }
}
}
val `test Gen.frequencey` =
Property.forAllG(
Gen.sequenceNList(
100,
Gen.frequency(
1 -> Gen.value(true),
5 -> Gen.value(false)
)
)
) { list =>
val (t, f) = list.partition(identity)
(t.size < f.size) && t.nonEmpty
}
val testMaybeGen = Property.forAllG(
Gen[Int],
Gen.choose(500, 10000),
Gen[Int]
) { (size, listSize, seed) =>
val values = Gen[Maybe[Int]].samples(size = size, listSize = listSize, seed = seed)
val just = values.count(_.isJust)
(values.size == listSize) && (just > (listSize / 2)) && (just < listSize)
}
val choose = Property.forAll { (a: Int, b: Int, size: Int, seed: Long) =>
val x = Gen.choose(a, b).sample(size = size, seed = seed)
val max = math.max(a, b)
val min = math.min(a, b)
(min <= x) && (x <= max)
}
val listOfN_1 = Property.forAll { (size0: Byte, seed: Long) =>
val size = math.abs(size0.toInt)
val result = Gen.listOfN(size, Gen[Unit]).map(_.size).sample(seed = seed)
result <= size
}
val listOfN_2 = Property.forAll { seed: Long =>
val size = 3
Gen.listOfN(size, Gen[Unit]).map(_.size).samples(seed = seed, listSize = 100).distinct.size == (size + 1)
}
val arrayOfN = Property.forAll { (size0: Byte, seed: Long) =>
val size = math.abs(size0.toInt)
val result = Gen.arrayOfN(size, Gen[Unit]).map(_.size).sample(seed = seed)
result <= size
}
val posLong = Property.forAllG(Gen.positiveLong) { _ > 0 }
val posInt = Property.forAllG(Gen.positiveInt) { _ > 0 }
val posShort = Property.forAllG(Gen.positiveShort) { _ > 0 }
val posByte = Property.forAllG(Gen.positiveByte) { _ > 0 }
val posFloat = Property.forAllG(Gen.positiveFloat) { _ > 0.0f }
val posDouble = Property.forAllG(Gen.positiveDouble) { _ > 0.0d }
val posFiniteFloat = Property.forAllG(Gen.positiveFiniteFloat) { f => f > 0.0f && !f.isInfinity }
val posFiniteDouble = Property.forAllG(Gen.positiveFiniteDouble) { d => d > 0.0d && !d.isInfinity }
val negLong = Property.forAllG(Gen.negativeLong) { _ < 0 }
val negInt = Property.forAllG(Gen.negativeInt) { _ < 0 }
val negShort = Property.forAllG(Gen.negativeShort) { _ < 0 }
val negByte = Property.forAllG(Gen.negativeByte) { _ < 0 }
val negFloat = Property.forAllG(Gen.negativeFloat) { _.compare(0.0f) < 0 }
val negDouble = Property.forAllG(Gen.negativeDouble) { _.compare(0.0d) < 0 }
val negFiniteFloat = Property.forAllG(Gen.negativeFiniteFloat) { f => f.compare(0.0f) < 0 && !f.isInfinity }
val negFiniteDouble = Property.forAllG(Gen.negativeFiniteDouble) { d => d.compare(0.0d) < 0 && !d.isInfinity }
val nonNegLong = Property.forAllG(Gen.nonNegativeLong) { 0 <= _ }
val nonNegInt = Property.forAllG(Gen.nonNegativeInt) { 0 <= _ }
val nonNegShort = Property.forAllG(Gen.nonNegativeShort) { 0 <= _ }
val nonNegByte = Property.forAllG(Gen.nonNegativeByte) { 0 <= _ }
val nonNegFloat = Property.forAllG(Gen.nonNegativeFloat) { f => f.compare(0.0f) >= 0 && !f.isNaN }
val nonNegDouble = Property.forAllG(Gen.nonNegativeDouble) { f => f.compare(0.0d) >= 0 && !f.isNaN }
val nonNegFiniteFloat = Property.forAllG(Gen.nonNegativeFiniteFloat) { f =>
f.compare(0.0f) >= 0 && !f.isInfinity && !f.isNaN
}
val nonNegFiniteDouble = Property.forAllG(Gen.nonNegativeFiniteDouble) { d =>
d.compare(0.0d) >= 0 && !d.isInfinity && !d.isNaN
}
val finiteFloat = Property.forAllG(Gen.genFiniteFloat) { f => !f.isInfinity && !f.isNaN }
val finiteDouble = Property.forAllG(Gen.genFiniteDouble) { d => !d.isInfinity && !d.isNaN }
val genFunction = {
def test1[A: Gen: Cogen](name: String) =
test[A, A](s"$name => $name")
def test[A: Gen: Cogen, B: Gen](name: String) =
Property.forAll { seed: Int =>
val size = 10
val as = Gen[A].infiniteStream(seed = seed).distinct.take(5).toList
val values = Gen[A => B].samples(listSize = size, seed = seed).map(as.map(_))
val set = values.toSet
val result = set.size == size
assert(result, s"$name ${set.size} $as $set $values")
result
}.toProperties(name)
Properties
.list(
test1[Long]("Long"),
test1[Int]("Int"),
test1[Byte]("Byte"),
test1[Short]("Short"),
test1[Either[Byte, Short]]("Either[Byte, Short]"),
test1[Long \/ Int]("""(Long \/ Int)"""),
test1[(Int, Byte)]("Tuple2[Int, Byte]"),
test1[Option[Int]]("Option[Int]"),
test1[Map[Int, Int]]("Map[Int, Int]").andThenParam(Param.maxSize(10) andThen Param.minSuccessful(5)),
test1[Int ==>> Int]("(Int ==>> Int)").andThenParam(Param.maxSize(10) andThen Param.minSuccessful(5)),
test1[IList[Int]]("IList[Int]").andThenParam(Param.maxSize(10)),
test1[Byte \&/ Byte]("""Byte \&/ Byte)"""),
test[Int, List[Int]]("Int => List[Int]"),
test[List[Int], Int]("List[Int] => Int").andThenParam(Param.maxSize(20)),
test[Option[Byte], Byte]("Option[Byte] => Byte"),
test[Byte, Option[Byte]]("Byte => Option[Byte]"),
test[Either[Byte, Boolean], Int]("Either[Byte, Boolean] => Int"),
test[Int, Map[Int, Boolean]]("Int => Map[Int, Boolean]").andThenParam(Param.minSuccessful(5))
)
.composeParam(Param.minSuccessful(20))
}
val functionGenTest = {
def permutations[A](xs: IList[A], n: Int): IList[IList[A]] =
if (xs.isEmpty) {
IList.empty
} else {
def f(ls: IList[A], rest: IList[A], n: Int): IList[IList[A]] =
if (n == 0) IList(ls) else rest.flatMap(v => f(v :: ls, rest, n - 1))
f(IList.empty, xs, n)
}
def combinations[A: Order, B](as: IList[A], bs: IList[B]): IList[A ==>> B] = {
val xs = permutations(bs, as.length)
IList.fill(xs.length)(as).zip(xs).map { case (keys, values) =>
keys.zip(values).toMap
}
}
val defaultSize = 10000
def test[A: Cogen: Order, B: Gen: Order](
domain: IList[A],
codomain: IList[B],
name: String,
streamSize: Int = defaultSize
) = {
import scalaz.std.stream._
val size = List.fill(domain.length)(codomain.length).product
Property.forAll { seed: Long =>
val x = IList
.fromFoldable(
Gen[A => B]
.infiniteStream(seed = seed)
.map { f => IMap.fromFoldable(domain.map(a => a -> f(a))) }
.take(streamSize)
.distinct
.take(size)
)
.sorted
assert(x.length == size, s"${x.length} != $size")
Equal[IList[A ==>> B]].equal(x, combinations(domain, codomain).sorted)
}.toProperties(name)
}
def test1[A: Cogen: Order: Gen](values: IList[A], name: String, streamSize: Int = defaultSize) =
test[A, A](values, values, s"($name) => ($name)", streamSize)
val orderingValues = IList[Ordering](Ordering.EQ, Ordering.GT, Ordering.LT)
Properties.list(
test1(IList(true, false), "Boolean"),
test1(orderingValues, "Ordering"),
test(
IList(true, false),
IList(Maybe.just(true), Maybe.just(false), Maybe.empty[Boolean]),
"Boolean => Maybe[Boolean]"
),
test(IList(true, false), orderingValues, "Boolean => Ordering"),
test(orderingValues, IList(true, false), "Ordering => Boolean"),
test(
IList(Maybe.just(true), Maybe.just(false), Maybe.empty[Boolean]),
IList(true, false),
"Maybe[Boolean] => Boolean"
),
test1(IList(Maybe.just(true), Maybe.just(false), Maybe.empty[Boolean]), "Maybe[Boolean]", 100000)
.andThenParam(Param.minSuccessful(3)),
test1(
IList(true, false).flatMap(a => IList(\/.right[Boolean, Boolean](a), \/.left[Boolean, Boolean](a))),
"""Boolean \/ Boolean""",
50000
).andThenParam(Param.minSuccessful(3))
)
}
}
|
xuwei-k/scalaprops | core/src/main/scala/scalaprops/internal/Tree.scala | <gh_stars>10-100
package scalaprops
package internal
sealed abstract class Tree[A] {
import Tree._
def rootLabel: A
def subForest: Stream[Tree[A]]
def zipper: TreeZipper[A] = TreeZipper(this, Stream.Empty, Stream.Empty, Stream.Empty)
def map[B](f: A => B): Tree[B] =
Node(f(rootLabel), subForest map (_ map f))
private def traverse[S, B](f: A => State[S, B]): State[S, Tree[B]] = {
def traverseStream[S, A, B](fa: Stream[A])(f: A => State[S, B]): State[S, Stream[B]] = {
val seed = State[S, Stream[B]](s => (s, Stream.empty[B]))
fa.foldRight(seed) { (x, ys) =>
for {
b <- f(x)
bs <- ys
} yield b #:: bs
}
}
subForest match {
case Stream.Empty =>
f(rootLabel).map(Leaf(_))
case xs =>
for {
h <- f(rootLabel)
t <- traverseStream(xs)(_.traverse(f))
} yield Node(h, t.toStream)
}
}
private[this] def traverseS[S, B](s: S)(f: A => State[S, B]): (S, Tree[B]) = {
val x = traverse(f).run(s)
(x._1, x._2)
}
def mapAccumL[S, B](z: S)(f: (S, A) => (S, B)): (S, Tree[B]) =
traverseS(z)(a =>
for {
s1 <- State.init[S]
(s2, b) = f(s1, a)
_ <- State.put(s2)
} yield b
)
private def draw: Stream[String] = {
def drawSubTrees(s: Stream[Tree[A]]): Stream[String] =
s match {
case Stream.Empty => Stream.Empty
case Stream(t) => "|" #:: shift("`- ", " ", t.draw)
case t #:: ts => "|" #:: shift("+- ", "| ", t.draw) append drawSubTrees(ts)
}
def shift(first: String, other: String, s: Stream[String]): Stream[String] =
(first #:: Stream.continually(other)).zip(s).map { case (a, b) =>
a + b
}
rootLabel.toString #:: drawSubTrees(subForest)
}
def drawTree: String =
draw.map(_ + "\n").mkString
}
object Tree {
object Node {
def apply[A](root: => A, forest: => Stream[Tree[A]]): Tree[A] = {
new Tree[A] {
private[this] val rootc = Lazy(root)
private[this] val forestc = Lazy(forest)
def rootLabel = rootc.value
def subForest = forestc.value
override def toString = "<tree>"
}
}
def unapply[A](t: Tree[A]): Option[(A, Stream[Tree[A]])] = Some((t.rootLabel, t.subForest))
}
object Leaf {
def apply[A](root: => A): Tree[A] = {
Node(root, Stream.empty)
}
def unapply[A](t: Tree[A]): Option[A] = {
t match {
case Node(root, Stream.Empty) =>
Some(root)
case _ =>
None
}
}
}
def unfoldForest[A, B](s: Stream[A])(f: A => (B, () => Stream[A])): Stream[Tree[B]] =
s.map(unfoldTree(_)(f))
def unfoldTree[A, B](v: A)(f: A => (B, () => Stream[A])): Tree[B] =
f(v) match {
case (a, bs) => Node(a, unfoldForest(bs.apply())(f))
}
private final case class State[S, A](run: S => (S, A)) {
def map[B](f: A => B): State[S, B] =
State(run.andThen { case (s, a) => (s, f(a)) })
def flatMap[B](f: A => State[S, B]): State[S, B] =
State[S, B] { s0 =>
val (s1, a) = run(s0)
f(a).run(s1)
}
}
private object State {
def init[S]: State[S, S] = State(s => (s, s))
def put[S](s: S): State[S, Unit] = State(_ => (s, ()))
}
}
|
xuwei-k/scalaprops | scalaprops/src/test/scala/scalaprops/ShrinkTest.scala | package scalaprops
object ShrinkTest extends Scalaprops {
def law[A](a: A)(implicit s: Shrink[A]): Boolean =
!s(a).contains(a)
val boolean = Property.forAll(law[Boolean] _)
val byte = Property.forAll(law[Byte] _)
val short = Property.forAll(law[Short] _)
val int = Property.forAll(law[Int] _)
val long = Property.forAll(law[Long] _)
val option = Property.forAll(law[Option[Byte]] _)
val either = Property.forAll(law[Either[Byte, Byte]] _)
val list = Property.forAll(law[List[Byte]] _)
val tuple2 = Property.forAll(law[(Byte, Byte)] _)
val tuple3 = Property.forAll(law[(Byte, Byte, Byte)] _)
val tuple4 = Property.forAll(law[(Byte, Byte, Byte, Byte)] _)
val map = Property.forAll(law[Map[Byte, Byte]] _)
val array = Property.forAll(law[Array[Byte]] _)
val bigInt = Property.forAll(law[BigInt] _)
val bigInteger = Property.forAll(law[java.math.BigInteger] _)
}
|
shibayu36/joda-time-fake-scala | src/main/scala/com/github/shibayu36/jodatimefake/FakeTimer.scala | <filename>src/main/scala/com/github/shibayu36/jodatimefake/FakeTimer.scala
package com.github.shibayu36.jodatimefake
import org.joda.time.{DateTime, DateTimeUtils}
import scala.util.DynamicVariable
import scala.concurrent.ExecutionContext
/** Provides utility methods to fake current time of org.joda.time.DateTime.
*
* ==Provided Methods==
* <ul>
* <li>fake</li>
* <li>fakeWithTimer</li>
* </ul>
* ==Basic Usage==
* {{{
* import com.github.shibayu36.jodatimefake.FakeTimer
* import org.joda.time.DateTime
*
* // fake by millis
* val result = FakeTimer.fake(1515974400000L) {
* println(DateTime.now.toString) // 2018-01-15T00:00:00.000Z
* "hoge"
* }
*
* // current time is restored after block
* println(DateTime.now.toString) // current time is printed
*
* // You can get the value returned from block
* println(result) // hoge
*
* // You can also pass DateTime instance
* FakeTimer.fake(new DateTime(2018, 2, 13, 14, 59)) {
*
* }
*
* // You can also pass ISODateTimeFormat
* FakeTimer.fake("2018-03-02T12:34:56+09:00") {
*
* }
*
* // If you use fakeWithTimer, a timer instance is passed to block.
* // You can advance time using tick() method.
* FakeTimer.fakeWithTimer(1515974400000L) { t =>
* println(DateTime.now.toString) // 2018-01-15T00:00:00.000Z
* t.tick(3000) // Advance time by 3000ms
* println(DateTime.now.toString) // 2018-01-15T00:00:03.000Z
* }
* }}}
*/
object FakeTimer {
/** Fakes DateTime.now only in passed block by specified timeMillis.
*
* Time will be restored after block.
*/
def fake[T](timeMillis: Long)(block: => T): T = {
val timer = new FakeTimer(timeMillis)
DynamicDateTimeUtils.setCurrentMillisProvider(new FakeTimerMillisProvider(timer))
try {
block
} finally {
DynamicDateTimeUtils.setCurrentMillisSystem()
}
}
/** Fakes DateTime.now by specified DateTime object. */
def fake[T](t: DateTime)(block: => T): T =
fake(t.getMillis)(block)
/** Fakes DateTime.now by specified ISODateTimeFormat string
*
* e.g. TimeFaker.fake("2018-03-01T12:34:56") { }
*/
def fake[T](t: String)(block: => T): T =
fake(DateTime.parse(t).getMillis)(block)
/** Fakes DateTime.now by specified timeMillis.
*
* This method passes FakeTimer instance to block,
* so you can advance time by tick method.
*
* {{{
* FakeTimer.fakeWithTimer(1515974400000L) { t =>
* t.tick(3000) // Advance time by 3000ms
* }
* }}}
*/
def fakeWithTimer[T](timeMillis: Long)(block: FakeTimer => T): T = {
val timer = new FakeTimer(timeMillis)
DynamicDateTimeUtils.setCurrentMillisProvider(new FakeTimerMillisProvider(timer))
try {
block(timer)
} finally {
DynamicDateTimeUtils.setCurrentMillisSystem()
}
}
/** DateTime object version of fakeWithTimer */
def fakeWithTimer[T](t: DateTime)(block: FakeTimer => T): T =
fakeWithTimer(t.getMillis)(block)
/** ISODateTimeFormat string version of fakeWithTimer */
def fakeWithTimer[T](t: String)(block: FakeTimer => T): T =
fakeWithTimer(DateTime.parse(t).getMillis)(block)
}
/** FakeTimer class to advance time in fakeWithTimer */
class FakeTimer(private[this] var currentMillis: Long) {
/** Advance time by millis */
def tick(millis: Long): Unit = {
currentMillis = currentMillis + millis
}
private[jodatimefake] def getMillis(): Long = currentMillis
}
private[jodatimefake] class FakeTimerMillisProvider(timer: FakeTimer) extends DateTimeUtils.MillisProvider {
def getMillis(): Long = timer.getMillis()
}
private[jodatimefake] object SystemMillisProvider extends DateTimeUtils.MillisProvider {
def getMillis(): Long = System.currentTimeMillis
}
private[jodatimefake] object DynamicDateTimeUtils {
def setCurrentMillisSystem() = {
install()
DynamicMillisProvider.set(SystemMillisProvider)
}
def setCurrentMillisProvider(millisProvider: DateTimeUtils.MillisProvider) = {
install()
DynamicMillisProvider.set(millisProvider)
}
private def install() = DateTimeUtils.setCurrentMillisProvider(DynamicMillisProvider)
}
private[jodatimefake] object DynamicMillisProvider extends DateTimeUtils.MillisProvider {
private val local = new DynamicVariable[DateTimeUtils.MillisProvider](SystemMillisProvider)
def get = local.value
def set(millisProvider: DateTimeUtils.MillisProvider) = local.value_=(millisProvider)
override def getMillis(): Long = local.value.getMillis
}
object Implicits {
implicit class RichExecutionContext(ec: ExecutionContext) {
def withFakeTimer: ExecutionContext = new ExecutionContext {
override def execute(task: Runnable): Unit = {
val copyValue = DynamicMillisProvider.get
ec.execute(new Runnable {
override def run = {
DynamicMillisProvider.set(copyValue)
task.run
}
})
}
override def reportFailure(cause: Throwable): Unit = ec.reportFailure(cause)
}
}
}
|
greven77/PlaySlickTest | app/utils/UserPayloadWrapper.scala | package utils
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
case class UserPayloadWrapper(
id: Option[Long] = None,
username: String,
fullname: String,
email: String,
token: Option[String] = None
)
object UserPayloadWrapper {
implicit val userReads: Reads[UserPayloadWrapper] = (
(JsPath \ "id").readNullable[Long] and
(JsPath \ "username").read[String] and
(JsPath \ "fullname").read[String] and
(JsPath \ "email").read[String](email) and
(JsPath \ "token").readNullable[String]
)(UserPayloadWrapper.apply _)
}
|
greven77/PlaySlickTest | app/models/QuestionThread.scala | package models
import play.api.libs.json._
case class QuestionThread(question: Option[Question], tags: Seq[Tag],
answers: Seq[(Answer, User, Int, Int)])
object QuestionThread {
implicit val answerUserWrites = new Writes[(Answer, User, Int, Int)] {
def writes(answerUser: (Answer, User, Int, Int)) = {
val answer = answerUser._1
val answerAuthor = answerUser._2
val voteSum = answerUser._3
val loggedUserVote = answerUser._4
Json.obj(
"id" -> answer.id,
"content" -> answer.content,
"created_at" -> answer.created_at,
"updated_at" -> answer.updated_at,
"created_by" -> answerAuthor.username,
"votes" -> voteSum,
"loggedUserVote" -> loggedUserVote
)
}
}
implicit val writes = Json.writes[QuestionThread]
}
|
greven77/PlaySlickTest | app/models/FavouriteQuestion.scala | <filename>app/models/FavouriteQuestion.scala
package models
import play.api.libs.json.Json
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
case class FavouriteQuestion(question_id: Long, user_id: Long)
object FavouriteQuestion {
implicit val format = Json.format[FavouriteQuestion]
}
class FavouriteQuestionTable(tag: SlickTag)
extends Table[FavouriteQuestion](tag, "FavouriteQuestions") {
def question_id = column[Long]("question_id")
def user_id = column[Long]("user_id")
def pk = primaryKey("favouritequestion_pk", (question_id, user_id))
def * = (question_id, user_id) <> ((FavouriteQuestion.apply _).tupled, FavouriteQuestion.unapply)
}
|
greven77/PlaySlickTest | app/dao/BaseDao.scala | package dao
import scala.concurrent.Future
trait BaseDao[T] {
// def add(o: T): Future[T]
// def update(o: T): Future[Unit]
// def findAll(): Future[Seq[T]]
def remove(id: Long): Future[Int]
def findById(id: Long): Future[Option[T]]
}
|
greven77/PlaySlickTest | app/utils/QuestionFavouriteWrapper.scala | <reponame>greven77/PlaySlickTest
package utils
import models.Question
import play.api.libs.json._
case class QuestionFavouriteWrapper(question: Question, favouriteCount: Int,
answerCount: Int,
current_user_favourited: Option[Boolean] = Some(false))
object QuestionFavouriteWrapper {
implicit val answerVoteWrites = Json.writes[QuestionFavouriteWrapper]
}
|
greven77/PlaySlickTest | app/utils/AnswerVoteWrapper.scala | <gh_stars>0
package utils
import models.Answer
import play.api.libs.json._
case class AnswerVoteWrapper(answer: Answer, voteCount: Int, current_user_vote: Int)
object AnswerVoteWrapper {
implicit val answerVoteWrites = Json.writes[AnswerVoteWrapper]
}
|
greven77/PlaySlickTest | app/controllers/TagController.scala | package controllers
import dao.TagDao
import models.Tag
import play.api.libs.json.{Json, JsError}
import play.api.mvc.{Action, Controller}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class TagController(tagDao: TagDao, auth: SecuredAuthenticator) extends Controller {
def index = Action.async { request =>
tagDao.findAll().map { tags =>
Ok(Json.toJson(tags))
}
}
def create = auth.JWTAuthentication.async(parse.json) { request =>
val tagResult = request.body.validate[Tag]
tagResult.fold(
valid = { t =>
val tag = tagDao.add(t)
tag.map(t => Created(Json.toJson(t))).recoverWith {
case _ => Future { InternalServerError}
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def destroy(id: Long) = auth.JWTAuthentication.async { request =>
tagDao.remove(id).map(tag => Ok(s"Tag with id: ${id} removed")).recoverWith {
case _ => Future { NotFound }
}
}
}
|
greven77/PlaySlickTest | app/utils/CustomColumnTypes.scala | <filename>app/utils/CustomColumnTypes.scala
package utils
import java.sql.Timestamp
import org.joda.time.DateTime
import org.joda.time.DateTimeZone.UTC
import slick.driver.MySQLDriver.api._
object CustomColumnTypes {
implicit val jodaDateTimeType =
MappedColumnType.base[DateTime, Timestamp](
dt => new Timestamp(dt.getMillis),
ts => new DateTime(ts.getTime, UTC)
)
}
|
greven77/PlaySlickTest | app/models/TagsQuestions.scala | <reponame>greven77/PlaySlickTest<gh_stars>0
package models
import play.api.libs.json.Json
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
case class TagsQuestions(tag_id: Long, question_id: Long)
object TagsQuestions {
implicit val format = Json.format[TagsQuestions]
}
class TagsQuestionsTable(tag: SlickTag) extends Table[TagsQuestions](tag, "TagsQuestions") {
def tag_id = column[Long]("tag_id")
def question_id = column[Long]("question_id")
def pk = primaryKey("tag_question_pk", (tag_id, question_id))
def * = (tag_id, question_id) <> ((TagsQuestions.apply _).tupled, TagsQuestions.unapply)
}
|
greven77/PlaySlickTest | build.sbt | name := """ReactiveOverflow"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.7"
libraryDependencies ++= Seq(
cache,
ws,
evolutions,
"org.scalatest" % "scalatest_2.11" % "3.0.1" % "test",
"mysql" % "mysql-connector-java" % "6.0.3",
"com.typesafe.play" %% "play-slick" % "2.0.2",
"com.typesafe.play" %% "play-slick-evolutions" % "2.0.2",
"de.svenkubiak" % "jBCrypt" % "0.4.1",
"com.softwaremill.macwire" %% "macros" % "2.2.2" % "provided",
"com.softwaremill.macwire" %% "util" % "2.2.2",
"com.softwaremill.macwire" %% "proxy" % "2.2.2",
"com.jason-goodwin" % "authentikat-jwt_2.11" % "0.4.5",
"com.github.tototoshi" %% "slick-joda-mapper" % "2.2.0"
)
resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"
resolvers += DefaultMavenRepository
routesGenerator := InjectedRoutesGenerator
|
greven77/PlaySlickTest | app/utils/SortingPaginationWrapper.scala | package utils
import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class SortingPaginationWrapper(sort_by: String,
page: Int = 1,
resultsPerPage: Int = 25, direction: String = "desc")
object SortingPaginationWrapper {
val sortingParameters = List("date", "votes", "title")
val directionParameters = List("asc", "desc")
val sortValidate = Reads.StringReads.
filter(ValidationError("invalid parameter"))(sortByValidator(_))
val sortValidateAnswers = Reads.StringReads.
filter(ValidationError("invalid parameter"))(sortByValidator)
val directionValidate = Reads.StringReads.
filter(ValidationError("invalid parameter"))(directionValidator(_))
implicit val sortingPaginationReads: Reads[SortingPaginationWrapper] = (
((JsPath \ "sort_by").read[String](sortValidate) orElse Reads.pure("date")) and
((JsPath \ "page").read[Int] orElse Reads.pure(1)) and
((JsPath \ "resultsPerPage").read[Int] orElse Reads.pure(25)) and
((JsPath \ "direction").read[String](directionValidate) orElse Reads.pure("desc"))
)(SortingPaginationWrapper.apply _)
val sortingPaginationAnswerReads: Reads[SortingPaginationWrapper] = (
((JsPath \ "sort_by").read[String](sortValidateAnswers) orElse Reads.pure("created_at")) and
((JsPath \ "page").read[Int] orElse Reads.pure(1)) and
((JsPath \ "resultsPerPage").read[Int] orElse Reads.pure(25)) and
((JsPath \ "direction").read[String](directionValidate) orElse Reads.pure("desc"))
)(SortingPaginationWrapper.apply _)
def sortByValidator(criteria: String) =
List("date", "votecount", "title", "answercount", "favouritecount")
.contains(criteria.toLowerCase)
def sortByValidatorAnswers(criteria: String) =
List("created_at", "updated_at", "voteCount").contains(criteria.toLowerCase)
def directionValidator(param: String) =
List("asc", "desc").contains(param.toLowerCase)
def getPage(pageNum: Int, resultsPerPage: Int) =
resultsPerPage * (pageNum - 1)
}
|
greven77/PlaySlickTest | app/AppApplicationLoader.scala | import com.softwaremill.macwire._
import controllers._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.i18n._
import play.api.routing.Router
import router.Routes
import modules._
import scala.concurrent.ExecutionContext
/**
* Application loader that wires up the application dependencies using Macwire
*/
class AppApplicationLoader extends ApplicationLoader {
def load(context: Context): Application = {
(new BuiltInComponentsFromContext(context) with AppComponents).application
}
}
trait AppComponents extends BuiltInComponents
with I18nComponents
with DatabaseModule
with ControllerModule
with DaoModule
{
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
lazy val assets: Assets = wire[Assets]
lazy val router: Router = {
lazy val prefix = "/"
wire[Routes]
}
lazy val mainController = wire[MainController]
// def userDao: UserDao
}
|
greven77/PlaySlickTest | app/modules/ControllerModule.scala | <filename>app/modules/ControllerModule.scala
package modules
import com.softwaremill.macwire._
import controllers._
import dao._
import scala.concurrent.ExecutionContext
trait ControllerModule {
// Dependencies
implicit def ec: ExecutionContext
def userDao: UserDao
def tagDao: TagDao
def questionDao: QuestionDao
def answerDao: AnswerDao
// Controllers
lazy val authController = wire[AuthController]
lazy val tagController = wire[TagController]
lazy val questionController = wire[QuestionController]
lazy val answerController = wire[AnswerController]
lazy val securedAuthenticator = wire[SecuredAuthenticator]
lazy val loginChecker = wire[LoginChecker]
}
|
greven77/PlaySlickTest | app/utils/TokenAuthentication.scala | <reponame>greven77/PlaySlickTest
package utils
import java.util.Date
import scala.util.Random
import authentikat.jwt.{JsonWebToken, JwtClaimsSet, JwtHeader}
class JwtUtility {
val JwtSecretKey = "secretKey"
val JwtSecretAlgo = "HS256"
def createToken(payload: String): String = {
val randomString = payload + (new Date).toString + Random.nextInt(1000).toString
val header = JwtHeader(JwtSecretAlgo)
val claimsSet = JwtClaimsSet(randomString.slice(0, 255))
JsonWebToken(header, claimsSet, JwtSecretKey)
}
def isValidToken(jwtToken: String): Boolean =
JsonWebToken.validate(jwtToken, JwtSecretKey)
def decodePayload(jwtToken: String): Option[String] =
jwtToken match {
case JsonWebToken(header, claimsSet, signature) => Option(claimsSet.asJsonString)
case _ => None
}
}
object JwtUtility extends JwtUtility
|
greven77/PlaySlickTest | app/models/Vote.scala | package models
import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
case class Vote(answer_id: Option[Long], user_id: Option[Long], value: Int)
object Vote {
val userValidate = Reads.IntReads.
filter(ValidationError("Value must be -1 or 1"))(validValue(_))
implicit val voteReads: Reads[Vote] = (
(JsPath \ "answer_id").readNullable[Long] and
(JsPath \ "user_id").readNullable[Long] and
(JsPath \ "value").read[Int](userValidate)
)(Vote.apply _)
implicit val voteWrites = Json.writes[Vote]
def validValue(value: Int) = value == -1 || value == 1
}
class VoteTable(tag: SlickTag) extends Table[Vote](tag, "votes") {
def answer_id = column[Option[Long]]("answer_id")
def user_id = column[Option[Long]]("user_id")
def value = column[Int]("vote_value")
def pk = primaryKey("vote_pk", (answer_id, user_id))
def * = (answer_id, user_id, value) <> ((Vote.apply _).tupled, Vote.unapply)
}
|
greven77/PlaySlickTest | app/controllers/AnswerController.scala | package controllers
import dao.AnswerDao
import models.{Answer, Vote}
import java.sql._
import play.api.libs.json._
import play.api.mvc.{Action, Controller}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Failure
import scala.util.Success
class AnswerController(answerDao: AnswerDao, auth: SecuredAuthenticator) extends Controller {
def create(qId: Long) = auth.JWTAuthentication.async(parse.json) { request =>
val answerResult = request.body.validate[Answer]
answerResult.fold(
valid = { a =>
val answerWithQuestionId = a.copy(question_id = qId, user_id = request.user.id)
val answer = answerDao.add(answerWithQuestionId)
answer.map(a => Created(Json.toJson(a))).recoverWith {
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def update(qId: Long, id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
val answerResult = request.body.validate[Answer]
answerResult.fold(
valid = { a =>
val answerWithIds = a.copy(question_id = qId, id = Some(id))
answerDao.update(answerWithIds).
map(updatedAnswer => Accepted(Json.toJson(updatedAnswer))).
recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound("invalid id or id not provided") }
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def destroy(qId: Long, id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
answerDao.remove(id).map(answer => NoContent).
recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound("invalid id or id not provided")}
case _ => Future { InternalServerError }
}
}
def vote(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
val voteResult = request.body.validate[Vote]
voteResult.fold(
valid = { v =>
val vote = v.copy(answer_id = Some(id), user_id = request.user.id)
answerDao.vote(v).
map(voteUpdatedAnswer => Accepted(Json.toJson(voteUpdatedAnswer))).
recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound("invalid id or id not provided")}
case oe: Exception =>
Future { BadRequest(s"${oe.getClass().getName()} ${oe.getMessage()}")}
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
}
|
greven77/PlaySlickTest | app/dao/TagDao.scala | <reponame>greven77/PlaySlickTest
package dao
import models.{Tag => TagM, TagTable}
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext
class TagDao(dbConfig: DatabaseConfig[JdbcProfile]) extends BaseDao[TagM] {
import dbConfig.driver.api._
val db = dbConfig.db
val tags = TableQuery[TagTable]
def add(tag: TagM): Future[TagM] = {
db.run(tagsReturningRow += tag)
}
def findAll(): Future[Seq[TagM]] = db.run(tags.result)
override def findById(id: Long): Future[Option[TagM]] =
db.run(tags.filter(_.id === id).result.headOption)
def findByName(name: String): Future[Option[TagM]] =
db.run(tags.filter(_.text === name).result.headOption)
override def remove(id: Long): Future[Int] =
db.run(tags.filter(_.id === id).delete)
private def tagsReturningRow =
tags returning tags.map(_.id) into { (b, id) =>
b.copy(id = id)
}
}
|
greven77/PlaySlickTest | app/dao/QuestionDao.scala | package dao
import java.sql.SQLIntegrityConstraintViolationException
import javax.naming.AuthenticationException
import models._
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import com.github.tototoshi.slick.MySQLJodaSupport._
import org.joda.time.DateTime
import slick.lifted.ColumnOrdered
import utils.{QuestionFavouriteWrapper, SortingPaginationWrapper, TaggedQuestion}
import utils.SortingPaginationWrapper.getPage
class QuestionDao(val dbConfig: DatabaseConfig[JdbcProfile], answerDao: AnswerDao) extends BaseDao[Question] {
import dbConfig.driver.api._
val db = dbConfig.db
val questions = TableQuery[QuestionTable]
val favouriteQuestions = TableQuery[FavouriteQuestionTable]
val answers = TableQuery[AnswerTable]
val users = TableQuery[UserTable]
val votes = TableQuery[VoteTable]
val tags = TableQuery[TagTable]
val questionTags = TableQuery[TagsQuestionsTable]
type AnswersQuery = Query[AnswerTable, Answer, Seq]
def add(question: Question): Future[Option[Question]] =
db.run(addQuestionQuery(question))
def addWithTags(tq: TaggedQuestion): Future[TaggedQuestion] = {
for {
question <- db.run(addQuestionQuery(tq.question))
tagsQuestions <- Future { getTagsQuestions(question.get.id, tq.tagIds) }
tags <- db.run(insertTagsQuery(tagsQuestions))
taggedQuestionIds <- db.run(getTagsIdsQuery(question.get.id))
} yield TaggedQuestion(question.get, Some(taggedQuestionIds))
}
def update(tq: TaggedQuestion, user: User): Future[Option[TaggedQuestion]] = {
val id = tq.question.id
val title = tq.question.title
val content = tq.question.content
val updateQuestion = (questions.filter(_.id === id).map(q =>
(q.title, q.content)
).update((title, content))
andThen
findByIdQuery(id.get)
)
val updatedTagsQuery = insertOrUpdateTagsQuery(getTagsQuestions(tq.question.id, tq.tagIds))
for {
question <- db.run(updateQuestion)
tags <- db.run(updatedTagsQuery) if !tq.tagIds.isEmpty
taggedQuestionIds <- db.run(getTagsIdsQuery(tq.question.id))
} yield Option(TaggedQuestion(question.get, Some(taggedQuestionIds)))
}
def setCorrectAnswer(qId: Long, correct_answer_id: Option[Long]): Future[Option[Question]] = {
val filteringQuery = questions.filter(_.id === qId).
join(answers).on {
case (question, answer) => answer.question_id === question.id &&
answer.id === correct_answer_id
}.result
val validationQuery = filteringQuery.flatMap { q =>
q match {
case q +: Nil => DBIO.successful(q)
case _ => DBIO.failed(
new SQLIntegrityConstraintViolationException("Answer does not belong to question")
)
}
}
val query = questions.filter(_.id === qId).map(_.correct_answer)
db.run(validationQuery
andThen query.update(correct_answer_id)
andThen findByIdQuery(qId))
}
def markFavourite(favouriteQuestion: FavouriteQuestion): Future[FavouriteQuestion] = {
val markFavourite =
favouriteQuestions += favouriteQuestion
val question_id = favouriteQuestion.question_id
val user_id = favouriteQuestion.user_id
val retrieveFavourite = findFQ(question_id, user_id).result.head
db.run(markFavourite andThen retrieveFavourite)
}
def removeFavourite(fq: FavouriteQuestion): Future[Int] =
db.run(findFQ(fq.question_id, fq.user_id).delete)
def findAll(params: SortingPaginationWrapper): Future[Seq[QuestionFavouriteWrapper]] = {
sortedAndPaginatedQuestions(params, questions)
}
override def findById(id: Long): Future[Option[Question]] =
db.run(findByIdQuery(id))
def findByTag(tag: String, params: SortingPaginationWrapper):
Future[Seq[QuestionFavouriteWrapper]] = {
val query = questions.
join(questionTags).on(_.id === _.question_id).
join(tags.filter(_.text === tag)).on {
case ((question, questionTag), tag) =>
questionTag.tag_id === tag.id
}.map {
case ((question, _), _) =>
question
}
sortedAndPaginatedQuestions(params,query)
}
def findAndRetrieveThread(id: Long, params: SortingPaginationWrapper,
logged_user: Option[User] = None): Future[QuestionThread] = {
val logged_user_id: Option[Long] = logged_user match {
case Some(user) => user.id
case _ => None
}
for {
question <- db.run(findByIdQuery(id))
tags <- db.run(getTagsQuery(id))
answers <- db.run(answerDao.answerUsersQuery(id,logged_user_id, params))
} yield QuestionThread(question, tags, answers)
}
override def remove(id: Long): Future[Int] =
db.run(questions.filter(_.id === id).delete)
private def sortedAndPaginatedQuestions(params: SortingPaginationWrapper,
questions: Query[models.QuestionTable,models.Question,Seq]) = {
val qr = for {
(question, sub) <- questions
.joinLeft(answers).on { case (question, answer) =>
question.id === answer.question_id
}.joinLeft(favouriteQuestions).on { case ((question, _), favouriteQuestion) =>
question.id === favouriteQuestion.question_id
}.groupBy { case ((question, _), _) =>
question
}
} yield (question, sub.map(_._1._2).map(_.map(_.id)).countDistinct, sub.map(_._2)
.map(_.map(_.user_id)).countDistinct)
val sortPaginateQr = qr.sortBy(sorter(_, params)).
drop(getPage(params.page, params.resultsPerPage)).
take(params.resultsPerPage)
val action = sortPaginateQr.result.
map { case q =>
q.map { case ((question, answer, fq)) =>
QuestionFavouriteWrapper(question, fq, answer)
}
}
db.run(action)
}
private def sorter (qfcount: (QuestionTable, Rep[Int], Rep[Int]), settings: SortingPaginationWrapper) =
{
val (question, answerCount, favouriteCount) = qfcount
settings match {
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "title" && direction == "desc" => question.title.desc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "title" && direction == "asc" => question.title.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "date" && direction == "desc" => question.created_at.desc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "date" && direction == "asc" => question.created_at.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "favouritecount" && direction == "asc" => favouriteCount.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "favouritecount" && direction == "desc" => favouriteCount.desc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "answercount" && direction == "asc" => answerCount.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "answercount" && direction == "desc" => answerCount.desc
case SortingPaginationWrapper(_,_,_,_) => question.created_at.desc
}
}
private def insertTagsQuery(updatedTags: Seq[TagsQuestions]) =
questionTags ++= updatedTags
private def insertOrUpdateTagsQuery(updatedTags: Seq[TagsQuestions]) =
DBIO.sequence(updatedTags.map(questionTags.insertOrUpdate(_)))
private def getTagsQuestions(question_id: Option[Long], tagIds: Option[Seq[Long]]): Seq[TagsQuestions] = {
val qId = question_id.get
tagIds.getOrElse(Seq[Long]()).map(TagsQuestions(_, qId))
}
private def getTagsIdsQuery(id: Option[Long]) = {
questionTags.filter(_.question_id === id).map(_.tag_id).result
}
private def getTagsQuery(id: Long) =
questionTags.filter(_.question_id === id).
join(tags).on(_.tag_id === _.id).
map { case (questionTag, tag) => tag }.
result
private def findByIdQuery(id: Long) =
questions.filter(_.id === id).result.headOption
private def findByTitleQuery(title: String) =
questions.filter(_.title === title).result.headOption
private def findFQ(id: Long, user_id: Long) =
favouriteQuestions.filter(fq => fq.question_id === id && fq.user_id === user_id)
private def addQuestionQuery(question: Question) =
(questionsReturningRow += question) andThen (findByTitleQuery(question.title))
private def questionsReturningRow =
questions returning questions.map(_.id) into { (q, id) =>
q.copy(id = Some(id))
}
}
|
greven77/PlaySlickTest | app/controllers/QuestionController.scala | <reponame>greven77/PlaySlickTest
package controllers
import dao.QuestionDao
import javax.naming.AuthenticationException
import models.{Question, FavouriteQuestion}
import java.sql._
import play.api.libs.json._
import play.api.mvc.{Action, Controller}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Failure
import scala.util.Success
import utils.{TaggedQuestion, SortingPaginationWrapper}
import utils.SortingPaginationWrapper.sortingPaginationAnswerReads
class QuestionController(questionDao: QuestionDao, auth: SecuredAuthenticator,
sessionInfo: LoginChecker) extends Controller {
def index = Action.async(parse.json) { request =>
val result =
request.body.validate[SortingPaginationWrapper]
result.fold(
valid = { r =>
questionDao.findAll(r).map { questions =>
Ok(Json.toJson(questions))
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def tagged(tag: String) = Action.async(parse.json) { request =>
val result = request.body.validate[SortingPaginationWrapper]
result.fold (
valid = { params =>
questionDao.findByTag(tag, params).map { questions =>
Ok(Json.toJson(questions))
}.recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound }
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def show(id: Long) = Action.async { request =>
questionDao.findById(id).map(q => Ok(Json.toJson(q))).recoverWith {
case _ => Future { NotFound }
}.recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound }
case _ => Future { InternalServerError }
}
}
def showThread(id: Long) = sessionInfo.LoginInfo.async(parse.json) { request =>
val result = request.body.validate[SortingPaginationWrapper](sortingPaginationAnswerReads)
result.fold(
valid = { spw =>
questionDao.findAndRetrieveThread(id, spw, request.user).map(qt => Ok(Json.toJson(qt))).
recoverWith {
case e: SQLIntegrityConstraintViolationException => Future { NotFound }
case _ => Future { InternalServerError}
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def create = auth.JWTAuthentication.async(parse.json) { request =>
val questionResult = request.body.validate[TaggedQuestion]
questionResult.fold(
valid = {tq =>
val questionWithUser = tq.question.copy(created_by = request.user.id)
val taggedQuestionWithUser: TaggedQuestion = tq.copy(question = questionWithUser)
val question = questionDao.addWithTags(taggedQuestionWithUser)
question.map(q => Created(Json.toJson(q))).recoverWith {
case e: Exception => Future { BadRequest(s"create: ${e.getClass().getName()}")}
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def update(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
val questionResult = request.body.validate[TaggedQuestion]
val user = request.user
questionResult.fold(
valid = { tq =>
val questionWithId = tq.question.copy(id = Some(id))
val taggedQuestion = tq.copy(question = questionWithId)
questionDao.update(taggedQuestion, user).
map(updatedQuestion => Accepted(Json.toJson(updatedQuestion))).
recoverWith {
case authEx: AuthenticationException => Future { Unauthorized }
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound("invalid id or id not provided or title is not unique")}
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def setCorrectAnswer(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
(request.body \ "answer_id").validate[Long] match {
case a: JsSuccess[Long] => {
val answer_id = Some(a.get)
questionDao.setCorrectAnswer(id, answer_id).
map(updatedQuestion => Accepted(Json.toJson(updatedQuestion))).
recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { NotFound(s"${e.getMessage()}")}
case _ => Future { InternalServerError }
}
}
case e: JsError => Future { BadRequest }
}
}
def destroy(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
questionDao.remove(id).map(question => NoContent).
recoverWith {
case _ => Future { NotFound }
}
}
def markFavourite(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
val fqResult = request.body.validate[FavouriteQuestion]
fqResult.fold(
valid = { fq =>
val fqWithId = fq.copy(question_id = id)
val favouritedQuestion = questionDao.markFavourite(fqWithId)
favouritedQuestion.map(f => Created(Json.toJson(f))).recoverWith {
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def removeFavourite(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
val fqResult = request.body.validate[FavouriteQuestion]
fqResult.fold(
valid = { fq =>
val fqWithId = fq.copy(question_id = id)
questionDao.removeFavourite(fqWithId).map(favourite =>
favourite match {
case 1 => Ok(s"Tag with id: ${fq.question_id} removed")
case 0 => NotFound
}).recoverWith {
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
private def getQuestion(id: Long): Future[Option[Question]] = {
val questionQuery = questionDao.findById(id)
questionQuery.map(question =>
question
).recoverWith {
case _ => Future {None}
}
}
}
|
greven77/PlaySlickTest | app/dao/AnswerDao.scala | package dao
import models.{Answer, AnswerTable, Vote, VoteTable, UserTable}
import utils.{AnswerVoteWrapper, SortingPaginationWrapper}
import utils.SortingPaginationWrapper.getPage
import scala.concurrent.Future
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import com.github.tototoshi.slick.MySQLJodaSupport._
class AnswerDao(val dbConfig: DatabaseConfig[JdbcProfile]) {
import dbConfig.driver.api._
val db = dbConfig.db
val answers = TableQuery[AnswerTable]
val votes = TableQuery[VoteTable]
val users = TableQuery[UserTable]
def add(answer: Answer): Future[Answer] =
db.run(answersReturningRow += answer)
def update(a2: Answer): Future[Answer] = {
db.run(answers.filter(_.id === a2.id).map(_.content).update(a2.content) andThen
answers.filter(_.id === a2.id).result.head
)
}
def findById(id: Long): Future[Option[Answer]] =
db.run(answers.filter(_.id === id).result.headOption)
def remove(id: Long): Future[Int] =
db.run(answers.filter(_.id === id).delete)
// upvote and downvote methods here
def vote(user_vote: Vote): Future[AnswerVoteWrapper] = {
val answerWithVotes = answers.filter(_.id === user_vote.answer_id).
join(votes).on {
case (answer, vote) => answer.id === vote.answer_id
}.result.
map { rows =>
val answer = rows.filter { case (answer, vote) => answer.id == Some(vote.answer_id) }.
map { case (answer, vote) => answer}.head
rows.groupBy { case (answer, vote) => answer.id.get }.
mapValues { values =>
val voteSum = values.map { case (answer, vote) => vote.value}.sum
val userVoteValue = values.
filter { case (answer, vote) => vote.user_id == user_vote.user_id }
.map { case (answer, vote) => vote.value}.headOption
AnswerVoteWrapper(answer, voteSum, userVoteValue.getOrElse(0))
}.head._2
}
db.run(votes.insertOrUpdate(user_vote) andThen answerWithVotes)
}
def answerUsersQuery(question_id: Long, logged_user_id: Option[Long],
params: SortingPaginationWrapper) = {
val qr = answers.filter(_.question_id === question_id).
joinLeft(votes).on(_.id === _.answer_id).
join(users).on { case ((answer, vote), user) => answer.user_id === user.id }.
groupBy { case ((answer, vote), user) => (answer, user) }.
map { case ((answer, user), votes) => (answer, user,
votes.map {
case ((answer, vote), user) =>
vote.map(_.value)
}.sum.getOrElse(0),
votes.map {
case ((answer, vote), user) =>
vote.filter(_.user_id === logged_user_id).map(_.value)
}.sum.getOrElse(0)
)
}
val sortPaginateQr = qr.sortBy(answerSorter(_, params)).
drop(getPage(params.page, params.resultsPerPage)).
take(params.resultsPerPage)
sortPaginateQr.result
}
private def answerSorter (qfcount: (AnswerTable, UserTable, Rep[Int], Rep[Int]),
settings: SortingPaginationWrapper) =
{
val (answer, user, voteCount, userVoteValue) = qfcount
settings match {
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "created_at" && direction == "desc" => answer.created_at.desc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "created_at" && direction == "asc" => answer.created_at.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "updated_at" && direction == "desc" => answer.updated_at.desc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "updated_at" && direction == "asc" => answer.updated_at.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "votecount" && direction == "asc" => voteCount.asc
case SortingPaginationWrapper(sort_by,_,_,direction)
if sort_by == "votecount" && direction == "desc" => voteCount.desc
case SortingPaginationWrapper(_,_,_,_) => answer.created_at.desc
}
}
private def answersReturningRow =
answers returning answers.map(_.id) into { (a, id) =>
a.copy(id = Some(id))
}
}
|
greven77/PlaySlickTest | app/controllers/AuthController.scala | package controllers
import dao.UserDao
import java.sql.SQLIntegrityConstraintViolationException
import play.api.libs.json.JsError
import play.api.data.Form
import models.{User, UserLogin}
import models.User._
import play.api.libs.json.Json
import play.api.mvc.Action
import play.api.mvc.Controller
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class AuthController(userDao: UserDao, auth: SecuredAuthenticator) extends Controller {
def register = Action.async(parse.json) { request =>
val userResult = request.body.validate[User]
userResult.fold(
valid = { u =>
import play.api.Logger
Logger.debug(s"user: ${u}")
val user = userDao.add(u)
user.map(u => Created(Json.toJson(u))).recoverWith {
case e: SQLIntegrityConstraintViolationException =>
Future { BadRequest(s"${e.getMessage}") }
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def login = Action.async(parse.json) { request =>
val userResult = request.body.validate[UserLogin]
userResult.fold(
valid = { u =>
val loggedUser = userDao.login(u)
loggedUser.map(lu =>
lu match {
case u: Some[User] => Ok(Json.toJson(u))
case None => Unauthorized
}
).recoverWith {
case _ => Future { InternalServerError }
}
},
invalid = { errors =>
Future.successful(
BadRequest(JsError.toJson(errors))
)
}
)
}
def logout = auth.JWTAuthentication.async { request =>
userDao.logout(request.user).map(u => u match {
case 0 => NotFound
case _ => Ok("User logged out successfully")
}
).recoverWith {
case _ => Future { NotFound }
}
}
def show(id: Long) = auth.JWTAuthentication.async(parse.json) { request =>
userDao.findById(id).map(u => Ok(Json.toJson(u)(profileWrites))).recoverWith {
case _ => Future { NotFound }
}
}
}
|
greven77/PlaySlickTest | app/modules/DaoModule.scala | <filename>app/modules/DaoModule.scala<gh_stars>0
package modules
import com.softwaremill.macwire._
import dao._
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
trait DaoModule {
def dbConfig: DatabaseConfig[JdbcProfile]
lazy val userDao = wire[UserDao]
lazy val tagDao = wire[TagDao]
lazy val questionDao = wire[QuestionDao]
lazy val answerDao = wire[AnswerDao]
}
|
greven77/PlaySlickTest | app/models/Question.scala | <gh_stars>0
package models
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.json.Reads
import play.api.libs.functional.syntax._
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
import com.github.tototoshi.slick.MySQLJodaSupport._
case class Question(id: Option[Long], title: String, content: String,
created_by: Option[Long], correct_answer: Option[Long],
created_at: Option[DateTime] = None, updated_at: Option[DateTime] = None)
object Question {
// implicit val format = Json.format[Question]
implicit val questionReads: Reads[Question] = (
(JsPath \ "id").readNullable[Long] and
(JsPath \ "title").read[String] and
(JsPath \ "content").read[String] and
(JsPath \ "created_by").readNullable[Long] and
(JsPath \ "correct_answer").readNullable[Long] and
(JsPath \ "created_at").readNullable[DateTime] and
(JsPath \ "updated_at").readNullable[DateTime]
)(Question.apply _)
implicit val questionWrites = Json.writes[Question]
}
class QuestionTable(tag: SlickTag) extends Table[Question](tag, "questions") {
// import utils.CustomColumnTypes._
// val dtf = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss")
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def title = column[String]("title")
def content = column[String]("content")
def created_by = column[Option[Long]]("created_by")
def correct_answer = column[Option[Long]]("correct_answer")
def created_at = column[Option[DateTime]]("created_at", O.Default(Some(new DateTime)))
def updated_at = column[Option[DateTime]]("updated_at")
def * = (id.?, title, content, created_by, correct_answer,
created_at, updated_at) <> ((Question.apply _).tupled, Question.unapply)
def creator = foreignKey("creator_fk", created_by, TableQuery[UserTable])(_.id.get)
def answer = foreignKey("answer_fk", correct_answer, TableQuery[AnswerTable])(_.id)
}
|
greven77/PlaySlickTest | app/controllers/LoginChecker.scala | package controllers
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits._
import play.api.Logger
import play.api.mvc._
import play.api.libs.json._
import scala.util.{Success, Failure}
import utils.JwtUtility
import models.User
import utils.UserPayloadWrapper
import dao.UserDao
case class OptionalUserRequest[A](val user: Option[User], val request: Request[A])
extends WrappedRequest[A](request)
class LoginChecker(userDao: UserDao) extends Controller {
object LoginInfo extends ActionBuilder[OptionalUserRequest] {
def invokeBlock[A](request: Request[A],
block: (OptionalUserRequest[A]) => Future[Result]): Future[Result] = {
val jwtToken = request.headers.get("token").getOrElse("")
if (JwtUtility.isValidToken(jwtToken)) {
JwtUtility.decodePayload(jwtToken).fold {
block(OptionalUserRequest(None, request))
} { payload =>
val userCredentials = Json.parse(payload).validate[UserPayloadWrapper].get
val userF: Future[Option[User]] = userDao.findByEmail(userCredentials.email).
map(identity)
.recoverWith {
case _ => Future { None }
}
userF.flatMap(usr => block(OptionalUserRequest(usr, request)))
}
} else {
block(OptionalUserRequest(None, request))
}
}
}
}
|
greven77/PlaySlickTest | app/models/User.scala | package models
import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
case class User(
id: Option[Long] = None,
username: String,
fullname: String,
email: String,
password: String,
token: Option[String] = None
)
object User {
implicit val userReads: Reads[User] = (
(JsPath \ "id").readNullable[Long] and
(JsPath \ "username").read[String] and
(JsPath \ "fullname").read[String] and
(JsPath \ "email").read[String](email) and
(JsPath \ "password" ).read[String] and
(JsPath \ "token").readNullable[String]
)(User.apply _)
implicit val userWrites = new Writes[User] {
def writes(user: User) = Json.obj(
"id" -> user.id,
"username" -> user.username,
"fullname" -> user.fullname,
"email" -> user.email,
"token" -> user.token
)
}
val profileWrites = new Writes[Option[User]] {
def writes(user: Option[User] ) = Json.obj(
"id" -> user.map(_.id),
"username" -> user.map(_.username),
"fullname" -> user.map(_.fullname),
"email" -> user.map(_.email)
)
}
}
class UserTable(tag: SlickTag) extends Table[User](tag, "users") {
def id = column[Option[Long]]("id", O.PrimaryKey, O.AutoInc)
def username = column[String]("username")
def fullname = column[String]("fullname")
def email = column[String]("email")
def password = column[String]("password")
def token = column[Option[String]]("token")
def * = (id, username, fullname, email, password, token) <> ((User.apply _).tupled, User.unapply _)
}
case class UserLogin(username: String, password: String)
object UserLogin {
implicit val userLoginReads = Json.reads[UserLogin]
}
|
greven77/PlaySlickTest | app/dao/UserDao.scala | package dao
import models.{User, UserTable, UserLogin}
import org.mindrot.jbcrypt.BCrypt
import play.api.libs.json.Json
import scala.concurrent.Future
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import utils.JwtUtility
class UserDao(dbConfig: DatabaseConfig[JdbcProfile]) extends BaseDao[User] {
import dbConfig.driver.api._
val db = dbConfig.db
val users = TableQuery[UserTable]
def add(user: User): Future[User] = {
val secureUser = user.copy(password = <PASSWORD>(user.password))
val payload = Json.toJson(secureUser).toString
val secureUserWithToken = secureUser.copy(token = Some(JwtUtility.createToken(payload)))
db.run(usersReturningRow += secureUserWithToken)
}
def update(u2: User) = Future[Unit] {
db.run(
users.filter(_.id === u2.id).map(u =>
(u.username, u.fullname, u.email, u.password))
.update((u2.username, u2.fullname, u2.email, u2.password))
)
}
def findAll(): Future[Seq[User]] = db.run(users.result)
override def findById(id: Long): Future[Option[User]] =
db.run(users.filter(_.id === id).result.headOption)
def findByEmail(email: String): Future[Option[User]] =
db.run(users.filter(_.email === email).result.headOption)
def findByUsername(username: String): Future[Option[User]] =
db.run(users.filter(_.username === username).result.headOption)
def findByToken(token: String): Future[Option[User]] =
db.run(users.filter(_.token === token).result.headOption)
override def remove(id: Long): Future[Int] = db.run(users.filter(_.id === id).delete)
def login(userLogin: UserLogin): Future[Option[User]] = {
val maybeUser = findByUsername(userLogin.username)
val userF: Future[Option[User]] = maybeUser.map(u =>
u match {
case user: Some[User] if (BCrypt.checkpw(userLogin.password, user.get.password)) => {
updateToken(user)
}
case None => None
}
)
for {
user <- userF
u <- findByUsername(user.get.username)
} yield u
}
def logout(user: User): Future[Int] = {
db.run(
users.filter(_.id === user.id).map(_.token).
update(None)
)
}
private def updateToken(u: Option[User]) = {
val user = u.get
val payload = Json.toJson(user).toString
val token = Some(JwtUtility.createToken(payload))
db.run(
users.filter(_.id === user.id).map(_.token).
update(token)
)
u
}
private def hashPW(password: String) =
BCrypt.hashpw(password, BCrypt.gensalt())
private def usersReturningRow =
users returning users.map(_.id) into { (b, id) =>
b.copy(id = id)
}
}
|
greven77/PlaySlickTest | app/models/Answer.scala | <gh_stars>0
package models
import org.joda.time.DateTime
import play.api.libs.json.Json
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
case class Answer(id: Option[Long], content: String,
user_id: Option[Long] , question_id: Long,
created_at: Option[DateTime] = None, updated_at: Option[DateTime] = None
)
object Answer {
implicit val format = Json.format[Answer]
}
class AnswerTable(tag: SlickTag) extends Table[Answer](tag, "answers") {
import utils.CustomColumnTypes._
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def content = column[String]("content")
def user_id = column[Option[Long]]("user_id")
def question_id = column[Long]("question_id")
def created_at = column[Option[DateTime]]("created_at")
def updated_at = column[Option[DateTime]]("updated_at")
def * = (id.?, content, user_id, question_id,
created_at, updated_at) <> ((Answer.apply _).tupled, Answer.unapply)
def creator = foreignKey("creator_fk", user_id, TableQuery[UserTable])(_.id.get)
def question = foreignKey("parent_question_fk", question_id, TableQuery[QuestionTable])(_.id)
}
|
greven77/PlaySlickTest | app/modules/DatabaseModule.scala | <gh_stars>0
package modules
import play.api.db.evolutions.EvolutionsComponents
import play.api.db.evolutions.{DynamicEvolutions, EvolutionsComponents}
import play.api.db.slick.evolutions.SlickEvolutionsComponents
import slick.driver.JdbcProfile
import play.api.db.slick.{DbName, SlickComponents}
trait DatabaseModule extends SlickComponents
with EvolutionsComponents
with SlickEvolutionsComponents
{
lazy val dbConfig = api.dbConfig[JdbcProfile](DbName("default"))
override lazy val dynamicEvolutions = new DynamicEvolutions
def onStart() = {
applicationEvolutions.start()
}
onStart()
}
|
greven77/PlaySlickTest | app/models/Tag.scala | package models
import play.api.data.validation.ValidationError
import play.api.libs.json.Json
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
case class Tag(id: Option[Long], text: String)
object Tag {
val textValidate = Reads.StringReads.
filter(ValidationError("Must not contain spaces or non-alphanumeric characters or other character than underscores or hyphens"))(validText(_))
implicit val tagReads: Reads[Tag] = (
(JsPath \ "id").readNullable[Long] and
(JsPath \ "text").read[String](textValidate keepAnd minLength[String](3) keepAnd maxLength[String](20))
)(Tag.apply _)
implicit val tagWrites = Json.writes[Tag]
def validText(text: String) = text.matches("^[a-zA-Z0-9_-]*$")
}
class TagTable(tag: SlickTag) extends Table[Tag](tag, "tags") {
def id = column[Option[Long]]("id", O.PrimaryKey, O.AutoInc)
def text = column[String]("text")
def * = (id, text) <> ((Tag.apply _).tupled, Tag.unapply _)
}
|
greven77/PlaySlickTest | app/utils/TaggedQuestionReader.scala | <gh_stars>0
package utils
import models.Question
case class TaggedQuestion(question: Question, tagIds: Option[Seq[Long]] = None)
object TaggedQuestion {
import play.api.libs.json._
import play.api.libs.json.Reads
import play.api.libs.functional.syntax._
implicit val taggedQuestionReads: Reads[TaggedQuestion] = (
(JsPath \ "question").read[Question] and
(JsPath \ "tagIds").readNullable[Seq[Long]]
)(TaggedQuestion.apply _)
implicit val taggedQuestionWrites: Writes[TaggedQuestion] = Json.writes[TaggedQuestion]
}
|
greven77/PlaySlickTest | app/controllers/SecuredAuthenticator.scala | package controllers
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits._
import play.api.Logger
import play.api.mvc._
import play.api.libs.json._
import scala.util.{Success, Failure}
import utils.JwtUtility
import models.User
import utils.UserPayloadWrapper
import dao.{AnswerDao, QuestionDao, UserDao}
case class UserRequest[A](val user: User, val request: Request[A])
extends WrappedRequest[A](request)
class SecuredAuthenticator(userDao: UserDao, questionDao: QuestionDao,
answerDao: AnswerDao) extends Controller {
object JWTAuthentication extends ActionBuilder[UserRequest] {
def invokeBlock[A](request: Request[A],
block: (UserRequest[A]) => Future[Result]): Future[Result] = {
val jwtToken = request.headers.get("token").getOrElse("")
if (JwtUtility.isValidToken(jwtToken)) {
JwtUtility.decodePayload(jwtToken).fold {
Future.successful(Unauthorized("Invalid credential 1"))
} { payload =>
//val userCredentials = Json.parse(payload).validate[UserPayloadWrapper].get
val userF: Future[Option[User]] = userDao.findByToken(jwtToken).
map(identity)
.recoverWith {
case _ => Future { None }
}
for {
user <- userF
isAccessGranted <- checkAuthorized(request.toString, user)
block <- decide(isAccessGranted, user, request, block)
} yield block
//userF.flatMap(usr => block(UserRequest(usr.get, request)))
}
} else {
Future.successful(Unauthorized("Invalid credential 2"))
}
}
def decide[A](isAccessGranted: Boolean, user: Option[User],
request: Request[A], block: (UserRequest[A]) => Future[Result]): Future[Result] =
if (isAccessGranted)
block(UserRequest(user.get, request))
else
Future.successful(Unauthorized)
def checkAuthorized(requestString: String, user: Option[User]): Future[Boolean] = {
val requestItems = requestString.split(" ")
val Array(verb, url) = requestItems
val reg = """(\/api\/[a-z]+)[\/]?(\d*).*?(\/([a-z]+)\/(\d+))?$""".r
val groupsList =
reg.findFirstMatchIn(url).get.subgroups.filter { group =>
group != null && group != ""
}
user match {
case Some(user) => groupsList match {
case (List(_, id)) =>
isAuthorized(requestItems, user, id.toLong)
case List(_, id, _, _, child_id) =>
isAuthorized(requestItems, user, id.toLong, child_id.toLong)
case _ => Future { true }
}
case _ => Future { false }
}
}
def isAuthorized(route: Array[String], user: User, parent_id: Long = -1,
child_id: Long = -1): Future[Boolean] = {
route match {
case Array("PUT", url) if url.matches("/api/questions/[0-9]+") =>
isQuestionOwner(user, parent_id)
case Array("PUT", url) if url.matches("/api/questions/[0-9]+/correctanswer") =>
isQuestionOwner(user, parent_id)
case Array("DELETE", url) if url.matches("/api/questions/[0-9]+") =>
isQuestionOwner(user, parent_id)
case Array("PUT",url) if url.matches("/api/questions/[0-9]+/answer/[0-9]+") =>
isAnswerOwner(user, parent_id)
case Array("DELETE",url) if url.matches("/api/questions/[0-9]+/answer/[0-9]+") =>
for {
answerOwner <- isAnswerOwner(user, child_id)
questionOwner <- isQuestionOwner(user, parent_id)
} yield answerOwner || questionOwner
case Array("POST", url) if url.matches("/api/answer/[0-9]+/vote") =>
isAnswerOwner(user, parent_id).map(!_)
case _ => Future { false }
}
}
def isQuestionOwner(user: User, id: Long): Future[Boolean] =
questionDao.findById(id).map(q => {
q.get.created_by == user.id}).recoverWith {
case _ => Future { false }
}
def isAnswerOwner(user: User, id: Long): Future[Boolean] =
answerDao.findById(id).map(a => a.get.user_id == user.id).recoverWith {
case _ => Future { false }
}
}
}
|
maet3608/zibble | src/quuux/zibble/gui/Zibble.scala | <gh_stars>0
package quuux.zibble.gui
//import au.com.quuux.utils.JErrorHandler
import javax.swing.JOptionPane.{showMessageDialog, ERROR_MESSAGE}
import javax.swing.UIManager.{setLookAndFeel, getSystemLookAndFeelClassName}
import javax.swing.JFrame.{EXIT_ON_CLOSE}
import java.awt.Toolkit.getDefaultToolkit
import javax.swing.{JOptionPane, JFrame}
import java.awt.event.{WindowAdapter, WindowEvent}
import java.awt.{EventQueue, Dimension}
import java.io.{FileWriter, File}
/**
* Graphical user interface for quuux.zibble.
* See ./doc/index.html for usage.
* @author <NAME>
*/
class Zibble extends JFrame {
// Thread.setDefaultUncaughtExceptionHandler(new JErrorHandler())
val VERSION = "0.1"
}
object Zibble {
def main(args:Array[String]) {
setLookAndFeel(getSystemLookAndFeelClassName)
new Zibble
}
} |
maet3608/zibble | src/quuux/zibble/ZParser.scala | <reponame>maet3608/zibble
package quuux.zibble
import java.io.File
import scala.io.Source
import scala.collection.JavaConversions.{mapAsScalaMap}
import javax.swing.filechooser.FileSystemView
import scala.util.parsing.combinator._
import ZParser._
/**
* Parses a project file.
* see ./doc/index.html for details and ./projects for examples.
* @author <NAME>
*/
class ZParser extends JavaTokenParsers {
/** variable definitions */
var varMap = Map[String,String]()++driveVariables++envVariables
/** regex for line comments */
val comment = """#.*$""".r
/** returns list of logical drive names and the drive letter as tuples ({name},letter) */
def driveVariables = {
val drive = """(.+) \((\w:)\)$""".r
val display = FileSystemView.getFileSystemView.getSystemDisplayName _
File.listRoots.map(display).collect{case drive(name,letters) => ("{"+name+"}",letters)}
}
/** returns list of environment variables as tuples ({name},value) */
def envVariables = mapAsScalaMap(System.getenv).map{ case (name,value) => ("{"+name+"}",value)}
/** replaces variable names in value by variable values */
def instantiate(value:String) = varMap.foldLeft(value){case (v,(n,l)) => v.replace(n,l)}.trim
/** Reads file content but removes comment sections before parsing */
def read(path:String) =
parseAll(projects, Source.fromFile(path).getLines().map(comment.replaceFirstIn(_,"\n")).mkString("\n"))
// grammar of a projects file
def projects = rep(variable)~>rep(project) ^^ (_.map(p => ZProject(p)))
def project = "PROJECT"~>rep(property)
def property = (NAME~"\\w+".r |
RUN~"(now)|(never)".r |
SIMULATE~"(off)|(on)".r |
FROM~value |
TO~value |
INCLUDE~value |
EXCLUDE~value |
COMPRESS~"[0-9]".r |
VERBOSE~"[01]".r) ^^ {case n~v => (n,v)}
def varname = """\{[^\}]+\}""".r
def variable = "VAR"~>varname~value ^^ {case n~v => varMap += n->v}
def value = """[^\n]+""".r ^^ instantiate
}
/**
* Defines constants for parser.
*/
object ZParser {
// property names
val NAME = "NAME"
val RUN = "RUN"
val FROM = "FROM"
val TO = "TO"
val INCLUDE = "INCLUDE"
val EXCLUDE = "EXCLUDE"
val SIMULATE = "SIMULATE"
val COMPRESS = "COMPRESS"
val VERBOSE = "VERBOSE"
// separator for values of a property
val SEP = ','
} |
maet3608/zibble | src/quuux/zibble/cmd/Zibble.scala | <reponame>maet3608/zibble
package quuux.zibble.cmd
import quuux.zibble._
import java.util.Date
/**
* Command line interface for quuux.zibble.
* See ./doc/index.html for usage.
* @author <NAME>
*/
object Zibble extends ZParser with ZLogger {
/** prints parsing errors */
def parseError(path:String, msg:String,next:Input) {
error("%s\n %s:\n%s at line %d column %d ".format(path,msg,next.pos.longString,next.pos.line,next.pos.column))
}
/** args is empty or path of a project file */
def main(args: Array[String]) {
ZLogger.open()
try {
val path = if(args.length>0) args(0) else "default.zpj"
output("ZIBBLE "+path)
output("DATE "+(new Date))
read(path) match {
case Success(result, next) => result.filter(_.isActive).foreach(_.run)
case Failure(msg, next) => parseError(path,msg,next)
case Error(msg, next) => parseError(path,msg,next)
}
output("FINISHED.")
}
catch { case e:Exception => error(e.getMessage) }
ZLogger.close()
}
}
|
maet3608/zibble | src/quuux/zibble/ZProject.scala | package quuux.zibble
import java.io.File
import util.matching.Regex
import ZParser._
/**
* A backup project.
* @param properties Map of properties (= name,value pairs) that describe project.
* see .doc/index.html for details
* @author <NAME>
*/
class ZProject(properties:Map[String,String]) extends ZLogger {
val (inPatterns,exPatterns) = (values(INCLUDE).map(toRegex), values(EXCLUDE).map(toRegex))
/** tests if the project is scheduled to be active */
val isActive = properties(RUN) == "now"
/** returns value of the property with the given name */
def value(name:String) = properties(name).trim
/** splits value of property with given name at separator and returns array of values */
def values(name:String) = value(name).split(SEP).map(_.trim)
/** tests if string is matched by at least on of the file patterns */
def test(string:String, patterns:Seq[Regex]) = patterns.exists(_.findFirstIn(string) != None)
/** tests if file name or dir is matched by includes or exclude patterns */
def testInEx(nameOrDir:String) = test(nameOrDir,inPatterns) && !test(nameOrDir,exPatterns)
/** tests if file name is matched by includes or exclude patterns */
def testName(file:File) = testInEx(file.getName)
/** tests if file dir is matched by includes or exclude patterns */
def testDir(file:File) = testInEx(file.getParent.replace('\\','/'))
/** replace wildcard symbols * and ? by their regex equivalents and disable '.' */
def convert(pattern:String) =
pattern.replace(".","\\.").replace('?','.').replace('@','?').replace("*",".*")
/** convert pattern to regular expression depending on name or dir matching */
def toRegex(pattern:String) =
if (pattern.startsWith("/")) convert(pattern).r else ("^"+convert(pattern)+"$").r
/** archives the file if it is matched by includes or exclude patterns */
def process(file:File, archives:Seq[ZArchive]) =
if (testName(file) && testDir(file))
try { output(file.getCanonicalPath, toConsole=value(VERBOSE)=="1");
archives.foreach(_.addFile(file)) }
catch { case e:Exception => error(e.getMessage) }
/** lists files in the given directory */
def dir(path:File) = path.listFiles match {
case null => Array[File]()
case list => list
}
/** recursively walks file tree */
def walker(path:File, archives:Seq[ZArchive]) {
dir(path).foreach(f => if (f.isDirectory) walker(f,archives) else process(f,archives))
}
/** run the project */
def run {
val mode = if (properties(SIMULATE) == "on") "SIMULATING" else "ARCHIVING"
output(mode+" "+value(NAME)+" -> "+value(TO))
val level = value(COMPRESS).toInt
val simulate = properties(SIMULATE) == "on"
val archives = values(TO).map(path => new ZArchive(path, level, simulate))
values(FROM).map(new File(_)).foreach(walker(_,archives))
archives.foreach(_.close())
}
override def toString =
properties.map{case (n,v) => " "+n+" "+v}.mkString("PROJECT\n","\n","\n")
}
/**
* Defines default values for properties.
*/
object ZProject {
/** default values */
val default =
Map(NAME -> "project",
RUN -> "now",
SIMULATE -> "off",
FROM -> ".",
TO -> "backup.zip",
INCLUDE -> "*",
EXCLUDE -> "",
COMPRESS -> "9",
VERBOSE -> "0"
)
/** Creates project from sequence of properties (= name,value pairs) */
def apply(properties:Seq[(String,String)]) = new ZProject(default ++ properties)
} |
maet3608/zibble | src/quuux/zibble/ZLogger.scala | package quuux.zibble
import java.io.{BufferedWriter, FileWriter}
/**
* A simple trait for logging that writes log messages to the console and a
* logging file.
* @author <NAME>
*/
trait ZLogger {
def output(msg:String, toConsole:Boolean=true, toFile:Boolean=true) {
ZLogger.output(msg, toConsole, toFile)
}
def error(msg:String) { output("ERROR: "+msg) }
def warning(msg:String) { output("WARNING: "+msg) }
}
object ZLogger {
private var logFile:BufferedWriter = null
def open() {
logFile = new BufferedWriter(new FileWriter("quuux.zibble.log"))
}
def output(msg:String, toConsole:Boolean=true, toFile:Boolean=true) {
if(toFile) { logFile.write(msg+"\n"); logFile.flush() }
if(toConsole) println(msg)
}
def close() {
if(logFile!=null) logFile.close()
}
} |
maet3608/zibble | src/quuux/zibble/ZArchive.scala | package quuux.zibble
import java.util.zip.{ZipEntry, ZipOutputStream}
import java.io._
/**
* A simple ZIP archive. Only zip but no unzip supported.
* Infos: http://blogs.sun.com/CoreJavaTechTips/entry/creating_zip_and_jar_files
* @param filename filepath of the zip file to be generated.
* @param level compression level [0-9].
* @param simulate true: nothing happens, false: archiving is active
* @author <NAME>
*/
class ZArchive(filename:String, level:Int=9, simulate:Boolean=false) {
val buf = new Array[Byte](4068)
val drive = """^([A-Za-z]:)?[/\\]""".r
val zos = if(!simulate) new ZipOutputStream(new FileOutputStream(filename)) else null
if(!simulate) {
zos.setLevel(level) // compression level
zos.setMethod(ZipOutputStream.DEFLATED) // this is default but just to be sure
}
/** adds a file to the archive (overwrites existing files). Stores file path if withPath==true */
def addFile(file:File, withPath:Boolean=true) {
if(simulate) return
val filepath = if(withPath) file.getCanonicalPath else file.getName
val fis = new FileInputStream(file)
zos.putNextEntry(new ZipEntry(drive.replaceFirstIn(filepath,"")))
var n = 0
while(n != -1) {
n = fis.read(buf)
if(n > 0) zos.write(buf,0,n)
}
fis.close()
zos.closeEntry()
zos.flush()
}
/** closes the archive */
def close() { if(!simulate) zos.close() }
}
|
lamusique/Scala.js-p5.js | src/main/scala/samples/P5SoundSampleApp.scala | package samples
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExportTopLevel, _}
import org.scalajs.dom
import org.scalajs.dom.document
import p5.js.modules.{FFT, Oscillator}
// This import decides which mode.
import p5.js.modes.instance.p5
@JSExportTopLevel("P5SoundSampleApp")
@JSExportAll
object P5SoundSampleApp {
// https://processing.github.io/p5.js-sound/examples/oscillatorMod_FM/
def main(args: js.Array[String]): Unit = {
println("Hello world p5.js!")
val sketchFn: js.Function1[p5, Unit] = (sketch: p5) => {
val carrier = Oscillator("sine")
val modulator = Oscillator("sawtooth")
val fft = FFT()
import sketch._
setup = () => {
createCanvas(800,400)
noFill()
// Start the audio context on a click/touch event
val myDiv = createDiv("click to start audio")
myDiv.style("color: white")
myDiv.position(100, 100)
// implicit conversion
// https://www.scala-js.org/doc/interoperability/types.html
val onFulfilled: js.Function1[Unit, Unit] = Unit => {
myDiv.remove()
()
}
userStartAudio().`then`[Unit](
onFulfilled)
carrier.amp(1)
carrier.freq(220)
carrier.start()
modulator.disconnect()
modulator.amp(1)
modulator.freq(4)
modulator.start()
carrier.freq(modulator.mult(200).add(100))
// switches
document.getElementById("start").addEventListener("click", (e: dom.Event) => {
carrier.start()
})
document.getElementById("stop").addEventListener("click", (e: dom.Event) => {
carrier.stop(0)
})
()
}
draw = () => {
background(30)
// map mouseY to moodulator freq between 0 and 20hz
val modFreq = map(mouseY, 0, height, 20, 0)
modulator.freq(modFreq)
// change the original amplitude of the sawOsc, before it's scaled.
// negative amp reverses the waveform, and sounds percussive
var modAmp = map(mouseX, 0, width, -1, 1)
modulator.amp(modAmp)
// analyze the waveform
val waveform = fft.waveform()
// draw the shape of the waveform
stroke(255)
strokeWeight(10)
beginShape()
for (i <- 0 until waveform.length) {
val x = map(i, 0, waveform.length, 0, width)
val y = map(waveform(i), -1, 1, -height/2, height/2)
vertex(x, y + height/2)
}
endShape()
}
}
// instantiate
val myp5 = p5(sketchFn)
println("the main ends.")
}
}
|
lamusique/Scala.js-p5.js | src/main/scala/p5/js/modules/package.scala | package p5.js.modules
//object Modules {
//
//}
//package p5.js.lib
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSGlobal, JSGlobalScope, JSName}
import scala.scalajs.js.|
@js.native
@JSGlobal("p5.Color")
class Color extends js.Object {
//@JSName("p5.Color")
//trait Color extends js.Object {
@JSName("_getRed")
def getRed(): Short = js.native
}
// https://github.com/processing/p5.js/blob/master/src/dom/dom.js
@js.native
@JSGlobal("p5.Element")
class Element protected () extends js.Object {
def this(elt: String, pInst: js.Any = "") = this()
var elt: js.Any = js.native
def parent(parent: String | js.Any): Element = js.native
def id(id: String): Element = js.native
def mousePressed(fxn: js.Function0[Any]): Element = js.native
def mouseWheel(fxn: js.Function0[Any]): Element = js.native
def mouseReleased(fxn: js.Function0[Any]): Element = js.native
def mouseClicked(fxn: js.Function0[Any]): Element = js.native
def mouseMoved(fxn: js.Function0[Any]): Element = js.native
def mouseOver(fxn: js.Function0[Any]): Element = js.native
def changed(fxn: js.Function0[Any]): Element = js.native
def input(fxn: js.Function0[Any]): Element = js.native
def mouseOut(fxn: js.Function0[Any]): Element = js.native
def touchStarted(fxn: js.Function0[Any]): Element = js.native
def touchMoved(fxn: js.Function0[Any]): Element = js.native
def touchEnded(fxn: js.Function0[Any]): Element = js.native
def dragOver(fxn: js.Function0[Any]): Element = js.native
def dragLeave(fxn: js.Function0[Any]): Element = js.native
def child(child: String | js.Any | Element = ???): Element = js.native
// https://p5js.org/reference/#/p5.Element/position
// https://www.scala-js.org/doc/interoperability/types.html
def position(x: js.UndefOr[Double] = js.undefined, y: js.UndefOr[Double] = js.undefined): js.Dynamic = js.native
def style(property: String, value: js.UndefOr[String | Double | Color] = js.undefined): String = js.native
def remove(): Unit = js.native
}
@js.native
@JSGlobal("p5.Graphics")
class Graphics extends Element {
}
@js.native
@JSGlobal("p5.Renderer")
class Renderer extends Element {
}
@js.native
@JSGlobal("p5.Image")
class Image extends js.Object {
def this(width: Double, height: Double, pInst: js.Any) = this()
var width: js.Any = js.native
var height: js.Any = js.native
def loadPixels(): Unit = js.native
def set(x: Double, y: Double, a: Double | js.Array[js.Any] | js.Any): Unit = js.native
def resize(width: Double, height: Double): Unit = js.native
def mask(srcImage: Image): Unit = js.native
def save(filename: String, extension: String): Unit = js.native
}
@js.native
@JSGlobal("p5.Table")
class Table protected () extends js.Object {
def this(rows: js.Array[js.Any] = ???) = this()
var columns: js.Any = js.native
var rows: js.Any = js.native
def addRow(row: TableRow = new TableRow): Unit = js.native
def removeRow(id: Double): Unit = js.native
def getRows(): js.Array[js.Any] = js.native
def findRows(value: String, column: Double | String): js.Array[js.Any] = js.native
def matchRows(regexp: String, column: String | Double = 1.0): js.Array[js.Any] = js.native
def getColumn(column: String | Double): js.Array[js.Any] = js.native
def clearRows(): Unit = js.native
def addColumn(title: String = ""): Unit = js.native
def getRowCount(): Double = js.native
def removeTokens(chars: String, column: String | Double = 1.0): Unit = js.native
def trim(column: String | Double): Unit = js.native
def removeColumn(column: String | Double): Unit = js.native
def set(column: String | Double, value: String | Double): Unit = js.native
def setNum(row: Double, column: String | Double, value: Double): Unit = js.native
def setString(row: Double, column: String | Double, value: String): Unit = js.native
def get(row: Double, column: String | Double): String | Double = js.native
def getNum(row: Double, column: String | Double): Double = js.native
def getString(row: Double, column: String | Double): String = js.native
def getObject(headerColumn: String): js.Dynamic = js.native
def getArray(): js.Array[js.Any] = js.native
}
@js.native
@JSGlobal("p5.TableRow")
class TableRow protected () extends js.Object {
def this(str: String = "", separator: String = "") = this()
def set(column: String | Double, value: String | Double): Unit = js.native
def setNum(column: String | Double, value: Double): Unit = js.native
def setString(column: String | Double, value: String): Unit = js.native
def get(column: String | Double): String | Double = js.native
def getNum(column: String | Double): Double = js.native
def getString(column: String | Double): String = js.native
}
@js.native
@JSGlobal("p5.Vector")
class Vector protected () extends js.Object {
def this(x: Double = 0.0, y: Double = 0.0, z: Double = 0.0) = this()
var x: js.Any = js.native
var y: js.Any = js.native
var z: js.Any = js.native
// def toString(): String = js.native
def set(x: Double | Vector | js.Array[js.Any] = ???, y: Double = 0.0, z: Double = 0.0): Unit = js.native
def copy(): Vector = js.native
def add(x: Double | Vector | js.Array[js.Any], y: Double = 0.0, z: Double = 0.0): Vector = js.native
def sub(x: Double | Vector | js.Array[js.Any], y: Double = 0.0, z: Double = 0.0): Vector = js.native
def mult(n: Double): Vector = js.native
def div(n: Double): Vector = js.native
def mag(): Double = js.native
def magSq(): Double = js.native
def dot(x: Double | Vector, y: Double = 0.0, z: Double = 0.0): Double = js.native
def cross(v: Vector): Vector = js.native
def dist(v: Vector): Double = js.native
def normalize(): Vector = js.native
def limit(max: Double): Vector = js.native
def setMag(len: Double): Vector = js.native
def heading(): Double = js.native
def rotate(angle: Double): Vector = js.native
def array(): js.Array[js.Any] = js.native
def equals(x: Double | Vector | js.Array[js.Any] = ???, y: Double = 0.0, z: Double = 0.0): Boolean = js.native
}
@js.native
@JSGlobal("p5.Vector")
object Vector extends js.Object {
def fromAngle(angle: Double): Vector = js.native
def random2D(): Vector = js.native
def random3D(): Vector = js.native
def angleBetween(v1: Vector, v2: Vector): Double = js.native
}
@js.native
@JSGlobal("p5.Font")
class Font protected () extends js.Object {
def this(pInst: js.Any = "") = this()
var font: js.Any = js.native
def textBounds(line: String, x: Double, y: Double, fontSize: Double, options: js.Any): js.Dynamic = js.native
}
@js.native
@JSGlobal("p5.MediaElement")
class MediaElement protected () extends js.Object {
def this(elt: String, pInst: js.Any = "") = this()
var src: js.Any = js.native
def volume(`val`: Double = 1.0): Double | MediaElement = js.native
def duration(): Double = js.native
def disconnect(): Unit = js.native
def showControls(): Unit = js.native
def hideControls(): Unit = js.native
def addCue(time: Double, callback: js.Function0[Any], value: js.Any = ""): Double = js.native
def removeCue(id: Double): Unit = js.native
def clearCues(): Unit = js.native
}
@js.native
@JSGlobal("p5.File")
class File extends js.Object {
var file: js.Any = js.native
var `type`: js.Any = js.native
var subtype: js.Any = js.native
var name: js.Any = js.native
var size: js.Any = js.native
var data: js.Any = js.native
}
@js.native
@JSGlobal("p5.SoundFile")
class SoundFile extends js.Object {
def isLoaded(): Boolean = js.native
def play(
startTime: Double = 1.0,
rate: Double = 1.0,
amp: Double = 1.0,
cueStart: Double = 1.0,
duration: Double = 1.0
): Unit = js.native
def playMode(str: String): Unit = js.native
def pause(startTime: Double = 1.0): Unit = js.native
def loop(
startTime: Double = 1.0,
rate: Double = 1.0,
amp: Double = 1.0,
cueLoopStart: Double = 1.0,
duration: Double = 1.0
): Unit = js.native
def isPlaying(): Boolean = js.native
def isPaused(): Boolean = js.native
def stop(startTime: Double = 1.0): Unit = js.native
def setVolume(volume: Double | js.Any, rampTime: Double = 1.0, timeFromNow: Double = 1.0): Unit = js.native
def rate(playbackRate: Double = 1.0): Unit = js.native
def duration(): Double = js.native
def currentTime(): Double = js.native
def jump(cueTime: Double, uuration: Double): Unit = js.native
def channels(): Double = js.native
def sampleRate(): Double = js.native
def frames(): Double = js.native
def reverseBuffer(): Unit = js.native
def onended(callback: js.Function0[Any]): Unit = js.native
def connect(`object`: js.Any = ""): Unit = js.native
def disconnect(): Unit = js.native
def setPath(path: String, callback: js.Function0[Any]): Unit = js.native
def processPeaks(
callback: js.Function0[Any],
initThreshold: Double = 1.0,
minThreshold: Double = 1.0,
minPeaks: Double = 1.0
): js.Array[js.Any] = js.native
def addCue(time: Double, callback: js.Function0[Any], value: js.Any = ""): Double = js.native
def removeCue(id: Double): Unit = js.native
def clearCues(): Unit = js.native
}
// https://github.com/processing/p5.js/blob/master/src/core/shape/vertex.js
@js.native
trait Shape extends js.Object {
//POINTS, LINES, TRIANGLES, TRIANGLE_FAN TRIANGLE_STRIP, QUADS, or QUAD_STRIP
def beginShape(kind: js.UndefOr[String] = js.undefined): Unit = js.native
// CLOSE
def endShape(mode: js.UndefOr[String] = js.undefined): Unit = js.native
}
@js.native
@JSGlobal("p5.Amplitude")
class Amplitude protected () extends js.Object {
def this(smoothing: Double = 1.0) = this()
def getLevel(channel: Double = 1.0): Double = js.native
def toggleNormalize(boolean: Boolean = false): Unit = js.native
def smooth(set: Double): Unit = js.native
}
@js.native
@JSGlobal("p5.Signal")
class Signal extends js.Object {
}
@js.native
@JSGlobal("p5.Env")
class Env extends js.Object {
var attackTime: js.Any = js.native
var attackLevel: js.Any = js.native
var decayTime: js.Any = js.native
var decayLevel: js.Any = js.native
var releaseTime: js.Any = js.native
var releaseLevel: js.Any = js.native
def set(attackTime: Double, attackLevel: Double, decayTime: Double, decayLevel: Double, releaseTime: Double, releaseLevel: Double): Unit = js.native
def setADSR(attackTime: Double, decayTime: Double = 1.0, susRatio: Double = 1.0, releaseTime: Double = 1.0): Unit = js.native
def setRange(aLevel: Double, rLevel: Double): Unit = js.native
def setInput(unit: js.Any): Unit = js.native
def setExp(isExp: Boolean): Unit = js.native
def play(unit: js.Any, startTime: Double = 1.0, sustainTime: Double = 1.0): Unit = js.native
def triggerAttack(unit: js.Any, secondsFromNow: Double): Unit = js.native
def triggerRelease(unit: js.Any, secondsFromNow: Double): Unit = js.native
def ramp(unit: js.Any, secondsFromNow: Double, v: Double, v2: Double = 1.0): Unit = js.native
def add(number: Double): Env = js.native
def mult(number: Double): Env = js.native
def scale(inMin: Double, inMax: Double, outMin: Double, outMax: Double): Env = js.native
}
@js.native
@JSGlobal("p5.Pulse")
class Pulse protected () extends js.Object {
def this(freq: Double = 1.0, w: Double = 1.0) = this()
def width(width: Double = 1.0): Unit = js.native
}
@js.native
@JSGlobal("p5.Noise")
class Noise protected () extends js.Object {
def this(`type`: String) = this()
def setType(`type`: String = ""): Unit = js.native
def start(): Unit = js.native
def stop(): Unit = js.native
def pan(panning: Double, timeFromNow: Double): Unit = js.native
def connect(unit: js.Any): Unit = js.native
def disconnect(): Unit = js.native
}
@js.native
@JSGlobal("p5.AudioIn")
class AudioIn extends js.Object {
var enabled: js.Any = js.native
def start(successCallback: js.Function0[Any], errorCallback: js.Function0[Any]): Unit = js.native
def stop(): Unit = js.native
def connect(unit: js.Any = ""): Unit = js.native
def disconnect(): Unit = js.native
def getLevel(smoothing: Double = 1.0): Double = js.native
def amp(vol: Double, time: Double = 1.0): Unit = js.native
def getSources(callback: js.Function0[Any]): Unit = js.native
def setSource(num: Double): Unit = js.native
}
@js.native
@JSGlobal("p5.Filter")
class Filter extends js.Object {
var biquadFilter: js.Any = js.native
def set(freq: Double, res: Double, timeFromNow: Double = 1.0): Unit = js.native
def freq(freq: Double, timeFromNow: Double = 1.0): Double = js.native
def res(res: Double, timeFromNow: Double = 1.0): Double = js.native
def setType(UNKNOWN: String): Unit = js.native
def amp(volume: Double, rampTime: Double = 1.0, timeFromNow: Double = 1.0): Unit = js.native
def connect(unit: js.Any): Unit = js.native
def disconnect(): Unit = js.native
}
@js.native
@JSGlobal("p5.Delay")
class Delay extends js.Object {
var leftDelay: js.Any = js.native
var rightDelay: js.Any = js.native
def process(Signal: js.Any, delayTime: Double = 1.0, feedback: Double = 1.0, lowPass: Double = 1.0): Unit = js.native
def delayTime(delayTime: Double): Unit = js.native
def feedback(feedback: Double | js.Any): Unit = js.native
def filter(cutoffFreq: Double | js.Any, res: Double | js.Any): Unit = js.native
def setType(`type`: String | Double): Unit = js.native
def amp(volume: Double, rampTime: Double = 1.0, timeFromNow: Double = 1.0): Unit = js.native
def connect(unit: js.Any): Unit = js.native
def disconnect(): Unit = js.native
}
@js.native
@JSGlobal("p5.Reverb")
class Reverb extends js.Object {
def process(src: js.Any, seconds: Double = 1.0, decayRate: Double = 1.0, reverse: Boolean = false): Unit = js.native
def set(seconds: Double = 1.0, decayRate: Double = 1.0, reverse: Boolean = false): Unit = js.native
def amp(volume: Double, rampTime: Double = 1.0, timeFromNow: Double = 1.0): Unit = js.native
def connect(unit: js.Any): Unit = js.native
def disconnect(): Unit = js.native
}
@js.native
@JSGlobal("p5.Convolver")
class Convolver protected () extends js.Object {
def this(path: String, callback: js.Function0[Any] = () => (), errorCallback: js.Function0[Any] = () => ()) = this()
var convolverNode: js.Any = js.native
def createConvolver(path: String, callback: js.Function0[Any] = () => (), errorCallback: js.Function0[Any] = () => ()): Convolver = js.native
def process(src: js.Any): Unit = js.native
var impulses: js.Any = js.native
def addImpulse(path: String, callback: js.Function0[Any], errorCallback: js.Function0[Any]): Unit = js.native
def resetImpulse(path: String, callback: js.Function0[Any], errorCallback: js.Function0[Any]): Unit = js.native
def toggleImpulse(id: String | Double): Unit = js.native
}
@js.native
@JSGlobal("p5.Phrase")
class Phrase protected () extends js.Object {
def this(name: String, callback: js.Function0[Any], sequence: js.Array[js.Any]) = this()
var sequence: js.Any = js.native
}
@js.native
@JSGlobal("p5.Part")
class Part protected () extends js.Object {
def this(steps: Double = 1.0, tatums: Double = 1.0) = this()
def setBPM(BPM: Double, rampTime: Double = 1.0): Unit = js.native
def getBPM(): Double = js.native
def start(time: Double = 1.0): Unit = js.native
def loop(time: Double = 1.0): Unit = js.native
def noLoop(): Unit = js.native
def stop(time: Double = 1.0): Unit = js.native
def pause(time: Double): Unit = js.native
def addPhrase(phrase: Phrase): Unit = js.native
def removePhrase(phraseName: String): Unit = js.native
def getPhrase(phraseName: String): Unit = js.native
def replaceSequence(phraseName: String, sequence: js.Array[js.Any]): Unit = js.native
def onStep(callback: js.Function0[Any]): Unit = js.native
}
@js.native
@JSGlobal("p5.Score")
class Score extends js.Object {
def start(): Unit = js.native
def stop(): Unit = js.native
def pause(): Unit = js.native
def loop(): Unit = js.native
def noLoop(): Unit = js.native
}
@js.native
@JSGlobal("p5.SoundRecorder")
class SoundRecorder extends js.Object {
def setInput(unit: js.Any = ""): Unit = js.native
def record(soundFile: SoundFile, duration: Double = 1.0, callback: js.Function0[Any] = () => ()): Unit = js.native
def stop(): Unit = js.native
def saveSound(soundFile: SoundFile, name: String): Unit = js.native
}
@js.native
@JSGlobal("p5.PeakDetect")
class PeakDetect protected () extends js.Object {
def this(freq1: Double = 1.0, freq2: Double = 1.0, threshold: Double = 1.0, framesPerPeak: Double = 1.0) = this()
def update(fftObject: FFT): Unit = js.native
def onPeak(callback: js.Function0[Any], `val`: js.Any = ""): Unit = js.native
}
@js.native
@JSGlobal("p5.Gain")
class Gain extends js.Object {
def setInput(src: js.Any): Unit = js.native
def connect(unit: js.Any): Unit = js.native
def disconnect(): Unit = js.native
def amp(volume: Double, rampTime: Double = 1.0, timeFromNow: Double = 1.0): Unit = js.native
}
|
lamusique/Scala.js-p5.js | src/main/scala/p5/js/modes/instance/p5.scala | package p5.js.modes.instance
import org.scalajs.dom.raw.Element
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSGlobal, JSImport}
@js.native
trait Sketch extends _root_.p5.js.p5 {
}
@js.native
//@JSImport("p5", JSImport.Default)
@JSGlobal
class p5 extends _root_.p5.js.p5 {
}
object p5 {
// type Oscillator = this.Oscillator
def apply(sketchFn: js.Function1[_root_.p5.js.modes.instance.p5, Unit]): p5 = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)(sketchFn).asInstanceOf[C]
val instantiatedP5 = instantiate[_root_.p5.js.modes.instance.p5]
instantiatedP5
}
def apply(sketchFn: js.Function1[_root_.p5.js.modes.instance.p5, Unit], id: String): p5 = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)(sketchFn, id).asInstanceOf[C]
val instantiatedP5 = instantiate[_root_.p5.js.modes.instance.p5]
instantiatedP5
}
def apply(sketchFn: js.Function1[_root_.p5.js.modes.instance.p5, Unit], elm: Element): p5 = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)(sketchFn, elm).asInstanceOf[C]
val instantiatedP5 = instantiate[_root_.p5.js.modes.instance.p5]
instantiatedP5
}
}
|
lamusique/Scala.js-p5.js | src/main/scala/p5/js/modes/global/p5.scala | package p5.js.modes.global
import scala.scalajs.js
@js.native
trait p5 extends _root_.p5.js.p5 {
}
object p5 {
def apply(): p5 = js.Dynamic.global.window.asInstanceOf[p5]
def apply(setup: js.Function0[Unit], draw: js.Function0[Unit]): p5 = {
val globalScope = js.Dynamic.global.window.asInstanceOf[p5]
globalScope.setup = setup
globalScope.draw = draw
globalScope
}
}
|
lamusique/Scala.js-p5.js | src/main/scala/p5/js/P5js.scala | package p5.js
import org.scalajs.dom.raw.HTMLElement
import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.|
@js.native
trait p5 extends js.Object with p5.js.modules.Shape with p5.js.modules.Sound {
import _root_.p5.js.modules._
type Color = _root_.p5.js.modules.Color
type Element = _root_.p5.js.modules.Element
// type Sound = _root_.p5.js.modules.Sound
type Oscillator = p5.js.modules.Oscillator
var HALF_PI: Double = js.native
var PI: js.Any = js.native
var QUARTER_PI: js.Any = js.native
var TAU: js.Any = js.native
var TWO_PI: js.Any = js.native
var setup: js.Function0[Unit] = js.native
var draw: js.Function0[Unit] = js.native
var frameCount: js.Any = js.native
var focused: js.Any = js.native
var displayWidth: Double = js.native
var displayHeight: Double = js.native
var windowWidth: Double = js.native
var windowHeight: Double = js.native
var width: Double = js.native
var height: Double = js.native
var deviceOrientation: js.Any = js.native
var accelerationX: js.Any = js.native
var accelerationY: js.Any = js.native
var accelerationZ: js.Any = js.native
var pAccelerationX: js.Any = js.native
var pAccelerationY: js.Any = js.native
var pAccelerationZ: js.Any = js.native
var rotationX: js.Any = js.native
var rotationY: js.Any = js.native
var rotationZ: js.Any = js.native
var pRotationX: js.Any = js.native
var pRotationY: js.Any = js.native
var pRotationZ: js.Any = js.native
var keyIsPressed: js.Any = js.native
var key: String = js.native
var keyCode: Int = js.native
var mouseX: Double = js.native
var mouseY: Double = js.native
var pmouseX: Double = js.native
var pmouseY: Double = js.native
var winMouseX: Double = js.native
var winMouseY: Double = js.native
var pwinMouseX: Double = js.native
var pwinMouseY: Double = js.native
var mouseButton: js.Any = js.native
var mouseIsPressed: Boolean = js.native
var touchX: js.Any = js.native
var touchY: js.Any = js.native
var ptouchX: js.Any = js.native
var ptouchY: js.Any = js.native
var touchIsDown: js.Any = js.native
def plane(width: Double, height: Double): p5 = js.native
def sphere(radius: Double, detail: Double = 1.0): Unit = js.native
def ellipsoid(
radiusx: Double,
radiusy: Double,
radiusz: Double,
detail: Double = 1.0
): p5 = js.native
def cylinder(radius: Double, height: Double, detail: Double = 1.0): p5 = js.native
def cone(radius: Double, height: Double, detail: Double = 1.0): Unit = js.native
def torus(radius: Double, tubeRadius: Double, detail: Double = 1.0): Unit = js
.native
def box(width: Double, height: Double, depth: Double): p5 = js.native
def camera(x: Double, y: Double, z: Double): p5 = js.native
def perspective(fovy: Double, aspect: Double, near: Double, far: Double): p5 = js.native
def ortho(
left: Double,
right: Double,
bottom: Double,
top: Double,
near: Double,
far: Double
): p5 = js.native
def ambientLight(
v1: Double | js.Array[js.Any] | String | modules.Color,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): p5 = js.native
def normalMaterial(): p5 = js.native
def texture(): p5 = js.native
def basicMaterial(
v1: Double | js.Array[js.Any] | String | modules.Color,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): p5 = js.native
def ambientMaterial(
v1: Double | js.Array[js.Any] | String | modules.Color,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): p5 = js.native
def specularMaterial(
v1: Double | js.Array[js.Any] | String | modules.Color,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): p5 = js.native
def alpha(obj: js.Any): Unit = js.native
def blue(obj: js.Any): Unit = js.native
def brightness(color: js.Any): Unit = js.native
def color(
v1: Double | String,
v2: Double = 1.0,
v3: Double = 1.0,
alpha: Double = 1.0
): this.Color = js.native
def green(color: js.Any): Unit = js.native
def hue(color: js.Any): Unit = js.native
def lightness(color: js.Any): Unit = js.native
def red(obj: js.Any): Unit = js.native
def saturation(color: js.Any): Unit = js.native
def background(
v1: Double | String | modules.Color | modules.Image,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): Unit = js.native
def clear(): Unit = js.native
def fill(
v1: Double | js.Array[js.Any] | String | modules.Color,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): Unit = js.native
def noFill(): Unit = js.native
def noStroke(): Unit = js.native
def stroke(
v1: Double | js.Array[js.Any] | String | modules.Color,
v2: Double = 1.0,
v3: Double = 1.0,
a: Double = 1.0
): Unit = js.native
def arc(
a: Double,
b: Double,
c: Double,
d: Double,
start: Double,
stop: Double,
mode: String = ""
): js.Dynamic = js.native
def ellipse(a: Double, b: Double, c: Double, d: Double): p5 = js.native
def line(x1: Double, y1: Double, x2: Double, y2: Double): p5 = js.native
def point(x: Double, y: Double): p5 = js.native
def quad(
x1: Double,
y1: Double,
x2: Double,
y2: Double,
x3: Double,
y3: Double,
x4: Double,
y4: Double
): p5 = js.native
def rect(
x: Double,
y: Double,
w: Double,
h: Double,
tl: Double = 1.0,
tr: Double = 1.0,
br: Double = 1.0,
bl: Double = 1.0
): p5 = js.native
def triangle(
x1: Double,
y1: Double,
x2: Double,
y2: Double,
x3: Double,
y3: Double
): p5 = js.native
def noSmooth(): p5 = js.native
def smooth(): p5 = js.native
def strokeWeight(weight: Double): p5 = js.native
def preload(): Unit = js.native
def remove(): Unit = js.native
def bezier(
x1: Double,
y1: Double,
x2: Double,
y2: Double,
x3: Double,
y3: Double,
x4: Double,
y4: Double
): js.Dynamic = js.native
def bezierPoint(
a: Double,
b: Double,
c: Double,
d: Double,
t: Double
): Double = js.native
def bezierTangent(
a: Double,
b: Double,
c: Double,
d: Double,
t: Double
): Double = js.native
def curve(
x1: Double,
y1: Double,
x2: Double,
y2: Double,
x3: Double,
y3: Double,
x4: Double,
y4: Double
): js.Dynamic = js.native
def curveTightness(amount: Double): js.Dynamic = js.native
def curvePoint(
a: Double,
b: Double,
c: Double,
d: Double,
t: Double
): Double = js.native
def curveTangent(
a: Double,
b: Double,
c: Double,
d: Double,
t: Double
): Double = js.native
def print(contents: js.Any): Unit = js.native
def frameRate(fps: Double = 1.0): Double = js.native
def noCursor(): Unit = js.native
def windowResized(): Unit = js.native
def fullscreen(`val`: Boolean = false): Boolean = js.native
def pixelDensity(`val`: Double = 1.0): Double = js.native
def displayDensity(): Double = js.native
def getURL(): String = js.native
def getURLPath(): js.Array[js.Any] = js.native
def getURLParams(): js.Dynamic = js.native
def createCanvas(w: Double, h: Double, renderer: String = ""): js.Dynamic = js.native
def resizeCanvas(): Unit = js.native
def noCanvas(): Unit = js.native
def createGraphics(w: Double, h: Double, renderer: String): js.Dynamic = js.native
def noLoop(): Unit = js.native
def loop(): Unit = js.native
def push(): Unit = js.native
def pop(): Unit = js.native
def redraw(): Unit = js.native
def applyMatrix(
n00: Double,
n01: Double,
n02: Double,
n10: Double,
n11: Double,
n12: Double
): p5 = js.native
def resetMatrix(): p5 = js.native
def rotate(angle: Double): p5 = js.native
def shearX(angle: Double): p5 = js.native
def shearY(angle: Double): p5 = js.native
def translate(x: Double, y: Double): p5 = js.native
def beginContour(): js.Dynamic = js.native
def bezierVertex(
x2: Double,
y2: Double,
x3: Double,
y3: Double,
x4: Double,
y4: Double
): js.Dynamic = js.native
def curveVertex(x: Double, y: Double): js.Dynamic = js.native
def endContour(): js.Dynamic = js.native
def quadraticVertex(
cx: Double,
cy: Double,
x3: Double,
y3: Double
): js.Dynamic = js.native
def vertex(x: Double, y: Double): js.Dynamic = js.native
def setMoveThreshold(value: Double): Unit = js.native
def setShakeThreshold(value: Double): Unit = js.native
def deviceMoved(): Unit = js.native
def deviceTurned(): Unit = js.native
def deviceShaken(): Unit = js.native
var keyPressed: js.Function0[Unit] = js.native
def keyReleased: js.Function0[Unit] = js.native
def keyTyped: js.Function0[Unit] = js.native
def keyIsDown(code: Double): Boolean = js.native
def mouseMoved(): Unit = js.native
def mouseDragged(): Unit = js.native
def mousePressed(): Unit = js.native
def mouseReleased(): Unit = js.native
def mouseClicked(): Unit = js.native
def mouseWheel(): Unit = js.native
def touchStarted(): Unit = js.native
def touchMoved(): Unit = js.native
def touchEnded(): Unit = js.native
// These functions are generative so missing in p5.js source.
def createDiv(html: js.UndefOr[String] = js.undefined): modules.Element = js.native
def createP(html: js.UndefOr[String] = js.undefined): modules.Element = js.native
def createSpan(html: js.UndefOr[String] = js.undefined): modules.Element = js.native
def createImage(width: Double, height: Double): modules.Image = js.native
def createA(href: String, html: String, target: js.UndefOr[String] = js.undefined): modules.Element = js.native
def createSlider(min: Double, max: Double, value: js.UndefOr[Double] = js.undefined, step: js.UndefOr[Double] = js.undefined): modules.Element = js.native
def createButton(label: String, value: js.UndefOr[String] = js.undefined): modules.Element = js.native
def createCheckbox(label: js.UndefOr[String] = js.undefined, value: js.UndefOr[String] = js.undefined): modules.Element = js.native
def createSelect(multiple: js.UndefOr[Boolean]): modules.Element = js.native
// TODO can be a typed element
def createSelect(existing: js.Object): modules.Element = js.native
def saveFrames(
filename: String,
extension: String,
duration: Double,
framerate: Double,
callback: js.Function0[Any] = () => ()
): Unit = js.native
def image(
img: modules.Image,
sx: Double = 0.0,
sy: Double = 0.0,
sWidth: Double = 1.0,
sHeight: Double = 1.0,
dx: Double = 0.0,
dy: Double = 0.0,
dWidth: Double = 1.0,
dHeight: Double = 1.0
): Unit = js.native
def tint(
v1: Double | js.Array[js.Any],
v2: Double | js.Array[js.Any] = ???,
v3: Double | js.Array[js.Any] = ???,
a: Double | js.Array[js.Any] = ???
): Unit = js.native
def noTint(): Unit = js.native
def imageMode(m: String): Unit = js.native
def filter(filterType: String, filterParam: Double): Unit = js.native
def get(
x: Double = 0.0,
y: Double = 0.0,
w: Double = 1.0,
h: Double = 1.0
): js.Array[js.Any] | modules.Image = js.native
def loadPixels(): Unit = js.native
def set(x: Double, y: Double, c: Double | js.Array[js.Any] | js.Any): Unit = js.native
def loadFont(
path: String,
callback: js.Function0[Any] = () => ()
): js.Dynamic = js.native
def loadJSON(
path: String,
callback: js.Function0[Any] = () => (),
errorCallback: js.Function0[Any] = () => (),
datatype: String = ""
): js.Any | js.Array[js.Any] = js.native
def loadStrings(
filename: String,
callback: js.Function0[Any] = () => (),
errorCallback: js.Function0[Any] = () => ()
): js.Array[js.Any] = js.native
def loadXML(
filename: String,
callback: js.Function0[Any] = () => (),
errorCallback: js.Function0[Any] = () => ()
): js.Dynamic = js.native
def httpGet(
path: String,
data: js.Any = "",
datatype: String = "",
callback: js.Function0[Any] = () => (),
errorCallback: js.Function0[Any] = () => ()
): Unit = js.native
def httpPost(
path: String,
data: js.Any = "",
datatype: String = "",
callback: js.Function0[Any] = () => (),
errorCallback: js.Function0[Any] = () => ()
): Unit = js.native
def httpDo(
path: String,
method: String = "",
data: js.Any = "",
datatype: String = "",
callback: js.Function0[Any] = () => (),
errorCallback: js.Function0[Any] = () => ()
): Unit = js.native
def saveJSON(
json: js.Array[js.Any] | js.Any,
filename: String,
optimize: Boolean = false
): Unit = js.native
def saveStrings(list: js.Array[js.Any], filename: String): Unit = js.native
def saveTable(
table: modules.Table,
filename: String,
options: String = ""
): Unit = js.native
def abs(n: Double): Double = js.native
def ceil(n: Double): Double = js.native
def constrain(n: Double, low: Double, high: Double): Double = js.native
def exp(n: Double): Double = js.native
def floor(n: Double): Double = js.native
def lerp(start: Double, stop: Double, amt: Double): Double = js.native
def log(n: Double): Double = js.native
def mag(a: Double, b: Double): Double = js.native
def map(
value: Double,
start1: Double,
stop1: Double,
start2: Double,
stop: Double
): Double = js.native
def max(n0: Double | js.Array[js.Any]): Double = js.native
def min(n0: Double | js.Array[js.Any]): Double = js.native
def norm(value: Double, start: Double, stop: Double): Double = js.native
def pow(n: Double, e: Double): Double = js.native
def round(n: Double): Double = js.native
def sq(n: Double): Double = js.native
def sqrt(n: Double): Double = js.native
def createVector(x: Double = 0.0, y: Double = 0.0, z: Double = 0.0): Unit = js.native
def noise(x: Double, y: Double, z: Double): Double = js.native
def noiseDetail(lod: Double, falloff: Double): Unit = js.native
def noiseSeed(seed: Double): Unit = js.native
def randomSeed(seed: Double): Unit = js.native
def random(min: Double, max: Double): Double = js.native
def randomGaussian(mean: Double, sd: Double): Double = js.native
def acos(value: Double): Double = js.native
def asin(value: Double): Double = js.native
def atan(value: Double): Double = js.native
def atan2(y: Double, x: Double): Double = js.native
def cos(angle: Double): Double = js.native
def sin(angle: Double): Double = js.native
def tan(angle: Double): Double = js.native
def degrees(radians: Double): Double = js.native
def radians(degrees: Double): Double = js.native
def textLeading(leading: Double): js.Any | Double = js.native
def textSize(theSize: Double): js.Any | Double = js.native
def textWidth(theText: String): Double = js.native
def text(
str: String,
x: Double,
y: Double,
x2: Double,
y2: Double
): js.Dynamic = js.native
def textFont(f: js.Any | String): js.Dynamic = js.native
def append(array: js.Array[js.Any], value: js.Any): Unit = js.native
def concat(a: js.Array[js.Any], b: js.Array[js.Any]): js.Array[js.Any] = js.native
def reverse(list: js.Array[js.Any]): Unit = js.native
def shorten(list: js.Array[js.Any]): js.Array[js.Any] = js.native
def shuffle(
array: js.Array[js.Any],
bool: Boolean = false
): js.Array[js.Any] = js.native
def sort(list: js.Array[js.Any], count: Double = 1.0): Unit = js.native
def splice(list: js.Array[js.Any], value: js.Any, position: Double): Unit = js.native
def subset(
list: js.Array[js.Any],
start: Double,
count: Double = 1.0
): js.Array[js.Any] = js.native
def float(str: String): Double = js.native
def int(n: String | Boolean | Double | js.Array[js.Any]): Double = js.native
def str(n: String | Boolean | Double | js.Array[js.Any]): String = js.native
def boolean(n: String | Boolean | Double | js.Array[js.Any]): Boolean = js.native
def byte(n: String | Boolean | Double | js.Array[js.Any]): Double = js.native
def char(n: String | Double | js.Array[js.Any]): String = js.native
def unchar(n: String | js.Array[js.Any]): Double = js.native
def hex(n: Double | js.Array[js.Any]): String = js.native
def unhex(n: String | js.Array[js.Any]): Double = js.native
def join(list: js.Array[js.Any], separator: String): String = js.native
def `match`(str: String, regexp: String): js.Array[js.Any] = js.native
def matchAll(str: String, regexp: String): js.Array[js.Any] = js.native
def nf(
num: Double | js.Array[js.Any],
left: Double = 1.0,
right: Double = 1.0
): String | js.Array[js.Any] = js.native
def nfc(
num: Double | js.Array[js.Any],
right: Double = 1.0
): String | js.Array[js.Any] = js.native
def nfp(
num: Double | js.Array[js.Any],
left: Double = 1.0,
right: Double = 1.0
): String | js.Array[js.Any] = js.native
def nfs(
num: Double | js.Array[js.Any],
left: Double = 1.0,
right: Double = 1.0
): String | js.Array[js.Any] = js.native
def split(value: String, delim: String): js.Array[js.Any] = js.native
def splitTokens(value: String, delim: String = ""): js.Array[js.Any] = js.native
def trim(str: String | js.Array[js.Any] = ???): String | js.Array[js.Any] = js.native
def day(): Double = js.native
def hour(): Double = js.native
def minute(): Double = js.native
def millis(): Double = js.native
def month(): Double = js.native
def second(): Double = js.native
def year(): Double = js.native
// https://github.com/processing/p5.js/blob/master/src/dom/dom.js
def select(name: String, container: String | Element | HTMLElement): js.Array[js.Any] = js.native
def selectAll(name: String, container: js.UndefOr[String] = js.undefined): js.Array[js.Any] = js.native
def removeElements(): Unit = js.native
// https://p5js.org/reference/#/p5/changed
def changed(fxn: js.ThisFunction): Unit = js.native
def changed(active: Boolean): Unit = js.native
// https://p5js.org/reference/#/p5/input
def input(fxn: js.ThisFunction): Unit = js.native
def input(active: Boolean): Unit = js.native
def createRadio(divId: js.UndefOr[String] = js.undefined): Element = js.native
// https://p5js.org/reference/#/p5/createColorPicker
def createColorPicker(): Element = js.native
def createColorPicker(value: String | Color): Element = js.native
def createInput(value: js.UndefOr[String] = js.undefined, `type`: js.UndefOr[String] = js.undefined): Element = js.native
def createFileInput(callback: js.UndefOr[js.Function1[File, Unit]] = js.undefined, multiple: js.UndefOr[String] = js.undefined): Element = js.native
// https://p5js.org/reference/#/p5/createVideo
def createVideo(src: String | js.Array[String], callback: js.UndefOr[js.ThisFunction]): MediaElement = js.native
def createAudio(src: js.UndefOr[String | js.Array[String]] = js.undefined, callback: js.UndefOr[js.ThisFunction]): MediaElement = js.native
def getAudioContext(): js.Dynamic = js.native
def getMasterVolume(): Double = js.native
def masterVolume(
volume: Double | js.Any,
rampTime: Double = 1.0,
timeFromNow: Double = 1.0
): Unit = js .native
def sampleRate(): Double = js.native
def midiToFreq(midiNote: Double): Double = js.native
// p5.Sound
}
|
lamusique/Scala.js-p5.js | project/Dependencies.scala | import sbt._
object Dependencies {
//lazy val scalajsDom = "org.scala-js" %%% "scalajs-dom" % "0.9.8"
lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.8"
}
|
lamusique/Scala.js-p5.js | build.sbt | <gh_stars>1-10
import Dependencies._
ThisBuild / scalaVersion := "2.13.1"
ThisBuild / version := "0.0.1"
ThisBuild / organization := "org.p5js"
ThisBuild / organizationName := "p5.js"
enablePlugins(ScalaJSPlugin)
// This is an application with a main method
//scalaJSUseMainModuleInitializer := true
//mainClass in (Compile, run) := Some("samples.TutorialP5jsApp")
//mainClass in Compile := Some("samples.TutorialP5jsApp")
lazy val root = (project in file("."))
.settings(
name := "scala-js-p5js",
// libraryDependencies += scalajsDom,
libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.8",
libraryDependencies += scalaTest % Test
)
// See https://www.scala-sbt.org/1.x/docs/Using-Sonatype.html for instructions on how to publish to Sonatype.
|
lamusique/Scala.js-p5.js | src/main/scala/samples/GlobalModeSampleApp.scala | package samples
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExportTopLevel, _}
// This import decides which mode.
import p5.js.modes.global.p5
@JSExportTopLevel("GlobalModeSampleApp")
@JSExportAll
object GlobalModeSampleApp {
def main(args: js.Array[String]): Unit = {
println("Hello world p5.js!")
val p5InGlobalScope = p5()
val setupFn = () => {
import p5InGlobalScope._
createCanvas(400, 400)
background(0)
noStroke()
val c = color(250, 100, 90)
println(c)
println(c.getRed())
()
}
val drawFn: () => Unit = () => {
import p5InGlobalScope._
if (mouseIsPressed) {
println(mouseX)
println(mouseY)
ellipse(mouseX, mouseY, 20, 20)
}
}
p5InGlobalScope.setup = setupFn
p5InGlobalScope.draw = drawFn
// Here this doesn't work owing to out of scope.
// val c = window.color(250, 100, 90)
val pijs = 31415926535897932d
println(pijs)
println(pijs + 1)
println(pijs + 2)
val long = 9223372036854775807L
println(long)
println(long + 1)
println("the main ends.")
}
}
|
lamusique/Scala.js-p5.js | src/main/scala/p5/js/modules/p5sound.scala | <gh_stars>1-10
package p5.js.modules
import org.scalajs.dom.raw.AudioParam
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSGlobal, JSName}
import scala.scalajs.js.|
@js.native
trait Sound extends js.Object {
def userStartAudio(elements: js.UndefOr[Element | js.Array[Element]] = js.undefined, callback: js.UndefOr[js.ThisFunction] = js.undefined): js.Promise[Unit] = js.native
}
//@js.native
//@JSGlobal("p5.Sound")
//class Sound extends js.Object {
//
// def userStartAudio(elements: js.UndefOr[Element | js.Array[Element]] = js.undefined, callback: js.UndefOr[js.ThisFunction] = js.undefined): js.Promise[Unit] = js.native
//
//}
@js.native
@JSGlobal("p5.Oscillator")
class Oscillator() extends js.Object {
def start(time: Double = 1.0, frequency: Double = 0.0): Unit = js.native
def stop(secondsFromNow: Double): Unit = js.native
def amp(vol: Double, rampTime: js.UndefOr[Double] = js.undefined, timeFromNow: js.UndefOr[Double] = js.undefined): AudioParam = js.native
// https://p5js.org/reference/#/p5.Oscillator/freq
def freq(frequency: Double | Signal | Oscillator, rampTime: js.UndefOr[Double] = js.undefined, timeFromNow: js.UndefOr[Double] = js.undefined): AudioParam = js.native
def setType(`type`: String): Unit = js.native
def connect(unit: js.Any): Unit = js.native
def disconnect(): Unit = js.native
def pan(panning: Double, timeFromNow: Double): Unit = js.native
def phase(phase: Double): Unit = js.native
def add(number: Double): Oscillator = js.native
def mult(number: Double): Oscillator = js.native
def scale(inMin: Double, inMax: Double, outMin: Double, outMax: Double): Oscillator = js.native
}
object Oscillator {
def apply(): Oscillator = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)().asInstanceOf[C]
val instance = instantiate[Oscillator]
instance
}
def apply(`type`: String): Oscillator = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)(`type`).asInstanceOf[C]
val instance = instantiate[Oscillator]
instance
}
def apply(freq: Double): Oscillator = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)(freq).asInstanceOf[C]
val instance = instantiate[Oscillator]
instance
}
def apply(freq: Double, `type`: String): Oscillator = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)(freq, `type`).asInstanceOf[C]
val instance = instantiate[Oscillator]
instance
}
}
@js.native
@JSGlobal("p5.FFT")
class FFT protected () extends js.Object {
def this(smoothing: Double = 1.0, bins: Double = 1.0) = this()
def setInput(source: js.Any = ""): Unit = js.native
def waveform(bins: Double = 1.0, precision: String = ""): js.Array[Double] = js.native
def analyze(bins: Double = 1.0, scale: Double = 1.0): js.Array[js.Any] = js.native
def getEnergy(frequency1: Double | String, frequency2: Double = 1.0): Double = js.native
def getCentroid(): Double = js.native
def smooth(smoothing: Double): Unit = js.native
}
object FFT {
def apply(): FFT = {
def instantiate[C <: js.Any : js.ConstructorTag]: C =
js.Dynamic.newInstance(js.constructorTag[C].constructor)().asInstanceOf[C]
val instance = instantiate[FFT]
instance
}
}
|
lamusique/Scala.js-p5.js | src/main/scala/samples/InstanceModeSampleApp.scala | package samples
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExportTopLevel, _}
// This import decides which mode.
import p5.js.modes.instance.p5
@JSExportTopLevel("InstanceModeSampleApp")
@JSExportAll
object InstanceModeSampleApp {
def main(args: js.Array[String]): Unit = {
println("Hello world p5.js!")
// https://github.com/processing/p5.js/wiki/Global-and-instance-mode
val sketchFn: js.Function1[p5, Unit] = (sketch: p5) => {
import sketch._
setup = () => {
createCanvas(400, 400)
background(0)
noStroke()
val c = color(250, 100, 90)
println(c)
println(c.getRed())
()
}
draw = () => {
if (mouseIsPressed) {
println(mouseX)
println(mouseY)
ellipse(mouseX, mouseY, 20, 20)
}
}
}
// instantiate
val myp5 = p5(sketchFn)
println("the main ends.")
}
}
|
ccellado/ergo | src/main/scala/scorex/core/utils/TypesafeConfigPropertyDefiner.scala | package scorex.core.utils
import ch.qos.logback.core.PropertyDefinerBase
import com.typesafe.config.ConfigFactory
class TypesafeConfigPropertyDefiner extends PropertyDefinerBase {
private var propertyName = "scorex.logging.level"
override def getPropertyValue: String = ConfigFactory.load.getString(propertyName)
def setPropertyName(propertyName: String): Unit = {
this.propertyName = propertyName
}
}
|
ccellado/ergo | src/main/scala/org/ergoplatform/http/api/EmissionApiRoute.scala | package org.ergoplatform.http.api
import akka.actor.ActorRefFactory
import akka.http.scaladsl.server.Route
import io.circe.{Encoder, Json}
import org.ergoplatform.{ErgoAddressEncoder, ErgoScriptPredef, Pay2SAddress}
import org.ergoplatform.mining.emission.EmissionRules
import org.ergoplatform.settings.{ErgoSettings, ReemissionSettings}
import scorex.core.api.http.ApiResponse
import scorex.core.settings.RESTApiSettings
import io.circe.syntax._
case class EmissionApiRoute(ergoSettings: ErgoSettings)
(implicit val context: ActorRefFactory) extends ErgoBaseApiRoute {
import EmissionApiRoute._
override val settings: RESTApiSettings = ergoSettings.scorexSettings.restApi
private val chainSettings = ergoSettings.chainSettings
private val emissionRules = chainSettings.emissionRules
private val reemissionSettings = chainSettings.reemission
private implicit val ergoAddressEncoder: ErgoAddressEncoder = new ErgoAddressEncoder(chainSettings.addressPrefix)
override def route: Route = pathPrefix("emission") {
emissionAt ~ scripts
}
/**
* API method to display emission data for given height
*/
val emissionAt: Route = (pathPrefix("at" / IntNumber) & get) { height =>
ApiResponse(emissionInfoAtHeight(height, emissionRules, reemissionSettings))
}
/**
* API method which displays emission and re-emission related scripts as P2S addresses
*/
val scripts: Route = pathPrefix("scripts") {
val ms = ergoSettings.chainSettings.monetary
ApiResponse(
Json.obj(
"emission" -> Pay2SAddress(ErgoScriptPredef.emissionBoxProp(ms)).toString().asJson,
"reemission" -> Pay2SAddress(reemissionSettings.reemissionRules.reemissionBoxProp(ms)).toString().asJson,
"pay2Reemission" -> Pay2SAddress(reemissionSettings.reemissionRules.payToReemission).toString().asJson
)
)
}
}
object EmissionApiRoute {
/**
* Data container for emission/at API request output. Contains emission info for a block at a given height.
*
* @param height - height emission info is given for
* @param minerReward - miner reward for given height
* @param totalCoinsIssued - total amount of ERG emitted
* @param totalRemainCoins - total amount of ERGs left in the emission contract box
* @param reemissionAmt - re-emission tokens issuance for given height (if EIP-27 is activated)
*/
final case class EmissionInfo(height: Int,
minerReward: Long,
totalCoinsIssued: Long,
totalRemainCoins: Long,
reemissionAmt: Long)
def emissionInfoAtHeight(height: Int,
emissionRules: EmissionRules,
reemissionSettings: ReemissionSettings): EmissionInfo = {
val reemissionAmt = reemissionSettings.reemissionRules.reemissionForHeight(height.toInt, emissionRules)
val minerReward = emissionRules.minersRewardAtHeight(height) - reemissionAmt
val totalCoinsIssued = emissionRules.issuedCoinsAfterHeight(height)
val totalRemainCoins = emissionRules.coinsTotal - totalCoinsIssued
EmissionInfo(height, minerReward, totalCoinsIssued, totalRemainCoins, reemissionAmt)
}
// todo: add totalReemitted ?
implicit val encoder: Encoder[EmissionInfo] = (ei: EmissionInfo) => Json.obj(
"height" -> Json.fromInt(ei.height),
"minerReward" -> Json.fromLong(ei.minerReward),
"totalCoinsIssued" -> Json.fromLong(ei.totalCoinsIssued),
"totalRemainCoins" -> Json.fromLong(ei.totalRemainCoins),
"reemitted" -> Json.fromLong(ei.reemissionAmt)
)
}
|
ccellado/ergo | src/main/scala/org/ergoplatform/reemission/ReemissionRules.scala | package org.ergoplatform.reemission
import org.ergoplatform.ErgoLikeContext.Height
import org.ergoplatform.contracts.ReemissionContracts
import org.ergoplatform.mining.emission.EmissionRules
import org.ergoplatform.{ErgoAddressEncoder, Pay2SAddress}
import org.ergoplatform.settings.{ErgoSettings, ReemissionSettings}
import sigmastate.SBoolean
import sigmastate.Values.Value
import sigmastate.eval.CompiletimeIRContext
import sigmastate.lang.{CompilerSettings, SigmaCompiler, TransformingSigmaBuilder}
import scala.util.Try
/**
* Contains re-emission contracts (defined in `ReemissionContracts`) and helper functions
* for re-emission.
*/
class ReemissionRules(reemissionSettings: ReemissionSettings) extends ReemissionContracts {
override val reemissionNftIdBytes: Array[Byte] = reemissionSettings.reemissionNftIdBytes
override val reemissionStartHeight: Height = reemissionSettings.reemissionStartHeight
/**
* How many ERG taken from emission to re-emission initially
*/
val basicChargeAmount = 12 // in ERG
/**
* @return how many re-emission tokens can be unlocked at given height
*/
def reemissionForHeight(height: Height,
emissionRules: EmissionRules): Long = {
val emission = emissionRules.emissionAtHeight(height)
if (height >= reemissionSettings.activationHeight &&
emission >= (basicChargeAmount + 3) * EmissionRules.CoinsInOneErgo) {
basicChargeAmount * EmissionRules.CoinsInOneErgo
} else if (height >= reemissionSettings.activationHeight &&
emission > 3 * EmissionRules.CoinsInOneErgo) {
emission - 3 * EmissionRules.CoinsInOneErgo
} else {
0L
}
}
}
object ReemissionRules {
/**
* @param mainnet - whether to create address for mainnet or testnet
* @return - P2S address for a box used to carry emission NFT and re-emission tokens
* to inject them into the emission box on activation height
*/
def injectionBoxP2SAddress(mainnet: Boolean): Pay2SAddress = {
val networkPrefix = if (mainnet) {
ErgoAddressEncoder.MainnetNetworkPrefix
} else {
ErgoAddressEncoder.TestnetNetworkPrefix
}
implicit val addrEncoder = new ErgoAddressEncoder(networkPrefix)
val source =
"""
| {
| INPUTS(0).value > 30000000L * 1000000000L
| }
""".stripMargin
val compiler = SigmaCompiler(CompilerSettings(networkPrefix, TransformingSigmaBuilder, lowerMethodCalls = true))
val compiled = Try(compiler.compile(Map.empty, source)(new CompiletimeIRContext)).get.asInstanceOf[Value[SBoolean.type]].toSigmaProp
Pay2SAddress.apply(compiled)
}
def main(args: Array[String]): Unit = {
val p2sAddress = injectionBoxP2SAddress(mainnet = false)
println(new ErgoAddressEncoder(ErgoAddressEncoder.TestnetNetworkPrefix).fromString(p2sAddress.toString()))
println("injectioon box p2s: " + p2sAddress)
val settings = ErgoSettings.read()
println("Monetary settings: " + settings.chainSettings.monetary)
println("Reemission settings: " + settings.chainSettings.reemission)
val ms = settings.chainSettings.monetary
val rs = settings.chainSettings.reemission
val emissionRules = settings.chainSettings.emissionRules
val reemissionRules = settings.chainSettings.reemission.reemissionRules
val et = reemissionRules.reemissionBoxProp(ms)
val enc = new ErgoAddressEncoder(ErgoAddressEncoder.MainnetNetworkPrefix)
println("p2s address: " + enc.fromProposition(et))
// reemission.tokenPreservation(Array.fill(32)(0: Byte), 0: Byte)
var lowSet = false
val total = (777217 to rs.reemissionStartHeight).map { h =>
val e = emissionRules.emissionAtHeight(h) / EmissionRules.CoinsInOneErgo
val r = reemissionRules.reemissionForHeight(h, emissionRules) / EmissionRules.CoinsInOneErgo
if ((e - r) == 3 && !lowSet) {
println("Start of low emission period: " + h)
lowSet = true
}
if ((h % 65536 == 0) || h == rs.activationHeight) {
println(s"Emission at height $h : " + e)
println(s"Reemission at height $h : " + r)
}
r
}.sum
val totalBlocks = total / 3 // 3 erg per block
println("Total reemission: " + total + " ERG")
println("Total reemission is enough for: " + totalBlocks + " blocks (" + totalBlocks / 720.0 / 365.0 + " years")
println(s"Emission at ${reemissionRules.reemissionStartHeight}: ${emissionRules.emissionAtHeight(reemissionRules.reemissionStartHeight)}")
println(s"Emission at ${reemissionRules.reemissionStartHeight - 1}: ${emissionRules.emissionAtHeight(reemissionRules.reemissionStartHeight - 1)}")
println("Tokens: " + 20000000 * EmissionRules.CoinsInOneErgo )
}
}
|
ccellado/ergo | src/main/scala/scorex/core/utils/utils.scala | <reponame>ccellado/ergo
package scorex.core
import java.security.SecureRandom
import scala.annotation.tailrec
import scala.collection.mutable
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
package object utils {
@deprecated("Use scorex.util.ScorexLogging instead.", "scorex-util 0.1.0")
type ScorexLogging = scorex.util.ScorexLogging
/**
* @param block - function to profile
* @return - execution time in seconds and function result
*/
def profile[R](block: => R): (Float, R) = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
((t1 - t0).toFloat / 1000000000, result)
}
def toTry(b: Boolean, msg: String): Try[Unit] = b match {
case true => Success(Unit)
case false => Failure(new Exception(msg))
}
@tailrec
final def untilTimeout[T](timeout: FiniteDuration,
delay: FiniteDuration = 100.milliseconds)(fn: => T): T = {
Try {
fn
} match {
case Success(x) => x
case _ if timeout > delay =>
Thread.sleep(delay.toMillis)
untilTimeout(timeout - delay, delay)(fn)
case Failure(e) => throw e
}
}
def randomBytes(howMany: Int): Array[Byte] = {
val r = new Array[Byte](howMany)
new SecureRandom().nextBytes(r) //overrides r
r
}
def concatBytes(seq: Traversable[Array[Byte]]): Array[Byte] = {
val length: Int = seq.map(_.length).sum
val result: Array[Byte] = new Array[Byte](length)
var pos: Int = 0
seq.foreach { array =>
System.arraycopy(array, 0, result, pos, array.length)
pos += array.length
}
result
}
def concatFixLengthBytes(seq: Traversable[Array[Byte]]): Array[Byte] = seq.headOption match {
case None => Array[Byte]()
case Some(head) => concatFixLengthBytes(seq, head.length)
}
def concatFixLengthBytes(seq: Traversable[Array[Byte]], length: Int): Array[Byte] = {
val result: Array[Byte] = new Array[Byte](seq.toSeq.length * length)
var index = 0
seq.foreach { s =>
Array.copy(s, 0, result, index, length)
index += length
}
result
}
implicit class MapPimp[K, V](underlying: mutable.Map[K, V]) {
/**
* One liner for updating a Map with the possibility to handle case of missing Key
* @param k map key
* @param f function that is passed Option depending on Key being present or missing, returning new Value
* @return Option depending on map being updated or not
*/
def adjust(k: K)(f: Option[V] => V): Option[V] = underlying.put(k, f(underlying.get(k)))
/**
* One liner for updating a Map with the possibility to handle case of missing Key
* @param k map key
* @param f function that is passed Option depending on Key being present or missing,
* returning Option signaling whether to update or not
* @return new Map with value updated under given key
*/
def flatAdjust(k: K)(f: Option[V] => Option[V]): Option[V] =
f(underlying.get(k)) match {
case None => None
case Some(v) => underlying.put(k, v)
}
}
}
|
ccellado/ergo | src/main/scala/org/ergoplatform/settings/ReemissionSettings.scala | <filename>src/main/scala/org/ergoplatform/settings/ReemissionSettings.scala<gh_stars>0
package org.ergoplatform.settings
import org.ergoplatform.ErgoBox
import org.ergoplatform.reemission.ReemissionRules
import org.ergoplatform.wallet.boxes.ErgoBoxSerializer
import scorex.util.ModifierId
import scorex.util.encode.Base16
/**
* Configuration section for re-emission (EIP27) parameters
*
* @see src/main/resources/application.conf for parameters description
*/
case class ReemissionSettings(checkReemissionRules: Boolean,
emissionNftId: ModifierId,
reemissionTokenId: ModifierId,
reemissionNftId: ModifierId,
activationHeight: Int,
reemissionStartHeight: Int,
injectionBoxBytesEncoded: String) {
val emissionNftIdBytes: Array[Byte] = Algos.decode(emissionNftId).get
val reemissionNftIdBytes: Array[Byte] = Algos.decode(reemissionNftId).get
val reemissionTokenIdBytes: Array[Byte] = Algos.decode(reemissionTokenId).get
lazy val InjectionBoxBytes: Array[Byte] = Base16.decode(injectionBoxBytesEncoded).get
lazy val injectionBox: ErgoBox = ErgoBoxSerializer.parseBytes(InjectionBoxBytes)
val reemissionRules = new ReemissionRules(reemissionSettings = this)
}
|
ccellado/ergo | src/main/scala/org/ergoplatform/nodeView/history/ErgoSyncInfo.scala | <gh_stars>0
package org.ergoplatform.nodeView.history
import org.ergoplatform.modifiers.history.header.{Header, HeaderSerializer}
import scorex.core.NodeViewModifier
import scorex.core.consensus.SyncInfo
import scorex.core.network.message.SyncInfoMessageSpec
import scorex.core.serialization.ScorexSerializer
import scorex.util.serialization.{Reader, Writer}
import scorex.util.{ModifierId, ScorexLogging, bytesToId, idToBytes}
/**
* Information on sync status to be sent to peer over the wire
*
*/
sealed trait ErgoSyncInfo extends SyncInfo {
/*
* Whether sync info message corresponds to non-empty blockchain
*/
val nonEmpty: Boolean
override type M = ErgoSyncInfo
override lazy val serializer: ScorexSerializer[ErgoSyncInfo] = ErgoSyncInfoSerializer
}
/**
* @param lastHeaderIds - last header ids known to a peer
*/
case class ErgoSyncInfoV1(lastHeaderIds: Seq[ModifierId]) extends ErgoSyncInfo {
override val nonEmpty: Boolean = lastHeaderIds.nonEmpty
}
/**
* @param lastHeaders - some recent headers (including last one) known to a peer
*/
case class ErgoSyncInfoV2(lastHeaders: Seq[Header]) extends ErgoSyncInfo {
/**
* Height of a chain reported by a peer (so most recent header it shows)
*/
val height = lastHeaders.headOption.map(_.height)
override val nonEmpty: Boolean = lastHeaders.nonEmpty
}
object ErgoSyncInfo {
val MaxBlockIds = 1000
}
object ErgoSyncInfoSerializer extends ScorexSerializer[ErgoSyncInfo] with ScorexLogging {
val v2HeaderMode: Byte = -1 // used to mark sync v2 messages
val MaxHeadersAllowed = 50 // in sync v2 message, no more than 50 headers allowed
val MaxHeaderSize = 1000 // currently header is about 200+ bytes, but new fields can be added via a SF,
// anyway we set hard max header size limit
override def serialize(obj: ErgoSyncInfo, w: Writer): Unit = {
obj match {
case v1: ErgoSyncInfoV1 =>
// in sync message we just write number of last header ids and then ids themselves
w.putUShort(v1.lastHeaderIds.size)
v1.lastHeaderIds.foreach(id => w.putBytes(idToBytes(id)))
case v2: ErgoSyncInfoV2 =>
w.putUShort(0) // to stop sync v1 parser
w.put(v2HeaderMode) // signal that v2 message started
w.putUByte(v2.lastHeaders.length) // number of headers peer is announcing
v2.lastHeaders.foreach { h =>
val headerBytes = h.bytes
w.putUShort(headerBytes.length)
w.putBytes(headerBytes)
}
case _ =>
log.error(s"Wrong SyncInfo version: $obj")
}
}
override def parse(r: Reader): ErgoSyncInfo = {
val length = r.getUShort()
if (length == 0 && r.remaining > 1) {
val mode = r.getByte()
if (mode == v2HeaderMode) {
// parse v2 sync message
val headersCount = r.getUByte()
require(headersCount <= MaxHeadersAllowed) // check to avoid spam
val headers = (1 to headersCount).map { _ =>
val headerBytesCount = r.getUShort()
require(headerBytesCount < MaxHeaderSize) // check to avoid spam
val headerBytes = r.getBytes(headerBytesCount)
HeaderSerializer.parseBytes(headerBytes)
}
ErgoSyncInfoV2(headers)
} else {
throw new Exception(s"Wrong SyncInfo version: $r")
}
} else { // parse v1 sync message
require(length <= ErgoSyncInfo.MaxBlockIds + 1, "Too many block ids in sync info")
val ids = (1 to length).map(_ => bytesToId(r.getBytes(NodeViewModifier.ModifierIdSize)))
ErgoSyncInfoV1(ids)
}
}
}
object ErgoSyncInfoMessageSpec extends SyncInfoMessageSpec[ErgoSyncInfo](ErgoSyncInfoSerializer)
|
ccellado/ergo | ergo-wallet/src/main/scala/org/ergoplatform/wallet/protocol/context/ErgoLikeParameters.scala | package org.ergoplatform.wallet.protocol.context
/**
* Blockchain parameters readjustable via miners voting and voting-related data.
* All these fields are included into extension section of a first block of a voting epoch.
*/
trait ErgoLikeParameters {
/**
* @return cost of storing 1 byte in UTXO for four years, in nanoErgs
*/
def storageFeeFactor: Int
/**
* @return cost of a transaction output, in computation unit
*/
def minValuePerByte: Int
/**
* @return max block size, in bytes
*/
def maxBlockSize: Int
/**
* @return cost of a token contained in a transaction, in computation unit
*/
def tokenAccessCost: Int
/**
* @return cost of a transaction input, in computation unit
*/
def inputCost: Int
/**
* @return cost of a transaction data input, in computation unit
*/
def dataInputCost: Int
/**
* @return cost of a transaction output, in computation unit
*/
def outputCost: Int
/**
* @return computation units limit per block
*/
def maxBlockCost: Int
/**
* @return height when voting for a soft-fork had been started
*/
def softForkStartingHeight: Option[Int]
/**
* @return votes for soft-fork collected in previous epochs
*/
def softForkVotesCollected: Option[Int]
/**
* @return Protocol version
*/
def blockVersion: Byte
}
|
ccellado/ergo | src/main/scala/org/ergoplatform/network/ErgoSyncTracker.scala | package org.ergoplatform.network
import java.net.InetSocketAddress
import akka.actor.ActorSystem
import org.ergoplatform.nodeView.history.ErgoHistory
import org.ergoplatform.nodeView.history.ErgoHistory.Height
import scorex.core.consensus.History.{Fork, HistoryComparisonResult, Older, Unknown}
import org.ergoplatform.network.ErgoNodeViewSynchronizer.Events.{BetterNeighbourAppeared, NoBetterNeighbour}
import scorex.core.network.ConnectedPeer
import scorex.core.settings.NetworkSettings
import scorex.core.utils.TimeProvider
import scorex.util.ScorexLogging
import scala.collection.mutable
import scala.concurrent.duration._
import scorex.core.utils.MapPimp
final case class ErgoSyncTracker(system: ActorSystem,
networkSettings: NetworkSettings,
timeProvider: TimeProvider)
extends ScorexLogging {
private val MinSyncInterval: FiniteDuration = 20.seconds
private val SyncThreshold: FiniteDuration = 1.minute
val heights: mutable.Map[ConnectedPeer, Height] = mutable.Map[ConnectedPeer, Height]()
protected[network] val statuses: mutable.Map[ConnectedPeer, ErgoPeerStatus] =
mutable.Map[ConnectedPeer, ErgoPeerStatus]()
def fullInfo(): Iterable[ErgoPeerStatus] = statuses.values
// returns diff
def updateLastSyncGetTime(peer: ConnectedPeer): Long = {
val prevSyncGetTime = statuses.get(peer).flatMap(_.lastSyncGetTime).getOrElse(0L)
val currentTime = timeProvider.time()
statuses.get(peer).foreach { status =>
statuses.update(peer, status.copy(lastSyncGetTime = Option(currentTime)))
}
currentTime - prevSyncGetTime
}
def notSyncedOrOutdated(peer: ConnectedPeer): Boolean = {
val peerOpt = statuses.get(peer)
val notSyncedOrMissing = peerOpt.forall(_.lastSyncSentTime.isEmpty)
val outdated =
peerOpt
.flatMap(_.lastSyncSentTime)
.exists(syncTime => (timeProvider.time() - syncTime).millis > SyncThreshold)
notSyncedOrMissing || outdated
}
def updateStatus(peer: ConnectedPeer, status: HistoryComparisonResult, height: Option[Height]): Unit = {
val seniorsBefore = numOfSeniors()
statuses.adjust(peer){
case None =>
ErgoPeerStatus(peer, status, height.getOrElse(ErgoHistory.EmptyHistoryHeight), None, None)
case Some(existingPeer) =>
existingPeer.copy(status = status, height = height.getOrElse(existingPeer.height))
}
val seniorsAfter = numOfSeniors()
// todo: we should also send NoBetterNeighbour signal when all the peers around are not seniors initially
if (seniorsBefore > 0 && seniorsAfter == 0) {
log.info("Syncing is done, switching to stable regime")
system.eventStream.publish(NoBetterNeighbour)
}
if (seniorsBefore == 0 && seniorsAfter > 0) {
system.eventStream.publish(BetterNeighbourAppeared)
}
heights += (peer -> height.getOrElse(ErgoHistory.EmptyHistoryHeight))
}
/**
* Get synchronization status for given connected peer
*/
def getStatus(peer: ConnectedPeer): Option[HistoryComparisonResult] = {
statuses.get(peer).map(_.status)
}
def clearStatus(remote: InetSocketAddress): Unit = {
statuses.find(_._1.connectionId.remoteAddress == remote) match {
case Some((peer, _)) => statuses -= peer
case None => log.warn(s"Trying to clear status for $remote, but it is not found")
}
}
def updateLastSyncSentTime(peer: ConnectedPeer): Unit = {
val currentTime = timeProvider.time()
statuses.get(peer).foreach { status =>
statuses.update(peer, status.copy(lastSyncSentTime = Option(currentTime)))
}
}
protected[network] def outdatedPeers: IndexedSeq[ConnectedPeer] = {
val currentTime = timeProvider.time()
statuses.filter { case (_, status) =>
status.lastSyncSentTime.exists(syncTime => (currentTime - syncTime).millis > SyncThreshold)
}.keys.toVector
}
def peersByStatus: Map[HistoryComparisonResult, Iterable[ConnectedPeer]] =
statuses.groupBy(_._2.status).mapValues(_.keys).view.force
protected def numOfSeniors(): Int = statuses.count(_._2.status == Older)
def maxHeight(): Option[Int] = if(heights.nonEmpty) Some(heights.maxBy(_._2)._2) else None
/**
* Return the peers to which this node should send a sync signal, including:
* outdated peers, if any, otherwise, all the peers with unknown status plus a random peer with
* `Older` status.
* Updates lastSyncSentTime for all returned peers as a side effect
*/
def peersToSyncWith(): IndexedSeq[ConnectedPeer] = {
val outdated = outdatedPeers
val peers =
if (outdated.nonEmpty) {
outdated
} else {
val currentTime = timeProvider.time()
val unknowns = statuses.filter(_._2.status == Unknown).toVector
val forks = statuses.filter(_._2.status == Fork).toVector
val elders = statuses.filter(_._2.status == Older).toVector
val nonOutdated =
(if (elders.nonEmpty) elders(scala.util.Random.nextInt(elders.size)) +: unknowns else unknowns) ++ forks
nonOutdated.filter { case (_, status) =>
(currentTime - status.lastSyncSentTime.getOrElse(0L)).millis >= MinSyncInterval
}.map(_._1)
}
peers.foreach(updateLastSyncSentTime)
peers
}
override def toString: String = {
val now = System.currentTimeMillis()
statuses.toSeq.sortBy(_._2.lastSyncSentTime.getOrElse(0L))(Ordering[Long].reverse).map {
case (peer, status) =>
(peer.connectionId.remoteAddress, statuses.get(peer), status.lastSyncSentTime.map(now - _))
}.map { case (address, status, millisSinceLastSync) =>
s"$address, height: ${status.map(_.height)}, status: ${status.map(_.status)}, lastSync: $millisSinceLastSync ms ago"
}.mkString("\n")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.